{"text": "#include <vector>\n#include <cassert>\n\n#include <iostream>\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n\n// Flag for slope reconstruction type\nenum class Slope { Zero, Reconstructed };\n\n//! \\breif Implements a piecewise cubic Herite interpolation on equidistant meshes.\nclass PCHI {\npublic:\n    //! \\brief Construct the slopes frome the data, either usinf dinite-differences or assuming f'(x_j) = 0\n    //! \\param[in] t vector of nodes (assumed equidistant and sorted)\n    //! \\param[in] y vector of values at nodes t\n    //! \\param[in] s Flag to set if you want to reconstruct or set slopes to zero\n    PCHI(const Eigen::VectorXd & t, const Eigen::VectorXd & y, Slope s = Slope::Reconstructed)\n        : t(t), y(y), c(t.size()) {\n        // Sanity check\n        n = t.size();\n        assert( n == y.size() && \"t and y must have same dimension.\" );\n        assert( n >= 3 && \"need at least two nodes.\" );\n        h = t(1) - t(0);\n        \n        switch(s) {\n            //// CASE: reconstruction of the slope, assuming f'(x_j) = 0 (O(1))\n            case Slope::Zero:\n                c = Eigen::VectorXd::Zero(n);\n                break;\n            //// CASE: reconstruction of the slope using a second order finite difference (O(h^2))\n            case Slope::Reconstructed:\n            default:\n//                 c(0) = ( y(1) - y(0) ) / h; // First order\n                c(0) = ( -1*y(2) + 4*y(1) - 3*y(0) ) / 2 / h;\n                for(int i = 1; i < n-1; ++i) {\n                    c(i) = ( y(i+1) - y(i-1) ) / 2 / h;\n                }\n//                 c(n-1) = ( y(n-1) - y(n-2) ) / h; // First order\n                c(n-1) = ( 3*y(n-1) - 4*y(n-2) + 1*y(n-3) ) / 2 / h;\n                break;\n        }\n    }\n    \n    //! \\brief Evaluate the intepolant at the nodes x\n    //! Input assumed sorted, unique and inside the interval\n    //! \\param[in] x vector of points t where to compute s(t)\n    //! \\return values of interpolant at x (vector)\n    Eigen::VectorXd operator() (Eigen::VectorXd x) const {\n        \n        Eigen::VectorXd ret(x.size());\n        // Stores the current interval index and some temporary variable\n        int i_star = 0;\n        double tmp,t1,y1,y2,c1,c2,a1,a2,a3;\n        for(int j = 0; j < x.size(); ++j) {\n            // Find interval and porting of hermloceval Matlab code 3.4.6\n            if( t(i_star) < x(j) || i_star == 0) { \n                ++i_star;\n                t1 = t(i_star-1);\n                y1 = y(i_star-1);\n                y2 = y(i_star);\n                c1 = c(i_star-1);\n                c2 = c(i_star);\n                a1 = y2 - y1;\n                a2 = a1 - h*c1;\n                a3 = h*c2 - a1 - a2;\n            }\n            // Compute s(x(j))\n            tmp = ( x(j) - t1 ) / h;\n            ret(j) = y1 + ( a1 + ( a2+a3*tmp ) * ( tmp - 1. ) ) * tmp;\n        }\n        \n        return ret;\n    }\n    \nprivate:\n    // Provided nodes and values (t,y) to compute spline, same size Eigen vectors, c contains slopes\n    Eigen::VectorXd t, y, c;\n    // Difference t(i)-t(i-1) and coefficients of spline (s'(t_j))\n    double h;\n    // Size of t, y and c.\n    int n;\n};\n\n// Interpoland\nauto f = [] (double x) { return 1. / (1. + x*x); };\n// auto f = [] (double x) {return cos(x); };\n\nint main() {\n    \n    double a = 5; // Interval (-a,a) bounds\n    int M = 1000; // Number of  points in which to evaluate\n    \n    // Number of subintervals for each test\n    std::vector<int> N = {4,8,16,32,64,128,256,512};\n    \n    // Precompute values at which evaluate f\n    Eigen::VectorXd x = Eigen::VectorXd::LinSpaced(M, -a, a);\n    Eigen::VectorXd fx(x.size());\n    for(int i = 0; i < x.size(); ++i) {\n        fx(i) = f(x(i));\n    }\n    \n    // Store error and rates\n    std::vector<double> err, err_zero, rate, rate_zero;\n    \n    std::cout << \"L^infty-error [reconstruction, zero] (rate / rate)\" << std::endl;\n    for(int n : N) {\n        // Define subintervals and evaluate f there (find pairs (t,y))\n        Eigen::VectorXd t = Eigen::VectorXd::LinSpaced(n, -a, a);\n        Eigen::VectorXd y(t.size());\n        for(int i = 0; i < t.size(); ++i) {\n            y(i) = f(t(i));\n        }\n        \n        // Construct PCHI with zero and reconstructed slopes\n        PCHI P(t,y), Pz(t,y,Slope::Zero);\n        \n        // Compute infinity norm of error\n        err.push_back((P(x) - fx).lpNorm<Eigen::Infinity>());\n        err_zero.push_back((Pz(x) - fx).lpNorm<Eigen::Infinity>());\n        \n        // Store errors and rates\n        std::cout << err.back()  << \"    \" << err_zero.back() ;\n        if( err.size() > 1 ) {\n            rate.push_back( log( *(err.end() - 2) / err.back()  ) / log(2) );\n            rate_zero.push_back( log( *(err_zero.end() - 2) / err_zero.back() ) / log(2) );\n            std::cout << \" (\" << rate.back() << \" / \" << rate_zero.back() << \")\";\n        }\n        std::cout << std::endl;\n        \n    }\n}\n", "meta": {"hexsha": "3d91a01416eb0b116fdd5267ca9f905ecc3b03d1", "size": 4880, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/PS9/solutions_ps9/piecewise_hermite_interpolation.cpp", "max_stars_repo_name": "valentinjacot/backupETHZ", "max_stars_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:21:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:21:30.000Z", "max_issues_repo_path": "Nummerical Methods for CSE/PS9/solutions_ps9/piecewise_hermite_interpolation.cpp", "max_issues_repo_name": "valentinjacot/backupETHZ", "max_issues_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Nummerical Methods for CSE/PS9/solutions_ps9/piecewise_hermite_interpolation.cpp", "max_forks_repo_name": "valentinjacot/backupETHZ", "max_forks_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1481481481, "max_line_length": 107, "alphanum_fraction": 0.4967213115, "num_tokens": 1435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086368, "lm_q2_score": 0.9273632926354616, "lm_q1q2_score": 0.8495664234252347}}
{"text": "#include <iostream>\n\n#include <Eigen/Dense>\n\nEigen::MatrixXd Vandermonde(const Eigen::VectorXd &x, int n) {\n  int m = x.size();\n\tEigen::MatrixXd V(m, n);\n\n\tV.col(0) = Eigen::VectorXd::Ones(m);\n\n  for(int i = 1; i < n; i++) {\n    V.col(i) = V.col(i - 1).cwiseProduct(x);\n  }\n\n  return V;\n}\n\nEigen::VectorXd r(const Eigen::VectorXd &x) {\n\treturn (1.0 / (1.0 + 25.0 * x.array() * x.array())).matrix();\n}\n\nint main() {\n\tint n = 11;\t\t\t\t// Number of polynomial coefficients\n\tint m;\t\t\t\t\t// Number of samples\n\tEigen::MatrixXd V;\t\t// Vandermonde matrix\n\tEigen::VectorXd x;\t\t// Samples in [-1, 1]\n\tEigen::VectorXd y;\t\t// r(x)\n\tEigen::VectorXd a(n);\t// Polynomial coefficients\n\n\tEigen::IOFormat PythonFmt(Eigen::StreamPrecision, Eigen::DontAlignCols, \", \", \";\\n\", \"[\", \"]\", \"[\", \"]\");\n\n\tstd::cout << \"Polynomial coefficients obtained by...\" << std::endl;\n\n\t// Compute overfitted polynomial coefficients\n\tm = n;\n\tx.setLinSpaced(m, -1.0, 1.0);\n  y = r(x);\n  V = Vandermonde(x, n);\n\ta = V.fullPivLu().solve(y);\n\n\tstd::cout << \"...overfitting:\" << std::endl;\n\tstd::cout << a.transpose().format(PythonFmt) << std::endl;\n\n\t// Compute least squares polynomial coefficients\n\tm = 3 * n;\n\tx.setLinSpaced(m, -1.0, 1.0);\n\n  y = r(x);\n  V = Vandermonde(x, n);\n  // no pivoting required gaussian elimination remains stable since V^TV is s.p.d\n  a = (V.transpose() * V).llt().solve(V.transpose() * y);\n\n\tstd::cout << \"...least squares:\" << std::endl;\n\tstd::cout << a.transpose().format(PythonFmt) << std::endl;\n\n\treturn 0;\n}\n", "meta": {"hexsha": "d978d605940203a866cb2f95127bacf82b660dcb", "size": 1499, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "exercise_2/least_squares.cpp", "max_stars_repo_name": "azurite/numCSE18-code", "max_stars_repo_head_hexsha": "f7104305375954a0528d366f8460bf8033d20f0a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-13T19:08:32.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-13T19:08:32.000Z", "max_issues_repo_path": "exercise_2/least_squares.cpp", "max_issues_repo_name": "azurite/numCSE18-code", "max_issues_repo_head_hexsha": "f7104305375954a0528d366f8460bf8033d20f0a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exercise_2/least_squares.cpp", "max_forks_repo_name": "azurite/numCSE18-code", "max_forks_repo_head_hexsha": "f7104305375954a0528d366f8460bf8033d20f0a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8448275862, "max_line_length": 106, "alphanum_fraction": 0.6090727151, "num_tokens": 478, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133447766225, "lm_q2_score": 0.8991213826762113, "lm_q1q2_score": 0.8450961861513794}}
{"text": "#include <iostream>\n#include \"Log.h\"\n//using namespace std;\n#include <ctime>\n// Eigen libraries\n#include <Eigen/Core>\n// Algebraic operations on dense matrices (inverse, eigenvalues, etc.)\n#include <Eigen/Dense>\n\n#define MATRIX_SIZE 50\n\n/****************************\n* Basic usage of Eigen matrix\n****************************/\n\nint main( int argc, char** argv )\n{\n    //Set the log first \n    za::my_logger::logger_type log = za::my_logger::get();\n    za::Log logManager;   \n    logManager.set_log_file(\"./log/logEigenMatix.log\"); \n    BOOST_LOG_SEV(log, za::report) <<\"Basic Eigen lib Matrix demo\\n\";\n    \n    //All vectors and matrices in Eigen are Eigen::Matrix, which is a template class. \n    //Its first three parameters are: data type, row, column\n    // Declare a 2*3 float matrix\n    Eigen::Matrix<float, 2, 3> matrix_23;\n\n    // At the same time, Eigen provides many built-in types through typedef, \n    // but the bottom layer is still Eigen::Matrix\n    // For example, Vector3d is essentially Eigen::Matrix<double, 3, 1>, \n    // which is a three-dimensional vector\n    Eigen::Vector3d v_3d;\n\t// Same as \n    Eigen::Matrix<float,3,1> vd_3d;\n\n    // Matrix3d is essentially Eigen::Matrix<double, 3, 3>\n    Eigen::Matrix3d matrix_33 = Eigen::Matrix3d::Zero(); //Initialized to zero\n    // If you are not sure about the size of the matrix\n    // you can use a dynamically sized matrix\n    Eigen::Matrix< double, Eigen::Dynamic, Eigen::Dynamic > matrix_dynamic;\n    // Simple format for unknown size\n    Eigen::MatrixXd matrix_x;\n    // Check other type of dynamic matrix\n\n    // The following is the operation of the Eigen array\n     // Input data (initialization) \n    matrix_23 << 1, 2, 3, 4, 5, 6;\n    BOOST_LOG_SEV(log, za::report)  << \"2 by 3 matrix initialization, row major:\\n\";\n    // Output\n    BOOST_LOG_SEV(log, za::report)  << matrix_23 << \"\\n\";\n\n    // Use () to access the elements in the matrix\n    for (int i=0; i<matrix_23.rows(); i++) \n    {\n        for (int j=0; j < matrix_23.cols(); j++)BOOST_LOG_SEV(log, za::report) <<matrix_23(i,j)<<\"\\t\";BOOST_LOG_SEV(log, za::report) <<\"\\n\";\n    }\n\n    // Multiply matrix and vector (actually it is still matrix and matrix)\n    v_3d << 3, 2, 1;\n    vd_3d << 4,5,6;\n    // But in Eigen you cannot mix two different types of matrices, like this is wrong\n    // Eigen::Matrix<double, 2, 1> result_wrong_type = matrix_23 * v_3d;\n    // should be explicitly converted\n    Eigen::Matrix<double, 2, 1> result = matrix_23.cast<double>() * v_3d;\n    BOOST_LOG_SEV(log, za::report)  << result << \"\\n\";\n\n    Eigen::Matrix<float, 2, 1> result2 = matrix_23 * vd_3d;\n    BOOST_LOG_SEV(log, za::report)  << result2 << \"\\n\";\n\n    // Similarly you can't make a mistake about the dimensions of the matrix\n    // Try to cancel the comment below and see what error Eigen will report\n    // Eigen::Matrix<double, 2, 3> result_wrong_dimension = matrix_23.cast<double>() * v_3d;\n\n    // some matrix operations\n    // The four arithmetic operations will not be demonstrated, just use +-*/.\u3002\n    matrix_33 = Eigen::Matrix3d::Random();      // Random number matrix\n    BOOST_LOG_SEV(log, za::report)  << matrix_33 << \"\\n\" << \"\\n\";\n\n    BOOST_LOG_SEV(log, za::report)  << matrix_33.transpose() << \"\\n\";      // Transpose\n    BOOST_LOG_SEV(log, za::report)  << matrix_33.sum() << \"\\n\";            // Sum\n    BOOST_LOG_SEV(log, za::report)  << matrix_33.trace() << \"\\n\";          // Trace\n    BOOST_LOG_SEV(log, za::report)  << 10*matrix_33 << \"\\n\";               // Multiplication\n    BOOST_LOG_SEV(log, za::report)  << matrix_33.inverse() << \"\\n\";        // Inverse\n    BOOST_LOG_SEV(log, za::report)  << matrix_33.determinant() << \"\\n\";    // Determinant\n\n    // Eigenvalues\n    // Real symmetric matrix can ensure the success of diagonalization\n    Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> eigen_solver ( matrix_33.transpose()*matrix_33 );\n    BOOST_LOG_SEV(log, za::report)  << \"Eigen values = \\n\" << eigen_solver.eigenvalues() << \"\\n\";\n    BOOST_LOG_SEV(log, za::report)  << \"Eigen vectors = \\n\" << eigen_solver.eigenvectors() << \"\\n\";\n\n    // Solving equations\n    // We solve the equation matrix_NN * x = v_Nd\n    // The size of N is defined in the previous macro, it is generated by a random number\n    // Direct inversion is naturally the most straightforward, but the amount of inversion calculations is large\n\n    Eigen::Matrix< double, MATRIX_SIZE, MATRIX_SIZE > matrix_NN;\n    matrix_NN = Eigen::MatrixXd::Random( MATRIX_SIZE, MATRIX_SIZE );\n    Eigen::Matrix< double, MATRIX_SIZE,  1> v_Nd;\n    v_Nd = Eigen::MatrixXd::Random( MATRIX_SIZE,1 );\n\n    clock_t time_stt = clock(); // timer\n    // take inverse\n    Eigen::Matrix<double,MATRIX_SIZE,1> x = matrix_NN.inverse()*v_Nd;\n    BOOST_LOG_SEV(log, za::report)  <<\"time use in normal inverse is \" << 1000* (clock() - time_stt)/(double)CLOCKS_PER_SEC << \"ms\"<< \"\\n\";\n    \n\t// qr decomposition\n    time_stt = clock();\n    x = matrix_NN.colPivHouseholderQr().solve(v_Nd);\n    BOOST_LOG_SEV(log, za::report)  <<\"time use in Qr decomposition is \" <<1000*  (clock() - time_stt)/(double)CLOCKS_PER_SEC <<\"ms\" << \"\\n\";\n\n    return 0;\n}\n", "meta": {"hexsha": "381abc8f2833c35dcaef3928f1183bab799bc6c5", "size": 5138, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/eigenMatrix.cpp", "max_stars_repo_name": "zoumson/Eigen", "max_stars_repo_head_hexsha": "9975ba3a123708a9b4cbe5131e818f19edd9e378", "max_stars_repo_licenses": ["Unlicense", "MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/eigenMatrix.cpp", "max_issues_repo_name": "zoumson/Eigen", "max_issues_repo_head_hexsha": "9975ba3a123708a9b4cbe5131e818f19edd9e378", "max_issues_repo_licenses": ["Unlicense", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/eigenMatrix.cpp", "max_forks_repo_name": "zoumson/Eigen", "max_forks_repo_head_hexsha": "9975ba3a123708a9b4cbe5131e818f19edd9e378", "max_forks_repo_licenses": ["Unlicense", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.6782608696, "max_line_length": 141, "alphanum_fraction": 0.6457765668, "num_tokens": 1461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067195846919, "lm_q2_score": 0.896251377983158, "lm_q1q2_score": 0.8447229461861661}}
{"text": "/* ------------------------------------------------------------\n * @file: pseudoinversa.cpp\n * @dependencias: armadillo, matplotlibcpp\n * @version 0.1\n * ------------------------------------------------------------*/\n\n// [1] $ g++ pseudoinversa.cpp -o psi.out -std=c++11\n// [2] $ ./psi.out\n// Nota: Asegurarse de tener armadillo bien instalado.\n\n#include <armadillo>\n\nusing namespace std;\nusing namespace arma;\n\n\n/**\n * @brief Calcula la aproximaci\u00f3n a la soluci\u00f3n de un sistema de ecuaciones por \n *        el m\u00e9todo de la pseudoinversa.\n * @param A Matriz de coeficientes.\n * @param b Vector de t\u00e9rminos independientes.\n * @param tol Tolerancia de la aproximaci\u00f3n.\n * @param max_itr Iteraciones m\u00e1ximas.\n */\nvoid pseudoinversa(mat A, vec b, double tol, int max_itr=15){\n    int n = A.n_rows;\n    int m = A.n_cols;\n    double alpha = eig_sym(A*A.t()).max();\n\n    mat I(n,m);\n    I.eye();\n    mat x = (1/alpha)*A.t();\n\n    double error = tol;\n    int k = 0;\n\n    while (k < max_itr){\n        x = x*(2*I-A*x);\n        error = norm((A*x*A)-A);\n\n        if (error < tol)\n            break;\n        k++;\n    }\n    mat x_p = x*b;\n\n    // Mostrar los resultados\n    x_p.print(\"x_p: \\n\");\n    cout<<\"Error: \"<< norm(A*x_p-b)<<endl;\n\n}\n\n\nint main(int argc, char const *argv[])\n{\n    mat A = {{ 1, 2, 4},\n             { 2,-1, 1},\n             { 1, 0, 1}};\n    vec b = {4,3,9};\n    pseudoinversa(A,b,10e-8,3);\n    return 0;\n}\n", "meta": {"hexsha": "058a575b690d9a4dcddf75cbb2b9c67f27d6edf7", "size": 1416, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Catalogo/03. Sistemas de Ecuaciones/C++/pseudoinversa.cpp", "max_stars_repo_name": "ce-box/CE3102-Numerical-Methods-Catalog", "max_stars_repo_head_hexsha": "f9b70a719286a5aea9d826b0941d5e5d9c0514e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Catalogo/03. Sistemas de Ecuaciones/C++/pseudoinversa.cpp", "max_issues_repo_name": "ce-box/CE3102-Numerical-Methods-Catalog", "max_issues_repo_head_hexsha": "f9b70a719286a5aea9d826b0941d5e5d9c0514e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Catalogo/03. Sistemas de Ecuaciones/C++/pseudoinversa.cpp", "max_forks_repo_name": "ce-box/CE3102-Numerical-Methods-Catalog", "max_forks_repo_head_hexsha": "f9b70a719286a5aea9d826b0941d5e5d9c0514e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.4761904762, "max_line_length": 80, "alphanum_fraction": 0.5127118644, "num_tokens": 424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541561135441, "lm_q2_score": 0.8947894611926921, "lm_q1q2_score": 0.8425822149786972}}
{"text": "// Group A - Exact Pricing Methods\r\n//\r\n// by Scott Sidoli\r\n//\r\n// 6-9-19\r\n//\r\n// Main.cpp\r\n//\r\n// In this work we create pricing methods for European options\r\n// Questions for Group A are answered in the comments here in Main.cpp. We give an\r\n// outline of file contents here:\r\n// \r\n// This is done by creating the EuropeanOption class in EuropeanOption.hpp. We outline\r\n// array pricing. We organize the option data in a struct. This is contained in\r\n// OptionData.hpp. \r\n\r\n\r\n#include \"EuropeanOption.hpp\"\r\n#include \"MeshArray.hpp\"\r\n#include <boost/tuple/tuple_io.hpp>\r\n#include <iomanip>\r\n\r\n\r\nint main()\r\n{\r\n\t// Group A =Exact Solutions of One-Factor Plain Options==================================================\r\n\t// 1 part a) Implement the above formula for call and put option pricing using data sets\r\n\t// Batch 1 to Batch 4. Check your answers.\r\n\r\n\t// Batch 1\r\n\tTime T1 = (Time) 0.25;\r\n\tStrike_Price K1 = (Strike_Price)65;\r\n\tVolatility sig1 = (Volatility) 0.30;\r\n\trate r1 = (rate) 0.08;\r\n\tcost_of_carry b1 = (cost_of_carry) 0.08;\r\n\tcurr_stock_price S1 = (curr_stock_price) 60.0;\r\n\r\n\t// Create option and set parameters\r\n\tEuropeanOption option1;\r\n\toption1.SetOption(T1, K1, sig1, r1, b1, S1);\r\n\r\n\tcout << \"Batch 1 Call price: \" << option1.CallPriceEuro() << endl;\r\n\tcout << \"Batch 1 Put price: \" << option1.PutPriceEuro() << endl;\r\n\r\n\t// Batch 2\r\n\tTime T2 = (Time) 1.0;\r\n\tStrike_Price K2 = (Strike_Price) 100.0;\r\n\tVolatility sig2 = (Volatility) 0.2;\r\n\trate r2 = (rate) 0.00;\r\n\tcost_of_carry b2 = (cost_of_carry) 0.00;\r\n\tcurr_stock_price S2 = (curr_stock_price) 100.0;\r\n\r\n\t// Create option and set parameters\r\n\tEuropeanOption option2;\r\n\toption2.SetOption(T2, K2, sig2, r2, b2, S2);\r\n\r\n\tcout << \"Batch 2 Call price: \" << option2.CallPriceEuro() << endl;\r\n\tcout << \"Batch 2 Put price: \" << option2.PutPriceEuro() << endl;\r\n\r\n\t// Batch 3\r\n\tTime T3 = (Time) 1.0;\r\n\tStrike_Price K3 = (Strike_Price) 10.0;\r\n\tVolatility sig3 = (Volatility) 0.50;\r\n\trate r3 = (rate) 0.12;\r\n\tcost_of_carry b3 = (cost_of_carry) 0.12;\r\n\tcurr_stock_price S3 = (curr_stock_price) 5.0;\r\n\r\n\t// Create option and set parameters\r\n\tEuropeanOption option3;\r\n\toption3.SetOption(T3, K3, sig3, r3, b3, S3);\r\n\r\n\tcout << \"Batch 3 Call price: \" << option3.CallPriceEuro() << endl;\r\n\tcout << \"Batch 3 Put price: \" << option3.PutPriceEuro() << endl;\r\n\r\n\t// Batch 4\r\n\tTime T4 = (Time) 30.0;\r\n\tStrike_Price K4 = (Strike_Price) 100.0;\r\n\tVolatility sig4 = (Volatility) 0.30;\r\n\trate r4 = (rate) 0.08;\r\n\tcost_of_carry b4 = (cost_of_carry) 0.08;\r\n\tcurr_stock_price S4 = (curr_stock_price) 100.0;\r\n\r\n\t// Create option and set parameters\r\n\tEuropeanOption option4;\r\n\toption4.SetOption(T4, K4, sig4, r4, b4, S4);\r\n\r\n\tcout << \"Batch 4 Call price: \" << option4.CallPriceEuro() << endl;\r\n\tcout << \"Batch 4 Put price: \" << option4.PutPriceEuro() << endl;\r\n\r\n\tcout << endl;\r\n\t//================================================================================================================================================================================\r\n\t\t// 1 b) Apply the put-call parity relationship lto compute the put prices given the call prices\r\n\t\t// We use our CalltoPutParity function.\r\n\r\n\tcout << \"Using Parity: \" << endl;\r\n\tcout << \"Batch 1 Put Price: \" << option1.CalltoPutParity() << endl;\r\n\tcout << \"Batch 2 Put Price: \" << option2.CalltoPutParity() << endl;\r\n\tcout << \"Batch 3 Put Price: \" << option3.CalltoPutParity() << endl;\r\n\tcout << \"Batch 4 Put Price: \" << option4.CalltoPutParity() << endl;\r\n\r\n\tcout << endl;\r\n\r\n\t// Now we check if the batches satisfy put-call parity.\r\n\tcout << \"Batch 1 satisfies parity: \" << (option1.ParityChecker() ? \"True.\" : \"False.\") << endl;\r\n\tcout << \"Batch 2 satisfies parity: \" << (option2.ParityChecker() ? \"True.\" : \"False.\") << endl;\r\n\tcout << \"Batch 3 satisfies parity: \" << (option3.ParityChecker() ? \"True.\" : \"False.\") << endl;\r\n\tcout << \"Batch 4 satisfies parity: \" << (option4.ParityChecker() ? \"True.\" : \"False.\") << endl;\r\n\t//================================================================================================================================================================================\t\r\n\t\t// 1 c) We compute the option prices for a monotonically increasing ranges of values for S, the current stock price.\r\n\t\t// Let S = 10, 11, 12, ... 50. We use our MeshArray.\r\n\tcurr_stock_price S_start = (curr_stock_price) 10.0;\r\n\tcurr_stock_price S_end = (curr_stock_price) 50.0;\r\n\tcurr_stock_price S_interval = (curr_stock_price) 1.0;\r\n\r\n\t// Compute the Call prices and Put prices\r\n\tvector<curr_stock_price> S_array = MeshArray(S_start, S_end, S_interval);\r\n\tvector<double> S_CallPrices = option1.CallPriceEuro(S_array);\r\n\tvector<double> S_PutPrices = option1.PutPriceEuro(S_array);\r\n\r\n\tcout << endl;\r\n\tcout << \"S - Value, Call Price, Put Price\" << endl;\r\n\tPrintArray(S_array, S_CallPrices, S_PutPrices);\r\n\r\n\tcout << endl;\r\n\r\n\t// reset the option\r\n\toption1.SetOption(T1, K1, sig1, r1, b1, S1);\r\n\t//================================================================================================================================================================================\r\n\t\t// 1 d) We create a matrix pricer to determine prices as we vary two parameters. We use expiry time and volatility.\r\n\r\n\t\t// Create Vector of T-values. This is where we change our option parameter.\r\n\tTime T_start = (Time) 0.25;\r\n\tTime T_end = (Time) 5.0;\r\n\tTime T_interval = (Time) 0.25;\r\n\tvector<Time> T_array = MeshArray(T_start, T_end, T_interval);\r\n\r\n\t// Create Vector of sig-values. This is where we change our second option parameter.\r\n\r\n\tVolatility sig_start = (Volatility) 0.05;\r\n\tVolatility sig_end = (Volatility) 1.00;\r\n\tVolatility sig_interval = (Volatility) 0.05;\r\n\tvector<Volatility> sig_array = MeshArray(sig_start, sig_end, sig_interval);\r\n\r\n\t// Create two-dimensional array to store call prices and put prices\r\n\ttypedef boost::tuple<double, double> CallPrice_PutPrice;\r\n\tconst int num_rows = 50;\r\n\tconst int num_columns = 50;\r\n\tCallPrice_PutPrice PriceMatrix[num_rows][num_columns]; // Price matrix stores call and put price when parameter I takes value x and parameter J takes value y.\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t   // In this example we use expiry time and volatility. \r\n\r\n\tcout << \"(Time, Volatility, (Call Price Put Price))\" << endl;\r\n\r\n\tfor (int i = 0; i < T_array.size(); ++i)\r\n\t{\r\n\t\toption1.SetOption(T_array[i]);\r\n\r\n\t\tfor (int j = 0; j < sig_array.size(); ++j)\r\n\t\t{\r\n\t\t\toption1.SetOption(sig_array[j]);\r\n\t\t\tPriceMatrix[i][j] = CallPrice_PutPrice(option1.CallPriceEuro(), option1.PutPriceEuro());\r\n\r\n\t\t\tcout << \"(\" << T_array[i] << \", \" << sig_array[j] << \", \" << PriceMatrix[i][j] << \")\" << endl;\r\n\t\t}\r\n\t}\r\n\tcout << endl;\r\n\r\n\t// reset the option\r\n\toption1.SetOption(T1, K1, sig1, r1, b1, S1);\r\n\t//==============================================================================================================================================================================\r\n\t\t// Group A =Option Sensitivities, aka the Greeks ==================================================\r\n\t\t// 2 a) We implement formula for gamma for call and put future option pricing. We also compute\r\n\t\t// Delta for call and Delta for put.\r\n\tEuropeanOption greek_option;\r\n\tTime T_greek = (Time) 0.5;\r\n\tStrike_Price K_greek = (Strike_Price)100;\r\n\tVolatility sig_greek = (Volatility) 0.36;\r\n\trate r_greek = (rate) 0.1;\r\n\tcost_of_carry b_greek = (cost_of_carry)0;\r\n\tcurr_stock_price S_greek = (curr_stock_price)105;\r\n\r\n\tgreek_option.SetOption(T_greek, K_greek, sig_greek, r_greek, b_greek, S_greek);\r\n\r\n\tcout << \"Call Gamma: \" << greek_option.CallPutGammaEuro() << endl;\r\n\tcout << \"Call Delta: \" << greek_option.CallDeltaEuro() << endl;\r\n\tcout << \"Put Delta: \" << greek_option.PutDeltaEuro() << endl;\r\n\t//================================================================================================================================================================================\r\n\t\t// 2 b) In the same spirit as the first part, we use our previous code to compute the call delta \r\n\t\t// price for a monotonically increasing range of underlying values of S. We take S to range from \r\n\t\t// 10 up to 50. We use S_array from the previous question.\r\n\r\n\tvector<double> delta_call_array = greek_option.CallDeltaEuro(S_array);\r\n\r\n\tcout << \"S - Value, Call Delta\" << endl;\r\n\tPrintArray(S_array, delta_call_array);\r\n\r\n\tcout << endl;\r\n\r\n\t// reset the option\r\n\tgreek_option.SetOption(T_greek, K_greek, sig_greek, r_greek, b_greek, S_greek);\r\n\t//================================================================================================================================================================================\r\n\t\t// 2 c) We create a new matrix that holds gamma's as we input a matrix of parameters. As before,\r\n\t\t// we use expiry time and volatility.\r\n\r\n\tcout << \"(Time, Volatility, Gamma)\" << endl;\r\n\tdouble Gamma_Matrix[num_rows][num_columns];\r\n\r\n\tfor (int i = 0; i < T_array.size(); ++i)\r\n\t{\r\n\t\tgreek_option.SetOption(T_array[i]);\t\t\t// Set the ith row by using the expiry time. Setting the row means we set the option parameter.\r\n\r\n\t\tfor (int j = 0; j < sig_array.size(); ++j)\r\n\t\t{\r\n\t\t\tgreek_option.SetOption(sig_array[j]);\t// Set the column by using the volatility. Here, we set the option parameter with column value.\r\n\t\t\tGamma_Matrix[i][j] = greek_option.CallPutGammaEuro();\r\n\r\n\t\t\tcout << \"(\" << T_array[i] << \", \" << sig_array[j] << \", \" << Gamma_Matrix[i][j] << \")\" << endl;\r\n\t\t}\r\n\t}\r\n\tcout << endl;\r\n\t// reset the option\r\n\tgreek_option.SetOption(T_greek, K_greek, sig_greek, r_greek, b_greek, S_greek);\r\n\t//================================================================================================================================================================================\r\n\t\t// 2 d) We repeat parts a) and b) but now we use the formulas for the appoximations.\r\n\r\n\r\n\tcurr_stock_price h = (curr_stock_price) 0.05;\r\n\r\n\tcout << \"Gamma and Delta from the exact formula: \" << endl;\r\n\tcout << \"Gamma: \" << greek_option.CallPutGammaEuro() << endl;\r\n\tcout << \"Delta for call: \" << greek_option.CallDeltaEuro() << endl;\r\n\tcout << \"Delta for put: \" << greek_option.PutDeltaEuro() << endl;\r\n\r\n\tcout << endl;\r\n\r\n\tcout << \"Gamma and Delta from divided difference approximation: \" << endl;\r\n\tcout << \"Gamma: \" << greek_option.CallPutGammaEuro(h) << endl;\r\n\tcout << \"Delta for call: \" << greek_option.CallDeltaEuro(h) << endl;\r\n\tcout << \"Delta for put: \" << greek_option.PutDeltaEuro(h) << endl;\r\n\r\n\r\n\treturn 0;\r\n}", "meta": {"hexsha": "669b187d58f5d66f40c366d0e75e71d98689162d", "size": 10397, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "GroupA/GroupA/Main.cpp", "max_stars_repo_name": "scottsidoli/C-for-Financial-Engineering---Baruch-Pre-MFE-Certificate", "max_stars_repo_head_hexsha": "79c2fb297a85c914d5f0b8671bb17636801e3ce7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-05T08:14:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-05T08:14:37.000Z", "max_issues_repo_path": "GroupA/GroupA/Main.cpp", "max_issues_repo_name": "scottsidoli/C-for-Financial-Engineering---Baruch-Pre-MFE-Certificate", "max_issues_repo_head_hexsha": "79c2fb297a85c914d5f0b8671bb17636801e3ce7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GroupA/GroupA/Main.cpp", "max_forks_repo_name": "scottsidoli/C-for-Financial-Engineering---Baruch-Pre-MFE-Certificate", "max_forks_repo_head_hexsha": "79c2fb297a85c914d5f0b8671bb17636801e3ce7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.9628099174, "max_line_length": 181, "alphanum_fraction": 0.5821871694, "num_tokens": 2694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218434359675, "lm_q2_score": 0.9136765234137297, "lm_q1q2_score": 0.8423383447697517}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include \"gaussQuad.hpp\"\n\n\nusing namespace Eigen;\n\nconst double PI = 3.141592653589793;\n\n// small helper function to evaluate f_alpha_(x)\ndouble f(VectorXd alpha, double x) {\n\treturn std::exp(alpha(0) + alpha(1) * x + alpha(2) * x * x);\n}\n\n// rho(x) = (1, x, x^2)^T\nVectorXd rho(double x) {\n\tVectorXd r(3);\n\tr << 1, x, x * x;\n\treturn r;\n}\n\n// helper function to compute the jacobian of F\nMatrixXd m_rho(double x) {\n\tMatrixXd m(3, 3);\n\tdouble x2 = x * x;\n\tdouble x3 = x * x * x;\n\tdouble x4 = x * x * x * x;\n\n\tm << 1,  x,  x2,\n\t     x,  x2, x3,\n\t     x2, x3, x4;\n\n\treturn m;\n}\n\n// maps quadrature weights and nodes to arbitrary intervals [a, b]\nstruct QuadRule map_to_interval(const QuadRule& qr, const int a, const int b) {\n\tstruct QuadRule m_qr;\n\tm_qr.nodes = VectorXd::Zero(qr.nodes.size());\n\tm_qr.weights = VectorXd::Zero(qr.weights.size());\n\n\t// map nodes from [-1, 1] to [a, b]\n\tfor(int i = 0; i < qr.nodes.size(); i++) {\n\t\tm_qr.nodes(i) = (0.5 * (1 - qr.nodes(i)) * a) + (0.5 * (1 + qr.nodes(i)) * b);\n\t}\n\n\t// scale the weights with |[a, b]| / |[-1, 1]|\n\tfor(int i = 0; i < qr.weights.size(); i++) {\n\t\tm_qr.weights(i) = 0.5 * (b - a) * qr.weights(i);\n\t}\n\n\treturn m_qr;\n}\n\n// routine: evalF\n// \" Computes F(\\alpha) \"\n// (in)  qr: quad nodes and weights\n// (in)  \\alpha: model parameters\n// (in)  u: vector of moments\n// (out) F(\\alpha)\nVectorXd evalF(const QuadRule& qr, const VectorXd& alpha, const VectorXd& u) {\n\n\tint m = alpha.size();\n\tVectorXd F = VectorXd::Zero(m);\n\n\tconst QuadRule m_qr = map_to_interval(qr, -PI / 2, PI / 2);\n\n\t// calculate the integral with the quadrature\n\tfor(int i = 0; i < m_qr.nodes.size(); i++) {\n\t\tdouble s = m_qr.nodes(i);\n\t\tdouble x = std::tan(s);\n\t\tF += (m_qr.weights(i) * f(alpha, x) * (1 + x * x)) * rho(x);\n\t}\n\n\tF -= u;\n\n\treturn F;\n}\n\n\n// routine: evalJ\n// \" Computes the Jacobian of $F(\\alpha)$ \"\n// (in)  qr: quad nodes and weights\n// (in)  alpha: model parameters\n// (out) jacobian: Jacobian\nMatrixXd evalJ(const QuadRule& qr, const VectorXd& alpha, const VectorXd& u) {\n\n\tint m = alpha.size();\n\tMatrixXd jacobian = MatrixXd::Zero(m, m);\n\n\tconst QuadRule m_qr = map_to_interval(qr, -PI / 2, PI / 2);\n\n\tfor(int i = 0; i < m_qr.nodes.size(); i++) {\n\t\tdouble s = m_qr.nodes(i);\n\t\tdouble x = std::tan(s);\n\t\tjacobian += (m_qr.weights(i) * f(alpha, x) * (1 + x * x)) * m_rho(x);\n\t}\n\n\treturn jacobian;\n}\n\n\n// routine: newtonMethod\n// \" Solves the non-linear system using Newton method \"\n// (in)  qr: quad nodes and weights\n// (in)  u: vector of moments\n// (in)  atol: absolute tolerance\n// (in)  rtol: relative tolerance\n// (in)  maxItr: maximum iterations\n// (in/out) alpha\\_: model parameters\nvoid newtonMethod(const QuadRule& qr, const VectorXd& u, const double atol, const double rtol, const int maxItr, VectorXd& alpha_) {\n\n\tfor(int i = 0; i < maxItr; i++) {\n\t\tMatrixXd J = evalJ(qr, alpha_, u);\n\t\tVectorXd F = evalF(qr, alpha_, u);\n\n\t\tVectorXd correction_term = J.fullPivLu().solve(F);\n\n\t\t// what kind of stopping criterion is this ?\n\t\t// souldn't it just be: correction_term.norm() <= rtol * alpha_ like in the lecture notes p.249 ?\n\t\tif(correction_term.norm() <= atol || F.norm() <= rtol * u.norm()) {\n\t\t\treturn;\n\t\t}\n\t\t\n\t\talpha_ -= correction_term;\n\t}\n}\n\n\n// -- DO NOT CHANGE THIS ROUTINE --\n// routine: testEvalF\n// \" test evalF computation \"\n// (in) alpha: model parameters\n// (in) u: vector of moments\n// (in) nQuad: number of quad nodes and weights\nvoid testEvalF(const VectorXd& alpha, const VectorXd& u, const int nQuad) {\n\n\tQuadRule qr;\n\tgaussQuad(nQuad, qr);\n\n\tVectorXd F = evalF(qr, alpha, u);\n\tstd::cout << \"Norm of F: \" << F.norm() << \", should be small\" << std::endl;  \n}\n\n\n// routine: main\nint main() {\n\n\tint nQ = 40; // number of Gauss points\n\n\t// -- DO NOT CHANGE THIS TEST SNIPPET --\n\t// test evalF\n\t// optimal model parameters corresponding to a moment vector are given\n\tVectorXd u_test(3), alpha_test(3);\n\tu_test << 1, 0, 1;\n\talpha_test << -0.9189385332, 0, -0.5;\n\ttestEvalF (alpha_test, u_test, nQ);\n\n\t// subproblem (h)\n\tVectorXd u(3);\n\tu << 1, -1, 2;\n\n\tVectorXd alpha(3);\n\talpha << 0, 0, -0.2;\n\n\tdouble atol = 1e-8;\n\tdouble rtol = 1e-6;\n\tint maxItr = 100;\n\n\tQuadRule qr;\n\tgaussQuad(nQ, qr);\n\tnewtonMethod(qr, u, atol, rtol, maxItr, alpha);\n\n\tstd::cout << alpha.transpose() << std::endl;  \n}\n\n\n// END OF FILE\n", "meta": {"hexsha": "79ed0aba5b66c9befa46e9771d96208fa8767b6e", "size": 4317, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "final_exam_ws17/3/3.cpp", "max_stars_repo_name": "azurite/numCSE18-code", "max_stars_repo_head_hexsha": "f7104305375954a0528d366f8460bf8033d20f0a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-13T19:08:32.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-13T19:08:32.000Z", "max_issues_repo_path": "final_exam_ws17/3/3.cpp", "max_issues_repo_name": "azurite/numCSE18-code", "max_issues_repo_head_hexsha": "f7104305375954a0528d366f8460bf8033d20f0a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "final_exam_ws17/3/3.cpp", "max_forks_repo_name": "azurite/numCSE18-code", "max_forks_repo_head_hexsha": "f7104305375954a0528d366f8460bf8033d20f0a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.1173184358, "max_line_length": 132, "alphanum_fraction": 0.6217280519, "num_tokens": 1445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122768904644, "lm_q2_score": 0.8791467722591728, "lm_q1q2_score": 0.8421454863356869}}
{"text": "#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <iostream>\n#include <vector>\n\nusing namespace Eigen;\nusing namespace std;\n\n//! \\brief Compute the matrix C from A.\n//! \\param[in] A Matrix $n \\times n$\n//! \\param[out] C MatrixXd with $C=A\\otimes I+I\\otimes A$.\n\nSparseMatrix<double> buildC(const MatrixXd &A)\n{\n    int n=A.rows();\n    \n    Eigen::SparseMatrix<double> C(n*n,n*n);\n    std::vector<Triplet<double> > triplets;\n    MatrixXd I=MatrixXd::Identity(n,n);\n\n    for (int i=0; i<n; i++) {\n      for (int j=0; j<n; j++) {\n        if (i==j){\n          for (int k1=0; k1<n; k1++) {\n            for (int k2=0; k2<n; k2++) {\n              Triplet<double>\n              triplet(i*n+k1,j*n+k2,A(i,j)*I(k1,k2)+A(k1,k2));\n              triplets.push_back(triplet);\n             }\n          }\n        }\n        else {\n          for (int k=0; k<n ; k++) {\n            Triplet<double> triplet(i*n+k,j*n+k,A(i,j));\n            triplets.push_back(triplet);\n          }\n        }\n      }\n    }\n    C.setFromTriplets(triplets.begin(), triplets.end());\n    C.makeCompressed();\n    return C;\n}\n\n//! \\brief Solve the Lyapunov system\n//! \\param[in] A Matrix $n \\times n$\n//! \\param[out] X MatrixXd, the solution.\n\nvoid solveLyapunov(const MatrixXd &A, MatrixXd &X)\n{\n    int n=A.rows();\n    SparseMatrix <double> C;\n    C=buildC(A);\n    MatrixXd I=MatrixXd::Identity(n,n);\n    VectorXd b(n*n);\n    b=Map<MatrixXd>(I.data(),n*n,1);\n    VectorXd vecX(n*n);\n    SparseLU<SparseMatrix <double> > solver;\n    solver.compute(C) ;\n    vecX = solver.solve(b);\n    X=Map<MatrixXd>(vecX.data(),n,n);\n}\n\nint main(){\n    \n    // test buildC\n    int n=5;\n    MatrixXd A(n,n);\n    A<<10, 2, 3, 4, 5, 6, 20, 8, 9, 1, 1, 2, 30, 4, 5, 6, 7, 8, 20, 0, 1, 2, 3, 4, 10;\n    \n    SparseMatrix <double> C;\n    C=buildC(A);\n    cout<<\"C= \"<<C<<endl;\n    \n    // solve lynear system\n    MatrixXd X(n,n);\n    solveLyapunov(A,X);\n    cout<<\"X= \"<<X<<endl;\n    MatrixXd I=MatrixXd::Identity(n,n);\n    \n    // test to verify the solution\n    cout<<(A*X+X*A.transpose()-I).norm()<<endl;\n}", "meta": {"hexsha": "10b37fc91cb2faeb3d79eb39ddb748e7df3535f9", "size": 2051, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/solutions/solution_2/solveLyapunov.cpp", "max_stars_repo_name": "valentinjacot/backupETHZ", "max_stars_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:21:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:21:30.000Z", "max_issues_repo_path": "Nummerical Methods for CSE/solutions/solution_2/solveLyapunov.cpp", "max_issues_repo_name": "valentinjacot/backupETHZ", "max_issues_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Nummerical Methods for CSE/solutions/solution_2/solveLyapunov.cpp", "max_forks_repo_name": "valentinjacot/backupETHZ", "max_forks_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.7108433735, "max_line_length": 86, "alphanum_fraction": 0.5382740127, "num_tokens": 677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122684798184, "lm_q2_score": 0.8791467659263147, "lm_q1q2_score": 0.8421454728751719}}
{"text": "\n#include <stdio.h>\n#include <math.h>\n#include <Eigen/Core>\n\n\n\nfloat deg2rad(float orientation){\n\n   return orientation*M_PI /180.0;\n}\n\n\n\n\nEigen::Matrix3f Rx(float angle)\n{\n\n  Eigen::Matrix3f R;\n  R.setIdentity();\n  R <<   1 ,     0  ,          0,\n         0 , cos(angle) ,  -sin(angle) ,\n         0 , sin(angle) ,  cos(angle)   ; \nreturn R;\n\n}\n\nEigen::Matrix3f Ry(float angle)\n{\n  Eigen::Matrix3f R;\n  R.setIdentity();\n\n  R << cos(angle) ,   0   ,   sin(angle),\n        0             , 1     ,  0 ,\n        -sin(angle)  , 0 ,  cos(angle)   ;\n\nreturn R;\n\n}\n\nEigen::Matrix3f Rz(float angle)\n{\n\n  Eigen::Matrix3f R;\n  R.setIdentity();\n\n  R << cos(angle) ,   -sin(angle)   ,  0,\n       sin(angle)     , cos(angle)    ,  0 ,\n       0              , 0 ,          1   ; \n\nreturn R;\n}\n\n\n\nvoid fromRotationToRPYAngle(float& roll,float&  pitch, float& yaw,const Eigen::Matrix3f R)\n{\n\n  //yaw   = atan2(R(1,0), R(0,0)  );\n  //pitch = atan2( -R(2,0)  , sqrt( pow((R(2,1)),2) + pow(R(2,2),2)) );\n  //roll  = atan2( R(2,1) , R(2,2) );\n\n  yaw=atan2(R(1,0),R(0,0));\n  pitch=atan2( -R(2,0)   ,   sqrt(  pow(R(2,1),2)+ pow(R(2,2),2)    )  );\n  roll=atan2(R(2,1),R(2,2));\n\n}\n", "meta": {"hexsha": "c96732367f18799a78118a77811334072dac8ce3", "size": 1157, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mathUtils.cpp", "max_stars_repo_name": "LCrob/apriltag", "max_stars_repo_head_hexsha": "40560f29c775a1544123bbf7cd6248fb79f15e62", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mathUtils.cpp", "max_issues_repo_name": "LCrob/apriltag", "max_issues_repo_head_hexsha": "40560f29c775a1544123bbf7cd6248fb79f15e62", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mathUtils.cpp", "max_forks_repo_name": "LCrob/apriltag", "max_forks_repo_head_hexsha": "40560f29c775a1544123bbf7cd6248fb79f15e62", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.0147058824, "max_line_length": 90, "alphanum_fraction": 0.4961106309, "num_tokens": 438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338079816758, "lm_q2_score": 0.8757869981319863, "lm_q1q2_score": 0.8420988072946896}}
{"text": "/*\nThis example demonstrates the basic operations of Eigen matrix.\n*/\n#include <iostream>\n\nusing namespace std;\n\n#include <ctime>\n\n// Eigen core\n#include <Eigen/Core>\n// Eigen dense matrix (inverse, eigenvalues, etc.)\n#include <Eigen/Dense>\nusing namespace Eigen;\n\n#define MATRIX_SIZE 50\n\nint main(int argc, char **argv) {\n    // All vectors and matrices in Eigen are Eigen::Matrix, which is a template\n    // class. Its first three parameters are: data type, row, column Declare a 2*3\n    // float matrix\n    Matrix<float, 2, 3> matrix_23;\n    \n    // At the same time, Eigen provides many built-in types via typedef, but the\n    // bottom layer is still Eigen::Matrix. For example, Vector3d is essentially\n    // Eigen::Matrix<double, 3, 1>, which is a three-dimensional vector.\n    Vector3d v_3d;\n    // This is the same\n    Matrix<float, 3, 1> vd_3d;\n    \n    // Matrix3d is essentially Eigen::Matrix<double, 3, 3>\n    Matrix3d matrix_33 = Matrix3d::Zero(); // initialized to zero\n    // If you are not sure about the size of the matrix, you can use a matrix of\n    // dynamic size\n    Matrix<double, Dynamic, Dynamic> matrix_dynamic;\n    // simpler\n    MatrixXd matrix_x;\n    // There are still many types of this kind. We don't list them one by one.\n    \n    // Here is the operation of the Eigen matrix\n    // input data (initialization)\n    matrix_23 << 1, 2, 3, 4, 5, 6;\n    // output\n    cout << \"matrix 2x3 from 1 to 6: \\n\" << matrix_23 << endl;\n    \n    // Use () to access elements in the matrix\n    cout << \"print matrix 2x3: \" << endl;\n    for (int i = 0; i < 2; i++) {\n        for (int j = 0; j < 3; j++)\n        cout << matrix_23(i, j) << \"\\t\";\n        cout << endl;\n    }\n    \n    // We can easily multiply a matrix with a vector (but actually still matrices and matrices)\n    v_3d << 3, 2, 1;\n    vd_3d << 4, 5, 6;\n    \n    // In Eigen you can't mix two different types of matrices, like this is\n    // wrong Matrix<double, 2, 1> result_wrong_type = matrix_23 * v_3d; \n    // It should be explicitly converted\n    Matrix<double, 2, 1> result = matrix_23.cast<double>() * v_3d;\n    cout << \"[1,2,3;4,5,6]*[3,2,1]=\" << result.transpose() << endl;\n    \n    Matrix<float, 2, 1> result2 = matrix_23 * vd_3d;\n    cout << \"[1,2,3;4,5,6]*[4,5,6]: \" << result2.transpose() << endl;\n    \n    // Also you can't misjudge the dimensions of the matrix\n    // Try canceling the comments below to see what Eigen will report.\n    // Eigen::Matrix<double, 2, 3> result_wrong_dimension =\n    // matrix_23.cast<double>() * v_3d;\n    \n    // some matrix operations\n    // The basic operations are not demonstrated, just use +-*/ operators.\n    matrix_33 = Matrix3d::Random(); // Random Number Matrix\n    cout << \"random matrix: \\n\" << matrix_33 << endl;\n    cout << \"transpose: \\n\" << matrix_33.transpose() << endl;\n    cout << \"sum: \" << matrix_33.sum() << endl;\n    cout << \"trace: \" << matrix_33.trace() << endl;\n    cout << \"times 10: \\n\" << 10 * matrix_33 << endl;\n    cout << \"inverse: \\n\" << matrix_33.inverse() << endl;\n    cout << \"det: \" << matrix_33.determinant() << endl;\n    \n    // Eigenvalues\n    // Real symmetric matrix can guarantee successful diagonalization\n    SelfAdjointEigenSolver<Matrix3d> eigen_solver(matrix_33.transpose() *\n\t    matrix_33);\n    cout << \"Eigen values = \\n\" << eigen_solver.eigenvalues() << endl;\n    cout << \"Eigen vectors = \\n\" << eigen_solver.eigenvectors() << endl;\n    \n    // Solving equations\n    // We solve the equation of matrix_NN * x = v_Nd\n    // The size of N is defined in the previous macro, which is generated by a\n    // random number Direct inversion is the most direct, but the amount of\n    // inverse operations is large.\n    \n    Matrix<double, MATRIX_SIZE, MATRIX_SIZE> matrix_NN =\n\t    MatrixXd::Random(MATRIX_SIZE, MATRIX_SIZE);\n    matrix_NN =\n\t    matrix_NN * matrix_NN.transpose(); // Guarantee semi-positive definite\n    Matrix<double, MATRIX_SIZE, 1> v_Nd = MatrixXd::Random(MATRIX_SIZE, 1);\n    \n    clock_t time_stt = clock(); // timing\n    // Direct inversion\n    Matrix<double, MATRIX_SIZE, 1> x = matrix_NN.inverse() * v_Nd;\n    cout << \"time of normal inverse is \"\n\t    << 1000 * (clock() - time_stt) / (double)CLOCKS_PER_SEC << \"ms\" << endl;\n    cout << \"x = \" << x.transpose() << endl;\n    \n    // Usually solved by matrix decomposition, such as QR decomposition, the speed\n    // will be much faster\n    time_stt = clock();\n    x = matrix_NN.colPivHouseholderQr().solve(v_Nd);\n    cout << \"time of Qr decomposition is \"\n\t    << 1000 * (clock() - time_stt) / (double)CLOCKS_PER_SEC << \"ms\" << endl;\n    cout << \"x = \" << x.transpose() << endl;\n    \n    // For positive definite matrices, you can also use cholesky decomposition to\n    // solve equations.\n    time_stt = clock();\n    x = matrix_NN.ldlt().solve(v_Nd);\n    cout << \"time of ldlt decomposition is \"\n\t    << 1000 * (clock() - time_stt) / (double)CLOCKS_PER_SEC << \"ms\" << endl;\n    cout << \"x = \" << x.transpose() << endl;\n    \n    return 0;\n}", "meta": {"hexsha": "6bdfd059ff6c9379c50a20fd4199806575e49620", "size": 4985, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "exercise/ch3_eigen/useEigen/eigenMatrix.cpp", "max_stars_repo_name": "shengchen-liu/slambook2", "max_stars_repo_head_hexsha": "a3a511c26b6a352564be8c85b5b831b7f5f1d73d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-02-08T04:47:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-13T20:29:38.000Z", "max_issues_repo_path": "exercise/ch3_eigen/useEigen/eigenMatrix.cpp", "max_issues_repo_name": "shengchen-liu/slambook2", "max_issues_repo_head_hexsha": "a3a511c26b6a352564be8c85b5b831b7f5f1d73d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exercise/ch3_eigen/useEigen/eigenMatrix.cpp", "max_forks_repo_name": "shengchen-liu/slambook2", "max_forks_repo_head_hexsha": "a3a511c26b6a352564be8c85b5b831b7f5f1d73d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.5634920635, "max_line_length": 95, "alphanum_fraction": 0.6272818455, "num_tokens": 1435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810511092412, "lm_q2_score": 0.8887587875995482, "lm_q1q2_score": 0.8419932343786348}}
{"text": "#include \"ode45.hpp\"\n\n#include <iostream>\n#include <iomanip>\n\n#include <Eigen/Dense>\n#include <Eigen/QR>\n\n//! \\file stabrk.cpp Solution for Problem 1, PS13, involving ode45 and matrix ODEs\n\n//! \\brief Solve matrix IVP Y' = -(Y-Y')*Y using ode45 up to time T\n//! \\param[in] Y0 Initial data Y(0) (as matrix)\n//! \\param[in] T final time of simulation\n//! \\return Matrix of solution of IVP at t = T\nEigen::MatrixXd matode(const Eigen::MatrixXd & Y0, double T) {\n\n    auto F = [] (const Eigen::MatrixXd & M) { return -(M  - M.transpose())*M; };\n    ode45<Eigen::MatrixXd> O(F);\n    \n    // Set tolerances\n    O.options.atol = 10e-10;\n    O.options.rtol = 10e-8;\n    \n    // Return only matrix at T, (solution is vector of pairs (y(t_k), t_k) for each step k\n    return O.solve(Y0, T).back().first;\n}\n\n//! \\brief Find if invariant is preserved after evolution with matode\n//! \\param[in] Y0 Initial data Y(0) (as matrix)\n//! \\param[in] T final time of simulation\n//! \\return true if invariant was preserved (up to round-off), i.e. if norm was less than 10*eps\nbool checkinvariant(const Eigen::MatrixXd & M, double T) {\n    Eigen::MatrixXd N(3,3);\n    \n    N = matode(M, T);\n    \n    if( (N.transpose()*N-M.transpose()*M).norm() < 10 * std::numeric_limits<double>::epsilon() ) {\n        return true;\n    } else {\n        return false;\n    }\n}\n\n//! \\brief Implement ONE step of explicit Euler applied to Y0, of ODE Y' = A*Y\n//! \\param[in] A matrix A of the ODE\n//! \\param[in] Y0 Initial state\n//! \\param[in] h step size\n//! \\return next step\nEigen::MatrixXd expeulstep(const Eigen::MatrixXd & A, const Eigen::MatrixXd & Y0, double h) {\n    return Y0 + h*A*Y0;\n}\n\n//! \\brief Implement ONE step of implicit Euler applied to Y0, of ODE Y' = A*Y\n//! \\param[in] A matrix A of the ODE\n//! \\param[in] Y0 Initial state\n//! \\param[in] h step size\n//! \\return next step\nEigen::MatrixXd impeulstep(const Eigen::MatrixXd & A, const Eigen::MatrixXd & Y0, double h) {\n    return (Eigen::MatrixXd::Identity(3,3) - h*A).partialPivLu().solve(Y0);\n}\n\n//! \\brief Implement ONE step of implicit midpoint ruler applied to Y0, of ODE Y' = A*Y\n//! \\param[in] A matrix A of the ODE\n//! \\param[in] Y0 Initial state\n//! \\param[in] h step size\n//! \\return next step\nEigen::MatrixXd impstep(const Eigen::MatrixXd & A, const Eigen::MatrixXd & Y0, double h) {\n    return (Eigen::MatrixXd::Identity(3,3) - h*0.5*A).partialPivLu().solve(Y0+h*0.5*A*Y0);\n}\n\nint main() {\n    \n    double T = 1;\n    unsigned int n = 3;\n    \n    Eigen::MatrixXd M(n,n);\n    M << 8,1,6,3,5,7,4,9,2;\n    \n    std::cout << \"SUBTASK 1. c)\" << std::endl;\n    // Test preservation of orthogonality\n    \n    // Build Q\n    Eigen::HouseholderQR<Eigen::MatrixXd> qr(M.rows(), M.cols());\n    qr.compute(M);\n    Eigen::MatrixXd Q = qr.householderQ();\n    \n    // Build A\n    Eigen::MatrixXd A(n,n);\n    A << 0, 1, 1, -1, 0, 1, -1, -1, 0;\n    Eigen::MatrixXd I = Eigen::MatrixXd::Identity(n,n);\n    \n    // Norm of Y'Y-I for 20 steps\n    Eigen::MatrixXd Mexpeul = Q, Mimpeul = Q, Mimp = Q;\n    double h = 0.01;\n    std::vector<int> sep = {8,15,15,15};\n    std::cout << \"Evolution of norm(Y_k'*Y_k - I) for three methods:\" << std::endl;\n    std::cout   << std::setw(sep[0]) << \"step\"\n                << std::setw(sep[1]) << \"exp. Eul\"\n                << std::setw(sep[2]) << \"imp. Eul\"\n                << std::setw(sep[3]) << \"IMP\"\n                << std::endl;\n    std::cout   << std::setw(sep[0]) << \"-1\"\n                << std::setw(sep[1]) << (Mexpeul.transpose()*Mexpeul - I).norm()\n                << std::setw(sep[2]) << (Mimpeul.transpose()*Mimpeul - I).norm()\n                << std::setw(sep[3]) << (Mimp.transpose()*Mimp - I).norm()\n                << std::endl;\n    for(unsigned int j = 0; j < 20; ++j) {\n        Mexpeul = expeulstep(A, Mexpeul, h);\n        Mimpeul = impeulstep(A, Mimpeul, h);\n        Mimp = impstep(A, Mimp, h);\n        \n        std::cout   << std::setw(sep[0]) << j\n                    << std::setw(sep[1]) << (Mexpeul.transpose()*Mexpeul - I).norm()\n                    << std::setw(sep[2]) << (Mimpeul.transpose()*Mimpeul - I).norm()\n                    << std::setw(sep[3]) << (Mimp.transpose()*Mimp - I).norm()\n                    << std::endl;\n    }\n    \n    std::cout << \"SUBTASK 1. d)\" << std::endl;\n    // Test implementation of ode45\n    \n    std::cout << \"M = \" << std::endl << M << std::endl;\n    Eigen::MatrixXd  N = matode(M, T);\n    std::cout << \"N = \" << std::endl << N << std::endl;\n    \n    std::cout << \"SUBTASK 1. g)\" << std::endl;\n    // Test whether invariant was preserved or not\n    \n    bool is_invariant = checkinvariant(N, T);\n    \n    if( is_invariant ) {\n        std::cout << \"Invariant was preserved.\" << std::endl;\n    } else {\n        std::cout << \"Invariant was NOT preserved.\" << std::endl;\n    }\n    \n    \n    return 0;\n}\n", "meta": {"hexsha": "0f7f91cc6351b65d9a57e7097141d06cfc984df3", "size": 4813, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/PS13/solutions_ps13/matrix_ode.cpp", "max_stars_repo_name": "valentinjacot/backupETHZ", "max_stars_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:21:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:21:30.000Z", "max_issues_repo_path": "Nummerical Methods for CSE/PS13/solutions_ps13/matrix_ode.cpp", "max_issues_repo_name": "valentinjacot/backupETHZ", "max_issues_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Nummerical Methods for CSE/PS13/solutions_ps13/matrix_ode.cpp", "max_forks_repo_name": "valentinjacot/backupETHZ", "max_forks_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.3785714286, "max_line_length": 98, "alphanum_fraction": 0.5632661542, "num_tokens": 1509, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248140158416, "lm_q2_score": 0.8962513828326955, "lm_q1q2_score": 0.8416022880759126}}
{"text": "/*\r\n * Copyright John Maddock, 2017\r\n * Use, modification and distribution are subject to the\r\n * Boost Software License, Version 1.0. (See accompanying file\r\n * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n *\r\n * This example Illustrates numerical integration via Gauss and Gauss-Kronrod quadrature.\r\n */\r\n\r\n#include <iostream>\r\n#include <cmath>\r\n#include <limits>\r\n#include <boost/math/quadrature/gauss.hpp>\r\n#include <boost/math/quadrature/gauss_kronrod.hpp>\r\n#include <boost/math/constants/constants.hpp>\r\n#include <boost/math/special_functions/relative_difference.hpp>\r\n#include <boost/multiprecision/cpp_bin_float.hpp>\r\n\r\nvoid gauss_examples()\r\n{\r\n   //[gauss_example\r\n\r\n   /*`\r\n   We'll begin by integrating t[super 2] atan(t) over (0,1) using a 7 term Gauss-Legendre rule,\r\n   and begin by defining the function to integrate as a C++ lambda expression:\r\n   */\r\n   using namespace boost::math::quadrature;\r\n\r\n   auto f = [](const double& t) { return t * t * std::atan(t); };\r\n\r\n   /*`\r\n   Integration is simply a matter of calling the `gauss<double, 7>::integrate` method:\r\n   */\r\n\r\n   double Q = gauss<double, 7>::integrate(f, 0, 1);\r\n\r\n   /*`\r\n   Which yields a value 0.2106572512 accurate to 1e-10.\r\n\r\n   For more accurate evaluations, we'll move to a multiprecision type and use a 20-point integration scheme:\r\n   */\r\n\r\n   using boost::multiprecision::cpp_bin_float_quad;\r\n\r\n   auto f2 = [](const cpp_bin_float_quad& t) { return t * t * atan(t); };\r\n\r\n   cpp_bin_float_quad Q2 = gauss<cpp_bin_float_quad, 20>::integrate(f2, 0, 1);\r\n\r\n   /*`\r\n   Which yields 0.2106572512258069881080923020669, which is accurate to 5e-28.\r\n   */\r\n\r\n   //]\r\n\r\n   std::cout << std::setprecision(18) << Q << std::endl;\r\n   std::cout << boost::math::relative_difference(Q, (boost::math::constants::pi<double>() - 2 + 2 * boost::math::constants::ln_two<double>()) / 12) << std::endl;\r\n\r\n   std::cout << std::setprecision(34) << Q2 << std::endl;\r\n   std::cout << boost::math::relative_difference(Q2, (boost::math::constants::pi<cpp_bin_float_quad>() - 2 + 2 * boost::math::constants::ln_two<cpp_bin_float_quad>()) / 12) << std::endl;\r\n}\r\n\r\nvoid gauss_kronrod_examples()\r\n{\r\n   //[gauss_kronrod_example\r\n\r\n   /*`\r\n   We'll begin by integrating exp(-t[super 2]/2) over (0,+[infin]) using a 7 term Gauss rule\r\n   and 15 term Kronrod rule,\r\n   and begin by defining the function to integrate as a C++ lambda expression:\r\n   */\r\n   using namespace boost::math::quadrature;\r\n\r\n   auto f1 = [](double t) { return std::exp(-t*t / 2); };\r\n   \r\n   //<-\r\n   double Q_expected = sqrt(boost::math::constants::half_pi<double>());\r\n   //->\r\n\r\n   /*`\r\n   W'll start off with a one shot (ie non-adaptive)\r\n   integration, and keep track of the estimated error:\r\n   */\r\n   double error;\r\n   double Q = gauss_kronrod<double, 15>::integrate(f1, 0, std::numeric_limits<double>::infinity(), 0, 0, &error);\r\n\r\n   /*`\r\n   This yields Q = 1.25348207361, which has an absolute error of 1e-4 compared to the estimated error\r\n   of 5e-3: this is fairly typical, with the difference between Gauss and Gauss-Kronrod schemes being\r\n   much higher than the actual error.  Before moving on to adaptive quadrature, lets try again\r\n   with more points, in fact with the largest Gauss-Kronrod scheme we have cached (30/61):\r\n   */\r\n   //<-\r\n   std::cout << std::setprecision(16) << Q << std::endl;\r\n   std::cout << boost::math::relative_difference(Q, Q_expected) << std::endl;\r\n   std::cout << fabs(Q - Q_expected) << std::endl;\r\n   std::cout << error << std::endl;\r\n   //->\r\n   Q = gauss_kronrod<double, 61>::integrate(f1, 0, std::numeric_limits<double>::infinity(), 0, 0, &error);\r\n   //<-\r\n   std::cout << std::setprecision(16) << Q << std::endl;\r\n   std::cout << boost::math::relative_difference(Q, Q_expected) << std::endl;\r\n   std::cout << fabs(Q - Q_expected) << std::endl;\r\n   std::cout << error << std::endl;\r\n   //->\r\n   /*`\r\n   This yields an absolute error of 3e-15 against an estimate of 1e-8, which is about as good as we're going to get\r\n   at double precision\r\n\r\n   However, instead of continuing with ever more points, lets switch to adaptive integration, and set the desired relative\r\n   error to 1e-14 against a maximum depth of 5:\r\n   */\r\n   Q = gauss_kronrod<double, 15>::integrate(f1, 0, std::numeric_limits<double>::infinity(), 5, 1e-14, &error);\r\n   //<-\r\n   std::cout << std::setprecision(16) << Q << std::endl;\r\n   std::cout << boost::math::relative_difference(Q, Q_expected) << std::endl;\r\n   std::cout << fabs(Q - Q_expected) << std::endl;\r\n   std::cout << error << std::endl;\r\n   //->\r\n   /*`\r\n   This yields an actual error of zero, against an estimate of 4e-15.  In fact in this case the requested tolerance was almost \r\n   certainly set too low: as we've seen above, for smooth functions, the precision achieved is often double\r\n   that of the estimate, so if we integrate with a tolerance of 1e-9:\r\n   */\r\n   Q = gauss_kronrod<double, 15>::integrate(f1, 0, std::numeric_limits<double>::infinity(), 5, 1e-9, &error);\r\n   //<-\r\n   std::cout << std::setprecision(16) << Q << std::endl;\r\n   std::cout << boost::math::relative_difference(Q, Q_expected) << std::endl;\r\n   std::cout << fabs(Q - Q_expected) << std::endl;\r\n   std::cout << error << std::endl;\r\n   //->\r\n   /*`\r\n   We still achieve 1e-15 precision, with an error estimate of 1e-10.\r\n   */\r\n   //]\r\n}\r\n\r\nint main()\r\n{\r\n   gauss_examples();\r\n   gauss_kronrod_examples();\r\n   return 0;\r\n}\r\n", "meta": {"hexsha": "ba73ea4378157d3275d1d0fe5939f8bdae937dbf", "size": 5449, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/math/example/gauss_example.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/math/example/gauss_example.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-03-04T11:21:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-24T01:36:31.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/math/example/gauss_example.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 38.1048951049, "max_line_length": 187, "alphanum_fraction": 0.6494769683, "num_tokens": 1534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474181553805, "lm_q2_score": 0.880797068590724, "lm_q1q2_score": 0.8408506474489622}}
{"text": "//  This function computes the autocorrelation function for \n//  the Mersenne random number generator with a uniform distribution\n#include <iostream>\n#include <fstream>\n#include <iomanip>\n#include <cstdlib>\n#include <random>\n#include <armadillo>\n#include <string>\n#include <cmath>\nusing namespace  std;\nusing namespace arma;\n// output file\nofstream ofile;\n\n//     Main function begins here     \nint main(int argc, char* argv[])\n{\n  int MonteCarloCycles;\n  string filename;\n  if (argc > 1) {\n    filename=argv[1];\n    MonteCarloCycles = atoi(argv[2]);\n    string fileout = filename;\n    string argument = to_string(MonteCarloCycles);\n    fileout.append(argument);\n    ofile.open(fileout);\n  }\n\n  // Compute the variance and the mean value of the uniform distribution\n  // Compute also the specific values x for each cycle in order to be able to\n  // compute the covariance and the correlation function  \n\n  vec X  = zeros<vec>(MonteCarloCycles);\n  double MCint = 0.;      double MCintsqr2=0.;\n  std::random_device rd;\n  std::mt19937_64 gen(rd());\n  // Set up the uniform distribution for x \\in [[0, 1]\n  std::uniform_real_distribution<double> RandomNumberGenerator(0.0,1.0);\n  for (int i = 0;  i < MonteCarloCycles; i++){\n    double x =   RandomNumberGenerator(gen); \n    X(i) = x;\n    MCint += x;\n    MCintsqr2 += x*x;\n  }\n  double Mean = MCint/((double) MonteCarloCycles );\n  MCintsqr2 = MCintsqr2/((double) MonteCarloCycles );\n  double STDev = sqrt(MCintsqr2-Mean*Mean);\n  double Variance = MCintsqr2-Mean*Mean;\n  //   Write mean value and variance\n  cout << \" Sample variance= \" << Variance  << \" Mean value = \" << Mean << endl;\n  // Now we compute the autocorrelation function\n  vec autocorrelation = zeros<vec>(MonteCarloCycles);\n  for (int j = 0; j < MonteCarloCycles; j++){\n    double sum = 0.0;\n    for (int k = 0; k < (MonteCarloCycles-j); k++){\n      sum  += (X(k)-Mean)*(X(k+j)-Mean); \n    }\n    autocorrelation(j) = sum/Variance/((double) MonteCarloCycles );\n    ofile << setiosflags(ios::showpoint | ios::uppercase);\n    ofile << setw(15) << setprecision(8) << j;\n    ofile << setw(15) << setprecision(8) << autocorrelation(j) << endl;\n  }\n  // Now compute the exact covariance using the autocorrelation function\n  double Covariance = 0.0;\n  for (int j = 0; j < MonteCarloCycles; j++){\n    Covariance  += autocorrelation(j);\n  }\n  Covariance *=  2.0/((double) MonteCarloCycles);\n  // Compute now the total variance, including the covariance, and obtain the standard deviation\n  double TotalVariance = (Variance/((double) MonteCarloCycles ))+Covariance;\n  cout << \" Covariance = \" << Covariance << \" Totalvariance= \" << TotalVariance << \" Sample Variance/n= \" << (Variance/((double) MonteCarloCycles )) << endl;\n  cout << \" STD from sample variance= \" << sqrt(Variance/((double) MonteCarloCycles )) << \" STD with covariance = \" << sqrt(TotalVariance) << endl;\n  ofile.close();  // close output file\n  return 0;\n}  // end of main program \n\n", "meta": {"hexsha": "58d452556c46eb410ca000a5cfcdc6b2270d46d2", "size": 2951, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/Programs/LecturePrograms/programs/MCIntro/cpp/program6.cpp", "max_stars_repo_name": "kimrojas/ComputationalPhysicsMSU", "max_stars_repo_head_hexsha": "a47cfc18b3ad6adb23045b3f49fab18c0333f556", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 220.0, "max_stars_repo_stars_event_min_datetime": "2016-08-25T09:18:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:09:16.000Z", "max_issues_repo_path": "doc/Programs/LecturePrograms/programs/MCIntro/cpp/program6.cpp", "max_issues_repo_name": "dnhdang94/ComputationalPhysicsMSU", "max_issues_repo_head_hexsha": "16990c74cf06eb5b933982137f0536d669567259", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-12-04T12:55:10.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-04T12:55:10.000Z", "max_forks_repo_path": "doc/Programs/LecturePrograms/programs/MCIntro/cpp/program6.cpp", "max_forks_repo_name": "dnhdang94/ComputationalPhysicsMSU", "max_forks_repo_head_hexsha": "16990c74cf06eb5b933982137f0536d669567259", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 136.0, "max_forks_repo_forks_event_min_datetime": "2016-08-25T09:04:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T09:54:21.000Z", "avg_line_length": 37.8333333333, "max_line_length": 157, "alphanum_fraction": 0.6726533379, "num_tokens": 856, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308165850443, "lm_q2_score": 0.9005297901222472, "lm_q1q2_score": 0.8405822573529678}}
{"text": "//\n//  main.cpp\n//  Assignment 4 - Even More Triangles!\n//\n//  Created by - on 2016/10/19.\n//  Copyright \u00a9 2016 Eddie of The Ren. All rights reserved.\n//\n\n#include <iostream>\n//#include \"stdafx.h\"\nusing namespace std;\n#include <stdio.h>      /* printf */\n#include <math.h>\n//#include <boost/lexical_cast.hpp>\n#include <string>\n#include <cstdlib>\n\nint getNum() {\n    //User inputs a number and returns its value\n    double inputNum = 0;\n    cin >> inputNum;\n    return inputNum;\n}\n\nbool thisIsTheEnd(double a, double b, double c) {\n    //Checks if all three numbers are 0 and displays an approximate end message if true\n    if (a == b && b == c && c == 0) {\n        cout<< a << \" \" << b << \" \" << c <<\" Program was terminated by user\" << endl;\n        cout << \"\"<< endl;\n        \n        exit(0);\n        return true;\n    } else {\n        return false;\n    }\n}\n\nbool checkValid (double x, double y, double z) {\n    \n    if ((x > y + z)||(y>x+z) || (z > x + y)){\n        //Checks if one side of the triangle is greater than the other two combined\n        cout<< x << \" \" << y << \" \" << z <<\" Triangle cannot be formed\" << endl;\n        return false;\n    } else if ((x <=0)|| (y <=0) || (z<=0) ) {\n        //Checks if one side of the triangle is 0 or negative\n        cout<< x << \" \" << y << \" \" << z <<\" Triangle cannot be formed - Invalid Length entry\" << endl;\n        return false;\n    }\n    \n    else {\n        return true;\n    }\n    \n}\n\nstring sideClass(double x, double y, double z) {\n    //Classifies the triangles by their side lengths\n    if ((x == y) && (y==z)) {\n        return \"Equilateral\";\n    } else if ((x != y) && (y != z) && (z != x)) {\n        return \"Scalene\";\n    } else {\n        return \"Isoceles\";\n    }\n    \n}\n\nstring angleClass(double x, double y, double z) {\n    //Classifies triangles by their largest angles.\n    double largest = 3122;\n    double meh = 12342;\n    double meh2 = 12342;\n    \n    //Finds the largest side of the triangle\n    if ((x>y) && (x>z)) {\n        largest = x;\n        meh = y;\n        meh2 = z;\n    } else if ((y>x) && (y>z)) {\n        largest = y;\n        meh = x;\n        meh2 = z;\n    } else if ((z>x) && (z > y)) {\n        largest = z;\n        meh = x;\n        meh2 = y;\n    }\n    \n    //Uses the pythogorean theory to determine if the triangle is right, acute or obtuse\n    if ((largest*largest) == (meh*meh) + (meh2*meh2)) {\n        return \"Right\";\n    } else if ((largest*largest) > (meh*meh) + (meh2*meh2)) {\n        return \"Obtuse\";\n    } else if ((largest*largest) < (meh*meh) + (meh2*meh2)) {\n        return \"Acute\";\n    } else {\n        //Eddie is not always perfect\n        return \"Crap I screwed up\";\n    }\n}\n\nint main(int argc, const char * argv[]) {\n    \n    bool validity = false;\n    double firstNum = 0;\n    double secondNum = 0;\n    double thirdNum = 0;\n    string sClass = \"Derp\";\n    string aClass = \"Derpity Derp\";\n    \n    do {\n        //Continues asking for input as long as the input values are invalid. when 0 0 0 is entered the program ends\n        cout << \"Provide three side lengths, x, y and z. - 0 0 0 to terminate.\" << endl;\n        \n        firstNum = getNum();\n        secondNum = getNum();\n        thirdNum = getNum();\n        \n        thisIsTheEnd(firstNum, secondNum, thirdNum);\n        validity = checkValid(firstNum, secondNum, thirdNum);\n        \n    } while (validity == false);\n    //sClass and aClass are the angle and side lengths\n    sClass = sideClass(firstNum, secondNum, thirdNum);\n    aClass = angleClass(firstNum, secondNum, thirdNum);\n    \n    //Outputs the results of the calculations for side and angle classificaitons\n    if (checkValid(firstNum, secondNum, thirdNum) == true) {\n        cout<< \"Length x: \"<< firstNum << \" Length Y: \" << secondNum << \" Length Z: \" << thirdNum << \" Triangle Possible \" << sClass << \" \" << aClass << endl;\n    }\n    \n    //Finds perimeter and outputs it\n    double perimeter = firstNum + secondNum + thirdNum;\n    cout << \"The perimeter of the triangle is \" << perimeter<< endl;\n    \n    //Finds semi-perimeter and outputs it\n    double semiPerimeter = 0;\n    semiPerimeter = perimeter/2;\n    //cout << \"Calculation No.2 - Semi-Perimeter\" << endl;\n    cout << \"The semi-perimeter of the triangle is \" << semiPerimeter<< endl;\n    \n    //Finds the total area and outputs it\n    double totalArea = 0;\n    double s = semiPerimeter;\n    totalArea = sqrt((s*(s-firstNum)*(s-secondNum)*(s-thirdNum)));\n    //cout << \"Calculation No.3 - Area \" << endl;\n    cout << \"The area of the triangle is \" << totalArea << endl;\n    \n    //Finds the radius of the circumsized circle and outputs it\n    double radiusCircumsized = 0;\n    double a = totalArea;\n    radiusCircumsized = ((firstNum * secondNum * thirdNum)/(4*a));\n    //cout << \"Calculation No.4 - Radius of Circumsized Circle \" << endl;\n    cout << \"The radius of the circumsized circle is \" << radiusCircumsized << endl;\n    \n    //FInds the radius of the inscribed circle and outputs it\n    double radiusInscribed = 0;\n    radiusInscribed = ((2*a)/(perimeter));\n    // cout << \"Calculation No.5 - Radius of Inscribed Circle \" << endl;\n    cout << \"The radius of the inscribed circle is \" << radiusInscribed << endl;\n    \n    \n    double num1 = firstNum;\n    double num2 = secondNum;\n    double num3 = thirdNum;\n    double angleX = 0;\n    double angleY = 0;\n    double angleZ = 0;\n    double x1 = firstNum;\n    double y1 = secondNum;\n    double z1 = thirdNum;\n    \n    cout << \"\"<<  endl;\n    double theta = 0;\n    \n    //Uses the cosine formula to find the angle of each side length\n    theta = ((((y1)*(y1))+((z1)*(z1))-((x1)*(x1)))/(2*z1*y1));\n    angleX = acos(theta) * 180/3.141592653589793238463;\n    \n    theta = ((((x1)*(x1))+((z1)*(z1))-((y1)*(y1)))/(2*z1*x1));\n    angleY = acos(theta) * 180/3.141592653589793238463;\n    \n    theta = ((((y1)*(y1))+((x1)*(x1))-((z1)*(z1)))/(2*x1*y1));\n    angleZ = acos(theta) * 180/3.141592653589793238463;\n    \n    //Outputs the angle calculations.\n    cout << \"Calculation No.6 - Finding The Angles \" << endl;\n    cout << \"AngleX = \" << angleX << endl;\n    cout << \"AngleY = \" << angleY << endl;\n    cout << \"AngleZ = \" << angleZ << endl;\n    \n    \n    return 0;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "e8e77cae4b156367a37864d72ac470f561ed51a9", "size": 6220, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Assignment 4 Even More Triangles/Assignment 4/main.cpp", "max_stars_repo_name": "NyteCore/Senior_School_Projects", "max_stars_repo_head_hexsha": "2a6e9e6bbdfaf62b8282e511bcf84fd9700ad949", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-04-17T01:19:11.000Z", "max_stars_repo_stars_event_max_datetime": "2017-06-28T23:52:48.000Z", "max_issues_repo_path": "Assignment 4 Even More Triangles/Assignment 4/main.cpp", "max_issues_repo_name": "EdwaRen/Senior_School_Projects", "max_issues_repo_head_hexsha": "2a6e9e6bbdfaf62b8282e511bcf84fd9700ad949", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assignment 4 Even More Triangles/Assignment 4/main.cpp", "max_forks_repo_name": "EdwaRen/Senior_School_Projects", "max_forks_repo_head_hexsha": "2a6e9e6bbdfaf62b8282e511bcf84fd9700ad949", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7678571429, "max_line_length": 158, "alphanum_fraction": 0.5654340836, "num_tokens": 1810, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620550745212, "lm_q2_score": 0.8757869948899665, "lm_q1q2_score": 0.8405471260231334}}
{"text": "/*FCTRL2 - Small factorials\n#math #big-numbers\n\nYou are asked to calculate factorials of some small positive integers.\nInput\n\nAn integer t, 1<=t<=100, denoting the number of testcases, followed by t lines, each containing a single integer n, 1<=n<=100.\nOutput\n\nFor each integer n given at input, display a line with the value of n!\nExample\nSample input:\n\n4\n1\n2\n5\n3\n\nSample output:\n\n1\n2\n120\n6\n\n*/\n\n#include <iostream>\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing namespace boost::multiprecision;\nusing namespace std;\n\ninline cpp_int factorial(const int num)\n{\n    cpp_int res = 1;\n    for (int i=1; i<= num; ++i)\n        res *= i;\n    \n    return res;    \n}\n\nint main()\n{\n    int t;\n    cin >> t;\n\n    while (t--) {\n        int n;\n        cin >> n;\n        cout << factorial(n) << endl;\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "fc87a28cdf7af4f086e7821fb8272d6cec11d281", "size": 815, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SPOJ/FCTRL2 - Small factorials.cpp", "max_stars_repo_name": "ravirathee/Competitive-Programming", "max_stars_repo_head_hexsha": "20a0bfda9f04ed186e2f475644e44f14f934b533", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-11-26T02:38:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-28T00:16:41.000Z", "max_issues_repo_path": "SPOJ/FCTRL2 - Small factorials.cpp", "max_issues_repo_name": "ravirathee/Competitive-Programming", "max_issues_repo_head_hexsha": "20a0bfda9f04ed186e2f475644e44f14f934b533", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-30T09:25:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-05T08:33:56.000Z", "max_forks_repo_path": "SPOJ/FCTRL2 - Small factorials.cpp", "max_forks_repo_name": "ravirathee/Competitive-Programming", "max_forks_repo_head_hexsha": "20a0bfda9f04ed186e2f475644e44f14f934b533", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-04-16T07:15:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-04T06:26:07.000Z", "avg_line_length": 14.298245614, "max_line_length": 126, "alphanum_fraction": 0.6355828221, "num_tokens": 229, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122696813392, "lm_q2_score": 0.8774767890838836, "lm_q1q2_score": 0.8405457826240368}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\n\nusing namespace std;\nusing namespace Eigen;\n\nvoid legvals(const VectorXd &x, MatrixXd &Lx, MatrixXd &DLx){\n    int n = Lx.cols()-1;\n    int N = x.size();\n\tfor (int i=0;i<N;i++){\n\t\tLx(i,0)=1.;\n\t\tLx(i,1)=x(i);\n\t\tDLx(i,0)=0;\n\t\tDLx(i,1)=1.;\n\t\tfor (int j=2;j<n+1;j++){\n\t\t\tLx(i,j)=((2*j-1.)/j)*x(i)*Lx(i,j-1)-((j-1.)/j)*Lx(i,j-2);\n\t\t\tDLx(i,j)=((2*j-1.)/j)*(Lx(i,j)+x(i)*DLx(i,j-1))-((j-1.)/j)*DLx(i,j-2);\n\t\t}\n\n\t}\n\n}\n\ndouble Pnx (double x, int n){\n\tif (n==0){return 1.;}\n\telse if(n==1){return x;}\n\telse{\n\t\treturn (((2*n-1.)/n)*x*Pnx(x,n-1)-((n-1.)/n)*Pnx(x,n-2));\n\t}\n}\n\n// Find the Gauss points using the secant method with regula falsi. The standard secant method may be obtained by commenting out lines 50 and 52.\nMatrixXd gaussPts(int n, double rtol=1e-10, double atol=1e-12) {\n\tMatrixXd Pkn(n,n);\n\tdouble f0, fn,x0,x1,s;\n\tfor (int k=1;k<n+1;k++){// k de 1-n\n\t\tfor (int j=1;j<k+1;j++){ // j de 1 - k\n\n\t\t\tif (j==1) x0 = -1.;\n            else      x0 = Pkn(j-2,k-2);\n            if (j==k) x1 = 1.;\n            else      x1 = Pkn(j-1,k-2);\n\n\t\t\tf0 = Pnx(x0,k);\n\t\t\tfor (int i=0;i<1e4;i++){\n\t\t\t\tfn=Pnx(x1,k);\n\t\t\t\ts=fn*(x1-x0)/(fn-f0);\n\t\t\t\tif (Pnx(x1 - s,k)*fn<0) { x0 = x1; f0 = fn;} // without this correstion, the zero KI8-6 is not a zero, because the initial guess is to far away for the sought zero ---> not the case of a local convergence (I got 0.273438)\n\t\t\t\t// x0 = x1; f0 = fn;\n                x1=x1-s;\n\t\t\t\tif (abs(s)<max(atol,rtol*min(abs(x0),abs(x1)))){Pkn(j-1,k-1)=x1;break;}\n\t\t\t}\n\t\t}\n\n}\nreturn Pkn;\n\n}\n// Test the implementation.\nint main(){\n    int n = 8;\n    MatrixXd zeros = gaussPts(n);\n    cout<<\"Zeros: \"<<endl<< zeros <<endl;\n\n    for (int k=1; k<n+1; k++) {\n        VectorXd xi = zeros.block(0, k-1, k, 1);\n        MatrixXd Lx(k,n+1), DLx(k,n+1);\n        legvals(xi, Lx, DLx);\n        cout<<\"Values of the \"<<k<<\"-th polynomial in the calculated zeros: \"<<endl;\n        cout<<Lx.col(k).transpose() <<endl;\n    }\n}\n", "meta": {"hexsha": "1f6add59d253dd4a693d8448a13bf031576ff87f", "size": 1969, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/PS10/legendre.cpp", "max_stars_repo_name": "valentinjacot/backupETHZ", "max_stars_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:21:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:21:30.000Z", "max_issues_repo_path": "Nummerical Methods for CSE/PS10/legendre.cpp", "max_issues_repo_name": "valentinjacot/backupETHZ", "max_issues_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Nummerical Methods for CSE/PS10/legendre.cpp", "max_forks_repo_name": "valentinjacot/backupETHZ", "max_forks_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6081081081, "max_line_length": 225, "alphanum_fraction": 0.5352971051, "num_tokens": 778, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.944176863577751, "lm_q2_score": 0.8887587846530938, "lm_q1q2_score": 0.8391454817709318}}
{"text": "// SPDX-License-Identifier: Apache-2.0\n// Copyright 2021 - 2021, the Anboto author and contributors\n#include <Core/Core.h>\n#include <Eigen/Eigen.h>\n\nusing namespace Upp;\n\n#ifdef USE_FFTW\n#include <fftw3.h>\n#endif\n\nusing namespace Eigen;\n\n\nvoid FFTTests()\n{\n\tUppLog() << \"\\nFFT sample\\nGets the FFT of equation\"\n\t\t\t  \"\\n f(t) = 2*sin(2*PI*t/50 - PI/3) + 5*sin(2*PI*t/30 - PI/2) + 30*sin(2*PI*t/10 - PI/5)\"\n\t\t\t  \"\\nsampled with a frequency of 14 samples/second\";\n\t\n\tint numData = 8000;\n\tdouble samplingFrecuency = 14;\t\n\n    // Filling the data series\n    VectorXd timebuf(numData);\n    {\n\t    double t = 0;\n\t    for (int i = 0; i < numData; ++i, t = i/samplingFrecuency) \n\t       \ttimebuf[i] = 2*sin(2*M_PI*t/50 - M_PI/3) + 5*sin(2*M_PI*t/30 - M_PI/2) + 30*sin(2*M_PI*t/10 - M_PI/5);\n    }\n    \n    // FFT\n    VectorXcd freqbuf;\n    FFT<double> fft;\n    fft.SetFlag(fft.HalfSpectrum);\n    fft.fwd(freqbuf, timebuf);\n\t\n\t// Filter the FFT. Frequencies between 1/25 and 1/35 Hz are removed\n\t// Original FFT is not changed for saving it later\n\tVectorXcd freqbuf2(freqbuf.size());\n\t{\n\t    for (int i = 0; i < freqbuf.size(); ++i) {\n\t        double freq = i*samplingFrecuency/numData;\n\t        double T = 1/freq;\n\t        if (T > 25 && T < 35)\n\t            freqbuf2[i] = 0;\n\t        else\n\t            freqbuf2[i] = freqbuf[i];\n\t    }\n\t}\n\t\n\t// Inverse filtered FFT to get filtered series\n\tVectorXd timebuf2(numData);\n\tfft.inv(timebuf2, freqbuf2);\n\t\n\tString csvSep = \";\";\n\n\t// Saving original and filtered FFT\n\t{\n\t    String str;\n\t    str << \"Frec\" << csvSep << \"T\" << csvSep << \"fft\" << csvSep << \"Filtered fft\";\n\t    for (int i = 0; i < freqbuf.size(); ++i) {\n\t        double freq = i*samplingFrecuency/numData;\n\t        double T = 1/freq;\n\t        str << \"\\n\" << freq << csvSep << (freq > 0 ? FormatDouble(T) : \"\") << csvSep \n\t        \t\t\t<< 2*std::abs(freqbuf[i])/numData << csvSep \n\t        \t\t\t<< 2*std::abs(freqbuf2[i])/numData;\n\t    }\n\t    String fftFileName = GetExeDirFile(\"fft.csv\");\n\t    UppLog() << \"\\nFFT saved in '\" << fftFileName << \"'\";\n\t    VERIFY(SaveFile(fftFileName, str));\n\t}\n\t\n\t// Saving original and filtered series\n\t{\n\t    String str;\n\t    str << \"Time\" << csvSep << \"Data\" << csvSep << \"Filtered data\";\n\t    double t = 0;\n\t    for (int i = 0; i < numData; ++i, t = i*1/samplingFrecuency) \n\t       \tstr << \"\\n\" << t << csvSep << timebuf[i] << csvSep << timebuf2[i];;\n\t    String dataFileName = GetExeDirFile(\"data.csv\");\n\t    UppLog() << \"\\nSource data saved in '\" << dataFileName << \"'\";\n\t    VERIFY(SaveFile(dataFileName, str));\n    }\n}\n\n", "meta": {"hexsha": "15665fddf501d3e3e50af69a46a7d87bde6bb5ca", "size": 2553, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/Eigen_demo_cl/fft.cpp", "max_stars_repo_name": "anboto/Anboto", "max_stars_repo_head_hexsha": "fc40730e87b85bba4d9387724fcece7e98069843", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2021-02-28T12:07:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T19:40:45.000Z", "max_issues_repo_path": "examples/Eigen_demo_cl/fft.cpp", "max_issues_repo_name": "anboto/Anboto", "max_issues_repo_head_hexsha": "fc40730e87b85bba4d9387724fcece7e98069843", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2021-03-20T10:46:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-27T19:50:32.000Z", "max_forks_repo_path": "examples/Eigen_demo_cl/fft.cpp", "max_forks_repo_name": "anboto/Anboto", "max_forks_repo_head_hexsha": "fc40730e87b85bba4d9387724fcece7e98069843", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-20T09:15:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-20T09:15:18.000Z", "avg_line_length": 29.3448275862, "max_line_length": 111, "alphanum_fraction": 0.5761848805, "num_tokens": 836, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632288833652, "lm_q2_score": 0.8791467738423874, "lm_q1q2_score": 0.8368274868120085}}
{"text": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <unordered_map>\n#include <boost/functional/hash.hpp>\n\nusing namespace std;\n  \n// https://www.geeksforgeeks.org/count-maximum-points-on-same-line/  \n// method to find maximum colinear point \n\nint maxPointOnSameLine(vector< pair<int, int> > points) \n{ \n    int N = points.size(); \n    if (N < 2) \n        return N; \n  \n    int maxPoint = 0; \n    int curMax, overlapPoints, verticalPoints; \n  \n    // here since we are using unordered_map which is based on hash function  \n    // But by default we don't have hash function for pairs so we'll use hash function defined in Boost library \n    unordered_map<pair<int, int>, int, boost::hash<pair<int, int>>> slopeMap; \n  \n    // looping for each point \n    for (int i = 0; i < N; i++) \n    { \n        curMax = overlapPoints = verticalPoints = 0; \n  \n        // looping from i + 1 to ignore same pair again \n        for (int j = i + 1; j < N; j++) \n        { \n            // If both point are equal then just  increase overlapPoint count \n            if (points[i] == points[j]) \n                overlapPoints++; \n  \n            // If x co-ordinate is same, then both point are vertical to each other \n            else if (points[i].first == points[j].first) \n                verticalPoints++; \n  \n            else\n            { \n                int yDif = points[j].second - points[i].second; \n                int xDif = points[j].first - points[i].first; \n                int g = __gcd(xDif, yDif); \n  \n                // reducing the difference by their gcd \n                yDif /= g; \n                xDif /= g; \n  \n                // increasing the frequency of current slope in map \n                slopeMap[make_pair(yDif, xDif)]++; \n                curMax = max(curMax, slopeMap[make_pair(yDif, xDif)]); \n            } \n            curMax = max(curMax, verticalPoints); \n        } \n  \n        // updating global maximum by current point's maximum \n        maxPoint = max(maxPoint, curMax + overlapPoints + 1); \n  \n        // printf(\"maximum colinear point which contains current point are : %d\\n\", curMax + overlapPoints + 1); \n        slopeMap.clear(); \n    } \n  \n    return maxPoint; \n} \n \nint main() \n{ \n    const int N = 6; \n    int arr[N][2] = {{-1, 1}, {0, 0}, {1, 1}, {2, 2}, {3, 3}, {3, 4}}; \n    vector< pair<int, int> > points; \n    for (int i = 0; i < N; i++) {\n        points.push_back(make_pair(arr[i][0], arr[i][1])); \n    }\n    cout << maxPointOnSameLine(points) << endl; \n    return 0; \n};\n\n/***  Java Implementation\n    //https://www.interviewbit.com/problems/points-on-the-straight-line/\n    public int maxPoints(ArrayList<Integer> a, ArrayList<Integer> b) {\n        if (a.size() == 0) {\n            return 0;\n        }\n        if (a.size() == 1 && b.size() == 1) {\n            return 1;\n        }\n        int max = Integer.MIN_VALUE;\n        for (int i = 0; i < a.size(); i++) {\n            int x1 = a.get(i);\n            int y1 = b.get(i);\n\n            HashMap<Double, Integer> map = new HashMap<Double, Integer>();\n            int samePoint = 1; // 1 is taken point itself\n            int infValue = 0;\n\n            for (int j = i + 1; j < a.size(); j++) {\n                int x2 = a.get(j);\n                int y2 = b.get(j);\n\n                if ((x1 == x2) && (y1 == y2)) {\n                    samePoint += 1;\n                } else if (x2 - x1 == 0) {\n                    infValue++;\n                } else {\n                    double slope = 0.0;\n                    if (y1 != y2) {\n                        slope = (double) (y2 - y1) / (double) (x2 - x1);\n                    }\n                    if (map.containsKey(slope)) {\n                        map.put(slope, map.get(slope) + 1);\n                    } else {\n                        map.put(slope, 1);\n                    }\n                }\n            }\n            if ((infValue + samePoint) > max) {\n                max = infValue + samePoint;\n            }\n            for (Integer value : map.values()) {\n                max = Math.max(value + samePoint, max);\n            }\n        }\n        return max;\n    }\n\n*/", "meta": {"hexsha": "1716a53c23e12cb52c30dd3a78ed8c770e89f224", "size": 4123, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Math_Bit/MaxPointLine.cpp", "max_stars_repo_name": "satyam289/Data-structure-and-Algorithm", "max_stars_repo_head_hexsha": "75a0267958549991a1ca4a19b794faabe5997cb6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Math_Bit/MaxPointLine.cpp", "max_issues_repo_name": "satyam289/Data-structure-and-Algorithm", "max_issues_repo_head_hexsha": "75a0267958549991a1ca4a19b794faabe5997cb6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Math_Bit/MaxPointLine.cpp", "max_forks_repo_name": "satyam289/Data-structure-and-Algorithm", "max_forks_repo_head_hexsha": "75a0267958549991a1ca4a19b794faabe5997cb6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2109375, "max_line_length": 113, "alphanum_fraction": 0.479020131, "num_tokens": 1072, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897426182321, "lm_q2_score": 0.8887588008585925, "lm_q1q2_score": 0.8361351635094438}}
{"text": "#include <iostream>\n#include <iomanip>\n#include<vector>\n#include<string>\n#include <cmath>\n\n#include <Eigen/Dense>\n\nvoid newton3d(Eigen::VectorXd& x,\n              double tolerance,\n              std::function<Eigen::VectorXd(const Eigen::VectorXd&)> F,\n              std::function<Eigen::MatrixXd(const Eigen::VectorXd&)> DF\n              )\n\n{\n\tEigen::VectorXd x_prev, s;\n\t\n    std::vector<double> errors;\n\terrors.push_back((F(x)).norm());\n\tdo\t{\n        x_prev = x;\n\t\ts = DF(x).lu().solve(F(x));\n\t  \tx = x-s; // newton iteration\n\t} while (s.norm() > tolerance*x.norm());\n}\n\nint main()\n{\n    // F\n    auto F = [](const Eigen::VectorXd &x){ \n   \t\tEigen::VectorXd res(3);\n        res << 0.2*x(0)-0.2*x(1)-3, \n        0.4*x(1)-0.2*x(0)-0.3*x(2)+1e-13*(exp(19*x(1)-1)), \n        -0.2*x(1)+0.3*x(2);\n        return res;\n\t};\n\t// jacobian of F\n\tauto DF= [] (const Eigen::VectorXd &x){\n    \tEigen::MatrixXd J(3,3);\n\t\tJ << 0.2, -0.2, 0,\n\t\t  \t -0.2, 0.4 + 19*1e-13*exp(19*x(1)), -0.3,\n               0, -0.2, 0.3;\n\t  \treturn J;\n\t};\t\n\n    Eigen::VectorXd x(3);\n\tx << 16.0, 2.0, 2.0; // initial value\n    double tolerance = 1e-14;\n\tnewton3d(x, tolerance, F, DF);\n    \n    std::cout << std::setprecision(17) << \"solution = \" << x << std::endl;\n    std::cout << std::setprecision(17) << \"error norm = \" << F(x).norm() << std::endl;\n}\n", "meta": {"hexsha": "92d0b32c746c947521e7bf426d8930f62334a139", "size": 1319, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/3dcircuit.cpp", "max_stars_repo_name": "leannejdong/Lachine-Est", "max_stars_repo_head_hexsha": "6175a1398d3f5690fd2c0ad05eb87f628488c593", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cpp/3dcircuit.cpp", "max_issues_repo_name": "leannejdong/Lachine-Est", "max_issues_repo_head_hexsha": "6175a1398d3f5690fd2c0ad05eb87f628488c593", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-06-21T10:08:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-21T10:08:11.000Z", "max_forks_repo_path": "cpp/3dcircuit.cpp", "max_forks_repo_name": "leannejdong/Lachine-Est", "max_forks_repo_head_hexsha": "6175a1398d3f5690fd2c0ad05eb87f628488c593", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-06-21T10:04:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-21T10:04:42.000Z", "avg_line_length": 24.4259259259, "max_line_length": 86, "alphanum_fraction": 0.5231235785, "num_tokens": 463, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811651448431, "lm_q2_score": 0.8652240825770433, "lm_q1q2_score": 0.835271032949604}}
{"text": "#include<vector>\n#include<iostream>\n#include<cmath>\n//#include <boost/numeric/ublas/matrix.hpp>\n//#include <boost/numeric/ublas/io.hpp>\n#include <armadillo>\n\nusing namespace std;\nusing namespace arma;\n//using namespace boost::numeric::ublas;\n\n\n/*\nUzawa's method: Minimize the quadratic functional (Av,v) - (b,v) with the constraints: Cv <= d.\nHere A must be symmetric positive definite and has dim = n.\nNote A is square since it is symmetric.\nThere are m constraints and hence C is an mxn matrix.\n\n\nLagrange is an mx1 vector of lagrange multipliers\np is a parameter used in the convergence algorithm. It must be within certain bounds\nto ensure convergence of the algorithm.\nSome of the mat variables below are actually vectors. We leave them as nx1 mats for simplicity.\n\nREFERENCE:\nIntroduction to Numerical Linear Algebra and Optimization. Philippe G. Ciarlet.\n*/\n\nmat UzawasMethod(mat A, mat b, mat C, mat d, double p, int iterations)\n{\n    \n    int dim = A.n_rows;\n    int dualDim = C.n_rows;\n    mat Lagrange(dualDim,1);\n    mat solution(dim,1);\n    \n    for(int i=0;i<iterations;i++)\n    {\n        for(int j=0;j<dualDim;j++)\n        {\n            mat temp = C*solution - d;\n            Lagrange(j,0) = max(Lagrange(j,0) + p*(temp)(j,0),0.0);\n        }\n        solution = solve(A,b - C.t()*Lagrange);\n    }\n    return solution;\n}\n\n/*EXAMPLE \nMinimize 2x_1^2 + x_2^2 with respect to x_2 >= x_1 + 1\n\nmat a(2,2);\n    a(0,0) = 2; a(0,1) = 0;\n    a(1,0) = 0; a(1,1) = 1;\n    \nmat b(2,1); \n    b(0,0) = 0; \n    b(1,0) = 0;\n\nmat c(1,2); \n    c(0,0) = 1; c(0,1) = -1;\n\nmat d(1,1); \n    d(0,0) = -1;\n    \n    mat s = UzawasMethod(a,b,c,d,.1,40);\n    cout << s;\n    \nOne can check directly using Lagrange Multiplier techniques that \nthe solution given by the code for this example is indeed correct. \nx_1 = -1/3,  x_2 = 2/3\n*/\n", "meta": {"hexsha": "0b1e8c62db6d547babbf9ae6b1d4cc4a2d3246e1", "size": 1821, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "UzawasMethod.cpp", "max_stars_repo_name": "thomasjmurphy/Optimization", "max_stars_repo_head_hexsha": "6743c25013b54732a7356331fded84357324f78c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "UzawasMethod.cpp", "max_issues_repo_name": "thomasjmurphy/Optimization", "max_issues_repo_head_hexsha": "6743c25013b54732a7356331fded84357324f78c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "UzawasMethod.cpp", "max_forks_repo_name": "thomasjmurphy/Optimization", "max_forks_repo_head_hexsha": "6743c25013b54732a7356331fded84357324f78c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9452054795, "max_line_length": 95, "alphanum_fraction": 0.6370126304, "num_tokens": 582, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517050371973, "lm_q2_score": 0.8688267796346599, "lm_q1q2_score": 0.8349005752719038}}
{"text": "/* ------------------------------------------------------------\n * @file: jacobi.cpp\n * @dependencias: armadillo, matplotlibcpp\n * @version 0.1\n * ------------------------------------------------------------*/\n\n// [1] $ g++ jacobi.cpp -o jac.out -std=c++11 -I/usr/include/python3.8 -lpython3.8 \n// [2] $ ./jac.out\n// Nota: Asegurarse de tener armadillo bien instalado.\n\n#include <armadillo>\n#include \"matplotlibcpp.h\"\n\nusing namespace std;\nusing namespace arma;\nnamespace plt = matplotlibcpp;\n\n\n/**\n * @brief Indica si una matriz es diagonal dominante\n * @param M Matriz de coeficientes, debe ser cuadrada.\n * @return True si la matriz es diagonal dominante, False si no lo es.\n */\nbool dominant_diagonal(mat M){\n    int n = M.n_rows;\n    double d_value, row_sum;\n\n    for (int i = 0; i < n; i++){\n        d_value = M(i,i);\n        row_sum = 0; \n        for (int j = 0; j < n; j++){\n            row_sum += abs(M(i,j));\n        }\n        \n        if (abs(d_value) < row_sum-abs(d_value))\n            return false; \n    }\n\n    return true;\n}\n\n\n/**\n * @brief Retorna la matriz superior\n */\nmat upper_mat(mat A){\n    int n = A.n_rows;\n    mat U(n,n);\n    U.zeros();\n\n    for(int i = 0; i < n; i++){\n        for (int j = i; j < n; j++){\n            if (i == j){\n                continue;\n            }\n            U(i,j) = A(i,j);\n        }\n    }\n\n    return U;\n}\n\n\n/**\n * @brief Retorna la matriz diagonal\n */\nmat diag_mat(mat A){\n    int n = A.n_rows;\n    mat D(n,n);\n    D.zeros();\n\n    for(int i = 0; i < n; i++){\n        D(i,i) = A(i,i);\n    }\n\n    return D;\n}\n\n\n/**\n * @brief Retorna la matriz inferior\n */\nmat lower_mat(mat A){\n    int n = A.n_rows;\n    mat L(n,n);\n    L.zeros();\n\n    for(int i = 0; i < n; i++){\n        for (int j = 0; j < i; j++){\n            L(i,j) = A(i,j);\n        }\n    }\n\n    return L;\n}\n\n\n/**\n * @brief Grafica el error en funcion de la cantidad de iteraciones.\n * @param x Set de valores del eje x.\n * @param y Set de valores del eje y.\n */ \nvoid plot(vector<double> x, vector<double> y){\n    \n    plt::named_plot(\"Error |Ax-b|\",x,y);\n    plt::title(\"Error Jacobi\");\n    plt::legend();\n    plt::show();\n}\n\n\n/**\n * @brief Calcula la aproximaci\u00f3n a la soluci\u00f3n de un sistema de ecuaciones por \n *        el m\u00e9todo de Jacobi.\n * @param A Matriz de coeficientes.\n * @param b Vector de t\u00e9rminos independientes.\n * @param x_o Vector de valor inicial.\n * @param tol Tolerancia de la aproximaci\u00f3n.\n * @param max_itr Iteraciones m\u00e1ximas.\n */ \nvoid jacobi(mat A, vec b, vec x_o, double tol, int max_itr=100){\n\n    if (!dominant_diagonal(A)){\n        cout<<\"[Error] La matriz no es diagonal dominante.\"<<endl;\n        return;\n    }\n\n    mat L = lower_mat(A);\n    mat D = diag_mat(A);\n    mat U = upper_mat(A);\n    \n    vec x = x_o;\n    int k = 0;\n\n    mat T = -D.i()*(L+U);\n    vec c = D.i()*b;\n\n    vector<double> errors, itr;\n    double error = tol;\n\n    while(error > tol && k < max_itr){\n        x = T*x + c;\n        error = norm(A*x-b);\n        errors.push_back(error);\n        itr.push_back(k);\n        k++;\n    }\n\n    x.print(\"x: \");\n    plot(itr,errors);\n}\n\n\nint main(int argc, char const *argv[])\n{\n    mat M = {{5,1,1},{1,5,1},{1,1,5}};\n    vec b = {7,7,7};\n    vec x_o = {0,0,0};\n    jacobi(M,b,x_o,5);\n\n    return 0;\n}\n", "meta": {"hexsha": "80bfa3abe532271faae44ff3f7f97521d1cdeff6", "size": 3249, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Catalogo/03. Sistemas de Ecuaciones/C++/jacobi.cpp", "max_stars_repo_name": "ce-box/CE3102-Numerical-Methods-Catalog", "max_stars_repo_head_hexsha": "f9b70a719286a5aea9d826b0941d5e5d9c0514e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Catalogo/03. Sistemas de Ecuaciones/C++/jacobi.cpp", "max_issues_repo_name": "ce-box/CE3102-Numerical-Methods-Catalog", "max_issues_repo_head_hexsha": "f9b70a719286a5aea9d826b0941d5e5d9c0514e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Catalogo/03. Sistemas de Ecuaciones/C++/jacobi.cpp", "max_forks_repo_name": "ce-box/CE3102-Numerical-Methods-Catalog", "max_forks_repo_head_hexsha": "f9b70a719286a5aea9d826b0941d5e5d9c0514e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.9325153374, "max_line_length": 83, "alphanum_fraction": 0.512465374, "num_tokens": 955, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.951142215838086, "lm_q2_score": 0.8774767954920548, "lm_q1q2_score": 0.834605223610816}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n\nusing namespace std;\nusing namespace Eigen;\n\nvoid main(int argc, char** argv) {\n\t{\n\t\tcout << \"Matrix3f A, Vector3f b\" << endl;\n\t\tMatrix3f A;\n\t\tVector3f b;\n\n\t\tA << 1, 2, 3, 4, 5, 6, 7, 8, 10;\n\t\tb << 3, 3, 4;\n\t\tcout << \"Matrix3f A: \\n\" << A << endl;\n\t\tcout << \"Vector3f b: \\n\" << b << endl;\n\n\t\tVector3f x = A.colPivHouseholderQr().solve(b);\n\t\tcout << \"Solution:\\n\" << x << endl;\n\t}\n\t{\n\t\tcout << \"Matrix2f A, b\" << endl;\n\t\tMatrix2f A, b;\n\t\tA << 2, -1, -1, 3;\n\t\tb << 1, 2, 3, 1;\n\n\t\tcout << \"Matrix2f A: \\n\" << A << endl;\n\t\tcout << \"Matrix2f b: \\n\" << b << endl;\n\t\tMatrix2f x = A.ldlt().solve(b);\n\t\tcout << \"Solution: \\n\" << x << endl;\n\t}\n\n\t{\n\t\tcout << \"Checking if a solution really exists\" << endl;\n\t\tMatrixXd A = MatrixXd::Random(100, 100);\n\t\tMatrixXd b = MatrixXd::Random(100, 50);\n\n\t\tMatrixXd x = A.fullPivLu().solve(b);\n\t\tdouble relative_error = (A*x - b).norm() / b.norm(); \n\t\tcout << \"Relative error :\\n\" << relative_error << endl;\n\t}\n\n\t{\n\t\tcout << \"Computing eigenvalues and eigenvectors\" << endl;\n\t\tMatrix2f A;\n\t\tA << 1, 2, 2, 3;\n\t\tcout << \"Matrix2f A:\\n\" << A << endl;\n\n\t\tSelfAdjointEigenSolver<Matrix2f> eigensolver(A);\n\t\tif (eigensolver.info() != Success) {\n\t\t\tcout << \"EigenSolver failed\" << endl;\n\t\t}\n\t\telse {\n\t\t\tcout << \"Eigenvalues of A: \\n\" << eigensolver.eigenvalues() << endl;\n\t\t\tcout << \"Matrix whose columns are eigenvectors of A: \\n\" << eigensolver.eigenvectors() << endl;\n\t\t}\n\t}\n\t{\n\t\tcout << \"Least squares solving\" << endl;\n\t\tMatrixXf A = MatrixXf::Random(3, 2);\n\t\tcout << \"MatrixXf A: \\n\" << A << endl;\n\t\tVectorXf b = VectorXf::Random(3);\n\t\tcout << \"VectorXf b: \\n\" << b << endl;\n\t\tcout << \"The least-squares solution is: \\n\" << A.jacobiSvd(ComputeThinU | ComputeThinV).solve(b) << endl;\n\t}\n\t{\n\t\tcout << \"Separating the computation from the construction\" << endl;\n\t\tMatrix2f A, b;\n\t\tLLT<Matrix2f> llt;\n\t\tA << 2, -1, -1, 3;\n\t\tb << 1, 2, 3, 1;\n\t\tcout << \"A:\\n\" << A << endl;\n\t\tcout << \"b:\\n\" << b << endl;\n\t\tcout << \"Computing LLT decomposition...\" << endl;\n\t\tllt.compute(A);\n\t\tcout << \"The solution is: \\n\" << llt.solve(b) << endl;\n\t\tA(1, 1)++;\n\t\tcout << \"The matrix A is now: \\n\" << A << endl;\n\t\tcout << \"Computing LLT decomposition...\" << endl;\n\t\tllt.compute(A);\n\t\tcout << \"The solution is: \\n\" << llt.solve(b) << endl;\n\t}\n\n\t{\n\t\tMatrix3f A;\n\t\tA << 1, 2, 5,\n\t\t\t2, 1, 4,\n\t\t\t3, 0, 3;\n\t\tcout << \"Here is the matrix A:\\n\" << A << endl;\n\t\tFullPivLU<Matrix3f> lu_decomp(A);\n\t\tcout << \"The rank of A is \" << lu_decomp.rank() << endl;\n\t\tcout << \"Here is a matrix whose columns form a basis of the null-space of A:\\n\"\n\t\t\t<< lu_decomp.kernel() << endl;\n\t\tcout << \"Here is a matrix whose columns form a basis of the column-space of A:\\n\"\n\t\t\t<< lu_decomp.image(A) << endl; // yes, have to pass the original A\n\t}\n\n\t{\n\t\tcout << \"Inplace matrix decompositions\" << endl;\n\t\tcout << \"Useful when dealing with huge matrices and or when the memory is limited\" << endl;\n\n\t\tMatrixXd A(2, 2);\n\t\tA << 2, -1, 1, 3;\n\t\tcout << \"A:\\n\" << A << endl;\n\t\tPartialPivLU<Ref<MatrixXd>> lu(A);\n\t\tcout << \"Matrix A after decomposition: \\n\" << A << endl;\n\t\tcout << \"Here is the matrix storing the L and U factors: \\n\" << lu.matrixLU() << endl;\n\t\tcout << \"Use lu object to solve the Ax=b problem: \" << endl;\n\t\tVectorXd b(2); b << 1, 2;\n\t\tVectorXd x = lu.solve(b);\n\t\tMatrixXd A0(2, 2); A0 << 2, -1, 1, 3; // only for verification of the result.\n\t\tcout << \"Residual: \" << (A0 * x - b).norm() << endl;\n\t}\n\n\tsystem(\"pause\");\n}", "meta": {"hexsha": "31b98145f10865d147f73214e94849a9f904285c", "size": 3448, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/eigen/eigen/linear_algebra_decomposition/linear_algebra_decomposition.cpp", "max_stars_repo_name": "quanhua92/learning-notes", "max_stars_repo_head_hexsha": "a9c50d3955c51bb58f4b012757c550b76c5309ef", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/eigen/eigen/linear_algebra_decomposition/linear_algebra_decomposition.cpp", "max_issues_repo_name": "quanhua92/learning-notes", "max_issues_repo_head_hexsha": "a9c50d3955c51bb58f4b012757c550b76c5309ef", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/eigen/eigen/linear_algebra_decomposition/linear_algebra_decomposition.cpp", "max_forks_repo_name": "quanhua92/learning-notes", "max_forks_repo_head_hexsha": "a9c50d3955c51bb58f4b012757c550b76c5309ef", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.724137931, "max_line_length": 107, "alphanum_fraction": 0.5754060325, "num_tokens": 1261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545348152283, "lm_q2_score": 0.8791467675095294, "lm_q1q2_score": 0.8335669943823094}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n#include <vector>\n\n #include \"timer.h\"\n\nusing namespace Eigen;\nusing namespace std;\n\n//! \\brief Compute the Matrix product $A \\times B$ using Strassen's algorithm.\n//! \\param[in] A Matrix $2^k \\times 2^k$\n//! \\param[in] B Matrix $2^k \\times 2^k$\n//! \\param[out] Matrix product of A and B of dim $2^k \\times 2^k$\n\nMatrixXd strassenMatMult(const MatrixXd & A, const MatrixXd & B)\n{\n    int n=A.rows();\n    MatrixXd C(n,n);\n    \n    if (n==2)\n    {\n        C<< A(0,0)*B(0,0) + A(0,1)*B(1,0),\n            A(0,0)*B(0,1) + A(0,1)*B(1,1),\n            A(1,0)*B(0,0) + A(1,1)*B(1,0),\n            A(1,0)*B(0,1) + A(1,1)*B(1,1);\n        return C;\n    }\n    \n    else\n    {   MatrixXd Q0(n/2,n/2),Q1(n/2,n/2),Q2(n/2,n/2),Q3(n/2,n/2),\n        Q4(n/2,n/2),Q5(n/2,n/2),Q6(n/2,n/2);\n        \n        MatrixXd A11=A.topLeftCorner(n/2,n/2);\n        MatrixXd A12=A.topRightCorner(n/2,n/2);\n        MatrixXd A21=A.bottomLeftCorner(n/2,n/2);\n        MatrixXd A22=A.bottomRightCorner(n/2,n/2);\n        \n        MatrixXd B11=B.topLeftCorner(n/2,n/2);\n        MatrixXd B12=B.topRightCorner(n/2,n/2);\n        MatrixXd B21=B.bottomLeftCorner(n/2,n/2);\n        MatrixXd B22=B.bottomRightCorner(n/2,n/2);\n        \n        Q0=strassenMatMult(A11+A22,B11+B22);\n        Q1=strassenMatMult(A21+A22,B11);\n        Q2=strassenMatMult(A11,B12-B22);\n        Q3=strassenMatMult(A22,B21-B11);\n        Q4=strassenMatMult(A11+A12,B22);\n        Q5=strassenMatMult(A21-A11,B11+B12);\n        Q6=strassenMatMult(A12-A22,B21+B22);\n        \n        C<< Q0+Q3-Q4+Q6 ,\n        Q2+Q4,\n        Q1+Q3,\n        Q0+Q2-Q1+Q5;\n        return C;\n    }\n}\n\n\nint main(void)\n{\n    srand((unsigned int) time(0));\n    \n    //check if strassenMatMult works\n    int k=2;\n    int n=pow(2,k);\n    MatrixXd A=MatrixXd::Random(n,n);\n    MatrixXd B=MatrixXd::Random(n,n);\n    MatrixXd AB(n,n), AxB(n,n);\n    AB=strassenMatMult(A,B);\n    AxB=A*B;\n    cout<<\"Using Strassen's method, A*B=\"<<AB<<endl;\n    cout<<\"Using standard method, A*B=\"<<AxB<<endl;\n    cout<<\"The norm of the error is \"<<(AB-AxB).norm()<<endl;\n    \n    //compare runtimes of strassenMatMult and of direct multiplication\n    \n    unsigned int repeats = 10;\n    timer<> tm_x, tm_strassen;\n    std::vector<int> times_x, times_strassen;\n    \n    for(unsigned int k = 4; k <= 10; k++) {\n        tm_x.reset();\n        tm_strassen.reset();\n        for(unsigned int r = 0; r < repeats; ++r) {\n            unsigned int n = pow(2,k);\n            A = MatrixXd::Random(n,n);\n            B = MatrixXd::Random(n,n);\n            MatrixXd AB(n,n);\n            \n            tm_x.start();\n            AB=A*B;\n            tm_x.stop();\n            \n            tm_strassen.start();\n            AB=strassenMatMult(A,B);\n            tm_strassen.stop();\n        }\n        std::cout << \"The standard matrix multiplication took:       \" << tm_x.avg().count() / 1000000. << \" ms\" << std::endl;\n        std::cout << \"The Strassen's algorithm took:       \" << tm_strassen.avg().count() / 1000000. << \" ms\" << std::endl;\n        \n        times_x.push_back( tm_x.avg().count() );\n        times_strassen.push_back( tm_strassen.avg().count() );\n    }\n    \n    for(auto it = times_x.begin(); it != times_x.end(); ++it) {\n        std::cout << *it << \" \";\n    }\n    std::cout << std::endl;\n    for(auto it = times_strassen.begin(); it != times_strassen.end(); ++it) {\n        std::cout << *it << \" \";\n    }\n    std::cout << std::endl;\n    \n}\n", "meta": {"hexsha": "f384d54cf94a414fc78a000ea93cc40982c44905", "size": 3449, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/solutions/solution_0/strassen.cpp", "max_stars_repo_name": "valentinjacot/backupETHZ", "max_stars_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:21:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:21:30.000Z", "max_issues_repo_path": "Nummerical Methods for CSE/solutions/solution_0/strassen.cpp", "max_issues_repo_name": "valentinjacot/backupETHZ", "max_issues_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Nummerical Methods for CSE/solutions/solution_0/strassen.cpp", "max_forks_repo_name": "valentinjacot/backupETHZ", "max_forks_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7327586207, "max_line_length": 126, "alphanum_fraction": 0.5308785155, "num_tokens": 1116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248174286373, "lm_q2_score": 0.8872045996818986, "lm_q1q2_score": 0.833107137238142}}
{"text": "#include <Eigen/Dense>\n#include <unsupported/Eigen/MatrixFunctions>\n#include <iostream>\n#include <vector>\n#include <iomanip>\n\nusing namespace Eigen;\nusing namespace std;\n\n// This C++ function phim gives the function phi used for the construction of the exponential Euler single step method for an autonomous ODE.\nMatrixXd  phim(MatrixXd Z) {\n    int n = Z.cols();\n    assert( n == Z.rows() && \"Matrix must be square.\");\n    MatrixXd C(2*n,2*n);\n    C << Z, MatrixXd::Identity(n,n), MatrixXd::Zero(n,2*n);\n    return C.exp().block(0,n,n,n);\n}\n\n// This function calculates a single step of the exponential Euler method, where y0 is the initial state, f and df are object with evaluation operators representing f and df, and h is the stepsize.\ntemplate <class Function, class Function2>\nVectorXd ExpEulStep(VectorXd y0, Function f, Function2 df, double h) {\n   return  y0 + h * phim( h * df(y0)) * f(y0);\n}\n\n// Test the exponential Euler method with the logistic ODE and determine the approximated order of algebraic convergence.\nint main() {\n    double T = 1;\n    VectorXd y0(1); y0 << 0.1;\n    auto f = [] (VectorXd y) {return y(0)*(1-y(0));};\n    auto df = [] (VectorXd y) {VectorXd dfy(1); dfy << 1-2*y(0); return dfy;};\n    double exactyT = y0(0)/(y0(0)+(1-y0(0))*exp(-T));\n    \n    vector<double> error(15);\n    \n    for (int j=0; j < 15; j++) {\n        int N = pow(2,j+1);\n        double h = T / N;\n        VectorXd y = y0;\n        for (int k=0; k < N; k++) y = ExpEulStep(y,f,df,h);\n        \n        error[j] = abs(y(0) - exactyT);\n        cout << left << setw(3) << setfill(' ') << \"N = \";\n        cout << left << setw(7) << setfill(' ') << N;\n        cout << left << setw(8) << setfill(' ') << \"Error = \";\n        cout << left << setw(13) << setfill(' ') << error[j];\n        if (j > 0)  cout << left << setw(10) << setfill(' ') << \"Approximated order = \" << log(error[j-1]/error[j])/log(2) <<endl;\n        else cout << endl;\n    }\n}", "meta": {"hexsha": "c7bff1eccd247f99d3c970eff189ed0fba05dc28", "size": 1940, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/PS13/solutions_ps13/ExpEul.cpp", "max_stars_repo_name": "valentinjacot/backupETHZ", "max_stars_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:21:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:21:30.000Z", "max_issues_repo_path": "Nummerical Methods for CSE/PS13/solutions_ps13/ExpEul.cpp", "max_issues_repo_name": "valentinjacot/backupETHZ", "max_issues_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Nummerical Methods for CSE/PS13/solutions_ps13/ExpEul.cpp", "max_forks_repo_name": "valentinjacot/backupETHZ", "max_forks_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.5918367347, "max_line_length": 197, "alphanum_fraction": 0.5902061856, "num_tokens": 583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342037088041, "lm_q2_score": 0.8705972700870909, "lm_q1q2_score": 0.8328431262208229}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n#include <cassert>\n\n/**\n * @brief Resolve given polynom at x value\n * \n * @param p \n * @param x \n * @return double \n */\ndouble evalPolynomial(const Eigen::VectorXd &p, const double x) {\n    double result = 0;\n    double power_x = 1;\n    for (unsigned int i = 0; i < p.size(); i++) {\n        result += p[i] * power_x;\n        power_x *= x;\n    }\n    return result;\n}\n\n/**\n * @brief Multiply given polynom by X at value power\n * \n * @param p \n * @param value \n * @return Eigen::VectorXd \n */\nEigen::VectorXd multiplyPolynomByX(const Eigen::VectorXd &p, const unsigned int value) {\n    Eigen::VectorXd result(p.size() + value);\n    for (unsigned int i = 0; i < value; i++) {\n        result[i] = 0;\n    }\n    for (unsigned int i = value; i < result.size(); i++) {\n        result[i] = p[i - value];\n    }\n    return result;\n}\n\n/**\n * @brief Multiply given polynom by given constant\n * \n * @param p \n * @param value \n * @return Eigen::VectorXd \n */\nEigen::VectorXd multiplyPolynomByConstant(Eigen::VectorXd p, const unsigned int value) {\n    for (unsigned int i = 0; i < p.size(); i++) {\n        p[i] *= value;\n    }\n    return p;\n}\n\n/**\n * @brief Substract p1 polynom by p2\n * \n * @param p1 \n * @param p2 \n * @return Eigen::VectorXd \n */\nEigen::VectorXd substractPolynoms(const Eigen::VectorXd& p1, const Eigen::VectorXd& p2) {\n    assert(p1.size() == p2.size() && \"To be substracted, polynoms must be same size\");\n    Eigen::VectorXd result(p1.size());\n    result[0] = -p2[0];\n    result[result.size() - 1] = p1[result.size() - 1];\n\n    for (unsigned int i = 1; i < result.size() - 1; i++) {\n        result[i] = p1[i] - p2[i];\n    }\n    return result;\n}\n\n/**\n * @brief Returns a polynom from its root values\n * \n * @param roots \n * @return Eigen::VectorXd \n */\nEigen::VectorXd polynomialFromRoots(const Eigen::VectorXd &roots) {\n    Eigen::VectorXd p = Eigen::VectorXd::Ones(roots.size() + 1);\n\n    // For the first root\n    p(0) = -roots(0);\n\n    // For the other roots\n    for (unsigned int i = 0; i < roots.size(); i++) {\n        for (unsigned int j = i; j > 0; j--) {\n            p(j) = p(j-1)-roots(i)*p(j);\n        }\n        p(0) *= -roots(i);\n    }\n\n    return p;\n}\n\n/**\n * @brief \n * \n * @param p - Polynom to solve\n * @return Eigen::VectorXd \n */\nEigen::VectorXd findRoots(const Eigen::VectorXd &p, unsigned int nbIter) {\n    Eigen::VectorXd pUnit = p / p(p.size() - 1);\n    Eigen::MatrixXd c = Eigen::MatrixXd::Zero(p.size() - 1, p.size() - 1);\n    c.bottomLeftCorner(c.rows() - 1, c.cols() - 1).setIdentity();\n    c.rightCols(1) = -pUnit.head(pUnit.size() - 1);\n\n    // Iterative solver\n    for (size_t i = 0; i < nbIter; i++) {\n        Eigen::HouseholderQR<Eigen::MatrixXd> qr(c);\n        Eigen::MatrixXd q = qr.householderQ();\n        Eigen::MatrixXd r = qr.matrixQR().triangularView<Eigen::Upper>();\n        c = r * q;\n    }\n    \n    return c.diagonal();\n}\n\n/**\n * @brief Returns the derivate of a polynom\n * \n * @param p \n * @return Eigen::VectorXd \n */\nEigen::VectorXd derivative(const Eigen::VectorXd& p) {\n    Eigen::VectorXd derivate(p.size() - 1);\n    for (unsigned int i = 0; i < derivate.size(); ++i) {\n        derivate(i) = (i + 1) * p(i + 1);\n    }\n    return derivate;\n}\n\n/**\n * @brief \n * \n * @param p \n * @param roots \n * @return Eigen::VectorXd \n */\nEigen::VectorXd rootsRafinement(const Eigen::VectorXd& p, Eigen::VectorXd roots, const unsigned int nbIter = 10) {\n    Eigen::VectorXd pDerivative = derivative(p);\n\n    for (unsigned int i = 0; i < roots.size(); i++) {\n        if (abs(roots(i)) > 0) {\n            for (unsigned int j = 0; j < nbIter; j++) {\n                roots(i) = roots(i) - ( evalPolynomial(p, roots(i)) / evalPolynomial(pDerivative, roots(i)) );\n            }\n        }\n    }\n    \n    return roots;\n}\n\nint main(int argc, char const *argv[]) {\n    Eigen::VectorXd myRoot(5);\n    myRoot << 1, 2, 2, 3, 4;\n    auto myPolynom = polynomialFromRoots(myRoot);\n\n    auto foundRoot = findRoots(myPolynom, 10);\n    auto foundRootRaf = rootsRafinement(myPolynom, foundRoot, 50);\n\n    std::cout << foundRootRaf << std::endl;\n    return 0;\n}\n", "meta": {"hexsha": "06f38b760eba6b5de4ffbecf4137399500d1df6c", "size": 4119, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/semestre-3/maths-10/main.cpp", "max_stars_repo_name": "guillaume-haerinck/imac-c", "max_stars_repo_head_hexsha": "2d88de90acdb546479c4e310528e786358e66bd7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/semestre-3/maths-10/main.cpp", "max_issues_repo_name": "guillaume-haerinck/imac-c", "max_issues_repo_head_hexsha": "2d88de90acdb546479c4e310528e786358e66bd7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/semestre-3/maths-10/main.cpp", "max_forks_repo_name": "guillaume-haerinck/imac-c", "max_forks_repo_head_hexsha": "2d88de90acdb546479c4e310528e786358e66bd7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9636363636, "max_line_length": 114, "alphanum_fraction": 0.575139597, "num_tokens": 1232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109770159683, "lm_q2_score": 0.8757869867849167, "lm_q1q2_score": 0.8323575657681237}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include <vector>\n\nvoid choleskyDecompositionExample()\n{\n/*\nPositive-definite matrix:\n    Matrix Mnxn is said to be positive definite if the scalar zTMz is strictly positive for every non-zero\n    column vector z n real numbers. zTMz>0\n\n\nHermitian matrix:\n    Matrix Mnxn is said to be positive definite if the scalar z*Mz is strictly positive for every non-zero\n    column vector z n real numbers. z*Mz>0\n    z* is the conjugate transpose of z.\n\nPositive semi-definite same as above except zTMz>=0 or  z*Mz>=0\n\n\n    Example:\n            \u250c2  -1  0\u2510\n        M=  |-1  2 -1|\n            |0 - 1  2|\n            \u2514        \u2518\n          \u250c a \u2510\n        z=| b |\n          | c |\n          \u2514   \u2518\n        zTMz=a^2 +c^2+ (a-b)^2+ (b-c)^2\n\nCholesky decomposition:\nCholesky decomposition of a Hermitian positive-definite matrix A is:\n    A=LL*\n\n    L is a lower triangular matrix with real and positive diagonal entries\n    L* is the conjugate transpose of L\n*/\n\n    Eigen::MatrixXd A(3,3);\n    A << 6, 0, 0, 0, 4, 0, 0, 0, 7;\n    Eigen::MatrixXd L( A.llt().matrixL() );\n    Eigen::MatrixXd L_T=L.adjoint();//conjugate transpose\n\n    std::cout << \"L\" << std::endl;\n    std::cout << L << std::endl;\n    std::cout << \"L_T\" << std::endl;\n    std::cout << L_T << std::endl;\n    std::cout << \"A\" << std::endl;\n    std::cout << A << std::endl;\n    std::cout << \"L*L_T\" << std::endl;\n    std::cout << L*L_T << std::endl;\n\n}\n\n\nvoid qRDecomposition(Eigen::MatrixXd &A,Eigen::MatrixXd &Q, Eigen::MatrixXd &R)\n{\n    /*\n        A=QR\n        Q: is orthogonal matrix-> columns of Q are orthonormal\n        R: is upper triangulate matrix\n        this is possible when columns of A are linearly indipendent\n    */\n\n    Eigen::MatrixXd thinQ(A.rows(),A.cols() ), q(A.rows(),A.rows());\n\n    Eigen::HouseholderQR<Eigen::MatrixXd> householderQR(A);\n    q = householderQR.householderQ();\n    thinQ.setIdentity();\n    Q = householderQR.householderQ() * thinQ;\n    R=Q.transpose()*A;\n}\n\nvoid qRExample()\n{\n\n    Eigen::MatrixXd A;\n    A.setRandom(3,4);\n\n    std::cout<<\"A\" <<std::endl;\n    std::cout<<A <<std::endl;\n    Eigen::MatrixXd Q(A.rows(),A.rows());\n    Eigen::MatrixXd R(A.rows(),A.cols());\n\n    /////////////////////////////////HouseholderQR////////////////////////\n    Eigen::MatrixXd thinQ(A.rows(),A.cols() ), q(A.rows(),A.rows());\n\n    Eigen::HouseholderQR<Eigen::MatrixXd> householderQR(A);\n    q = householderQR.householderQ();\n    thinQ.setIdentity();\n    Q = householderQR.householderQ() * thinQ;\n\n    std::cout << \"HouseholderQR\" <<std::endl;\n\n    std::cout << \"Q\" <<std::endl;\n    std::cout << Q <<std::endl;\n\n    R = householderQR.matrixQR().template  triangularView<Eigen::Upper>();\n    std::cout << R<<std::endl;\n    std::cout << R.rows()<<std::endl;\n    std::cout << R.cols()<<std::endl;\n\n\n    R=Q.transpose()*A;\n// \tstd::cout << \"R\" <<std::endl;\n// \tstd::cout << R<<std::endl;\n\n    std::cout << \"A-Q*R\" <<std::endl;\n    std::cout << A-Q*R <<std::endl;\n\n    /////////////////////////////////ColPivHouseholderQR////////////////////////\n    Eigen::ColPivHouseholderQR<Eigen::MatrixXd> colPivHouseholderQR(A.rows(), A.cols());\n    colPivHouseholderQR.compute(A);\n    //R = colPivHouseholderQR.matrixR().template triangularView<Upper>();\n    R = colPivHouseholderQR.matrixR();\n    Q = colPivHouseholderQR.matrixQ();\n\n    std::cout << \"ColPivHouseholderQR\" <<std::endl;\n\n    std::cout << \"Q\" <<std::endl;\n    std::cout << Q <<std::endl;\n\n    std::cout << \"R\" <<std::endl;\n    std::cout << R <<std::endl;\n\n    std::cout << \"A-Q*R\" <<std::endl;\n    std::cout << A-Q*R <<std::endl;\n\n    /////////////////////////////////FullPivHouseholderQR////////////////////////\n    std::cout << \"FullPivHouseholderQR\" <<std::endl;\n\n    Eigen::FullPivHouseholderQR<Eigen::MatrixXd> fullPivHouseholderQR(A.rows(), A.cols());\n    fullPivHouseholderQR.compute(A);\n    Q=fullPivHouseholderQR.matrixQ();\n    R=fullPivHouseholderQR.matrixQR().template  triangularView<Eigen::Upper>();\n\n    std::cout << \"Q\" <<std::endl;\n    std::cout << Q <<std::endl;\n\n    std::cout << \"R\" <<std::endl;\n    std::cout << R <<std::endl;\n\n    std::cout << \"A-Q*R\" <<std::endl;\n    std::cout << A-Q*R <<std::endl;\n\n}\n\nvoid lDUDecomposition()\n{\n/*\n\n    L: lower triangular matrix L\n    U: upper triangular matrix U\n    D: is a diagonal matrix\n    A=LDU\n\n\n*/\n}\n\nvoid lUDecomposition()\n{\n/*\n    L: lower triangular matrix L\n    U: upper triangular matrix U\n    A=LU\n*/\n}\n\n/*\nfunction [U]=gramschmidt(V)\n[n,k] = size(V);\nU = zeros(n,k);\nU(:,1) = V(:,1)/norm(V(:,1));\nfor i = 2:k\n    U(:,i)=V(:,i);\n    for j=1:i-1\n        U(:,i)=U(:,i)-(U(:,j)'*U(:,i) )/(norm(U(:,j)))^2 * U(:,j);\n    end\n    U(:,i) = U(:,i)/norm(U(:,i));\nend\nend\n\n*/\n\nvoid householderTransformation()\n{\n\n}\n//http://eigen.tuxfamily.org/dox/group__DenseDecompositionBenchmark.html\n\n\nvoid denseDecompositions()\n{\n    //LLT\n    //LDLT\n    //PartialPivLU\n    //FullPivLU\n    //HouseholderQR\n    //ColPivHouseholderQR\n    //CompleteOrthogonalDecomposition\n    //FullPivHouseholderQR\n    //JacobiSVD\n    //BDCSVD\n}\nint main()\n{\n\n}\n\n", "meta": {"hexsha": "405c87df49399a27ce90352d90334156d61699fb", "size": 5066, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/matrix_decomposition.cpp", "max_stars_repo_name": "behnamasadi/Mastering_Eigen", "max_stars_repo_head_hexsha": "99edbc819c89a4805b777eef69044a1658d96206", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/matrix_decomposition.cpp", "max_issues_repo_name": "behnamasadi/Mastering_Eigen", "max_issues_repo_head_hexsha": "99edbc819c89a4805b777eef69044a1658d96206", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/matrix_decomposition.cpp", "max_forks_repo_name": "behnamasadi/Mastering_Eigen", "max_forks_repo_head_hexsha": "99edbc819c89a4805b777eef69044a1658d96206", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8962264151, "max_line_length": 106, "alphanum_fraction": 0.572641137, "num_tokens": 1572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133447766224, "lm_q2_score": 0.8840392802184581, "lm_q1q2_score": 0.8309203167840487}}
{"text": "#include <Eigen/Core>\n#include <iostream>\n#include <LBFGSB.h>\n\nusing namespace LBFGSpp;\n\ntypedef double Scalar;\ntypedef Eigen::Matrix<Scalar, Eigen::Dynamic, 1> Vector;\n\n// Example from the roptim R package\n// f(x) = (x[0] - 1)^2 + 4 * (x[1] - x[0]^2)^2 + ... + 4 * (x[end] - x[end - 1]^2)^2\nclass Rosenbrock\n{\nprivate:\n    int n;\npublic:\n    Rosenbrock(int n_) : n(n_) {}\n    Scalar operator()(const Vector& x, Vector& grad)\n    {\n        Scalar fx = (x[0] - 1.0) * (x[0] - 1.0);\n        grad[0] = 2 * (x[0] - 1) + 16 * (x[0] * x[0] - x[1]) * x[0];\n        for(int i = 1; i < n; i++)\n        {\n            fx += 4 * std::pow(x[i] - x[i - 1] * x[i - 1], 2);\n            if(i == n - 1)\n            {\n                grad[i] = 8 * (x[i] - x[i - 1] * x[i - 1]);\n            } else {\n                grad[i] = 8 * (x[i] - x[i - 1] * x[i - 1]) + 16 * (x[i] * x[i] - x[i + 1]) * x[i];\n            }\n        }\n        return fx;\n    }\n};\n\nint main()\n{\n    const int n = 25;\n    LBFGSBParam<Scalar> param;\n    LBFGSBSolver<Scalar> solver(param);\n    Rosenbrock fun(n);\n\n    // Variable bounds\n    Vector lb = Vector::Constant(n, 2.0);\n    Vector ub = Vector::Constant(n, 4.0);\n    // The third variable is unbounded\n    lb[2] = -std::numeric_limits<Scalar>::infinity();\n    ub[2] = std::numeric_limits<Scalar>::infinity();\n    // Initial values\n    Vector x = Vector::Constant(n, 3.0);\n    // Make some initial values at the bounds\n    x[0] = x[1] = 2.0;\n    x[5] = x[7] = 4.0;\n\n    Scalar fx;\n    int niter = solver.minimize(fun, x, fx, lb, ub);\n\n    std::cout << niter << \" iterations\" << std::endl;\n    std::cout << \"x = \\n\" << x.transpose() << std::endl;\n    std::cout << \"f(x) = \" << fx << std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "d5d1e53c6aa45aa4f4e8af3eb6d712758a24835f", "size": 1715, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/example-rosenbrock-box.cpp", "max_stars_repo_name": "mpayrits/LBFGSpp", "max_stars_repo_head_hexsha": "b28f6969787b748cd32acfc8e6c684e6d00b5b9f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 335.0, "max_stars_repo_stars_event_min_datetime": "2016-08-05T06:18:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T06:30:01.000Z", "max_issues_repo_path": "examples/example-rosenbrock-box.cpp", "max_issues_repo_name": "mpayrits/LBFGSpp", "max_issues_repo_head_hexsha": "b28f6969787b748cd32acfc8e6c684e6d00b5b9f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 24.0, "max_issues_repo_issues_event_min_datetime": "2017-06-24T18:51:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T04:42:49.000Z", "max_forks_repo_path": "examples/example-rosenbrock-box.cpp", "max_forks_repo_name": "mpayrits/LBFGSpp", "max_forks_repo_head_hexsha": "b28f6969787b748cd32acfc8e6c684e6d00b5b9f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 82.0, "max_forks_repo_forks_event_min_datetime": "2016-08-26T22:11:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T16:25:55.000Z", "avg_line_length": 26.796875, "max_line_length": 98, "alphanum_fraction": 0.4839650146, "num_tokens": 614, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813526452771, "lm_q2_score": 0.8688267864276108, "lm_q1q2_score": 0.8305822065035167}}
{"text": "//#include <DES.h>\n#include <NTL/ZZ.h>\n#include <RSA.h>\n#include <X917.h>\n#include <fstream>\n#include <json.hpp>\n#include <random>\n#include <sstream>\n#include <string>\nusing nlohmann::json;\nusing namespace NTL;\nusing namespace std;\nnamespace RSA {\ntemplate <typename T> string tostr(T t) {\n\tstringstream buf;\n\tbuf << t;\n\treturn buf.str();\n}\nZZ atozz(string in) {\n\tZZ zz;\n\tstringstream buf(in);\n\tbuf >> zz;\n\treturn zz;\n}\nbool is_Prime(const ZZ &n, long t) {\n\tif (n <= 1)\n\t\treturn 0;\n\t// first, perform trial division by primes up to 2000\n\tPrimeSeq s; // a class for quickly generating primes in sequence\n\tlong p;\n\tp = s.next(); // first prime is always 2\n\twhile (p && p < 2000) {\n\t\tif ((n % p) == 0)\n\t\t\treturn (n == p);\n\t\tp = s.next();\n\t}\n\t// second, perform t Miller-Rabin tests\n\tZZ x;\n\tint i;\n\tfor (i = 0; i < t; i++) {\n\t\tx = RandomBnd(n); // random number between 0 and n-1\n\t\tif (MillerWitness(n, x))\n\t\t\treturn 0;\n\t}\n\treturn 1;\n}\n\nZZ getPrime(int bits) {\n\tZZ prim;\n\twhile (1) {\n\t\tprim = X917rand(bitset<64>(rand()), bits / 64);\n\t\tif (is_Prime(prim, bits))\n\t\t\tbreak;\n\t}\n\treturn prim;\n}\nvoid savePrivateKey(privateKey const &key, std::string const &file) {\n\tjson keyJson;\n\tkeyJson[\"p\"] = tostr(key.p);\n\tkeyJson[\"q\"] = tostr(key.q);\n\tkeyJson[\"d\"] = tostr(key.d);\n\tofstream out(file, ios::out);\n\tout << keyJson.dump();\n\tout.close();\n\treturn;\n}\nvoid savePublicKey(publicKey const &key, std::string const &file) {\n\tjson keyJson;\n\tkeyJson[\"n\"] = tostr(key.n);\n\tkeyJson[\"e\"] = tostr(key.e);\n\tofstream out(file, ios::out);\n\tout << keyJson.dump();\n\tout.close();\n\treturn;\n}\nint loadPrivateKey(privateKey &priK, std::string const &file) {\n\ttry {\n\t\tjson keyJson;\n\t\tifstream in(file, ios::in);\n\t\tin >> keyJson;\n\t\tin.close();\n\t\tpriK.d = atozz(keyJson[\"d\"].get<string>());\n\t\tpriK.p = atozz(keyJson[\"p\"].get<string>());\n\t\tpriK.q = atozz(keyJson[\"q\"].get<string>());\n\t} catch (exception const &e) {\n\t\treturn 1;\n\t}\n\treturn 0;\n}\nint loadPublicKey(publicKey &pubK, std::string const &file) {\n\ttry {\n\t\tjson keyJson;\n\t\tifstream in(file, ios::in);\n\t\tin >> keyJson;\n\t\tin.close();\n\t\tpubK.e = atozz(keyJson[\"e\"].get<string>());\n\t\tpubK.n = atozz(keyJson[\"n\"].get<string>());\n\t} catch (exception const &e) {\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n\nvoid makeKey(privateKey &priK, publicKey &pubK, int bits) {\n\tZZ &p = priK.p, &q = priK.q, &n = pubK.n, &d = priK.d, &e = pubK.e;\n\t// p\n\tp = getPrime(bits);\n\t// q\n\tq = getPrime(bits);\n\t// n\n\tn = priK.p * priK.q;\n\t// e,d\n\tZZ phyN = (p - 1) * (q - 1);\n\twhile (1) {\n\t\te = RandomBnd(phyN);\n\t\tif (InvModStatus(d, e, phyN) == 0)\n\t\t\tbreak;\n\t}\n\treturn;\n}\nZZ encipher(NTL::ZZ data, publicKey const &key) {\n\treturn PowerMod(data, key.e, key.n);\n}\nZZ decipher(NTL::ZZ data, privateKey const &key) {\n\treturn PowerMod(data, key.d, key.p * key.q);\n}\n} // namespace RSA", "meta": {"hexsha": "434f1a8900f97eee5327d2e516083626ff1d3c41", "size": 2763, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/RSA.cpp", "max_stars_repo_name": "EUye9IM/Block_cipher", "max_stars_repo_head_hexsha": "6527330ceb6d92ca3f9a7069a449bca850de329d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/RSA.cpp", "max_issues_repo_name": "EUye9IM/Block_cipher", "max_issues_repo_head_hexsha": "6527330ceb6d92ca3f9a7069a449bca850de329d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/RSA.cpp", "max_forks_repo_name": "EUye9IM/Block_cipher", "max_forks_repo_head_hexsha": "6527330ceb6d92ca3f9a7069a449bca850de329d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.7559055118, "max_line_length": 69, "alphanum_fraction": 0.6188925081, "num_tokens": 918, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731158685837, "lm_q2_score": 0.8615382094310357, "lm_q1q2_score": 0.8293796725128155}}
{"text": "#include <Eigen/Dense>\n#include <unsupported/Eigen/MatrixFunctions>\n#include <iostream>\n#include <vector>\n#include <iomanip>\n\nusing namespace Eigen;\nusing namespace std;\n\n// This C++ function phim gives the function phi used for the construction of the exponential Euler single step method for an autonomous ODE.\nMatrixXd  phim(MatrixXd Z) {\n    int n = Z.cols();\n    assert( n == Z.rows() && \"Matrix must be square.\");\n    MatrixXd C(2*n,2*n);\n    C << Z, MatrixXd::Identity(n,n), MatrixXd::Zero(n,2*n);\n    return C.exp().block(0,n,n,n);\n}\n\n// This function calculates a single step of the exponential Euler method, where y0 is the initial state, f and df are object with evaluation operators representing f and df, and h is the stepsize.\ntemplate <class Function, class Function2>\nVectorXd ExpEulStep(VectorXd y0, Function f, Function2 df, double h) {\n   // TODO\n}\n\n// Test the exponential Euler method with the logistic ODE and determine the approximated order of algebraic convergence.\nint main() {\n    // TODO\n}", "meta": {"hexsha": "66a96953c9f762e25b81fb2cd40c2358b31d0c25", "size": 1017, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/PS13/templates_ps13/ExpEul_template.cpp", "max_stars_repo_name": "valentinjacot/backupETHZ", "max_stars_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:21:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:21:30.000Z", "max_issues_repo_path": "Nummerical Methods for CSE/PS13/templates_ps13/ExpEul_template.cpp", "max_issues_repo_name": "valentinjacot/backupETHZ", "max_issues_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Nummerical Methods for CSE/PS13/templates_ps13/ExpEul_template.cpp", "max_forks_repo_name": "valentinjacot/backupETHZ", "max_forks_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.3214285714, "max_line_length": 197, "alphanum_fraction": 0.7236971485, "num_tokens": 246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.962673111584966, "lm_q2_score": 0.8615382040983515, "lm_q1q2_score": 0.8293796636886835}}
{"text": "// haversine.cpp\n//\n// Haversine Formula Implementation\n//\n// The Haversine formula can be used to compute an estimated distance between \n// two points on a sphere. This program provides the ability to compute an \n// estimated distance between two points on the Earth from their respective \n// latitudes and longitudes.\n//\n// This implementation assumes that the Earth is a perfect sphere, with a \n// radius of 6378 km (3963 miles)\n\n#include <iostream>\n#include <iomanip>\n#include <cstdio>\n#include <boost/math/constants/constants.hpp>\n\nint main(int argc, char* argv[]) {\n\n\t// Validate usage\n\tif (argc != 5) {\n\t\tstd::cout << \"Usage: haversine lat1 lon1 lat2 lon2\" << std::endl;\n\t\treturn -1;\n\t}\n\n\tdouble lat_1_deg, lon_1_deg, lat_2_deg, lon_2_deg;\n\tsscanf(argv[1], \"%lf\", &lat_1_deg);\n\tsscanf(argv[2], \"%lf\", &lon_1_deg);\n\tsscanf(argv[3], \"%lf\", &lat_2_deg);\n\tsscanf(argv[4], \"%lf\", &lon_2_deg);\n\t\n\tstd::cout << \"Calculating distance between (\"\n\t\t\t  << std::setprecision(9) << lat_1_deg << \",\" \n\t\t\t  << std::setprecision(9) << lon_1_deg << \")\" << \" and (\"\n\t\t\t  << std::setprecision(9) << lat_2_deg << \",\" \n\t\t\t  << std::setprecision(9) << lon_2_deg << \")\" << std::endl;\n\t\n\t// Convert coordinates to radians (rad = deg * (pi / 2))\n\tdouble lat_1_rad, lon_1_rad, lat_2_rad, lon_2_rad;\n\tlat_1_rad = lat_1_deg * (boost::math::constants::pi<double>() / 180);\n\tlon_1_rad = lon_1_deg * (boost::math::constants::pi<double>() / 180);\n\tlat_2_rad = lat_2_deg * (boost::math::constants::pi<double>() / 180);\n\tlon_2_rad = lon_2_deg * (boost::math::constants::pi<double>() / 180);\n\n\t// Determine latitude and longitude deltas\n\tdouble delta_lat, delta_lon;\n\tdelta_lat = lat_1_rad - lat_2_rad;\n\tdelta_lon = lon_1_rad - lon_2_rad;\n\n\t// Calculate sin^2 (delta / 2) for both lat and long\n\tdouble sdlat = pow(sin(delta_lat / 2), 2);\n\tdouble sdlon = pow(sin(delta_lon / 2), 2);\n\n\t// Radius of the Earth (approximate)\n\tconst double radius_earth_miles = 3963;\n\tconst double radius_earth_km = 6378;\n\n\t// http://en.wikipedia/org/wiki/Haversine_formula\n\t// d=2r*asin(sqrt(sin^2((lat1-lat2)/2)+cos(l1)cos(l2)sin^2((lon2-lon1)/2)))\n\t//  if t = sqrt(sin^2((lat1-lat2)/2)+cos(l1)cos(l2)sin^2((lon2-lon1)/2)\n\t//  -> d = 2 * radius_earth * asin (t)\t\n\tdouble t = sqrt(sdlat + (cos(lat_1_rad) * cos(lat_2_rad) * sdlon));\n\tdouble distance_miles = 2 * radius_earth_miles * asin(t);\n\tdouble distance_km = 2 * radius_earth_km * asin(t);\n\n\t// Output results\n\tstd::cout << \"Distance: \" << std::endl;\n\tstd::cout << \"  \" << std::setprecision(4) << distance_miles \n\t\t\t\t\t  << \" miles\" << std::endl;\n\tstd::cout << \"  \" << std::setprecision(4) << distance_km \n\t\t\t\t\t  << \" kilometers\" << std::endl;\n\t\n\treturn 0;\n}\n", "meta": {"hexsha": "57da2d2331267a32b4a6ec27a890ab5e342838df", "size": 2664, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "haversine.cpp", "max_stars_repo_name": "stuartthompson/Haversine", "max_stars_repo_head_hexsha": "dd20ea283e476b85926e51165bf8be9a1144704e", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-05T07:11:06.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-05T07:11:06.000Z", "max_issues_repo_path": "haversine.cpp", "max_issues_repo_name": "stuartthompson/Haversine", "max_issues_repo_head_hexsha": "dd20ea283e476b85926e51165bf8be9a1144704e", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "haversine.cpp", "max_forks_repo_name": "stuartthompson/Haversine", "max_forks_repo_head_hexsha": "dd20ea283e476b85926e51165bf8be9a1144704e", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.52, "max_line_length": 78, "alphanum_fraction": 0.6572822823, "num_tokens": 852, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960361158630024, "lm_q2_score": 0.8615382076534743, "lm_q1q2_score": 0.8273878313061248}}
{"text": "// Copyright Nick Thompson 2017.\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <iostream>\n#include <string>\n#include <boost/math/constants/constants.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#include <boost/math/special_functions/legendre_stieltjes.hpp>\n\nusing boost::math::legendre_p;\nusing boost::math::legendre_p_zeros;\nusing boost::math::legendre_p_prime;\nusing boost::math::legendre_stieltjes;\nusing boost::multiprecision::cpp_bin_float_quad;\nusing boost::multiprecision::cpp_bin_float_100;\n\ntemplate<class Real>\nvoid gauss_konrod_rule(size_t order)\n{\n    std::cout << std::setprecision(std::numeric_limits<Real>::digits10);\n    std::cout << std::fixed;\n    auto gauss_nodes = boost::math::legendre_p_zeros<Real>(order);\n    auto E = legendre_stieltjes<Real>(order + 1);\n    std::vector<Real> gauss_weights(gauss_nodes.size(), std::numeric_limits<Real>::quiet_NaN());\n    std::vector<Real> gauss_konrod_weights(gauss_nodes.size(), std::numeric_limits<Real>::quiet_NaN());\n    for (size_t i = 0; i < gauss_nodes.size(); ++i)\n    {\n        Real node = gauss_nodes[i];\n        Real lp = legendre_p_prime<Real>(order, node);\n        gauss_weights[i] = 2/( (1-node*node)*lp*lp);\n        // P_n(x) = (2n)!/(2^n (n!)^2) pi_n(x), where pi_n is the monic Legendre polynomial.\n        gauss_konrod_weights[i] = gauss_weights[i] + static_cast<Real>(2)/(static_cast<Real>(order+1)*legendre_p_prime(order, node)*E(node));\n    }\n\n    std::cout << \"Gauss Nodes:\\n\";\n    for (auto const & node : gauss_nodes)\n    {\n        std::cout << node << \"\\n\";\n    }\n\n    std::cout << \"Gauss Weights:\\n\";\n    for (auto const & weight : gauss_weights)\n    {\n        std::cout << weight << \"\\n\";\n    }\n\n    std::cout << \"Gauss-Konrod weights: \\n\";\n    for (auto const & w : gauss_konrod_weights)\n    {\n        std::cout << w << \"\\n\";\n    }\n\n    auto konrod_nodes = E.zeros();\n    std::vector<Real> konrod_weights(konrod_nodes.size());\n    for (size_t i = 0; i < konrod_weights.size(); ++i)\n    {\n        Real node = konrod_nodes[i];\n        konrod_weights[i] = static_cast<Real>(2)/(static_cast<Real>(order+1)*legendre_p(order, node)*E.prime(node));\n    }\n\n    std::cout << \"Konrod nodes:\\n\";\n    for (auto node : konrod_nodes)\n    {\n        std::cout << node << \"\\n\";\n    }\n\n    std::cout << \"Konrod weights: \\n\";\n    for (auto const & w : gauss_konrod_weights)\n    {\n        std::cout << w << \"\\n\";\n    }\n\n}\n\nint main()\n{\n    std::cout << \"Gauss-Konrod 7-15 Rule:\\n\";\n    gauss_konrod_rule<cpp_bin_float_100>(7);\n\n    std::cout << \"\\n\\nGauss-Konrod 10-21 Rule:\\n\";\n    gauss_konrod_rule<cpp_bin_float_100>(10);\n\n    std::cout << \"\\n\\nGauss-Konrod 15-31 Rule:\\n\";\n    gauss_konrod_rule<cpp_bin_float_100>(15);\n\n    std::cout << \"\\n\\nGauss-Konrod 20-41 Rule:\\n\";\n    gauss_konrod_rule<cpp_bin_float_100>(20);\n\n    std::cout << \"\\n\\nGauss-Konrod 25-51 Rule:\\n\";\n    gauss_konrod_rule<cpp_bin_float_100>(25);\n\n    std::cout << \"\\n\\nGauss-Konrod 30-61 Rule:\\n\";\n    gauss_konrod_rule<cpp_bin_float_100>(30);\n\n}\n", "meta": {"hexsha": "ab92e68c4f03e71cfbbaf14e064aca4278dcc8e2", "size": 3152, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "androidboost/src/main/cpp/libs/math/example/legendre_stieltjes_example.cpp", "max_stars_repo_name": "playbar/AndroidUtils", "max_stars_repo_head_hexsha": "07612848773ad8153fec1a8e4c4b48c56f39b092", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-07-21T17:14:35.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-21T17:14:35.000Z", "max_issues_repo_path": "androidboost/src/main/cpp/libs/math/example/legendre_stieltjes_example.cpp", "max_issues_repo_name": "playbar/AndroidUtils", "max_issues_repo_head_hexsha": "07612848773ad8153fec1a8e4c4b48c56f39b092", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "androidboost/src/main/cpp/libs/math/example/legendre_stieltjes_example.cpp", "max_forks_repo_name": "playbar/AndroidUtils", "max_forks_repo_head_hexsha": "07612848773ad8153fec1a8e4c4b48c56f39b092", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-07-23T00:40:29.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-23T00:40:29.000Z", "avg_line_length": 31.8383838384, "max_line_length": 141, "alphanum_fraction": 0.6465736041, "num_tokens": 934, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214491222695, "lm_q2_score": 0.8577680977182187, "lm_q1q2_score": 0.8271641750024851}}
{"text": "// Solution: https://www.techiedelight.com/probability-alive-after-taking-n-steps-island/\n\n#include <iostream>\n#include <unordered_map>\n#include <unordered_set>\n#include <map>\n#include <set>\n#include <string>\n//#include <boost/functional/hash.hpp>\n\nusing namespace std;\n\n#define N 3\n\n// Find the probability that person is alive after he walks n steps\n// from location (x, y) on the island\ndouble aliveProbability( int x, int y, int steps_left, unordered_map<string, double>& dp )\n{\n    // base case\n    if ( steps_left == 0 )\n        return 1.0;\n  \n    // calculate unique map key from current coordinates(x, y) of person\n    // and number of steps(n) left\n    string key = to_string( x ) + \"|\" + to_string( y ) + \"|\" + to_string( steps_left );\n    //\"0|0|4\" -> [0;1]\n\n    // if sub-problem is seen for the first time\n    if ( dp.find( key ) == dp.end() )\n    {\n        double p = 0.0;\n\n        // move one step up\n        if ( y > 0 )\n            p += 0.25 * aliveProbability( x, y - 1, steps_left - 1, dp );\n\n        // move one step down\n        if ( y < N - 1 )\n            p += 0.25 * aliveProbability( x, y + 1, steps_left - 1, dp );\n\n        // move one step left\n        if ( x > 0 )\n            p += 0.25 * aliveProbability( x - 1, y, steps_left - 1, dp );\n\n        // move one step right\n        if ( x < N - 1 )\n            p += 0.25 * aliveProbability( x + 1, y, steps_left - 1, dp );\n\n        dp[ key ] = p;\n    }\n\n    return dp[ key ];\n}\n\nstruct Cell\n{\n    int x, y, n;\n};\n\nbool operator==( const Cell& lhs, const Cell& rhs )\n{\n    return lhs.x == rhs.x && lhs.y == rhs.y && lhs.n == rhs.n;\n}\n\nstruct MyHash\n{\n    std::size_t operator()( const Cell& cell ) const noexcept\n    {\n        std::cout << \"Using MyHash\" << std::endl;\n        std::hash<int> XHash;\n        std::size_t h1 = XHash(cell.x);\n        std::size_t h2 = std::hash<int>{}(cell.y);\n        std::size_t h3 = std::hash<int>{}(cell.n);\n        return h1 ^ (h2 << 1) ^ (h3 << 2); // or use boost::hash_combine\n    }\n};\n\n// custom specialization of std::hash can be injected in namespace std\nnamespace std\n{\n    template<> \n    struct hash<Cell>\n    {\n        std::size_t operator()( const Cell& cell) const noexcept\n        {\n            std::size_t h1 = std::hash<int>{}(cell.x);\n            std::size_t h2 = std::hash<int>{}(cell.y);\n            std::size_t h3 = std::hash<int>{}(cell.n);\n            return h1 ^ (h2 << 1) ^ (h3 << 2); // or use boost::hash_combine\n\n            //size_t seed = 0;\n            //hash_combine( seed, cell.x );\n            //hash_combine( seed, cell.y );\n            //hash_combine( seed, cell.steps_left );\n            //return seed;\n        }\n    };\n}\n\nstruct Cell1\n{\n    int x, y, n;\n\n    bool operator==( const Cell& rhs )\n    {\n        return x == rhs.x && y == rhs.y && n == rhs.n;\n    }\n\n    struct Hash\n    {\n        size_t operator()( const Cell& cell ) const noexcept\n        {\n            std::hash<int> XHash;\n            std::size_t h1 = XHash( cell.x );\n            std::size_t h2 = std::hash<int> {}( cell.y );\n            std::size_t h3 = std::hash<int> {}( cell.n );\n            return h1 ^ ( h2 << 1 ) ^ ( h3 << 2 ); // or use boost::hash_combine\n        }\n    };\n};\n\ndouble aliveProbability( int x, int y, int n, unordered_map<Cell1, double, Cell1::Hash>& dp )\n{\n    // base case\n    if ( n == 0 )\n        return 1.0;\n\n    // calculate unique map key from current coordinates(x, y) of person\n    // and number of steps(n) left\n    Cell1 key = { x, y, n };\n\n    // if sub-problem is seen for the first time\n    if ( dp.find( key ) == dp.end() )\n    {\n        double p = 0.0;\n\n        // move one step up\n        if ( y > 0 )\n            p += 0.25 * aliveProbability( x, y - 1, n - 1, dp );\n\n        // move one step down\n        if ( y < N - 1 )\n            p += 0.25 * aliveProbability( x, y + 1, n - 1, dp );\n\n        // move one step left\n        if ( x > 0 )\n            p += 0.25 * aliveProbability( x - 1, y, n - 1, dp );\n\n        // move one step right\n        if ( x < N - 1 )\n            p += 0.25 * aliveProbability( x + 1, y, n - 1, dp );\n\n        dp[ key ] = p;\n    }\n\n    return dp[ key ];\n}\n\nint main()\n{\n    int n = 4;        // number of steps to be taken\n    int x = 0, y = 0; // starting coordinates\n\n    // map to store solution to already computed sub-problems\n    //unordered_map<string, double> dp; // with key 'string'\n    unordered_map<Cell1, double, Cell1::Hash> dp; // with key 'Cell1' and hash function Cell1::Hash\n    //unordered_map<Cell, double> dp; // with key 'Cell' and hash function that is injected in namespace std \n\n    // calculate alive Probability\n    cout << \"Alive probability is \" << aliveProbability(x, y, n, dp);\n\n    return 0;\n}", "meta": {"hexsha": "666567c116078e536491037e29b48d6640e43390", "size": 4703, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "exercises/2&4/Data Structures/HashTables/Practice/aliveProbability.cpp", "max_stars_repo_name": "VGeorgiev1/SDP20-21", "max_stars_repo_head_hexsha": "23e11b6041d35cec779cefbcc219ca9b76a6ff3f", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-10-05T09:32:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T07:58:12.000Z", "max_issues_repo_path": "exercises/2&4/Data Structures/HashTables/Practice/aliveProbability.cpp", "max_issues_repo_name": "VGeorgiev1/SDP20-21", "max_issues_repo_head_hexsha": "23e11b6041d35cec779cefbcc219ca9b76a6ff3f", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-11-16T20:41:04.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-15T11:10:20.000Z", "max_forks_repo_path": "exercises/2&4/Data Structures/HashTables/Practice/aliveProbability.cpp", "max_forks_repo_name": "peshe/SDP20-21", "max_forks_repo_head_hexsha": "af298e723c2934036048b26b168f8f8607fcec40", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-10-09T15:46:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-12T17:47:11.000Z", "avg_line_length": 27.1849710983, "max_line_length": 109, "alphanum_fraction": 0.5273229853, "num_tokens": 1390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107984180243, "lm_q2_score": 0.8824278772763471, "lm_q1q2_score": 0.8270209354084876}}
{"text": "/**\n * @file finitevolumesineconslaw.cc\n * @brief NPDE homework \"FiniteVolumeSineConsLaw\" code\n * @author Oliver Rietmann\n * @date 25.04.2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"finitevolumesineconslaw.h\"\n\n#include <Eigen/Core>\n#include <cmath>\n\nnamespace FiniteVolumeSineConsLaw {\n\n/* SAM_LISTING_BEGIN_1 */\nconstexpr double PI = 3.14159265358979323846;\n\ndouble f(double x) { return std::sin(PI * x); }\n\ndouble sineGodFlux(double v, double w) {\n  double result;\n  // Rankine-Hugoniot speed. No safeguards against cancellation are taken. For v\n  // close to w the result will severely be affected by amplified round-off\n  // error. However, this does not do any harm, because we are interested in the\n  // the sign alone.\n  double s = (v != w) ? (f(w) - f(v)) / (w - v) : PI * std::cos(PI * v);\n  // Treat all different cases separately\n  if (((v < w) && (s > 0.0)) || ((v >= w) && (std::cos(PI * v) > 0.0))) {\n    result = f(v);\n  } else if (((v < w) && (s < 0.0)) || ((v >= w) && (std::cos(PI * w) < 0.0))) {\n    result = f(w);\n  } else\n    result = f(0.5);\n\n  return result;\n}\n/* SAM_LISTING_END_1 */\n\n/* SAM_LISTING_BEGIN_2 */\nEigen::VectorXd sineClawRhs(const Eigen::VectorXd &mu) {\n  int N = mu.size();\n  double h = 12.0 / N;\n  Eigen::VectorXd result(N);\n\n  double F_minus;\n  double F_plus = sineGodFlux(0.0, mu(0));\n  for (int j = 0; j < N - 1; ++j) {\n    F_minus = F_plus;\n    F_plus = sineGodFlux(mu(j), mu(j + 1));\n    result(j) = -1.0 / h * (F_plus - F_minus);\n  }\n  F_minus = F_plus;\n  F_plus = sineGodFlux(mu(N - 1), 0.0);\n  result(N - 1) = -1.0 / h * (F_plus - F_minus);\n\n  return result;\n}\n/* SAM_LISTING_END_2 */\n\n/* SAM_LISTING_BEGIN_3 */\nbool blowup(const Eigen::VectorXd &mu) {\n  return mu.minCoeff() < 0.0 || mu.maxCoeff() > 2.0;\n}\n\nunsigned int findTimesteps() {\n  const unsigned int N = 600;\n  unsigned int ML = 100;\n  unsigned int MR = 200;\n\n  for (int i = 0; i < 100; ++i) {\n    if (ML == MR) {\n      return MR;\n    }\n    unsigned int M = (unsigned int)(0.5 * (ML + MR));\n    if (blowup(solveSineConsLaw(&sineClawRhs, N, M))) {\n      ML = M + 1;\n    } else {\n      MR = M;\n    }\n  }\n\n  return MR;\n}\n/* SAM_LISTING_END_3 */\n\n/* SAM_LISTING_BEGIN_4 */\nEigen::VectorXd sineClawReactionRhs(const Eigen::VectorXd &mu, double c) {\n  Eigen::VectorXd rhs(mu.size());\n  rhs = sineClawRhs(mu) - c * mu;\n  return rhs;\n}\n/* SAM_LISTING_END_4 */\n\n}  // namespace FiniteVolumeSineConsLaw\n", "meta": {"hexsha": "1e4cf639cc5afccef1a665d0ef9e374b236da45e", "size": 2415, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/FiniteVolumeSineConsLaw/mastersolution/finitevolumesineconslaw.cc", "max_stars_repo_name": "padomu/NPDECODES", "max_stars_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/FiniteVolumeSineConsLaw/mastersolution/finitevolumesineconslaw.cc", "max_issues_repo_name": "padomu/NPDECODES", "max_issues_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/FiniteVolumeSineConsLaw/mastersolution/finitevolumesineconslaw.cc", "max_forks_repo_name": "padomu/NPDECODES", "max_forks_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 25.15625, "max_line_length": 80, "alphanum_fraction": 0.6099378882, "num_tokens": 819, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418283357702, "lm_q2_score": 0.8947894583870631, "lm_q1q2_score": 0.8269123660493941}}
{"text": "#include <iostream>\n#include <fstream>\n#include <random>\n\n#include <Eigen/Dense>\n\nusing namespace std;\nusing namespace Eigen;\n\nfloat normal_pdf(float x, float m, float s) {\n    static const float inv_sqrt_2pi = 0.3989422804014327;\n    float a = (x - m) / s;\n\n    return (inv_sqrt_2pi / s) * std::exp(-0.5f * a * a);\n}\n\nvoid solve_1D_wave_equation(double mu, double sigma, string output_filepath) {\n    IOFormat CommaInitFmt(StreamPrecision, DontAlignCols, \", \", \", \", \"\", \"\", \"\", \"\");\n    ofstream outfile(output_filepath);\n\n    /* Problem parameters */\n    double c = 1.0;  // Propagation speed of the wave.\n    double L = 1.0;  // Length of the domain.\n    int N = 100;     // Number of grid points.\n\n    double dx = L/N;\n    double dt = 0.01;\n    double t_end = 1.0;\n\n    double alpha = c*c * dt*dt / (2*dx*dx);\n\n    /* We'll discretize the wave equation using the Crank-Nicolson method and\n     * solve the resulting linear system A*u = b at every time step.\n     */\n    MatrixXf A(N,N);\n    VectorXf b(N);\n    VectorXf u_n(N);\n    VectorXf u_nm1(N);\n\n    // Initialize matrix of coefficients.\n    A(0,0)     = 1 + 2*alpha;\n    A(N-1,N-1) = 1 + 2*alpha;\n    A(0,1)     = -alpha;\n    A(N-1,N-2) = -alpha;\n\n    for (int i = 1; i < N-1; i++) {\n        A(i,i) = 1 + 2*alpha;\n        A(i,i+1) = -alpha;\n        A(i,i-1) = -alpha;\n    }\n\n    // Set initial conditions.\n    u_nm1(0)   = 0;\n    u_nm1(N-1) = 0;\n    for (int i = 1; i < N-1; i++)\n        u_nm1(i) = normal_pdf(i*dx, mu, sigma);\n\n    // Output first row corresponding to initial condition (t = 0)\n    outfile << u_nm1.format(CommaInitFmt) << '\\n';\n\n    // Take the first time step (requires special scheme).\n    u_n(0)   = 0;\n    u_n(N-1) = 0;\n\n    for (int i = 1; i < N-1; i++)\n        u_n(i) = u_nm1(i) + (c*c/2) * (u_nm1(i+1) - 2*u_nm1(i) + u_nm1(i-1));\n\n    // Output second row corresponding to first time step.\n    outfile << u_n.format(CommaInitFmt) << '\\n';\n\n    double t = dt; // We already took one step so t = dt now.\n\n    while (t < t_end) {\n        t += dt;\n\n        // Set up right-hand side vector b.\n        b(0)   = 2*(1-alpha)*u_n(0) - u_nm1(0) + alpha*u_n(1);\n        b(N-1) = 2*(1-alpha)*u_n(N-1) - u_nm1(N-1) + alpha*u_n(N-1);\n        for (int i = 1; i < N-1; i++)\n            b(i) = 2*(1-alpha)*u_n(i) - u_nm1(i) + alpha*(u_n(i+1) + u_n(i-1));\n\n        u_nm1 = u_n;\n        \n        VectorXf u_np1 = A.colPivHouseholderQr().solve(b);\n        \n        u_np1(0)   = 0;\n        u_np1(N-1) = 0;\n\n        outfile << u_np1.format(CommaInitFmt) << '\\n';\n        \n        u_n = u_np1;\n    }\n    \n    outfile.close();\n}\n\nvoid solve_1D_wave_equations(int M, float *mu, float *sigma) {\n    # pragma acc kernels\n    {\n    for (int i = 0; i < M; i++) {\n        string file_suffix = to_string(i);\n        file_suffix.insert(file_suffix.begin(), 3 - file_suffix.length(), '0');\n        string filename = \"cpu_wave_\" + file_suffix + \".dat\";\n\n        cout << \"Solving wave equation problem \" << i << \"...\" << \" (mu=\" << mu[i] << \", sigma=\"\n             << sigma[i] << \")\\n\";\n\n        solve_1D_wave_equation(mu[i], sigma[i], filename);\n    }\n    }\n}\n\nint main() {\n    int M = 25;  // Number of 1D wave equation problems to solve.\n\n    std::random_device rd;  // Obtain a random number generator from hardware.\n    std::mt19937 mt(rd()); // Seed the Mersenne Twister generator.\n\n    /* We will impose a Gaussian wave initial condition for the 1D wave equation, with randomly\n     * generated means (0.2 < mu < 0.8) and standard deviations (0.01 < sigma < 0.5).\n     */\n    std::uniform_real_distribution<float> uniform_mu(0.2, 0.8);\n    std::uniform_real_distribution<float> uniform_sigma(0.01, 0.5);\n\n    float *mu = new float[M];\n    float *sigma = new float[M];\n\n    for(int i = 0; i < M; i++) {\n        mu[i] = uniform_mu(mt);\n        sigma[i] = uniform_sigma(mt);\n    }\n\n    // Solve the M problems one-by-one on the CPU.\n    solve_1D_wave_equations(M, mu, sigma);\n\n    delete [] mu;\n    delete [] sigma;\n}\n", "meta": {"hexsha": "43bd5a02a589b5fc57f4a8b26b4ba68c8db2e9cc", "size": 3975, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "basic-tests/simple-wave/openacc_multicore_wave_equation_1d.cpp", "max_stars_repo_name": "christophernhill/gpu-numerics-testing", "max_stars_repo_head_hexsha": "299197e9d84f1f238e0df4a5d40669a5d2a13593", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "basic-tests/simple-wave/openacc_multicore_wave_equation_1d.cpp", "max_issues_repo_name": "christophernhill/gpu-numerics-testing", "max_issues_repo_head_hexsha": "299197e9d84f1f238e0df4a5d40669a5d2a13593", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "basic-tests/simple-wave/openacc_multicore_wave_equation_1d.cpp", "max_forks_repo_name": "christophernhill/gpu-numerics-testing", "max_forks_repo_head_hexsha": "299197e9d84f1f238e0df4a5d40669a5d2a13593", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-11-11T19:46:05.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-11T19:46:05.000Z", "avg_line_length": 28.5971223022, "max_line_length": 96, "alphanum_fraction": 0.5562264151, "num_tokens": 1287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248225478306, "lm_q2_score": 0.8791467643431002, "lm_q1q2_score": 0.8255406343807792}}
{"text": "//  Solves linear equations for simple tridiagonal matrix using the iterative Jacobi method\r\n//  This is armadillo version that calls the function solve. \r\n#include <iostream>\r\n#include <fstream>\r\n#include <iomanip>\r\n#include <cmath>\r\n#include <string>\r\n#include <armadillo>\r\n// use namespace for output and input\r\nusing namespace std;\r\nusing namespace arma;\r\n\r\n// object for output files\r\nofstream ofile;\r\n// Functions used\r\ndouble f(double x){return 100.0*exp(-10.0*x);\r\n}\r\ndouble exact(double x) {return 1.0-(1-exp(-10))*x-exp(-10*x);}\r\n\r\n// Begin main program\r\nint main(int argc, char *argv[]){\r\n  int exponent; \r\n    string filename;\r\n    // We read also the basic name for the output file and the highest power of 10^n we want\r\n    if( argc <= 1 ){\r\n          cout << \"Bad Usage: \" << argv[0] <<\r\n              \" read also file name on same line and max power 10^n\" << endl;\r\n          exit(1);\r\n    }\r\n        else{\r\n        filename = argv[1]; // first command line argument after name of program\r\n        exponent = atoi(argv[2]);\r\n    }\r\n    // Loop over powers of 10\r\n    for (int i = 1; i <= exponent; i++){\r\n      int  n = (int) pow(10.0,i);\r\n      // Declare new file name\r\n      string fileout = filename;\r\n      // Convert the power 10^i to a string\r\n      string argument = to_string(i);\r\n      // Final filename as filename-i-\r\n      fileout.append(argument);\r\n      double h = 1.0/(n);\r\n      double hh = h*h;\r\n      n = n-1;  //  shift so that only points between endpoints are studied\r\n      mat A = zeros<mat>(n,n);\r\n      // Set up arrays for the simple case\r\n      vec b(n);  vec x(n);\r\n      A(0,1) = -1;  x(0) = h;  b(0) =  hh*f(x(0)); \r\n      x(n-1) = x(0)+(n-1)*h; b(n-1) = hh*f(x(n-1)); \r\n      for (int i = 1; i < n-1; i++){ \r\n        x(i) = x(i-1)+h; \r\n\tb(i) = hh*f(x(i));\r\n        A(i,i-1)  = -1.0;\r\n        A(i,i+1)  = -1.0;\r\n      }\r\n      A(n-2,n-1) = -1.0; A(n-1,n-2) = -1.0;\r\n  // solve Ax = b by iteration with a random starting vector\r\n     int maxiter = 100; double diff = 1.0; \r\n     double epsilon = 1.0e-10;  int iter = 0;\r\n      vec SolutionOld  = randu<vec>(n);\r\n      vec SolutionNew  = zeros<vec>(n);\r\n      //  Start of Jacobi solver, note the division by from A(i,i) =2\r\n      while (iter <= maxiter || diff > epsilon){\r\n\tSolutionNew = (b -A*SolutionOld)*0.5; \r\n        iter++; diff = fabs(sum(SolutionNew-SolutionOld)/n);\r\n        SolutionOld = SolutionNew;\r\n      }\r\n      vec solution = SolutionOld;\r\n      ofile.open(fileout);\r\n      ofile << setiosflags(ios::showpoint | ios::uppercase);\r\n      for (int i = 0; i < n ;i++) {\r\n\tdouble RelativeError = fabs((exact(x(i))-solution(i))/exact(x(i)));\r\n\tofile << setw(15) << setprecision(8) << x(i);\r\n\tofile << setw(15) << setprecision(8) << solution(i);\r\n\tofile << setw(15) << setprecision(8) << exact(x(i));\r\n        ofile << setw(15) << setprecision(8) << log10(RelativeError) << endl;\r\n      }\r\n      ofile.close();\r\n    }\r\n    return 0;\r\n}\r\n\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "0fef868157d723330f644332b7b5da329ad27247", "size": 2953, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/Programs/LecturePrograms/programs/PDE/cpp/Jacobi.cpp", "max_stars_repo_name": "kimrojas/ComputationalPhysicsMSU", "max_stars_repo_head_hexsha": "a47cfc18b3ad6adb23045b3f49fab18c0333f556", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 220.0, "max_stars_repo_stars_event_min_datetime": "2016-08-25T09:18:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:09:16.000Z", "max_issues_repo_path": "doc/Programs/LecturePrograms/programs/PDE/cpp/Jacobi.cpp", "max_issues_repo_name": "dnhdang94/ComputationalPhysicsMSU", "max_issues_repo_head_hexsha": "16990c74cf06eb5b933982137f0536d669567259", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-12-04T12:55:10.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-04T12:55:10.000Z", "max_forks_repo_path": "doc/Programs/LecturePrograms/programs/PDE/cpp/Jacobi.cpp", "max_forks_repo_name": "dnhdang94/ComputationalPhysicsMSU", "max_forks_repo_head_hexsha": "16990c74cf06eb5b933982137f0536d669567259", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 136.0, "max_forks_repo_forks_event_min_datetime": "2016-08-25T09:04:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T09:54:21.000Z", "avg_line_length": 33.5568181818, "max_line_length": 93, "alphanum_fraction": 0.555367423, "num_tokens": 886, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.930458253565792, "lm_q2_score": 0.8856314662716159, "lm_q1q2_score": 0.8240431074099994}}
{"text": "#include <iostream>\r\n#include <Eigen/Dense>\r\n#include <cmath>\r\n\r\nusing namespace std;\r\nusing namespace Eigen;\r\n\r\n/*\r\nTest Example: f(v)=x^2+(x+y-10)^2+(2*y-z)^2+2*z;\r\nApproximate Hessian Matrix using SR1.\r\n*/\r\n\r\ndouble f(Vector3d v)\r\n{\r\n\tdouble x = v(0);\r\n\tdouble y = v(1);\r\n\tdouble z = v(2);\r\n\tdouble res;\r\n\r\n\tres = x * x + (x + y - 10)*(x + y - 10) + (2 * y - z)*(2 * y - z) + 2 * z;\r\n\r\n\treturn res;\r\n}\r\n\r\nVector3d J(Vector3d v)\r\n{\r\n\tVector3d J;\r\n\tdouble x = v(0);\r\n\tdouble y = v(1);\r\n\tdouble z = v(2);\r\n\r\n\tdouble dx = 2 * x + 2 * (x + y - 10);\r\n\tdouble dy = 2 * (x + y - 10) + 2 * (2 * y - z) * 2;\r\n\tdouble dz = 2 * (z - 2 * y) + 2;\r\n\r\n\tJ(0) = dx; J(1) = dy; J(2) = dz;\r\n\treturn J;\r\n}\r\n\r\nbool PositiveDefinite(Matrix3d G)\r\n{\r\n\tVector3cd E = G.eigenvalues();\r\n\t\r\n\tbool res = E(0).real() > 0 && E(1).real() > 0 && E(2).real() > 0;\r\n\r\n\treturn res;\r\n}\r\n\r\nint main()\r\n{\r\n\tVector3d v(100, 100, 100);\r\n\tdouble u = 0.25;\r\n\tMatrix3d G; G.setIdentity();\r\n\tMatrix3d I; I.setIdentity();\r\n\t\r\n\twhile (1)\r\n\t{\r\n\t\tVector3d g = J(v);\r\n\t\tif (g.norm() < 1e-6) break;\r\n\t\twhile (!PositiveDefinite(G + u * I))\r\n\t\t{\r\n\t\t\tu *= 4;\r\n\t\t}\r\n\t\tMatrix3d K = G + u * I;\r\n\t\tVector3d s = -K.inverse()*g;\r\n\r\n\t\tdouble fn = f(v + s);\r\n\t\tdouble qk = f(v) + g.transpose()*s + 0.5*s.transpose()*G*s;\r\n\t\tdouble rk = (f(v) - fn) / (f(v)-qk);\r\n\r\n\t\tif (rk < 0.25) u *= 4.0;\r\n\t\telse if (rk > 0.75) u /= 2.0;\r\n\r\n\t\tif (rk > 0)\r\n\t\t{\r\n\t\t\tv = v + s;\r\n\t\t\tVector3d sk = -s;\r\n\t\t\tVector3d yk = g-J(v);\r\n\t\t\tdouble den = (sk - G * yk).transpose()*yk;\r\n\t\t\tG = G + (sk - G * yk)*(sk - G * yk).transpose() / den;\r\n\t\t}\r\n\t}\r\n\r\n\tcout << v.transpose() << endl;\r\n\tcout << f(v) << endl;\r\n\r\n}", "meta": {"hexsha": "d25195c5183cc4d2e988fd70f39cd9480e2d8b91", "size": 1627, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Trust Region/LM.cpp", "max_stars_repo_name": "wkindling/Numerical-Optimization", "max_stars_repo_head_hexsha": "5f1a7092ae1f8ceb73f57be7bc39399bacdf6715", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Trust Region/LM.cpp", "max_issues_repo_name": "wkindling/Numerical-Optimization", "max_issues_repo_head_hexsha": "5f1a7092ae1f8ceb73f57be7bc39399bacdf6715", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Trust Region/LM.cpp", "max_forks_repo_name": "wkindling/Numerical-Optimization", "max_forks_repo_head_hexsha": "5f1a7092ae1f8ceb73f57be7bc39399bacdf6715", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.7011494253, "max_line_length": 76, "alphanum_fraction": 0.483712354, "num_tokens": 631, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109826342961, "lm_q2_score": 0.8670357477770337, "lm_q1q2_score": 0.8240402970238324}}
{"text": "#include \"ode45.hpp\"\n\n#include <iostream>\n#include <iomanip>\n\n#include <Eigen/Dense>\n#include <Eigen/QR>\n\n//! \\file stabrk.cpp Solution for Problem 1, PS13, involving ode45 and matrix ODEs\n\n//! \\brief Solve matrix IVP Y' = -(Y-Y')*Y using ode45 up to time T\n//! \\param[in] Y0 Initial data Y(0) (as matrix)\n//! \\param[in] T final time of simulation\n//! \\return Matrix of solution of IVP at t = T\nEigen::MatrixXd matode(const Eigen::MatrixXd & Y0, double T) {\n\tauto f=[](const Eigen::MatrixXd & Y){return (-(Y-Y.transpose())*Y);};\n\tode45<Eigen::MatrixXd> O(f);\n    O.options.rtol = 10e-8;\n    O.options.atol = 10e-10;\n    return O.solve(Y0,T).back().first;\n    // TODO: evolve Y0 up to T using ode45 (read ode45.hpp)\n}\n\n\n//! \\brief Find if invariant is preserved after evolution with matode\n//! \\param[in] Y0 Initial data Y(0) (as matrix)\n//! \\param[in] T final time of simulation\n//! \\return true if invariant was preserved (up to round-off), i.e. if norm was less than 10*eps\nbool checkinvariant(const Eigen::MatrixXd & M, double T) {\n\treturn (matode(M,0.1).norm()==matode(M,T).norm());\n\t\t// TODO: check if invariant is preserved applying matode\n}\n\n//! \\brief Implement ONE step of explicit Euler applied to Y0, of ODE Y' = A*Y\n//! \\param[in] A matrix A of the ODE\n//! \\param[in] Y0 Initial state\n//! \\param[in] h step size\n//! \\return next step\nEigen::MatrixXd expeulstep(const Eigen::MatrixXd & A, const Eigen::MatrixXd & Y0, double h) {\n    return Y0+h*A*Y0;\n    // TODO: ose step of EE\n}\n\n//! \\brief Implement ONE step of implicit Euler applied to Y0, of ODE Y' = A*Y\n//! \\param[in] A matrix A of the ODE\n//! \\param[in] Y0 Initial state\n//! \\param[in] h step size\n//! \\return next step\nEigen::MatrixXd impeulstep(const Eigen::MatrixXd & A, const Eigen::MatrixXd & Y0, double h) {\n    size_t n = Y0.cols();\n    Eigen::MatrixXd Y1(n,n);\n    Eigen::MatrixXd I = Eigen::MatrixXd::Identity(n,n);    \n    return (I-h*A).partialPivLu().inverse()*Y0;\n    // TODO: ose step of IE\n}\n\n//! \\brief Implement ONE step of implicit midpoint ruler applied to Y0, of ODE Y' = A*Y\n//! \\param[in] A matrix A of the ODE\n//! \\param[in] Y0 Initial state\n//! \\param[in] h step size\n//! \\return next step\nEigen::MatrixXd impstep(const Eigen::MatrixXd & A, const Eigen::MatrixXd & Y0, double h) {\n    size_t n = Y0.cols();\n    Eigen::MatrixXd Y1(n,n);\n    Eigen::MatrixXd I = Eigen::MatrixXd::Identity(n,n);    \n    return (I-h*0.5*A).partialPivLu().inverse()*(I+h*0.5*A)*Y0;    \n    // TODO: ose step of IMP\n}\n\nint main() {\n    \n    double T = 1;\n    unsigned int n = 3;\n    \n    Eigen::MatrixXd M(n,n);\n    M << 8,1,6,3,5,7,4,9,2;\n    \n    std::cout << \"SUBTASK 1. c)\" << std::endl;\n    // Test preservation of orthogonality\n    \n    // Build Q\n    Eigen::HouseholderQR<Eigen::MatrixXd> qr(M.rows(), M.cols());\n    qr.compute(M);\n    Eigen::MatrixXd Q = qr.householderQ();\n    \n    // Build A\n    Eigen::MatrixXd A(n,n);\n    A << 0, 1, 1, -1, 0, 1, -1, -1, 0;\n    Eigen::MatrixXd I = Eigen::MatrixXd::Identity(n,n);\n    \n    // TODO: compute norm of Y'Y-I for 20 steps and print table\n    Eigen::MatrixXd EE(n,n);\n    EE=Q;\n    Eigen::MatrixXd IE(n,n);\n    IE=Q;\n    Eigen::MatrixXd IM(n,n);\n\tIM=Q;\n\tdouble EE_norm,IE_norm,IM_norm;\n    std::cout << \"\\tStep\" << std::setw(15) << \"expl. Euler\" << std::setw(15) << \"impl. Euler\" << std::setw(15) << \"Impl.  Midpoint\" << std::endl;\n    for (int i=0; i< 21; i++){\n\t\tdouble h=0.01;\n\t\tEE=expeulstep(A, EE, h);\t\t\n\t\tIE=impeulstep(A, IE, h);\t\t\n\t\tIM=impstep(A, IM, h);\t\t\n\t\tEE_norm= (EE.transpose()*EE-I).norm();\n\t\tIE_norm= (IE.transpose()*IE-I).norm();\n\t\tIM_norm= (IM.transpose()*IM-I).norm();\n\t\tstd::cout << \"\\t\"<< i << std::setw(15) << EE_norm << std::setw(15) << IE_norm << std::setw(15) << IM_norm << std::endl;\n}\n    \n    \n    std::cout << \"SUBTASK 1. d)\" << std::endl;\n    // Test implementation of ode45\n    Eigen::MatrixXd mat_ode =matode(M,T);\n    std::cout << mat_ode <<std::endl;\n    std::cout << \"test matode norm : \"  << (mat_ode.transpose()*mat_ode-I).norm() << std::endl;\n    // TODO: TEST matode\n    \n    std::cout << \"SUBTASK 1. g)\" << std::endl;\n    // Test whether invariant was preserved or not\n\n    if (checkinvariant(M,T)){std::cout << \" Invariant preserved\" << std::endl;}\n    else {std::cout << \" Invariant not preserved\" << std::endl;}\n    // TODO: TEST if matode preserves invariant using checkinvariant\n    \n    \n    return 0;\n}\n", "meta": {"hexsha": "7cde3e69e1d042b0474e84323346f4cb7f534093", "size": 4375, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/PS13/matrix_ode.cpp", "max_stars_repo_name": "valentinjacot/backupETHZ", "max_stars_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:21:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:21:30.000Z", "max_issues_repo_path": "Nummerical Methods for CSE/PS13/matrix_ode.cpp", "max_issues_repo_name": "valentinjacot/backupETHZ", "max_issues_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Nummerical Methods for CSE/PS13/matrix_ode.cpp", "max_forks_repo_name": "valentinjacot/backupETHZ", "max_forks_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.9147286822, "max_line_length": 145, "alphanum_fraction": 0.6141714286, "num_tokens": 1396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897542390751, "lm_q2_score": 0.8757869932689566, "lm_q1q2_score": 0.8239314301632802}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nvoid matrixCreation()\n{\n    Eigen::Matrix4d m; // 4x4 double\n\n    Eigen::Matrix4cd objMatrix4cd; // 4x4 double complex\n\n\n    //a is a 3x3 matrix, with a static float[9] array of uninitialized coefficients,\n    Eigen::Matrix3f a;\n\n    //b is a dynamic-size matrix whose size is currently 0x0, and whose array of coefficients hasn't yet been allocated at all.\n    Eigen::MatrixXf b;\n\n    //A is a 10x15 dynamic-size matrix, with allocated but currently uninitialized coefficients.\n    Eigen::MatrixXf A(10, 15);\n}\n\nvoid arrayCreation()\n{\n    // ArrayXf\n    Eigen::Array<float, Eigen::Dynamic, 1> a1;\n    // Array3f\n    Eigen::Array<float, 3, 1> a2;\n    // ArrayXXd\n    Eigen::Array<double, Eigen::Dynamic, Eigen::Dynamic> a3;\n    // Array33d\n    Eigen::Array<double, 3, 3> a4;\n    Eigen::Matrix3d matrix_from_array = a4.matrix();\n}\n\nvoid vectorCreation()\n{\n    // Vector3f is a fixed column vector of 3 floats:\n    Eigen::Vector3f objVector3f;\n\n    // RowVector2i is a fixed row vector of 3 integer:\n    Eigen::RowVector2i objRowVector2i;\n\n    // VectorXf is a column vector of size 10 floats:\n    Eigen::VectorXf objv(10);\n\n    //V is a dynamic-size vector of size 30, with allocated but currently uninitialized coefficients.\n    Eigen::VectorXf V(30);\n}\n\nvoid buildMatrixFromVector()\n{\n    Eigen::Matrix2d mat;\n    mat<<1,2,3,4;\n\n    std::cout<<\"matrix is:\\n\"  <<mat <<std::endl;\n\n    Eigen::RowVector2d firstRow=mat.row(0);\n    Eigen::Vector2d firstCol=mat.col(0);\n\n    std::cout<<\"First column of the matrix is:\\n \"<<firstCol <<std::endl;\n    std::cout<<\"First column dims are: \"  <<firstCol.rows()<<\",\"<<firstCol.cols() <<std::endl;\n\n\n    std::cout<<\"First row of the matrix is: \\n\" <<firstRow <<std::endl;\n    std::cout<<\"First row dims are: \" <<firstRow.rows()<<\",\" <<firstRow.cols() <<std::endl;\n\n\n    firstRow = Eigen::RowVector2d::Random();\n    firstCol = Eigen::Vector2d::Random();\n\n\n    mat.row(0) =firstRow;\n    mat.col(0) = firstCol;\n\n    std::cout<<\"the new matrix is:\\n\"  <<mat <<std::endl;\n\n}\n\nvoid initialization()\n{\n    std::cout <<\"///////////////////Initialization//////////////////\"<< std::endl;\n\n    Eigen::Matrix2d rndMatrix;\n    rndMatrix.setRandom();\n\n    Eigen::Matrix2d constantMatrix;\n    constantMatrix.setRandom();\n    constantMatrix.setConstant(4.3);\n\n    Eigen::MatrixXd identity=Eigen::MatrixXd::Identity(6,6);\n\n    Eigen::MatrixXd zeros=Eigen::MatrixXd::Zero(3, 3);\n\n    Eigen::ArrayXXf table(10, 4);\n    table.col(0) = Eigen::ArrayXf::LinSpaced(10, 0, 90);\n\n\n\n\n}\n\nvoid elementAccess()\n{\n    std::cout <<\"//////////////////Elements Access////////////////////\"<< std::endl;\n\n    Eigen::MatrixXf matrix(4, 4);\n    matrix << 1, 2, 3, 4,\n        5, 6, 7, 8,\n        9, 10, 11, 12,\n        13, 14, 15, 16;\n\n    std::cout<<\"matrix is:\\n\"<<matrix <<std::endl;\n\n    std::cout<<\"All Eigen matrices default to column-major storage order. That means, matrix(2) is  matix(2,0):\" <<std::endl;\n\n    std::cout<<\"matrix(2): \"<<matrix(2) <<std::endl;\n    std::cout<<\"matrix(2,0): \"<<matrix(2,0) <<std::endl;\n\n\n    std::cout <<\"//////////////////Pointer to data ////////////////////\"<< std::endl;\n\n    for (int i = 0; i < matrix.size(); i++)\n    {\n          std::cout << *(matrix.data() + i) << \"  \";\n    }\n    std::cout <<std::endl;\n\n\n    std::cout <<\"//////////////////Row major Matrix////////////////////\"<< std::endl;\n    Eigen::Matrix<double, 4,4,Eigen::RowMajor> matrixRowMajor(4, 4);\n    matrixRowMajor << 1, 2, 3, 4,\n        5, 6, 7, 8,\n        9, 10, 11, 12,\n        13, 14, 15, 16;\n\n\n    for (int i = 0; i < matrixRowMajor.size(); i++)\n    {\n          std::cout << *(matrixRowMajor.data() + i) << \"  \";\n    }\n    std::cout <<std::endl;\n\n\n    std::cout <<\"//////////////////Block Elements Access////////////////////\"<< std::endl;\n\n    std::cout << \"Block elements in the middle\" << std::endl;\n\n    int starting_row,starting_column,number_rows_in_block,number_cols_in_block;\n\n    starting_row=1;\n    starting_column=1;\n    number_rows_in_block=2;\n    number_cols_in_block=2;\n\n    std::cout << matrix.block(starting_row,starting_column,number_rows_in_block,number_cols_in_block) << std::endl;\n\n    for (int i = 1; i <= 3; ++i)\n    {\n        std::cout << \"Block of size \" << i << \"x\" << i << std::endl;\n        std::cout << matrix.block(0, 0, i, i) << std::endl;\n    }\n}\n\nvoid matrixReshaping()\n{\n    //https://eigen.tuxfamily.org/dox/group__TutorialReshapeSlicing.html\n    /*\n    Eigen::MatrixXd m1(12,1);\n    m1<<0,1,2,3,4,5,6,7,8,9,10,11;\n    std::cout<<m1<<std::endl;\n\n    //Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic,Eigen::RowMajor> m2(m1);\n    //Eigen::Map<Eigen::MatrixXd> m3(m2.data(),3,4);\n    Eigen::Map<Eigen::MatrixXd> m2(m1.data(),4,3);\n    std::cout<<m2.transpose()<<std::endl;\n    //solution*/\n    //https://eigen.tuxfamily.org/dox/group__TutorialBlockOperations.html\n}\n\n//https://eigen.tuxfamily.org/dox/group__TutorialReshapeSlicing.html\nvoid matrixSlicing()\n{\n\n}\nvoid matrixResizing()\n{\n    std::cout <<\"//////////////////Matrix Resizing////////////////////\"<< std::endl;\n    int rows, cols;\n    rows=3;\n    cols=4;\n    Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> dynamicMatrix;\n\n    dynamicMatrix.resize(rows,cols);\n    dynamicMatrix=Eigen::MatrixXd::Random(rows,cols);\n\n    std::cout<<\"Matrix size is: \" << dynamicMatrix.size()<<std::endl;\n\n    std::cout<<\"Matrix is:\\n\" << dynamicMatrix<<std::endl;\n\n    dynamicMatrix.resize(2,6);\n    std::cout<<\"New Matrix size is: \" << dynamicMatrix.size()<<std::endl;\n    std::cout<<\"Matrix is:\\n\" << dynamicMatrix<<std::endl;\n\n    std::cout <<\"//////////////////Matrix conservativeResize////////////////////\"<< std::endl;\n\n\n    dynamicMatrix.conservativeResize(dynamicMatrix.rows(), dynamicMatrix.cols()+1);\n    dynamicMatrix.col(dynamicMatrix.cols()-1) = Eigen::Vector2d(1, 4);\n\n    std::cout<< dynamicMatrix<<std::endl;\n}\n\nvoid convertingMatrixtoArray()\n{\n    Eigen::Matrix<double, 4,4> mat1=Eigen::MatrixXd::Random(4,4);\n    Eigen::Matrix<double, 4,4> mat2=Eigen::MatrixXd::Random(4,4);\n\n    Eigen::Array<double, 4,4> array1=mat1.array();\n    Eigen::Array<double, 4,4> array2=mat2.array();\n\n    std::cout<<\"Matrix multipication:\\n\" << mat1*mat2 <<std::endl;\n    std::cout<<\"Array multipication(coefficientsweise) :\\n\"<<array1*array2 <<std::endl;\n    std::cout<<\"Matrix coefficientsweise multipication :\\n\"<<mat1.cwiseProduct(mat2) <<std::endl;\n\n}\n\nvoid coefficientWiseOperations()\n{\n    std::cout <<\"/////////////Matrix Coefficient Wise Operations///////////////////\"<< std::endl;\n    Eigen::Matrix<double, 2, 3> my_matrix;\n    my_matrix << 1, 2, 3, 4, 5, 6;\n    int i,j;\n    std::cout <<\"The matrix is: \\n\" << my_matrix << std::endl;\n\n    std::cout <<\"The matrix transpose is: \\n\" << my_matrix.transpose() << std::endl;\n\n    std::cout<<\"The minimum element is: \" <<my_matrix.minCoeff(&i, &j)<<\" and its indices are:\" << i<<\",\"<< j <<std::endl;\n\n\n    std::cout<<\"The maximum element is: \" <<my_matrix.maxCoeff(&i, &j)<<\" and its indices are:\" << i<<\",\"<< j <<std::endl;\n\n    std::cout<<\"The multipication of all elements: \" <<my_matrix.prod()<<std::endl;\n    std::cout<<\"The sum of all elements: \" <<my_matrix.sum()<<std::endl;\n    std::cout<<\"The mean of all element: \" <<my_matrix.mean()<<std::endl;\n    std::cout<<\"The trace of the matrix is: \" <<my_matrix.trace()<<std::endl;\n    std::cout<<\"The means of columns: \" <<my_matrix.colwise().mean()<<std::endl;\n    std::cout<<\"The max of each columns: \"  <<my_matrix.rowwise().maxCoeff()<<std::endl;\n    std::cout<<\"Norm 2 of the matrix is: \" <<my_matrix.lpNorm<2>()<<std::endl;\n    std::cout<<\"Norm infinty of the matrix is: \" <<my_matrix.lpNorm<Eigen::Infinity>()<<std::endl;\n    std::cout<<\"If all elemnts are positive: \"  << (my_matrix.array()>0).all()<<std::endl;\n    std::cout<<\"If any element is greater than 2: \"<<(my_matrix.array()>2).any()<<std::endl;\n    std::cout<<\"Counting the number of elements greater than 1\"<<(my_matrix.array()>1).count()<<std::endl;\n    std::cout <<\"subtracting 2 from all elements:\\n\" << my_matrix.array() - 2 << std::endl;\n    std::cout <<\"abs of the matrix: \\n\" << my_matrix.array().abs() << std::endl;\n    std::cout << \"square of the matrix: \\n\" <<my_matrix.array().square() << std::endl;\n\n    std::cout <<\"exp of the matrix: \\n\" <<my_matrix.array().exp() << std::endl;\n    std::cout << \"log of the matrix: \\n\" <<my_matrix.array().log() << std::endl;\n    std::cout << \"square root of the matrix: \\n\" <<my_matrix.array().sqrt() << std::endl;\n\n\n\n\n\n}\n\nvoid maskingArray()\n{\n    std::cout <<\"//////////////////Maskin Matrix/Array ////////////////////\"<< std::endl;\n\n    //Eigen::MatrixXf P, Q, R; // 3x3 float matrix.\n    // (R.array() < s).select(P,Q ); // (R < s ? P : Q)\n    // R = (Q.array()==0).select(P,R); // R(Q==0) = P(Q==0)\n    int cols, rows;\n    cols=2; rows=3;\n    Eigen::MatrixXf R=Eigen::MatrixXf::Random(rows, cols);\n\n    Eigen::MatrixXf Q=Eigen::MatrixXf::Zero(rows, cols);\n    Eigen::MatrixXf P=Eigen::MatrixXf::Constant(rows, cols,1.0);\n\n    double s=0.5;\n    Eigen::MatrixXf masked=(R.array() < s).select(P,Q ); // (R < s ? P : Q)\n\n    std::cout<<\"R\\n\" <<R <<std::endl;\n    std::cout<<\"masked\\n\" <<masked <<std::endl;\n    std::cout<<\"P\\n\"<< P <<std::endl;\n    std::cout<<\"Q\\n\" << Q<<std::endl;\n}\n\nvoid AdditionSubtractionOfMatrices()\n{\n\n}\n\n\n\nvoid transpositionConjugation()\n{\n\n}\n\n\nvoid scalarMultiplicationDivision()\n{\n\n}\n\n\nvoid multiplicationDotCrossProduct()\n{\n\n}\n\nint main()\n{\n    //buildMatrixFromVector();\n    //vectorCreation();\n    //elementAccess();\n    //matrixResizing();\n    //coefficientWiseOperations();\n    //convertingMatrixtoArray();\n    //maskingArray();\n\n}\n", "meta": {"hexsha": "cfdacd5c370e2f7823a021fc1d1fc0ca2afa92d6", "size": 9627, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/matrix_array_vector.cpp", "max_stars_repo_name": "behnamasadi/Mastering_Eigen", "max_stars_repo_head_hexsha": "99edbc819c89a4805b777eef69044a1658d96206", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-04-14T16:54:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-13T15:55:08.000Z", "max_issues_repo_path": "src/matrix_array_vector.cpp", "max_issues_repo_name": "behnamasadi/Mastering_Eigen", "max_issues_repo_head_hexsha": "99edbc819c89a4805b777eef69044a1658d96206", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/matrix_array_vector.cpp", "max_forks_repo_name": "behnamasadi/Mastering_Eigen", "max_forks_repo_head_hexsha": "99edbc819c89a4805b777eef69044a1658d96206", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-12-25T10:08:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-06T14:27:32.000Z", "avg_line_length": 29.712962963, "max_line_length": 127, "alphanum_fraction": 0.5985249818, "num_tokens": 2887, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.925229961215457, "lm_q2_score": 0.8902942275774318, "lm_q1q2_score": 0.8237268936518125}}
{"text": "/* =========================================================================\n   Copyright (c) 2010-2016, Institute for Microelectronics,\n                            Institute for Analysis and Scientific Computing,\n                            TU Wien.\n   Portions of this software are copyright by UChicago Argonne, LLC.\n\n                            -----------------\n                  ViennaCL - The Vienna Computing Library\n                            -----------------\n\n   Project Head:    Karl Rupp                   rupp@iue.tuwien.ac.at\n\n   (A list of authors and contributors can be found in the PDF manual)\n\n   License:         MIT (X11), see file LICENSE in the base directory\n============================================================================= */\n\n/** \\example least-squares.cpp\n*\n*   This tutorial shows how least Squares problems for matrices from ViennaCL or Boost.uBLAS can be solved solved.\n*\n*   We start with including the respective header files:\n**/\n\n// activate ublas support in ViennaCL\n#define VIENNACL_WITH_UBLAS\n\n//\n// include necessary system headers\n//\n#include <iostream>\n\n// Boost headers\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/vector_proxy.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n\n// ViennaCL headers\n#include \"viennacl/vector.hpp\"\n#include \"viennacl/matrix.hpp\"\n#include \"viennacl/matrix_proxy.hpp\"\n#include \"viennacl/linalg/qr.hpp\"\n#include \"viennacl/linalg/lu.hpp\"\n#include \"viennacl/linalg/direct_solve.hpp\"\n\n\n/**\n*  The minimization problem of finding x such that \\f$ \\Vert Ax - b \\Vert \\f$ is solved as follows:\n*   - Compute the QR-factorization of A = QR.\n*   - Compute \\f$ b' = Q^{\\mathrm{T}} b \\f$ for the equivalent minimization problem \\f$ \\Vert Rx - Q^{\\mathrm{T}} b \\f$.\n*   - Solve the triangular system \\f$ \\tilde{R} x = b' \\f$, where \\f$ \\tilde{R} \\f$ is the upper square matrix of R.\n*\n**/\nint main (int, const char **)\n{\n  typedef float               ScalarType;     //feel free to change this to 'double' if supported by your hardware\n\n  typedef boost::numeric::ublas::matrix<ScalarType>              MatrixType;\n  typedef boost::numeric::ublas::vector<ScalarType>              VectorType;\n  typedef viennacl::matrix<ScalarType, viennacl::column_major>   VCLMatrixType;\n  typedef viennacl::vector<ScalarType>                           VCLVectorType;\n\n  /**\n  *  Create vectors and matrices with data:\n  **/\n  VectorType ublas_b(4);\n  ublas_b(0) = -4;\n  ublas_b(1) =  2;\n  ublas_b(2) =  5;\n  ublas_b(3) = -1;\n\n  MatrixType ublas_A(4, 3);\n\n  ublas_A(0, 0) =  2; ublas_A(0, 1) = -1; ublas_A(0, 2) =  1;\n  ublas_A(1, 0) =  1; ublas_A(1, 1) = -5; ublas_A(1, 2) =  2;\n  ublas_A(2, 0) = -3; ublas_A(2, 1) =  1; ublas_A(2, 2) = -4;\n  ublas_A(3, 0) =  1; ublas_A(3, 1) = -1; ublas_A(3, 2) =  1;\n\n  /**\n  * Setup the matrix and vector with ViennaCL objects and copy the data from the uBLAS objects:\n  **/\n  VCLVectorType vcl_b(ublas_b.size());\n  VCLMatrixType vcl_A(ublas_A.size1(), ublas_A.size2());\n\n  viennacl::copy(ublas_b, vcl_b);\n  viennacl::copy(ublas_A, vcl_A);\n\n\n  /**\n  * <h2>Option 1: Using Boost.uBLAS</h2>\n  *\n  * The implementation in ViennaCL accepts both uBLAS and ViennaCL types.\n  * We start with a single-threaded implementation using Boost.uBLAS.\n  **/\n\n  std::cout << \"--- Boost.uBLAS ---\" << std::endl;\n  /**\n  * The first (and computationally most expensive) step is to compute the QR factorization of A.\n  * Since we do not need A later, we directly overwrite A with the householder reflectors and the upper triangular matrix R.\n  * The returned vector holds the scalar coefficients (betas) for the Householder reflections \\f$ I - \\beta v v^{\\mathrm{T}} \\f$\n  **/\n  std::vector<ScalarType> ublas_betas = viennacl::linalg::inplace_qr(ublas_A);\n\n  /**\n  * Compute the modified RHS of the minimization problem from the QR factorization, but do not form \\f$ Q^{\\mathrm{T}} \\f$ explicitly:\n  * b' := Q^T b\n  **/\n  viennacl::linalg::inplace_qr_apply_trans_Q(ublas_A, ublas_betas, ublas_b);\n\n  /**\n  * Final step: triangular solve: Rx = b'', where b'' are the first three entries in b'\n  * We only need the upper left square part of A, which defines the upper triangular matrix R\n  **/\n  boost::numeric::ublas::range ublas_range(0, 3);\n  boost::numeric::ublas::matrix_range<MatrixType> ublas_R(ublas_A, ublas_range, ublas_range);\n  boost::numeric::ublas::vector_range<VectorType> ublas_b2(ublas_b, ublas_range);\n  boost::numeric::ublas::inplace_solve(ublas_R, ublas_b2, boost::numeric::ublas::upper_tag());\n\n  std::cout << \"Result: \" << ublas_b2 << std::endl;\n\n  /**\n  *  <h2>Option 2: Use ViennaCL types</h2>\n  *\n  *  ViennaCL is used for the computationally intensive BLAS 3 computations.\n  *  Boost.uBLAS is used for the panel factorization on the host (CPU).\n  */\n\n  std::cout << \"--- ViennaCL (hybrid implementation)  ---\" << std::endl;\n  std::vector<ScalarType> hybrid_betas = viennacl::linalg::inplace_qr(vcl_A);\n\n  /**\n  * compute modified RHS of the minimization problem: \\f$ b' := Q^T b \\f$\n  **/\n  viennacl::linalg::inplace_qr_apply_trans_Q(vcl_A, hybrid_betas, vcl_b);\n\n  /**\n  * Final step: triangular solve: Rx = b'.\n  * We only need the upper part of A such that R is a square matrix\n  **/\n  viennacl::range vcl_range(0, 3);\n  viennacl::matrix_range<VCLMatrixType> vcl_R(vcl_A, vcl_range, vcl_range);\n  viennacl::vector_range<VCLVectorType> vcl_b2(vcl_b, vcl_range);\n  viennacl::linalg::inplace_solve(vcl_R, vcl_b2, viennacl::linalg::upper_tag());\n\n  std::cout << \"Result: \" << vcl_b2 << std::endl;\n\n  /**\n  *  That's it.\n  **/\n  std::cout << \"!!!! TUTORIAL COMPLETED SUCCESSFULLY !!!!\" << std::endl;\n\n  return EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "81588452dc1f03600c86361d2e21c26cf6713952", "size": 5819, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/tutorial/least-squares.cpp", "max_stars_repo_name": "yuchengs/viennacl-dev", "max_stars_repo_head_hexsha": "99f250fdb729de01ff5e9aebbed7b2ed3b1d8dfa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 224.0, "max_stars_repo_stars_event_min_datetime": "2015-02-15T21:50:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-14T18:27:03.000Z", "max_issues_repo_path": "examples/tutorial/least-squares.cpp", "max_issues_repo_name": "yuchengs/viennacl-dev", "max_issues_repo_head_hexsha": "99f250fdb729de01ff5e9aebbed7b2ed3b1d8dfa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 189.0, "max_issues_repo_issues_event_min_datetime": "2015-01-09T17:08:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-04T06:23:22.000Z", "max_forks_repo_path": "examples/tutorial/least-squares.cpp", "max_forks_repo_name": "yuchengs/viennacl-dev", "max_forks_repo_head_hexsha": "99f250fdb729de01ff5e9aebbed7b2ed3b1d8dfa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 84.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T14:06:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-23T14:51:17.000Z", "avg_line_length": 36.36875, "max_line_length": 134, "alphanum_fraction": 0.6440969239, "num_tokens": 1722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632261523028, "lm_q2_score": 0.8652240947405564, "lm_q1q2_score": 0.8235749981644517}}
{"text": "#include <armadillo>\n#include <iostream>\n#include <stdio.h>\n\nusing namespace std;\nusing namespace arma;\n\nmat computeCost(const mat& X, const mat& y, const mat& theta)\n{\n\tmat J;\n\tint m;\n\tm = y.n_rows;\n\tJ = arma::sum((pow(((X*theta)-y), 2))/(2*m)) ;\n\treturn J;\n}\n\nvoid gradientDescent(const mat&    X,\n                     const mat&    y,\n                           double  alpha,\n                           int     num_iters,\n                           mat&    theta)\n{\n\tmat delta;\n\tint iter;\n\tint m ;\n\tm = y.n_rows;\n\t//vec J_history = arma::zeros<vec>(num_iters) ;\n\tfor (iter = 0; iter < num_iters; iter++)\n\t{\n\t\tdelta = arma::trans(X)*(X*theta-y)/m ;\n\t\ttheta = theta-alpha*delta ;\n\t}\n}\n\nint main()\n{\n\tmat data;\n\tdata.load(\"ex1data1.txt\");\n\tmat X = data.col(0);\n\tmat y = data.col(1);\n\t\n\tint m = X.n_elem;\n\tcout << \"m = \" << m << endl;\n\t\n\tvec X_One(m);\n\tX_One.ones();\n\tX.insert_cols(0, X_One);\n  \n\tmat theta = arma::zeros<vec>(2);\n\tint iterations = 1500 ;\n\tdouble alpha = 0.01 ;\n\t\n\tmat J = computeCost(X, y, theta);\n\tJ.print(\"J:\");\n\t\n\tgradientDescent(X, y, alpha, iterations, theta) ;\n\tprintf(\"Theta found by gradient descent: \\n\") ;\n\tprintf(\"%f %f \\n\", theta(0), theta(1)) ;\n\t\n\treturn 0;\n}\n", "meta": {"hexsha": "911a5149cadb664658b594da2882bde6e4616733", "size": 1190, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gradient_descent/C++/gradient-descent.cpp", "max_stars_repo_name": "pasanmaleesha/ML-FromScratch", "max_stars_repo_head_hexsha": "c1bb65b3212a794dd4055eb3cdc842dcbac65e8c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2020-10-01T13:16:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T07:41:12.000Z", "max_issues_repo_path": "gradient_descent/C++/gradient-descent.cpp", "max_issues_repo_name": "pasanmaleesha/ML-FromScratch", "max_issues_repo_head_hexsha": "c1bb65b3212a794dd4055eb3cdc842dcbac65e8c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 63.0, "max_issues_repo_issues_event_min_datetime": "2020-10-01T05:20:42.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-08T11:50:51.000Z", "max_forks_repo_path": "gradient_descent/C++/gradient-descent.cpp", "max_forks_repo_name": "pasanmaleesha/ML-FromScratch", "max_forks_repo_head_hexsha": "c1bb65b3212a794dd4055eb3cdc842dcbac65e8c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 42.0, "max_forks_repo_forks_event_min_datetime": "2020-10-01T05:36:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-05T16:34:28.000Z", "avg_line_length": 19.1935483871, "max_line_length": 61, "alphanum_fraction": 0.5529411765, "num_tokens": 353, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133481428692, "lm_q2_score": 0.8757869981319862, "lm_q1q2_score": 0.8231638896742279}}
{"text": "#define _USE_MATH_DEFINES\n\n#include <iostream>\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <cmath>\n\nusing namespace Eigen;\n\n\nEigen::Quaterniond euler2Quaternion(double roll, double pitch, double yaw ){\n\tEigen::AngleAxisd rollAngle(roll, Eigen::Vector3d::UnitZ());\n\tEigen::AngleAxisd pitchAngle(pitch, Eigen::Vector3d::UnitY());\n\tEigen::AngleAxisd yawAngle(yaw, Eigen::Vector3d::UnitX());\n\n\tEigen::Quaternion<double> q = yawAngle * pitchAngle * rollAngle;\n    return q;\n}\n\nint main(){\n    MatrixXd rotationA(3,3),rotationB(3,3);\n\n    double rollA = M_PI/4, rollB = -M_PI/3;\n    double pitchA = 0, pitchB = 0;\n    double yawA = M_PI/3, yawB = 0;\n    \n    Eigen::Quaterniond qA = euler2Quaternion(rollA,pitchA,yawA);\n    Eigen::Quaterniond qB = euler2Quaternion(rollB,pitchB,yawB);\n    //Eigen::Quaterniond qA1 = euler2Quaternion1(rollA,pitchA,yawA);\n    rotationA = qA.toRotationMatrix();\n    rotationB = qB.toRotationMatrix();\n\n    //Eigen::Matrix3d rmx1 = qA1.matrix();\n    // Q2\n    std::cout<<\"\\nQuestion 2\\n\";\n    std::cout<<\"Rotation matrix A is\\n\"; \n    std::cout << rotationA <<\"\\n\";\n    //std::cout <<\"\\n\\n\"<< rmx1 <<\"\\n\\n\";\n\n    std::cout<<\"Rotation matrix B is\\n\";\n    std::cout << rotationB <<\"\\n\";\n\n    std::cout<<\"matrixA*matrixB is\\n\";\n    std::cout << rotationA*rotationB <<\"\\n\";\n\n    std::cout<<\"matrixB*matrixA is\\n\";\n    std::cout << rotationB*rotationA <<\"\\n\";    \n    // Q3\n    std::cout<<\"\\nQuestion 3\\n\";\n    std::cout<<\"Quarternion A:\"<<qA.w()<<\" \"<<qA.x()<<\" \"<<qA.y()<<\" \"<<qA.z()<<std::endl;\n    std::cout<<\"Quarternion B:\"<<qB.w()<<\" \"<<qB.x()<<\" \"<<qB.y()<<\" \"<<qB.z()<<std::endl;\n    \n    // Q4\n    std::cout<<\"\\nQuestion 4\\n\";\n    Quaterniond qC = qA*qB;\n    Quaterniond qD = qB*qA;\n    std::cout<<\"Quarternion C:\"<<qC.w()<<\" \"<<qC.x()<<\" \"<<qC.y()<<\" \"<<qC.z()<<std::endl;\n    std::cout<<\"Quarternion D:\"<<qD.w()<<\" \"<<qD.x()<<\" \"<<qD.y()<<\" \"<<qD.z()<<std::endl;\n    Quaterniond qE = qA * qB.inverse();\n    Quaterniond qF = qE*qB;\n    std::cout<<\"Quarternion E:\"<<qE.w()<<\" \"<<qE.x()<<\" \"<<qE.y()<<\" \"<<qE.z()<<std::endl;\n    std::cout<<\"Quarternion F:\"<<qF.w()<<\" \"<<qF.x()<<\" \"<<qF.y()<<\" \"<<qF.z()<<std::endl;\n}\n", "meta": {"hexsha": "f9d4c80a761ab00cfc3d5831c5f4f49eeab6d896", "size": 2160, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rotation.cpp", "max_stars_repo_name": "khushhallchandra/CMU-assignment", "max_stars_repo_head_hexsha": "097efdeb4a521681dfea0648acb16e9ee2e8582a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rotation.cpp", "max_issues_repo_name": "khushhallchandra/CMU-assignment", "max_issues_repo_head_hexsha": "097efdeb4a521681dfea0648acb16e9ee2e8582a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rotation.cpp", "max_forks_repo_name": "khushhallchandra/CMU-assignment", "max_forks_repo_head_hexsha": "097efdeb4a521681dfea0648acb16e9ee2e8582a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.75, "max_line_length": 90, "alphanum_fraction": 0.5814814815, "num_tokens": 719, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947148047778, "lm_q2_score": 0.8705972818382005, "lm_q1q2_score": 0.822709830060505}}
{"text": "#include \"iostream\"\nusing namespace std;\n\n#include <ctime>\n// include Core and Dense compuation parts from Eigen\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\n#define MATRIX_SIZE 20\n\n/**************************************************\n * Exercise 6\n * Different ways to solve linear equation: Ax = b\n * For more info, can refer to: https://eigen.tuxfamily.org/dox/group__TutorialLinearAlgebra.html\n * https://eigen.tuxfamily.org/dox/group__LeastSquares.html\n * 1. (If invertible): Take A^-1 and left multiply to b\n * 2. SVD decomposition\n * 3. QR decomposition\n * 4. Use Normal equations: solve A^T Ax = A^T b\n * 5. LU decomposition\n * 6. LLT decomposition: Need A to be positive definite\n * 7. LDLT decomposition (Cholesky algorithm): Need A to be positive/negative semi-definite\n * *************************************************/\n\nint main(int argc, char** argv) {\n    Matrix<double, Dynamic, Dynamic> A = MatrixXd::Random(MATRIX_SIZE, MATRIX_SIZE);\n    // since A*A^T is always positive definite, use it as an example\n    A = A * A.transpose();\n    \n    Matrix<double, Dynamic, Dynamic> b = MatrixXd::Random(MATRIX_SIZE, 1);\n\n    // 1. take the inverse\n    // count the time\n    clock_t start_time = clock();\n    Matrix<double, MATRIX_SIZE, 1> x1 = A.inverse() * b;\n    cout << \"time of normal inverse is \" << 1000 * (clock() - start_time) / (double) CLOCKS_PER_SEC << \"ms\" << endl;\n    cout << \"result is: \" << x1.transpose() << endl;\n\n\n    // 2. SVD decomposition\n    start_time = clock();\n    cout << \"The least-square SVD solution is: \\n\" << A.bdcSvd(ComputeThinU | ComputeThinV).solve(b) << endl;\n    cout << \"time of SVD decomposition is \" << 1000 * (clock() - start_time) / (double) CLOCKS_PER_SEC << \"ms\" << endl;\n\n\n    // 3. QR decomposition\n    /**\n     * The solve() method in QR decomposition classes also computes the least squares solution. \n     * There are three QR decomposition classes: HouseholderQR (no pivoting, fast but unstable if your matrix is not rull rank), \n     * ColPivHouseholderQR (column pivoting, thus a bit slower but more stable) \n     * and FullPivHouseholderQR (full pivoting, so slowest and slightly more stable than ColPivHouseholderQR).\n     */\n    start_time = clock();\n    cout << \"The least-square QR decomposition solution is: \\n\" << A.colPivHouseholderQr().solve(b) << endl;\n    cout << \"time of QR decomposition is \" << 1000 * (clock() - start_time) / (double) CLOCKS_PER_SEC << \"ms\" << endl;\n\n\n    // 4. Normal Equation\n    /**\n     * This method is usually the fastest, especially when A is \"tall and skinny\". \n     * However, if the matrix A is even mildly ill-conditioned, this is not a good method, \n     * because the condition number of ATA is the square of the condition number of A. \n     * This means that you lose roughly twice as many digits of accuracy using the normal equation, compared to the more stable methods mentioned above.\n     */\n    start_time = clock();\n    cout << \"The Normal equation solution is: \\n\" << (A.transpose() * A).ldlt().solve(A.transpose() * b) << endl;\n    cout << \"time of Normal Equation is \" << 1000 * (clock() - start_time) / (double) CLOCKS_PER_SEC << \"ms\" << endl;\n\n\n    // 5. LU decomposition\n    start_time = clock();\n    cout << \"The LU decomposition solution is: \\n\" << A.lu().solve(b) << endl;\n    cout << \"time of LU decomposition is \" << 1000 * (clock() - start_time) / (double) CLOCKS_PER_SEC << \"ms\" << endl;\n\n    // 6. LLT decomposition\n    start_time = clock();\n    cout << \"The LLT decomposition solution is: \\n\" << A.llt().solve(b) << endl;\n    cout << \"time of LLT decomposition is \" << 1000 * (clock() - start_time) / (double) CLOCKS_PER_SEC << \"ms\" << endl;\n\n    // 6. LDLT decomposition\n    start_time = clock();\n    cout << \"The LDLT decomposition solution is: \\n\" << A.ldlt().solve(b) << endl;\n    cout << \"time of LDLT decomposition is \" << 1000 * (clock() - start_time) / (double) CLOCKS_PER_SEC << \"ms\" << endl;\n\n\n\n}\n\n\n\n\n\n\n", "meta": {"hexsha": "4ec008e2dfabde05dcda9a523b6e0ee656c42729", "size": 3969, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch3/exercises/solveLinearEquations.cpp", "max_stars_repo_name": "henryxuy/slam-codeInBook-en", "max_stars_repo_head_hexsha": "ec3c8ec8d5facfdeb0832be121de105cea73790b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch3/exercises/solveLinearEquations.cpp", "max_issues_repo_name": "henryxuy/slam-codeInBook-en", "max_issues_repo_head_hexsha": "ec3c8ec8d5facfdeb0832be121de105cea73790b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch3/exercises/solveLinearEquations.cpp", "max_forks_repo_name": "henryxuy/slam-codeInBook-en", "max_forks_repo_head_hexsha": "ec3c8ec8d5facfdeb0832be121de105cea73790b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.34375, "max_line_length": 152, "alphanum_fraction": 0.6422272613, "num_tokens": 1069, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102561735719, "lm_q2_score": 0.8499711832583696, "lm_q1q2_score": 0.8222708401361334}}
{"text": "/* Point-based registration implemented via the method of \"Least-Squares Fitting of Two 3-D Point Sets\", Arun et al, 1987 */\n\n#include <iostream>\n\n#include <Eigen/Dense>\n#include <Eigen/SVD>\n#include <Eigen/Geometry>\n\n#include <PointMatching.hpp>\n#include <Exceptions.hpp>\n#include <Util.hpp>\n\nEigen::Matrix3d find_rotation(const Eigen::MatrixXd& H) {\n    // Estimate rotation matrix given H, the matrix product of residuals in both pointsets.\n\n    Eigen::JacobiSVD<Eigen::MatrixXd> svd(H, Eigen::ComputeFullU | Eigen::ComputeFullV);\n\n    Eigen::Matrix3d rotation;\n\n    auto proposed_rotation = svd.matrixV()*(svd.matrixU()).transpose();\n    if(isApproxEqual(proposed_rotation.determinant(), 1)) {\n        rotation = proposed_rotation;\n    } else if(isApproxEqual(proposed_rotation.determinant(), -1)) {\n        // Determinant of -1 can mean we've calculated a reflection (and so can compute a rotation) or we have insurmountable noise problems.\n        auto lambda = svd.singularValues();\n        if(isApproxEqual(lambda(2), 0) && !isApproxEqual(lambda(1), 0) && !isApproxEqual(lambda(0), 0)) { // This is a reflection.\n            auto V_new = svd.matrixV();\n            V_new.block(0,2,V_new.rows(),1) = -1 * V_new.block(0,2,V_new.rows(),1);\n            rotation = V_new*(svd.matrixU()).transpose();\n        } else {\n            std::cerr << \"Could not find a rotation. Colinear point cloud seems likely, or perhaps very noisy data?\" << std::endl;\n            throw(PointMatchingEx);\n        }\n    } else {\n        std::cerr << \"Could not find a rotation from SVD. Very noisy or otherwise invalid data?\" << std::endl;\n        throw(PointMatchingEx);\n    }\n\n    return rotation;\n}\n\nEigen::Matrix4d estimate_rigid_transform(const Eigen::MatrixXd& pointset, const Eigen::MatrixXd& pointset_dash) {\n    // Find a rigid transform that maps pointset to pointset_dash, with least error.\n\n    if(pointset.cols() < 4 || pointset_dash.cols() < 4) {\n        std::cerr << \"Not enough points provided -- there should be at least four points in the point cloud.\" << std::endl;\n        throw(PointMatchingEx);\n    }\n\n    if(pointset.rows() != 3 || pointset_dash.rows() != 3) {\n        std::cerr << \"Points must be 3D.\" << std::endl;\n        throw(PointMatchingEx);\n    }\n\n    if(pointset.cols() != pointset_dash.cols()) {\n        std::cerr << \"Pointsets must have the same number of points.\" << std::endl;\n        throw(PointMatchingEx);\n    }\n\n    auto p_average = find_pointset_average(pointset);\n    auto p_dash_average = find_pointset_average(pointset_dash);\n\n    auto q = residuals_from_point(pointset, p_average);\n    auto q_dash = residuals_from_point(pointset_dash, p_dash_average);\n\n    auto H = q * q_dash.transpose();\n\n    auto rotation = find_rotation(H);\n\n    auto translation = p_dash_average - rotation*p_average;\n\n    auto final_transform = compose_final_transform(rotation, translation);\n\n    return final_transform;\n}\n\ndouble fiducial_registration_error(const Eigen::MatrixXd& pointset, const Eigen::MatrixXd& pointset_dash, const Eigen::Matrix4d& transform) {\n    auto transformed = apply_transform(pointset, transform);\n\n    auto error_per_vector = distances_between_pointsets(transformed, pointset_dash);\n    auto fre = root_mean_square(error_per_vector);\n\n    return fre;\n}\n", "meta": {"hexsha": "1a93321fddc41fb0fa4418b9edf34b6f56d1b912", "size": 3284, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Code/PointMatching/PointMatching.cc", "max_stars_repo_name": "karnival/simple-registration", "max_stars_repo_head_hexsha": "0a7d952e566f0117c0d75f77337c23cfc97a3e7f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-02-04T00:54:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-04T00:54:17.000Z", "max_issues_repo_path": "Code/PointMatching/PointMatching.cc", "max_issues_repo_name": "karnival/simple-registration", "max_issues_repo_head_hexsha": "0a7d952e566f0117c0d75f77337c23cfc97a3e7f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code/PointMatching/PointMatching.cc", "max_forks_repo_name": "karnival/simple-registration", "max_forks_repo_head_hexsha": "0a7d952e566f0117c0d75f77337c23cfc97a3e7f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-01-20T14:50:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-20T14:50:14.000Z", "avg_line_length": 38.6352941176, "max_line_length": 141, "alphanum_fraction": 0.6836175396, "num_tokens": 792, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731126558705, "lm_q2_score": 0.853912747375134, "lm_q1q2_score": 0.8220388424521463}}
{"text": "/*\nhttps://stackoverflow.com/questions/34662940/how-to-compute-basis-of-nullspace-with-eigen-library\n*/\n#include <Eigen/Dense>\n#include <iostream>\n\nvoid fullPivLU()\n{\n//https://stackoverflow.com/questions/31041921/how-to-get-rank-of-a-matrix-in-eigen-library\n\n    Eigen::Matrix3d mat;\n    mat<<2, 1, -1,\n         -3, -1, 2,\n         -2, 1, 2;\n\n    Eigen::FullPivLU<Eigen::Matrix3d> lu_decomp(mat);\n    //Eigen::FullPivHouseholderQR\n    auto rank = lu_decomp.rank();\n    std::cout<<\"Rank:\" <<rank <<std::endl;\n\n\n    std::cout<<\"Kernel:\\n\" <<lu_decomp.kernel()<<std::endl;\n\n\n    std::cout<<\"MatrixLU:\\n\" <<lu_decomp.matrixLU()<<std::endl;\n\n\n    std::cout<<\"Determinant:\" <<lu_decomp.determinant()<<std::endl;\n\n//    lu_decomp.permutationP();\n//    std::cout<<lu_decomp.kernel()<<std::endl;\n\n//    lu_decomp.permutationQ();\n//    std::cout<<lu_decomp.kernel()<<std::endl;\n\n\n\n}\n\nvoid completeOrthogonalDecompositionNullSpace()\n{\n    Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> mat37(3,7);\n    mat37 = Eigen::MatrixXd::Random(3, 7);\n\n    Eigen::CompleteOrthogonalDecomposition<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > cod;\n    cod.compute(mat37);\n    std::cout << \"rank : \" << cod.rank() << \"\\n\";\n    // Find URV^T\n    Eigen::MatrixXd V = cod.matrixZ().transpose();\n    Eigen::MatrixXd Null_space = V.block(0, cod.rank(),V.rows(), V.cols() - cod.rank());\n    Eigen::MatrixXd P = cod.colsPermutation();\n    Null_space = P * Null_space; // Unpermute the columns\n    // The Null space:\n    std::cout << \"The null space: \\n\" << Null_space << \"\\n\" ;\n    // Check that it is the null-space:\n    std::cout << \"mat37 * Null_space = \\n\" << mat37 * Null_space  << '\\n';\n}\n\nint main()\n{\n    completeOrthogonalDecompositionNullSpace();\n}\n", "meta": {"hexsha": "7363140f05ace997803f82d6f307d1e1be85399d", "size": 1746, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/null_space_kernel_rank.cpp", "max_stars_repo_name": "behnamasadi/EigenDemo", "max_stars_repo_head_hexsha": "f09e1f530ff9c206389722b195e11cf69cf9e92b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-04-14T16:54:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-13T15:55:08.000Z", "max_issues_repo_path": "src/null_space_kernel_rank.cpp", "max_issues_repo_name": "behnamasadi/EigenDemo", "max_issues_repo_head_hexsha": "f09e1f530ff9c206389722b195e11cf69cf9e92b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/null_space_kernel_rank.cpp", "max_forks_repo_name": "behnamasadi/EigenDemo", "max_forks_repo_head_hexsha": "f09e1f530ff9c206389722b195e11cf69cf9e92b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-12-25T10:08:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-06T14:27:32.000Z", "avg_line_length": 27.7142857143, "max_line_length": 103, "alphanum_fraction": 0.6351660939, "num_tokens": 514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625126757596, "lm_q2_score": 0.8824278540866548, "lm_q1q2_score": 0.8219484662226341}}
{"text": "//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\file Operations.hpp\n/// \\brief Header file for the SE3 Lie Group math functions.\n/// \\details These namespace functions provide implementations of the special Euclidean (SE)\n///          Lie group functions that we commonly use in robotics.\n///\n/// \\author Sean Anderson\n//////////////////////////////////////////////////////////////////////////////////////////////\n\n#ifndef LGM_SE3_PUBLIC_HPP\n#define LGM_SE3_PUBLIC_HPP\n\n#include <Eigen/Core>\n\n/////////////////////////////////////////////////////////////////////////////////////////////\n/// Lie Group Math - Special Euclidean Group\n/////////////////////////////////////////////////////////////////////////////////////////////\nnamespace lgmath {\nnamespace se3 {\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Builds the 4x4 \"skew symmetric matrix\"\n///\n/// The hat (^) operator, builds the 4x4 skew symmetric matrix from the 3x1 axis angle\n/// vector and 3x1 translation vector.\n///\n/// hat(rho, aaxis) = [aaxis^ rho] = [0.0  -a3   a2  rho1]\n///                   [  0^T    0]   [ a3  0.0  -a1  rho2]\n///                                  [-a2   a1  0.0  rho3]\n///                                  [0.0  0.0  0.0   0.0]\n///\n/// See eq. 4 in Barfoot-TRO-2014 for more information.\n//////////////////////////////////////////////////////////////////////////////////////////////\nEigen::Matrix4d hat(const Eigen::Vector3d& rho, const Eigen::Vector3d& aaxis);\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Builds the 4x4 \"skew symmetric matrix\"\n///\n/// The hat (^) operator, builds the 4x4 skew symmetric matrix from\n/// the 6x1 se3 algebra vector, xi:\n///\n/// xi^ = [rho  ] = [aaxis^ rho] = [0.0  -a3   a2  rho1]\n///       [aaxis]   [  0^T    0]   [ a3  0.0  -a1  rho2]\n///                                [-a2   a1  0.0  rho3]\n///                                [0.0  0.0  0.0   0.0]\n///\n/// See eq. 4 in Barfoot-TRO-2014 for more information.\n//////////////////////////////////////////////////////////////////////////////////////////////\nEigen::Matrix4d hat(const Eigen::Matrix<double,6,1>& xi);\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Builds the 6x6 \"curly hat\" matrix (related to the skew symmetric matrix)\n///\n/// The curly hat operator builds the 6x6 skew symmetric matrix from the 3x1 axis angle\n/// vector and 3x1 translation vector.\n///\n/// curlyhat(rho, aaxis) = [aaxis^   rho^]\n///                        [     0 aaxis^]\n///\n/// See eq. 12 in Barfoot-TRO-2014 for more information.\n//////////////////////////////////////////////////////////////////////////////////////////////\nEigen::Matrix<double,6,6> curlyhat(const Eigen::Vector3d& rho, const Eigen::Vector3d& aaxis);\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Builds the 6x6 \"curly hat\" matrix (related to the skew symmetric matrix)\n///\n/// The curly hat operator builds the 6x6 skew symmetric matrix\n/// from the 6x1 se3 algebra vector, xi:\n///\n/// curlyhat(xi) = curlyhat([rho  ]) = [aaxis^   rho^]\n///                        ([aaxis])   [     0 aaxis^]\n///\n/// See eq. 12 in Barfoot-TRO-2014 for more information.\n//////////////////////////////////////////////////////////////////////////////////////////////\nEigen::Matrix<double,6,6> curlyhat(const Eigen::Matrix<double,6,1>& xi);\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Turns a homogeneous point into a special 4x6 matrix (circle-dot operator)\n///\n/// See eq. 72 in Barfoot-TRO-2014 for more information.\n//////////////////////////////////////////////////////////////////////////////////////////////\nEigen::Matrix<double,4,6> point2fs(const Eigen::Vector3d& p, double scale = 1);\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Turns a homogeneous point into a special 6x4 matrix (double-circle operator)\n///\n/// See eq. 72 in Barfoot-TRO-2014 for more information.\n//////////////////////////////////////////////////////////////////////////////////////////////\nEigen::Matrix<double,6,4> point2sf(const Eigen::Vector3d& p, double scale = 1);\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Builds a transformation matrix using the analytical exponential map\n///\n/// This function builds a transformation matrix, T_ab, using the analytical exponential map,\n/// from the se3 algebra vector, xi_ba,\n///\n///   T_ab = exp(xi_ba^) = [ C_ab r_ba_ina],   xi_ba = [  rho_ba]\n///                        [  0^T        1]            [aaxis_ba]\n///\n/// where C_ab is a 3x3 rotation matrix from 'b' to 'a', r_ba_ina is the 3x1 translation\n/// vector from 'a' to 'b' expressed in frame 'a', aaxis_ba is a 3x1 axis-angle vector,\n/// the magnitude of the angle of rotation can be recovered by finding the norm of the vector,\n/// and the axis of rotation is the unit-length vector that arises from normalization.\n/// Note that the angle around the axis, aaxis_ba, is a right-hand-rule (counter-clockwise\n/// positive) angle from 'a' to 'b'.\n///\n/// The parameter, rho_ba, is a special translation-like parameter related to 'twist' theory.\n/// It is most inuitively described as being like a constant linear velocity (expressed in\n/// the smoothly-moving frame) for a fixed duration; for example, consider the curve of a\n/// car driving 'x' meters while turning at a rate of 'y' rad/s.\n///\n/// For more information see Barfoot-TRO-2014 Appendix B1.\n///\n/// Alternatively, we that note that\n///\n///   T_ba = exp(-xi_ba^) = exp(xi_ab^).\n///\n/// Both the analytical (numTerms = 0) or the numerical (numTerms > 0) may be evaluated.\n//////////////////////////////////////////////////////////////////////////////////////////////\nvoid vec2tran_analytical(const Eigen::Vector3d& rho_ba, const Eigen::Vector3d& aaxis_ba,\n                         Eigen::Matrix3d* out_C_ab, Eigen::Vector3d* out_r_ba_ina);\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Builds a transformation matrix using the first N terms of the infinite series\n///\n/// Builds a transformation matrix numerically using the infinite series evalation\n/// of the exponential map.\n///\n/// For more information see eq. 96 in Barfoot-TRO-2014\n//////////////////////////////////////////////////////////////////////////////////////////////\nvoid vec2tran_numerical(const Eigen::Vector3d& rho_ba, const Eigen::Vector3d& aaxis_ba,\n                        Eigen::Matrix3d* out_C_ab, Eigen::Vector3d* out_r_ba_ina,\n                        unsigned int numTerms = 0);\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Builds the 3x3 rotation and 3x1 translation using the exponential map, the\n///        default parameters (numTerms = 0) use the analytical solution.\n//////////////////////////////////////////////////////////////////////////////////////////////\nvoid vec2tran(const Eigen::Matrix<double,6,1>& xi_ba, Eigen::Matrix3d* out_C_ab,\n              Eigen::Vector3d* out_r_ba_ina, unsigned int numTerms = 0);\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Builds a 4x4 transformation matrix using the exponential map, the\n///        default parameters (numTerms = 0) use the analytical solution.\n//////////////////////////////////////////////////////////////////////////////////////////////\nEigen::Matrix4d vec2tran(const Eigen::Matrix<double,6,1>& xi_ba, unsigned int numTerms = 0);\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Compute the matrix log of a transformation matrix (from the rotation and trans)\n///\n/// Compute the inverse of the exponential map (the logarithmic map). This lets us go from\n/// a the 3x3 rotation and 3x1 translation vector back to a 6x1 se3 algebra vector (composed\n/// of a 3x1 axis-angle vector and 3x1 twist-translation vector). In some cases, when the\n/// rotation in the transformation matrix is 'numerically off', this involves some\n/// 'projection' back to SE(3).\n///\n///   xi_ba = ln(T_ab)\n///\n/// where xi_ba is the 6x1 se3 algebra vector. Alternatively, we that note that\n///\n///   xi_ab = -xi_ba = ln(T_ba) = ln(T_ab^{-1})\n///\n/// See Barfoot-TRO-2014 Appendix B2 for more information.\n//////////////////////////////////////////////////////////////////////////////////////////////\nEigen::Matrix<double,6,1> tran2vec(const Eigen::Matrix3d& C_ab,\n                                   const Eigen::Vector3d& r_ba_ina);\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Compute the matrix log of a transformation matrix\n///\n/// Compute the inverse of the exponential map (the logarithmic map). This lets us go from\n/// a 4x4 transformation matrix back to a 6x1 se3 algebra vector (composed of a 3x1 axis-angle\n/// vector and 3x1 twist-translation vector). In some cases, when the rotation in the\n/// transformation matrix is 'numerically off', this involves some 'projection' back to SE(3).\n///\n///   xi_ba = ln(T_ab)\n///\n/// where xi_ba is the 6x1 se3 algebra vector. Alternatively, we that note that\n///\n///   xi_ab = -xi_ba = ln(T_ba) = ln(T_ab^{-1})\n///\n/// See Barfoot-TRO-2014 Appendix B2 for more information.\n//////////////////////////////////////////////////////////////////////////////////////////////\nEigen::Matrix<double,6,1> tran2vec(const Eigen::Matrix4d& T_ab);\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Builds the 6x6 adjoint transformation matrix from the 3x3 rotation matrix and 3x1\n///        translation vector.\n///\n/// Builds the 6x6 adjoint transformation matrix from the 3x3 rotation matrix and 3x1\n///        translation vector.\n///\n///  Adjoint(T_ab) = Adjoint([C_ab r_ba_ina]) = [C_ab r_ba_ina^*C_ab] = exp(curlyhat(xi_ba))\n///                         ([ 0^T        1])   [   0           C_ab]\n///\n/// See eq. 101 in Barfoot-TRO-2014 for more information.\n//////////////////////////////////////////////////////////////////////////////////////////////\nEigen::Matrix<double,6,6> tranAd(const Eigen::Matrix3d& C_ab,\n                                 const Eigen::Vector3d& r_ba_ina);\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Builds the 6x6 adjoint transformation matrix from a 4x4 one\n///\n/// Builds the 6x6 adjoint transformation matrix from a 4x4 transformation matrix\n///\n///  Adjoint(T_ab) = Adjoint([C_ab r_ba_ina]) = [C_ab r_ba_ina^*C_ab] = exp(curlyhat(xi_ba))\n///                         ([ 0^T        1])   [   0           C_ab]\n///\n/// See eq. 101 in Barfoot-TRO-2014 for more information.\n//////////////////////////////////////////////////////////////////////////////////////////////\nEigen::Matrix<double,6,6> tranAd(const Eigen::Matrix4d& T_ab);\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Construction of the 3x3 \"Q\" matrix, used in the 6x6 Jacobian of SE(3)\n///\n/// See eq. 102 in Barfoot-TRO-2014 for more information\n//////////////////////////////////////////////////////////////////////////////////////////////\nEigen::Matrix3d vec2Q(const Eigen::Vector3d& rho_ba, const Eigen::Vector3d& aaxis_ba);\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Construction of the 3x3 \"Q\" matrix, used in the 6x6 Jacobian of SE(3)\n///\n/// See eq. 102 in Barfoot-TRO-2014 for more information\n//////////////////////////////////////////////////////////////////////////////////////////////\nEigen::Matrix3d vec2Q(const Eigen::Matrix<double,6,1>& xi_ba);\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Builds the 6x6 Jacobian matrix of SE(3) using the analytical expression\n///\n/// Build the 6x6 left Jacobian of SE(3).\n///\n/// For the sake of a notation, we assign subscripts consistence with the transformation,\n///\n///   J_ab = J(xi_ba)\n///\n/// Where applicable, we also note that\n///\n///   J(xi_ba) = Adjoint(exp(xi_ba^)) * J(-xi_ba),\n///\n/// and\n///\n///   Adjoint(exp(xi_ba^)) = identity + curlyhat(xi_ba) * J(xi_ba).\n///\n/// For more information see eq. 100 in Barfoot-TRO-2014.\n//////////////////////////////////////////////////////////////////////////////////////////////\nEigen::Matrix<double,6,6> vec2jac(const Eigen::Vector3d& rho_ba,\n                                  const Eigen::Vector3d& aaxis_ba);\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Builds the 6x6 Jacobian matrix of SE(3) from the se(3) algebra; note that the\n///        default parameter (numTerms = 0) will call the analytical solution, but the\n///        numerical solution can also be evaluating to some number of terms.\n///\n/// For more information see eq. 100 in Barfoot-TRO-2014.\n//////////////////////////////////////////////////////////////////////////////////////////////\nEigen::Matrix<double,6,6> vec2jac(const Eigen::Matrix<double,6,1>& xi_ba,\n                                  unsigned int numTerms = 0);\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Builds the 6x6 inverse Jacobian matrix of SE(3) using the analytical expression\n///\n/// Build the 6x6 inverse left Jacobian of SE(3).\n///\n/// For the sake of a notation, we assign subscripts consistence with the transformation,\n///\n///   J_ab_inverse = J(xi_ba)^{-1},\n///\n/// Please note that J_ab_inverse is not equivalent to J_ba:\n///\n///   J(xi_ba)^{-1} != J(-xi_ba)\n///\n/// For more information see eq. 103 in Barfoot-TRO-2014.\n//////////////////////////////////////////////////////////////////////////////////////////////\nEigen::Matrix<double,6,6> vec2jacinv(const Eigen::Vector3d& rho_ba,\n                                     const Eigen::Vector3d& aaxis_ba);\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Builds the 6x6 inverse Jacobian matrix of SE(3) from the se(3) algebra; note that\n///        the default parameter (numTerms = 0) will call the analytical solution, but the\n///        numerical solution can also be evaluating to some number of terms.\n///\n/// For more information see eq. 103 in Barfoot-TRO-2014.\n//////////////////////////////////////////////////////////////////////////////////////////////\nEigen::Matrix<double,6,6> vec2jacinv(const Eigen::Matrix<double,6,1>& xi_ba,\n                                     unsigned int numTerms = 0);\n\n} // se3\n} // lgmath\n\n#endif // LGM_SE3_PUBLIC_HPP\n", "meta": {"hexsha": "865b7bd4ef6a399fcc27a9e74394fa3e4b533d51", "size": 14934, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/lgmath/se3/Operations.hpp", "max_stars_repo_name": "utiasASRL/lgmath", "max_stars_repo_head_hexsha": "d767997cc183f13f5d77ef3056f0c78af37547ae", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2019-11-18T11:56:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T15:55:11.000Z", "max_issues_repo_path": "include/lgmath/se3/Operations.hpp", "max_issues_repo_name": "utiasASRL/lgmath", "max_issues_repo_head_hexsha": "d767997cc183f13f5d77ef3056f0c78af37547ae", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-05-06T21:31:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-08T15:23:38.000Z", "max_forks_repo_path": "include/lgmath/se3/Operations.hpp", "max_forks_repo_name": "utiasASRL/lgmath", "max_forks_repo_head_hexsha": "d767997cc183f13f5d77ef3056f0c78af37547ae", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-11-18T11:56:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-12T15:15:09.000Z", "avg_line_length": 51.3195876289, "max_line_length": 94, "alphanum_fraction": 0.4725458685, "num_tokens": 3234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632343454895, "lm_q2_score": 0.8633916187614823, "lm_q1q2_score": 0.8218307387410924}}
{"text": "//\n// Created by light on 01.03.21.\n//\n\n#include <iostream>\n#include <eigen3/Eigen/Dense>\n\nusing namespace Eigen;\nusing namespace std;\n\nbool COMPARE (Eigen::MatrixXd& A, Eigen::MatrixXd& B){\n\n    if (A.norm() - B.norm() < 1e-4){\n\n        return true;\n    }\n\n}\n\n\n\nint main(){\n\n/*  A = [ 1 2 3 4 ; 5 6 7 8 ; 9 10 11 12; 13 14 15 16]\n\n For simplicity reasons we would be considering this matrix. b = [ 1  1 1 1], in case we have to Ax=b\n\n  */\n\n// creating a Matrix\n\nEigen::Matrix <double, 4,4, Eigen::RowMajor> Matrix1;\nMatrix1 << 1, 2, 3, 4,  5, 6, 7, 8 , 9, 10, 11, 12, 13, 14, 15, 16;\n\n// creating a Matrix 2nd way using a temporary matrix\nEigen::Matrix<double, 4,4, Eigen::RowMajor> Matrix2 = (Eigen::Matrix<double,4,4,RowMajor> () << 1, 2, 3, 4,  5, 6, 7, 8 , 9, 10, 11, 12, 13, 14, 15, 16 ).finished();\n\nstd::cout << \"The first matrix is  \\n \" << Matrix1  << \" \\n\"\n          << \" Second matrix is    \\n \" << Matrix2 << std::endl;\n\n\n/* create a row vector or column vector\n\n a. Vector2f, Vector3f, Vector4f This should give nx1 matrix (n rows and 1 column) something like [1 2 3 4]'\n b. RowVector2f, RowVector3f, RowVector4f Gives out  1xn (1 row and n columns), something like [1 2 3 4]\n c. VectorXf or VectorXd -> Dynamic Columns of floats or doubles.\n In general d implies double and f suffix implies it's float\n\n*/\n\nVector2f V2 = (Vector2f() << 1,2).finished();\nVector3d V3;\nV3 << 1,2,3 ;\n\nRowVector2f  RV2 = (RowVector2f()<< 1,2 ).finished();\n\n/*std::cout << \"Default is a colum vector \\n\" <<\n             \" V2 is = \\n\" << V2 << \"\\n\" <<\n             \" v3 is = \\n \" << V3 << std::endl;\n*/\n//std::cout << \"RowVector2f is given by \\n\" << RV2 << std::endl;\n// Other nicer ways to initialize a matrix are\nEigen::Matrix < double, 4,4, RowMajor > A_zero = Eigen::MatrixXd::Zero(4,4);\nMatrix4d A_identity = MatrixXd::Identity(4,4);\nMatrix4d A_setone = MatrixXd::Ones(4,4); // the r value is basically eye(4,4)\n\n//reinitialize an existing Matrix\nMatrix1.setZero();\n//std::cout << \"A_zero is \\n\" << A_zero << \"\\n\" << \"Matrix1 is reset to zero \\n\" << Matrix1 << std::endl;\nMatrix1.setOnes();\nMatrix1.setRandom();\n//std::cout << \"Matrix1 is reset to Random \\n\" << Matrix1 << std::endl;\nMatrix1.setIdentity(); // Matrix1 = eye(N);\n\n// Lengths of different tensors.\n\nMatrix1.size(); // total size 4x4 = 16\nMatrix1.rows(); //number of rows\nMatrix1.cols(); // number of cols\n\n// Element wise operations\n\n//to access specific element\nMatrix1(1,2);  // This should give out element at 2nd row and third cols, Remember the indices are i-1 and j-1 if you think in terms of matlab\n// for vectors it's simply V2(1) or V2(2) etc.,\n\n// to access specific row\nMatrix2.row(0); // This gives out first row\nstd::cout << Matrix2.row(0) << std::endl;\nMatrix2.col(0); // This gives out 1 col\nstd::cout << Matrix2.col(0) << std::endl;\n\n// to change specific row or cols\n\nMatrix2.col(0) << 1,2,3,4;\nstd::cout << Matrix2.col(0) << std::endl;\nstd::cout << Matrix2 << std::endl;\n\n// to access a specific block;\n\nMatrix2.block<2,2>(1, 1)  << 1.2, 1.3, 1.4, 1.5 ; // This is an interesting operation, it extracts the specific block and assigns value to it\n// for example here we would like to extract a block of 2 rows and 2 columns as descrbed inside <> . And the numbers inside braces indicate the starting col and starting row\n// here it's 1,1 which means 2,2 as the value is taken 1 less than actual value of rol or col\n//std::cout << Matrix2 << std::endl;\n\n\n\n// Resizing an existing matrix, matrix1 is 4x4. This can resized to 2x8, 8x2, 1x16 and 16x1\n//Matrix1.resize(2,8); // This normally fails due to assertations, i wouldn't wanna tamper with assertations at this stage\n//std::cout << Matrix1  << std::endl;\n\n\n// Stacking Vectors or Matrices\nMatrix1.setRandom();\nMatrixXd M( Matrix1.rows() + Matrix1.rows()+ Matrix1.rows(), Matrix1.cols()); // I could have written Matrix1.rows()*3, in case there were m << A,B,C; then we need to write em individually\nM << Matrix1, Matrix1, Matrix1;\nstd::cout << M << std::endl;\n\n\n// Filling all the elements with some constant value\n\nMatrix2.fill(1.0);\nstd::cout << Matrix2 << std::endl;\n\n\nVectorXd VX = VectorXd::LinSpaced(4,1,5) ;       // linspace(low,high,size)'\nVX.setLinSpaced(4,1,5);               // v = linspace(low,high,size)'\nstd::cout << VX << std::endl;\n\n// Matrix slicing\n// blocks -> always go for templated version, it has better speed up\n// there are two types of blocks one with vectors and second one with Matrix\n\n// for vectors, you simply pass on a single value\nint const n = 2;\nVX.head<n>() << 1, 2; // for head initial 2 values\nstd::cout << VX << std::endl;\nVX.tail<n>() << 3,4; // bottom two values or N-n till N\n\n// for matrix there is a block actually, you essentially pass on initial inidices of starting with size of the matrix as shown in line 101\n// Other try outs\n/*\n    P.col(j)                           // P(:, j+1)\n    P.leftCols<cols>()                 // P(:, 1:cols)\n    P.leftCols(cols)                   // P(:, 1:cols)\n    P.middleCols<cols>(j)              // P(:, j+1:j+cols)\n    P.middleCols(j, cols)              // P(:, j+1:j+cols)\n    P.rightCols<cols>()                // P(:, end-cols+1:end)\n    P.rightCols(cols)                  // P(:, end-cols+1:end)\n    P.topRows<rows>()                  // P(1:rows, :)\n    P.topRows(rows)                    // P(1:rows, :)\n    P.middleRows<rows>(i)              // P(i+1:i+rows, :)\n    P.middleRows(i, rows)              // P(i+1:i+rows, :)\n    P.bottomRows<rows>()               // P(end-rows+1:end, :)\n    P.bottomRows(rows)                 // P(end-rows+1:end, :)\n    P.topLeftCorner(rows, cols)        // P(1:rows, 1:cols)\n    P.topRightCorner(rows, cols)       // P(1:rows, end-cols+1:end)\n    P.bottomLeftCorner(rows, cols)     // P(end-rows+1:end, 1:cols)\n    P.bottomRightCorner(rows, cols)    // P(end-rows+1:end, end-cols+1:end)\n    P.topLeftCorner<rows,cols>()       // P(1:rows, 1:cols)\n    P.topRightCorner<rows,cols>()      // P(1:rows, end-cols+1:end)\n    P.bottomLeftCorner<rows,cols>()    // P(end-rows+1:end, 1:cols)\n    P.bottomRightCorner<rows,cols>()   // P(end-rows+1:end, end-cols+1:end)\n*/\n\n// Views, transpose, etc;\n// Eigen                           // Matlab\n /*    R.adjoint()                        // R'\n    R.transpose()                      // R.' or conj(R')       // Read-write\n    R.diagonal()                       // diag(R)               // Read-write\n    x.asDiagonal()                     // diag(x)\n    R.transpose().colwise().reverse()  // rot90(R)              // Read-write\n    R.rowwise().reverse()              // fliplr(R)\n    R.colwise().reverse()              // flipud(R)\n    R.replicate(i,j)                   // repmat(P,i,j)\n*/\n\n\n    // All the same as Matlab, but matlab doesn't have *= style operators.\n// Matrix-vector.  Matrix-matrix.   Matrix-scalar.\n  /*\n    y  = M*x;          R  = P*Q;        R  = P*s;\n    a  = b*M;          R  = P - Q;      R  = s*P;\n    a *= M;            R  = P + Q;      R  = P/s;\n    R *= Q;          R  = s*P;\n    R += Q;          R *= s;\n    R -= Q;          R /= s;\n\n   // Vectorized operations on each element independently\n// Eigen                       // Matlab\nR = P.cwiseProduct(Q);         // R = P .* Q\nR = P.array() * s.array();     // R = P .* s\nR = P.cwiseQuotient(Q);        // R = P ./ Q\nR = P.array() / Q.array();     // R = P ./ Q\nR = P.array() + s.array();     // R = P + s\nR = P.array() - s.array();     // R = P - s\nR.array() += s;                // R = R + s\nR.array() -= s;                // R = R - s\nR.array() < Q.array();         // R < Q\nR.array() <= Q.array();        // R <= Q\nR.cwiseInverse();              // 1 ./ P\nR.array().inverse();           // 1 ./ P\nR.array().sin()                // sin(P)\nR.array().cos()                // cos(P)\nR.array().pow(s)               // P .^ s\nR.array().square()             // P .^ 2\nR.array().cube()               // P .^ 3\nR.cwiseSqrt()                  // sqrt(P)\nR.array().sqrt()               // sqrt(P)\nR.array().exp()                // exp(P)\nR.array().log()                // log(P)\nR.cwiseMax(P)                  // max(R, P)\nR.array().max(P.array())       // max(R, P)\nR.cwiseMin(P)                  // min(R, P)\nR.array().min(P.array())       // min(R, P)\nR.cwiseAbs()                   // abs(P)\nR.array().abs()                // abs(P)\nR.cwiseAbs2()                  // abs(P.^2)\nR.array().abs2()               // abs(P.^2)\n(R.array() < s).select(P,Q );  // (R < s ? P : Q)\nR = (Q.array()==0).select(P,A) // R(Q==0) = P(Q==0)\nR = P.unaryExpr(ptr_fun(func)) // R = arrayfun(func, P)   // with: scalar func(const scalar &x\n\n//// Type conversion\n// Eigen                  // Matlab\nA.cast<double>();         // double(A)\nA.cast<float>();          // single(A)\nA.cast<int>();            // int32(A)\nA.real();                 // real(A)\nA.imag();                 // imag(A)\n// if the original type equals destination type, no work is done\n\n// Note that for most operations Eigen requires all operands to have the same type:\nMatrixXf F = MatrixXf::Zero(3,3);\nA += F;                // illegal in Eigen. In Matlab A = A+F is allowed\nA += F.cast<double>(); // F converted to double and then added (generally, conversion happens on-the-fly)\n\n// Eigen can map existing memory into Eigen matrices.\nfloat array[3];\nVector3f::Map(array).fill(10);            // create a temporary Map over array and sets entries to 10\nint data[4] = {1, 2, 3, 4};\nMatrix2i mat2x2(data);                    // copies data into mat2x2\nMatrix2i::Map(data) = 2*mat2x2;           // overwrite elements of data with 2*mat2x2\nMatrixXi::Map(data, 2, 2) += mat2x2;      // adds mat2x2 to elements of data (alternative syntax if size is not know at compile time)\n\n// Solve Ax = b. Result stored in x. Matlab: x = A \\ b.\nx = A.ldlt().solve(b));  // A sym. p.s.d.    #include <Eigen/Cholesky>\nx = A.llt() .solve(b));  // A sym. p.d.      #include <Eigen/Cholesky>\nx = A.lu()  .solve(b));  // Stable and fast. #include <Eigen/LU>\nx = A.qr()  .solve(b));  // No pivoting.     #include <Eigen/QR>\nx = A.svd() .solve(b));  // Stable, slowest. #include <Eigen/SVD>\n// .ldlt() -> .matrixL() and .matrixD()\n// .llt()  -> .matrixL()\n// .lu()   -> .matrixL() and .matrixU()\n// .qr()   -> .matrixQ() and .matrixR()\n// .svd()  -> .matrixU(), .singularValues(), and .matrixV()\n\n// Eigenvalue problems\n// Eigen                          // Matlab\nA.eigenvalues();                  // eig(A);\nEigenSolver<Matrix3d> eig(A);     // [vec val] = eig(A)\neig.eigenvalues();                // diag(val)\neig.eigenvectors();               // vec\n// For self-adjoint matrices use SelfAdjointEigenSolver<>\n\nThis was copied from\n\n*/\n\n}\n", "meta": {"hexsha": "35f13fc54c91224f4a0ea5087d1c4533f11bd128", "size": 10635, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "mdasifchand/EigenExamples", "max_stars_repo_head_hexsha": "81211b62cd991c15ee10842dbeaef1e47535a7eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "mdasifchand/EigenExamples", "max_issues_repo_head_hexsha": "81211b62cd991c15ee10842dbeaef1e47535a7eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.cpp", "max_forks_repo_name": "mdasifchand/EigenExamples", "max_forks_repo_head_hexsha": "81211b62cd991c15ee10842dbeaef1e47535a7eb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-06T14:29:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-06T14:29:33.000Z", "avg_line_length": 39.2435424354, "max_line_length": 188, "alphanum_fraction": 0.5506346968, "num_tokens": 3297, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.9046505318875316, "lm_q1q2_score": 0.8208004836419464}}
{"text": "\n#include <iostream>\n#include <Eigen/Dense>\n#include<fstream>\n#include<vector>\n\nusing namespace std;\nusing namespace Eigen;\n\n\n\n// TAREA 2\n\n\n// El codigo para la manipulacion de archivos fue modificado de la fuente dada por el curso\n// -> https://aleksandarhaber.com/eigen-matrix-library-c-tutorial-saving-and-loading-data-in-from-a-csv-file/\n\n\n//Funcion para guardar archivos\nvoid saveData(string fileName, MatrixXd  matrix)\n{\n\tconst static IOFormat CSVFormat(FullPrecision, DontAlignCols, \", \", \"\\n\");\n\n\tofstream file(fileName);\n\tif (file.is_open())\n\t{\n\t\tfile << matrix.format(CSVFormat);\n\t\tfile.close();\n\t}\n}\n\n\n//Funcion para abrir archivos\nMatrixXd openData(string fileToOpen)\n{\n\tvector<double> matrixEntries;\n\n\tifstream matrixDataFile(fileToOpen);\n\t\n\tstring matrixRowString;\n\t\n\tstring matrixEntry;\n\t\n\tint matrixRowNumber = 0;\n\n\n\twhile (getline(matrixDataFile, matrixRowString)) \n\t{\n\t\tstringstream matrixRowStringStream(matrixRowString); \n\n\t\twhile (getline(matrixRowStringStream, matrixEntry, ',')) \n\t\t{\n\t\t\tmatrixEntries.push_back(stod(matrixEntry));   \n\t\t}\n\t\tmatrixRowNumber++; \n\t}\n\n\treturn Map<Matrix<double, Dynamic, Dynamic, RowMajor>>(matrixEntries.data(), matrixRowNumber, matrixEntries.size() / matrixRowNumber);\n\n}\n\n\n\n//------------------------------------------------------------------------------\n\n//Funcion para obtener matriz identidad\nMatrixXd identidad(int filas, int cols) {\n\tMatrixXd N;\n\tN.resize(filas, cols);\n\tfor (int i = 0; i < filas; i++) {\n\t\tfor (int j = 0; j < cols; j++) {\n\t\t\tN(i,j) = 0.0;\n\t\t}\n\t\tN(i,i) = 1.0;\n\t}\n\treturn N;\n}\n\n\n//Funcion para cambiar filas\n\nMatrixXd cambiarFilas(MatrixXd  N, int r1, int r2) {\n\tfloat aux;\n\t\n\tfor (int i = 0; i < N.cols(); i++) {\n\t\taux = N(r1,i);\n\t\tN(r1,i) = N(r2,i);\n\t\tN(r2,i) = aux;\n\t}\n\n\treturn N;\n}\n\n//Funcion Multiplicar fila por constante\n\nMatrixXd FilaXCte(MatrixXd M, int r, float c) {\n\tfor (int i = 0; i < M.cols(); i++) {\n\t\tM(r,i)*= c;\n\t}\n\n\treturn M;\n}\n\n//Funcion Sumar filas\n\nMatrixXd sumarFilas(MatrixXd M, int r1, int r2, float c) {\n\tfor (int i = 0; i < M.cols(); i++) {\n\t\tM(r1,i) += M(r2,i) * c;\n\t}\n\n\treturn M;\n}\n\n//Gauss Jordan\n\nMatrixXd gaussjordann(MatrixXd  M) {\n\t\n\tMatrixXd Inv = identidad(M.rows(), M.cols());\n\tif (M.rows() == M.cols()) {\n\t\t\n\t\t\n\t\tfor (int i = 0; i < M.rows(); i++) {\n\t\t\tcout << Inv << \"\\n\";\n\t\t\t\n\t\t\tif (M(i,i) == 0.0) {\n\t\t\t\t\n\t\t\t\tint r = 0;\n\t\t\t\twhile (r < M.cols() && (M(i,r) == 0 || M(r,i) == 0)) {\n\t\t\t\t\tr++;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tM = cambiarFilas(M,i,r);\n\t\t\t}\n\t\t\tsystem(\"pause\");\n\t\t\tdouble c = 1.0 / M(i,i);\n\t\t\tM = FilaXCte(M, i, c);\n\t\t\tInv = FilaXCte(Inv, i, c);\n\t\t\tfor (int j = 0; j < M.rows(); j++) {\n\t\t\t\tif (i != j) {\n\t\t\t\t\tc = -M(j,i);\n\t\t\t\t\tM = sumarFilas(M, j, i, c);\n\t\t\t\t\tInv = sumarFilas(Inv, j, i, c);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}else {\n\t\tprintf(\"Error La matriz no cumple la regla de ser cuadrada \\n\");\n\t\t\n\t}\n\treturn Inv;\n}\n\n//Cofactores\n\nMatrixXd Cofactores(MatrixXd  M) {\n\t\n\tMatrixXd Inv = identidad(M.rows(), M.cols());\n\tif (M.rows() == M.cols()) {\n\t\t\n\t\t\n\t\tfor (int i = 0; i < M.rows(); i++) {\n\t\t\tcout << Inv << \"\\n\";\n\t\t\tsystem(\"pause\");\n\t\t\tif (M(i,i) == 0) {\n\t\t\t\tint r = 0;\n\t\t\t\twhile (r < M.cols() && (M(i,r) == 0 || M(r,i) == 0)) {\n\t\t\t\t\tr++;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tM = cambiarFilas(M,i,r);\n\t\t\t}\n\t\t\tdouble c = 1.0 / M(i,i);\n\t\t\tM = FilaXCte(M, i, c);\n\t\t\tInv = FilaXCte(Inv, i, c);\n\t\t\tfor (int j = 0; j < M.rows(); j++) {\n\t\t\t\tif (i != j) {\n\t\t\t\t\tc = -M(j,i);\n\t\t\t\t\tM = sumarFilas(M, j, i, c);\n\t\t\t\t\tInv = sumarFilas(Inv, j, i, c);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}else {\n\t\tprintf(\"Error La matriz no cumple la regla de ser cuadrada \\n\");\n\t\t\n\t}\n\treturn Inv;\n}\n\n//==========================================================================================\n//============================================MAIN==========================================\n//==========================================================================================\nint main()\n{\t\n\t//OBTENER MATRIZ DE ARCHIVO DADO -------------------------------------------------------\n\n\tstring Documento;\n\tcout << \"Introduzca el nombre del documento CSV:  \\n\";\n\t//cin >> Documento;\n\tDocumento = \"mxnC.csv\";\n\n\tMatrixXd matrizDada;\n\tmatrizDada = openData(Documento);\n\n\tcout << \"la matriz m es de tamano \" << matrizDada.rows() << \"x\" << matrizDada.cols()  << \" y es la siguiente: \\n\";\n\tcout << matrizDada << \"\\n\";\n\t//a) Gauss Jordan\n\n\tcout << \"la matriz m invertida es: \\n\" << gaussjordann(matrizDada) << endl << \"\\n\";\n\n\t//b) Cofactores\n\n\tcout << \"la matriz m invertida es: \\n\" << Cofactores(matrizDada) << endl << \"\\n\";\n\n\t//CREAR ARCHIVOS CON RESULTADOS ---------------------------------------------------------\n\n\tsaveData(\"matrizInvertidaGauss.csv\", gaussjordann(matrizDada));\n\tsaveData(\"matrizInvertidaEigen.csv\", matrizDada.inverse());\n\tsaveData(\"matrizInvertidaCofactores.csv\", Cofactores(matrizDada));\n\t\n}\n\n", "meta": {"hexsha": "b0d29ce51e3d2728d7208681084f149383bbb570", "size": 4730, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "soluciones/m.pelaez/tarea2/solucion.cpp", "max_stars_repo_name": "japeinado/FISI2028-202120", "max_stars_repo_head_hexsha": "6b16a779f3e34bcbf35d8b5e0ea345cf50ffdadd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-08-17T19:19:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T12:26:41.000Z", "max_issues_repo_path": "soluciones/m.pelaez/tarea2/solucion.cpp", "max_issues_repo_name": "japeinado/FISI2028-202120", "max_issues_repo_head_hexsha": "6b16a779f3e34bcbf35d8b5e0ea345cf50ffdadd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2021-09-18T01:33:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-16T00:11:45.000Z", "max_forks_repo_path": "soluciones/m.pelaez/tarea2/solucion.cpp", "max_forks_repo_name": "japeinado/FISI2028-202120", "max_forks_repo_head_hexsha": "6b16a779f3e34bcbf35d8b5e0ea345cf50ffdadd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 28.0, "max_forks_repo_forks_event_min_datetime": "2021-09-17T22:38:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-02T19:59:49.000Z", "avg_line_length": 21.2107623318, "max_line_length": 135, "alphanum_fraction": 0.5363636364, "num_tokens": 1444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012701768145, "lm_q2_score": 0.8670357649558007, "lm_q1q2_score": 0.8200435277839223}}
{"text": "//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\file Operations.hpp\n/// \\brief Header file for the SO3 Lie Group math functions.\n/// \\details These namespace functions provide implementations of the special orthogonal (SO)\n///          Lie group functions that we commonly use in robotics.\n///\n/// \\author Sean Anderson\n//////////////////////////////////////////////////////////////////////////////////////////////\n\n#ifndef LGM_SO3_PUBLIC_HPP\n#define LGM_SO3_PUBLIC_HPP\n\n#include <Eigen/Core>\n\n/////////////////////////////////////////////////////////////////////////////////////////////\n/// Lie Group Math - Special Orthogonal Group\n/////////////////////////////////////////////////////////////////////////////////////////////\nnamespace lgmath {\nnamespace so3 {\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Builds the 3x3 skew symmetric matrix\n///\n/// The hat (^) operator, builds the 3x3 skew symmetric matrix from the 3x1 vector:\n///\n/// v^ = [0.0  -v3   v2]\n///      [ v3  0.0  -v1]\n///      [-v2   v1  0.0]\n///\n/// See eq. 5 in Barfoot-TRO-2014 for more information.\n//////////////////////////////////////////////////////////////////////////////////////////////\nEigen::Matrix3d hat(const Eigen::Vector3d& vector);\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Builds a rotation matrix using the exponential map\n///\n/// This function builds a rotation matrix, C_ab, using the exponential map (from an axis-\n/// angle parameterization).\n///\n///   C_ab = exp(aaxis_ba^),\n///\n/// where aaxis_ba is a 3x1 axis-angle vector, the magnitude of the angle of rotation\n/// can be recovered by finding the norm of the vector, and the axis of rotation is the unit-\n/// length vector that arises from normalization. Note that the angle around the axis,\n/// aaxis_ba, is a right-hand-rule (counter-clockwise positive) angle from 'a' to 'b'.\n///\n/// Alternatively, we that note that\n///\n///   C_ba = exp(-aaxis_ba^) = exp(aaxis_ab^).\n///\n/// Typical robotics convention has some oddity when it comes using this exponential map in\n/// practice. For example, if we wish to integrate the kinematics:\n///\n///   d/dt C = omega^ * C,\n///\n/// where omega is the 3x1 angular velocity, we employ the convention:\n///\n///   C_20 = exp(deltaTime*-omega^) * C_10,\n///\n/// Noting that omega is negative (left-hand-rule).\n/// For more information see eq. 97 in Barfoot-TRO-2014.\n//////////////////////////////////////////////////////////////////////////////////////////////\nEigen::Matrix3d vec2rot(const Eigen::Vector3d& aaxis_ba, unsigned int numTerms = 0);\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Builds and returns both the rotation matrix and SO(3) Jacobian\n///\n/// Similar to the function 'vec2rot', this function builds a rotation matrix, C_ab, using an\n/// equivalent expression to the exponential map, but allows us to simultaneously extract\n/// the Jacobian of SO(3), which is also required in some cases.\n///\n///   J_ab = jac(aaxis_ba)\n///   C_ab = exp(aaxis_ba^) = identity + aaxis_ba^ * J_ab\n///\n/// For more information see eq. 97 in Barfoot-TRO-2014.\n//////////////////////////////////////////////////////////////////////////////////////////////\nvoid vec2rot(const Eigen::Vector3d& aaxis_ba, Eigen::Matrix3d* out_C_ab,\n             Eigen::Matrix3d* out_J_ab);\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Compute the matrix log of a rotation matrix\n///\n/// Compute the inverse of the exponential map (the logarithmic map). This lets us go from\n/// a 3x3 rotation matrix back to a 3x1 axis angle parameterization. In some cases, when the\n/// rotation matrix is 'numerically off', this involves some 'projection' back to SO(3).\n///\n///   aaxis_ba = ln(C_ab)\n///\n/// where aaxis_ba is a 3x1 axis angle, where the axis is normalized and the magnitude of\n/// the rotation can be recovered by finding the norm of the axis angle. Note that the\n/// angle around the axis, aaxis_ba, is a right-hand-rule (counter-clockwise positive)\n/// angle from 'a' to 'b'.\n///\n/// Alternatively, we that note that\n///\n///   aaxis_ab = -aaxis_ba = ln(C_ba) = ln(C_ab^T)\n///\n/// See Barfoot-TRO-2014 Appendix B2 for more information.\n//////////////////////////////////////////////////////////////////////////////////////////////\nEigen::Vector3d rot2vec(const Eigen::Matrix3d& C_ab);\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Builds the 3x3 Jacobian matrix of SO(3)\n///\n/// Build the 3x3 left Jacobian of SO(3).\n///\n/// For the sake of a notation, we assign subscripts consistence with the rotation,\n///\n///   J_ab = J(aaxis_ba),\n///\n/// although we note to the SO(3) novice that this Jacobian is not a rotation matrix, and\n/// should be used with care.\n///\n/// For more information see eq. 98 in Barfoot-TRO-2014.\n//////////////////////////////////////////////////////////////////////////////////////////////\nEigen::Matrix3d vec2jac(const Eigen::Vector3d& aaxis_ba, unsigned int numTerms = 0);\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Builds the 3x3 inverse Jacobian matrix of SO(3)\n///\n/// Build the 3x3 inverse left Jacobian of SO(3).\n///\n/// For the sake of a notation, we assign subscripts consistence with the rotation,\n///\n///   J_ab_inverse = J(aaxis_ba)^{-1},\n///\n/// although we note to the SO(3) novice that this Jacobian is not a rotation matrix, and\n/// should be used with care. Also, please note that J_ab_inverse is not equivalent to J_ba:\n///\n///   J(aaxis_ba)^{-1} != J(-aaxis_ba)\n///\n/// For more information see eq. 99 in Barfoot-TRO-2014.\n//////////////////////////////////////////////////////////////////////////////////////////////\nEigen::Matrix3d vec2jacinv(const Eigen::Vector3d& aaxis_ba, unsigned int numTerms = 0);\n\n} // so3\n} // lgmath\n\n\n#endif // LGM_SO3_PUBLIC_HPP\n", "meta": {"hexsha": "f6282ff114ec5946d88ae26d8f41727af27bfdff", "size": 6094, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/lgmath/so3/Operations.hpp", "max_stars_repo_name": "utiasASRL/lgmath", "max_stars_repo_head_hexsha": "d767997cc183f13f5d77ef3056f0c78af37547ae", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2019-11-18T11:56:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T15:55:11.000Z", "max_issues_repo_path": "include/lgmath/so3/Operations.hpp", "max_issues_repo_name": "utiasASRL/lgmath", "max_issues_repo_head_hexsha": "d767997cc183f13f5d77ef3056f0c78af37547ae", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-05-06T21:31:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-08T15:23:38.000Z", "max_forks_repo_path": "include/lgmath/so3/Operations.hpp", "max_forks_repo_name": "utiasASRL/lgmath", "max_forks_repo_head_hexsha": "d767997cc183f13f5d77ef3056f0c78af37547ae", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-11-18T11:56:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-12T15:15:09.000Z", "avg_line_length": 43.219858156, "max_line_length": 94, "alphanum_fraction": 0.5221529373, "num_tokens": 1322, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240194661945, "lm_q2_score": 0.8740772269642949, "lm_q1q2_score": 0.8199928414836095}}
{"text": "// students_t_example1.cpp\n\n// Copyright Paul A. Bristow 2006, 2007.\n\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n// Example 1 of using Student's t\n\n// http://en.wikipedia.org/wiki/Student's_t-test  says:\n// The t statistic was invented by William Sealy Gosset\n// for cheaply monitoring the quality of beer brews.\n// \"Student\" was his pen name.\n// WS Gosset was statistician for Guinness brewery in Dublin, Ireland,\n// hired due to Claude Guinness's innovative policy of recruiting the\n// best graduates from Oxford and Cambridge for applying biochemistry\n// and statistics to Guinness's industrial processes.\n// Gosset published the t test in Biometrika in 1908,\n// but was forced to use a pen name by his employer who regarded the fact\n// that they were using statistics as a trade secret.\n// In fact, Gosset's identity was unknown not only to fellow statisticians\n// but to his employer - the company insisted on the pseudonym\n// so that it could turn a blind eye to the breach of its rules.\n\n// Data for this example from:\n// P.K.Hou, O. W. Lau & M.C. Wong, Analyst (1983) vol. 108, p 64.\n// from Statistics for Analytical Chemistry, 3rd ed. (1994), pp 54-55\n// J. C. Miller and J. N. Miller, Ellis Horwood ISBN 0 13 0309907\n\n// Determination of mercury by cold-vapour atomic absorption,\n// the following values were obtained fusing a trusted\n// Standard Reference Material containing 38.9% mercury,\n// which we assume is correct or 'true'.\ndouble standard = 38.9;\n\nconst int values = 3;\ndouble value[values] = {38.9, 37.4, 37.1};\n\n// Is there any evidence for systematic error?\n\n// The Students't distribution function is described at\n// http://en.wikipedia.org/wiki/Student%27s_t_distribution\n#include <boost/math/distributions/students_t.hpp>\n   using boost::math::students_t;  // Probability of students_t(df, t).\n\n#include <iostream>\n   using std::cout;    using std::endl;\n#include <iomanip>\n   using std::setprecision;\n#include <cmath>\n   using std::sqrt;\n\nint main()\n{\n  cout << \"Example 1 using Student's t function. \" << endl;\n\n  // Example/test using tabulated value\n  // (deliberately coded as naively as possible).\n\n  // Null hypothesis is that there is no difference (greater or less)\n  // between measured and standard.\n\n  double degrees_of_freedom = values-1; // 3-1 = 2\n  cout << \"Measurement 1 = \" << value[0] << \", measurement 2 = \" << value[1] << \", measurement 3 = \" << value[2] << endl;\n  double mean = (value[0] + value[1] + value[2]) / static_cast<double>(values);\n  cout << \"Standard = \" << standard << \", mean = \" << mean << \", (mean - standard) = \" << mean - standard  << endl;\n  double sd = sqrt(((value[0] - mean) * (value[0] - mean) + (value[1] - mean) * (value[1] - mean) + (value[2] - mean) * (value[2] - mean))/ static_cast<double>(values-1));\n  cout << \"Standard deviation = \" << sd << endl;\n  if (sd == 0.)\n  {\n      cout << \"Measured mean is identical to SRM value,\" << endl;\n      cout << \"so probability of no difference between measured and standard (the 'null hypothesis') is unity.\" << endl;\n      return 0;\n  }\n\n  double t = (mean - standard) * std::sqrt(static_cast<double>(values)) / sd;\n  cout << \"Student's t = \" << t << endl;\n  cout.precision(2); // Useful accuracy is only a few decimal digits.\n  cout << \"Probability of Student's t is \" << cdf(students_t(degrees_of_freedom), std::abs(t)) << endl;\n  //  0.91, is 1 tailed.\n  // So there is insufficient evidence of a difference to meet a 95% (1 in 20) criterion.\n\n  return 0;\n}  // int main()\n\n/*\n\nOutput is:\n\nExample 1 using Student's t function. \nMeasurement 1 = 38.9, measurement 2 = 37.4, measurement 3 = 37.1\nStandard = 38.9, mean = 37.8, (mean - standard) = -1.1\nStandard deviation = 0.964365\nStudent's t = -1.97566\nProbability of Student's t is 0.91\n\n*/\n\n\n", "meta": {"hexsha": "c86b89d5dc0f388b501d81207e69b82a3783065f", "size": 3914, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/math/example/students_t_example1.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "boost/libs/math/example/students_t_example1.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "boost/libs/math/example/students_t_example1.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 38.3725490196, "max_line_length": 171, "alphanum_fraction": 0.6847215125, "num_tokens": 1093, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096044278532, "lm_q2_score": 0.8947894717137996, "lm_q1q2_score": 0.8197252289779366}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\n//! \\brief Given a matrix A of linearly independent columns, returns Gram-Schmidt orthonormalization\n//! Ustable GS algorithm. Output is prone to cancellation issues.\n//! \\param[in] A Matrix of linearly independent columns\n//! \\return Matrix with ONB of $span(a_1, \\cdots, a_n)$\ntemplate <class Matrix>\nMatrix gramschmidt( const Matrix & A ) {\n    \n    Matrix Q = A;\n    // First vector just gets normalized\n    Q.col(0).normalize();\n    \n    for(unsigned int j = 1; j < A.cols(); ++j) {\n        // Replace inner loop over each previous vector in Q with fast matrix-vector multiplication\n        Q.col(j) -= Q.leftCols(j) * (Q.leftCols(j).transpose() * A.col(j));\n        \n        // Normalize vector if possible (othw. means colums of A almsost lin. dep.\n        if( Q.col(j).norm() <= 10e-14 * A.col(j).norm() ) {\n            std::cerr << \"Gram-Schmidt failed because A has lin. dep columns. Bye.\" << std::endl;\n            break;\n        } else {\n            Q.col(j).normalize();\n        }\n    }\n    \n    return Q;\n}\n\nint main(void) {\n    // Ortho test\n    unsigned int n = 9;\n    Eigen::MatrixXd A = Eigen::MatrixXd::Random(n,n);\n    Eigen::MatrixXd Q = gramschmidt( A );\n    \n    // Output should be idenity matrix\n    std::cout << Q*Q.transpose() << std::endl;\n}\n", "meta": {"hexsha": "27f0e138b95772b8b1498a00ea26525ee4940b81", "size": 1314, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/solutions/solution_0/gramschmidt.cpp", "max_stars_repo_name": "valentinjacot/backupETHZ", "max_stars_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:21:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:21:30.000Z", "max_issues_repo_path": "Nummerical Methods for CSE/solutions/solution_0/gramschmidt.cpp", "max_issues_repo_name": "valentinjacot/backupETHZ", "max_issues_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Nummerical Methods for CSE/solutions/solution_0/gramschmidt.cpp", "max_forks_repo_name": "valentinjacot/backupETHZ", "max_forks_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.85, "max_line_length": 100, "alphanum_fraction": 0.604261796, "num_tokens": 349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582554941718, "lm_q2_score": 0.8807970811069351, "lm_q1q2_score": 0.8195449155311174}}
{"text": "// Arguments: Ints, Doubles, Doubles\r\n#include <stan/math/prim/scal.hpp>\r\n#include <boost/math/special_functions/binomial.hpp>\r\n\r\nusing stan::math::var;\r\nusing std::numeric_limits;\r\nusing std::vector;\r\n\r\nclass AgradCdfNegBinomial : public AgradCdfTest {\r\n public:\r\n  void valid_values(vector<vector<double> >& parameters, vector<double>& cdf) {\r\n    vector<double> param(3);\r\n\r\n    param[0] = 15;  // Failures/Counts\r\n    param[1] = 50;  // Successes/Shape\r\n    param[2] = 3;   // logit(p)/Inverse Scale\r\n    parameters.push_back(param);\r\n    cdf.push_back(0.4240861277740262114122);  // expected cdf\r\n\r\n    param[0] = 0;   // Failures/Counts\r\n    param[1] = 15;  // Successes/Shape\r\n    param[2] = 3;   // logit(p)/Inverse Scale\r\n    parameters.push_back(param);\r\n    cdf.push_back(0.013363461010158063716);  // expected cdf\r\n  }\r\n\r\n  void invalid_values(vector<size_t>& index, vector<double>& value) {\r\n    // Successes/Shape\r\n    index.push_back(1U);\r\n    value.push_back(-1);\r\n\r\n    // logit(p)/Inverse Scale\r\n    index.push_back(2U);\r\n    value.push_back(-1);\r\n  }\r\n\r\n  bool has_lower_bound() { return false; }\r\n\r\n  bool has_upper_bound() { return false; }\r\n\r\n  template <typename T_n, typename T_shape, typename T_inv_scale, typename T3,\r\n            typename T4, typename T5>\r\n  typename stan::return_type<T_shape, T_inv_scale>::type cdf(\r\n      const T_n& n, const T_shape& alpha, const T_inv_scale& beta, const T3&,\r\n      const T4&, const T5&) {\r\n    return stan::math::neg_binomial_cdf(n, alpha, beta);\r\n  }\r\n\r\n  template <typename T_n, typename T_shape, typename T_inv_scale, typename T3,\r\n            typename T4, typename T5>\r\n  typename stan::return_type<T_shape, T_inv_scale>::type cdf_function(\r\n      const T_n& n, const T_shape& alpha, const T_inv_scale& beta, const T3&,\r\n      const T4&, const T5&) {\r\n    using stan::math::binomial_coefficient_log;\r\n    using std::exp;\r\n    using std::log;\r\n\r\n    typename stan::return_type<T_shape, T_inv_scale>::type cdf(0);\r\n\r\n    for (int i = 0; i <= n; i++) {\r\n      typename stan::return_type<T_shape, T_inv_scale>::type temp;\r\n      temp = binomial_coefficient_log(i + alpha - 1, i);\r\n\r\n      cdf += exp(temp + alpha * log(beta / (1 + beta))\r\n                 + i * log(1 / (1 + beta)));\r\n    }\r\n\r\n    return cdf;\r\n  }\r\n};\r\n", "meta": {"hexsha": "6012fd967867a9c0bb5c52fefb073371c1e314dd", "size": 2287, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "tests/math_prob/neg_binomial/neg_binomial_cdf_test.hpp", "max_stars_repo_name": "alashworth/stan-monorepo", "max_stars_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-06T15:53:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-06T15:53:17.000Z", "max_issues_repo_path": "tests/math_prob/neg_binomial/neg_binomial_cdf_test.hpp", "max_issues_repo_name": "alashworth/stan-monorepo", "max_issues_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-01-17T18:51:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-17T18:51:39.000Z", "max_forks_repo_path": "tests/math_prob/neg_binomial/neg_binomial_cdf_test.hpp", "max_forks_repo_name": "alashworth/stan-monorepo", "max_forks_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2112676056, "max_line_length": 80, "alphanum_fraction": 0.6344556187, "num_tokens": 654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947179030094, "lm_q2_score": 0.8670357718273068, "lm_q1q2_score": 0.8193442246097639}}
{"text": "#include <iostream>\n#include <iomanip>\n#include <string>\n#include <map>\n#include <unordered_map>\n#include <iterator>\n#include <random>\n#include <tr1/cmath>  // to pick up beta()\n#include <eigen3/Eigen/Core>\n#include <boost/math/special_functions/binomial.hpp>\n\nusing std::cout;\nusing std::cin;\nusing std::endl;\n\n//double binomial_coefficient_nCk(int const n, int const k) {\n//    if (n == 0 || n == k) return 1;\n//    return 1/ ((n+1) * std::tr1::beta( n-k+1, k+1 ));\n//}\n\ndouble binomial_probability_mass_function(int const k_successes, int const n_trials, double const probability_of_success) {\n//    auto bc =           binomial_coefficient_nCk(n_trials, k_successes);\n    auto bc =           boost::math::binomial_coefficient<int>( n_trials, k_successes);\n    auto p_k =          std::pow(probability_of_success, k_successes);\n    auto p_complement = std::pow(1 - probability_of_success, n_trials - k_successes);\n    return bc * p_k * p_complement;\n}\n\nvoid histogram_binomial_map(int const trials, double const p_success ) {\n    std::random_device rd;\n    std::mt19937 gen(rd());\n    std::binomial_distribution<> dist(trials, p_success);\n    std::map<int, int> histogram;\n    cout << \"Probability Mass/Density Function Graph - Binomial Distribution with trials, likelyhood: \" << trials << \", \" << p_success << std::endl;\n\n    for (int n = 0; n < 1'000'000; ++n) {\n        ++histogram[dist(gen)];\n    }\n    for (auto p : histogram) {\n        cout << std::setw(4) << p.first << ' '\n                  << std::setw(10) << p.second << ' '\n                  << '\\n';\n    }\n}\n\nvoid histogram_binomial_vector(int const trials, double const p_success ) {\n    std::random_device rd;\n    std::mt19937 gen( rd() );\n    std::binomial_distribution<> dist( trials, p_success );\n    std::vector<int> histogram( static_cast<size_t>( trials + 1 ) , 0);\n    cout << \"Probability Mass/Density Function Graph - Binomial Distribution with trials, likelyhood: \" << trials << \", \" << p_success << std::endl;\n\n    double probes = 1'000'000;\n    for (long n = 0; n < probes; ++n) {\n        ++histogram[ static_cast<size_t>( dist(gen) )];\n    }\n    int i = 0;\n    for (auto p : histogram) {\n        cout << std::setw(4) << i++ << ' '\n                  << std::setw(10) << p/probes << ' '\n                  << '\\n';\n    }\n//    std::copy(histogram.begin(), histogram.end(), std::ostream_iterator<int>( cout, \" \\n\" ) );\n}\n\nvoid histogram_binomial_array(int const trials, double const p_success ) {\n    constexpr int MAX_TRIALS = 1000;\n    assert(1 <= trials && trials <= MAX_TRIALS);\n    assert( !(0.0 > p_success || p_success > 1.0) );\n    std::random_device rd;\n    std::mt19937 gen( rd() );\n    std::binomial_distribution<> dist( trials, p_success );\n    std::array<int, MAX_TRIALS> histogram;\n    cout << \"Probability Mass/Density Function Graph - Binomial Distribution with trials, likelyhood: \" << trials << \", \" << p_success << std::endl;\n\n    double probes = 1'000'000;\n    for (long n = 0; n < probes; ++n) {\n        ++histogram[ static_cast<size_t>( dist(gen) )];\n    }\n    for (int i = 0; i < trials+1; ++i ) {\n        cout << std::setw(4) << i << ' '\n                  << std::setw(10) << histogram[i]/probes << ' '\n                  << '\\n';\n    }\n}\n\nvoid distribution_values_binomial(double const mean, int const num_values = 100 ) { // creates a vector loaded with values from the distribution during its initialization.\n    std::random_device rd;\n    std::mt19937 gen(rd());\n\n    std::poisson_distribution<int> dist( mean /*4.1*/);       // http://eigen.tuxfamily.org/bz/show_bug.cgi?id=720\n    auto poisson = [&] (int) {return dist(gen);};\n    Eigen::RowVectorXi v = Eigen::RowVectorXi::NullaryExpr(num_values, poisson );\n    std::cout << \"Eigen::RowVextorXi:Poisson( mean ): (\" << mean << \"), \"  << v << \"\\n\";\n}\n\nvoid distribution_values_binomial(int const trials, double const p_success, int const num_values = 100 ) { // creates a vector loaded with values from the distribution during its initialization.\n    std::random_device rd;\n    std::mt19937 gen(rd());\n\n    std::binomial_distribution<int> dist( trials, p_success );       // http://eigen.tuxfamily.org/bz/show_bug.cgi?id=720\n    auto binomial = [&] (int) {return dist(gen);};\n    Eigen::RowVectorXi v = Eigen::RowVectorXi::NullaryExpr(num_values, binomial );\n    std::cout << \"Eigen::RowVextorXi:Binomial( trials, p_success ): (\" << trials <<\", \"<< p_success <<\"), \"  << v << \"\\n\";\n}\n\nint main()\n{\n    cout << binomial_coefficient_nCk(0,0) << \", \" << binomial_coefficient_nCk(5,6) << \", \"<<binomial_coefficient_nCk(-5,0)<<\n    int trials = 10;\n    histogram_binomial_array( trials, 0.5 );\n    histogram_binomial_vector( trials, 0.7 );\n    histogram_binomial_vector( trials, 1.0 );\n    distribution_values_binomial( 4.1, 100 );\n    distribution_values_binomial( trials, 0.5, 100 );\n\n    double mu_probability_in_bin        = 0.9;\n    int n_samples_drawn                 = 10;\n    double nu_probability_of_sample        = 0.1;\n    int k_successes = static_cast<int>( nu_probability_of_sample * n_samples_drawn );\n    auto r1 = binomial_probability_mass_function(k_successes, n_samples_drawn, mu_probability_in_bin);\n    cout << \"binomial_probability_mass_function(int k_successes, int n_trials, double p): \" << k_successes << \", \" << n_samples_drawn << \", \" << mu_probability_in_bin << endl;\n    cout << r1 << endl;\n\n    mu_probability_in_bin               = 0.9;\n    n_samples_drawn                     = 10;\n    nu_probability_of_sample            = 0;\n    k_successes = nu_probability_of_sample * n_samples_drawn;\n    auto r2 = binomial_probability_mass_function(k_successes, n_samples_drawn, mu_probability_in_bin);\n    cout << \"binomial_probability_mass_function(int k_successes, int n_trials, double p): \" << k_successes << \", \" << n_samples_drawn << \", \" << mu_probability_in_bin << endl;\n    cout << r2 << endl;\n    cout << r1+r2 << endl;\n\n    mu_probability_in_bin               = 0.9;\n    n_samples_drawn                     = 10;\n    nu_probability_of_sample            = 0.4;\n    k_successes = nu_probability_of_sample * n_samples_drawn;\n    mu_probability_in_bin               = 0.9;\n    r2 = binomial_probability_mass_function(k_successes, n_samples_drawn, mu_probability_in_bin);\n    cout << \"binomial_probability_mass_function(int k_successes, int n_trials, double p): \" << k_successes << \", \" << n_samples_drawn << \", \" << mu_probability_in_bin << endl;\n    cout << r2 << endl;\n\n    mu_probability_in_bin               = 0.6;\n    n_samples_drawn                     = 10;\n    nu_probability_of_sample            = 0;\n    k_successes = nu_probability_of_sample * n_samples_drawn;\n    r2 = binomial_probability_mass_function(k_successes, n_samples_drawn, mu_probability_in_bin);\n    cout << \"binomial_probability_mass_function(int k_successes, int n_trials, double p): \" << k_successes << \", \" << n_samples_drawn << \", \" << mu_probability_in_bin << endl;\n    cout << r2 << endl;\n\n    std::cout << \"###\" << std::endl;\n    return 0;\n}\n\n/* std::cout << \"Pascal's triangle:\\n\";\nfor(int n = 1; n < 10; ++n) {\n    std::cout << std::string(20-n*2, ' ');\n    for(int k = 1; k < n; ++k)\n        std::cout << std::setw(3) << binomial_coefficient_nCk(n,k) << ' ';\n    std::cout << '\\n';\n} */\n\n", "meta": {"hexsha": "c31b5a078765fe5f4671900a31bd93f0bfdd46c3", "size": 7249, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "grantrostig/probability_tests", "max_stars_repo_head_hexsha": "1d501289583232af9239bb48e294267eb5fd73b9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "grantrostig/probability_tests", "max_issues_repo_head_hexsha": "1d501289583232af9239bb48e294267eb5fd73b9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.cpp", "max_forks_repo_name": "grantrostig/probability_tests", "max_forks_repo_head_hexsha": "1d501289583232af9239bb48e294267eb5fd73b9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.472392638, "max_line_length": 194, "alphanum_fraction": 0.6279486826, "num_tokens": 1988, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850110816423, "lm_q2_score": 0.8740772482857833, "lm_q1q2_score": 0.818385426097466}}
{"text": "#include <Eigen/Dense>\n#include <unsupported/Eigen/MatrixFunctions>\n#include <iostream>\n#include <math.h>\n\n//! \\brief Compute powers of a square matrix using smart binary representation\n//! \\param[in,out] A matrix for which you want to compute $A^k$. $A^k$ is stored in $A$\n//! \\param[out] k integer for $A^k$\ntemplate <class Matrix>\nvoid matPow(Matrix & A, unsigned int k) {\n    Matrix X = Matrix::Identity(A.rows(), A.cols());\n    \n    // p is used as binary mask to check wether $k = \\sum_{i = 0}^M b_i 2^i$ has 1 in the $i$-th binary digit\n    // obtaining the binay representation of p can be done in many ways, here we use ~k & p to check i-th binary is 1\n    unsigned int p = 1;\n    // Cycle all the way up to the length of the binary representation of $k$\n    for(unsigned int j = 1; j <= ceil(log2(k)); ++j) {\n        if( ( ~k & p ) == 0 ) {\n            X = X*A;\n        }\n        \n        A = A*A;\n        p = p << 1;\n    }\n    A = X;\n}\n\nint main(void) {\n    // Check/Test with provided, complex, matrix\n    unsigned int n = 3; // size of matrix\n    unsigned int k = 9; // power\n    \n    double PI = M_PI; // from math.h\n    std::complex<double> I = std::complex<double>(0,1); // imaginary unit\n    \n    Eigen::MatrixXcd A(n,n);\n    \n    for(unsigned int i = 0; i < n; ++i) {\n        for(unsigned int j = 0; j < n; ++j) {\n            A(i,j) = exp(2. * PI * I * (double) i * (double) j / (double) n) / sqrt((double) n);\n        }\n    }\n    \n    // Test with simple matrix/simple power\n//     Eigen::MatrixXd A(2,2);\n//     k = 3;\n//     A << 1,2,3,4;\n         \n    // Output results\n    std::cout << \"A = \" << A << std::endl;\n    std::cout << \"Eigen:\" << std::endl << \"A^\" << k << \" = \" << A.pow(k) << std::endl;\n    matPow(A, k);\n    std::cout << \"Ours:\" << std::endl << \"A^\" << k << \" = \" << A <<std::endl;\n}\n\n", "meta": {"hexsha": "67db9b42ddf4199c75875a11b1d68aad73d1f3f3", "size": 1821, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/PS1/solutions_ps1/C++/matPow.cpp", "max_stars_repo_name": "valentinjacot/backupETHZ", "max_stars_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:21:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:21:30.000Z", "max_issues_repo_path": "Nummerical Methods for CSE/PS1/solutions_ps1/C++/matPow.cpp", "max_issues_repo_name": "valentinjacot/backupETHZ", "max_issues_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Nummerical Methods for CSE/PS1/solutions_ps1/C++/matPow.cpp", "max_forks_repo_name": "valentinjacot/backupETHZ", "max_forks_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5178571429, "max_line_length": 117, "alphanum_fraction": 0.5321252059, "num_tokens": 574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951588871157, "lm_q2_score": 0.8757869803008764, "lm_q1q2_score": 0.8183311146095047}}
{"text": "//  experiment with the exponential and Poisson distributions\n//\n//\n/*\n* Level_8 Exercise 5:\n* Test program for experimenting with the exponential and Poisson distributions\n*\n* work with exponential distribution instead of normal distribution\n* Poisson distribution instead of gamma distribution\n*\n* @file TestNormalDistribution.cpp\n* @author Chunyu Yuan\n* @version 1.0 02/22/2021\n*\n*/\n\n\n#include <boost/math/distributions/normal.hpp> //header file for using normal distributions\n#include <boost/math/distributions/gamma.hpp>//header file for using gamma distributions\n#include <boost/math/distributions.hpp> // For non-member functions of distributions\n\n#include <vector> //library for using vector\n#include <iostream> // Standard Input / Output Streams Library\nusing namespace std;\n\n\n/*\n* Controls operation of the program\n* Return type of main() expects an int\n*\n* @function main()\n* @param none\n* @return 0\n*/\nint main()\n{\n\t// Don't forget to tell compiler which namespace\n\tusing namespace boost::math;\n\n\n\t// Distributional properties\n\tdouble x = 10.25;\n\tdouble scaleParameter = 0.5;\n\texponential_distribution<> myExponential(scaleParameter);\n\t// Choose precision\n\tcout.precision(10); // Number of values behind the comma\n\n\t// properties\n\tcout << \"\\n***Exponential distribution: \\n\";\n\tcout << \"pdf: \" << pdf(myExponential, x) << endl;\n\tcout << \"cdf: \" << cdf(myExponential, x) << endl;\n\tcout << \"mean: \" << mean(myExponential) << endl;\n\tcout << \"variance: \" << variance(myExponential) << endl;\n\tcout << \"median: \" << median(myExponential) << endl;\n\tcout << \"mode: \" << mode(myExponential) << endl;\n\tcout << \"kurtosis excess: \" << kurtosis_excess(myExponential) << endl;\n\tcout << \"kurtosis: \" << kurtosis(myExponential) << endl;\n\tcout << \"skewness: \" << skewness(myExponential) << endl;\n\tcout << \"characteristic function: \" << chf(myExponential, x) << endl;\n\tcout << \"hazard: \" << hazard(myExponential, x) << endl;\n\n\t// Gamma distribution\n//\tdouble alpha = 3.0; // Shape parameter, k\n\t//double beta = 0.5;\t// Scale parameter, theta\n//\tgamma_distribution<double> myGamma(alpha, beta);\n\n\t//Passion distribution\n\tdouble mean1 = 3.0;\n\tpoisson_distribution<double> myPoisson(mean1);\n\n\tdouble val = 13.0;\n\tcout << \"\\n***Poisson distribution: \\n\";\n\tcout << \"pdf: \" << pdf(myPoisson, val) << endl;\n\tcout << \"cdf: \" << cdf(myPoisson, val) << endl;\n\tcout << \"mean: \" << mean(myPoisson) << endl;\n\tcout << \"variance: \" << variance(myPoisson) << endl;\n\tcout << \"median: \" << median(myPoisson) << endl;\n\tcout << \"mode: \" << mode(myPoisson) << endl;\n\tcout << \"kurtosis excess: \" << kurtosis_excess(myPoisson) << endl;\n\tcout << \"kurtosis: \" << kurtosis(myPoisson) << endl;\n\tcout << \"skewness: \" << skewness(myPoisson) << endl;\n\tcout << \"characteristic function: \" << chf(myPoisson, val) << endl;\n\tcout << \"hazard: \" << hazard(myPoisson, val) << endl;\n\tcout << \"\\n\\n \" << endl;\n\tvector<double> pdfList;\n\tvector<double> cdfList;\n\n\tdouble start = 0.0;\n\tdouble end = 10.0;\n\tlong N = 30;\t\t// Number of subdivisions\n\n\tval = 0.0;\n\tdouble h = (end - start) / double(N);\n\n\tfor (long j = 1; j <= N; ++j)\n\t{\n\t\tpdfList.push_back(pdf(myPoisson, val));\n\t\tcdfList.push_back(cdf(myPoisson, val));\n\n\t\tval += h;\n\t}\n\n\tfor (long j = 0; j < pdfList.size(); ++j)\n\t{\n\t\tcout << pdfList[j] << \", \";\n\n\t}\n\n\tcout << \"***\" << endl;\n\n\tfor (long j = 0; j < cdfList.size(); ++j)\n\t{\n\t\tcout << cdfList[j] << \", \";\n\n\t}\n\n\treturn 0;\n}", "meta": {"hexsha": "0c3672a5a680250133549079dd34cc55bce2aa69", "size": 3384, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Level8/Level8/Level8/Exercise5/TestNormalDistribution.cpp", "max_stars_repo_name": "chunyuyuan/My-Solution-for-C-Programming-for-Financial-Engineering", "max_stars_repo_head_hexsha": "478b414714edbea1ebdc2f565baad6f04f54bc70", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-12T08:15:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-12T08:15:57.000Z", "max_issues_repo_path": "Level8/Level8/Level8/Exercise5/TestNormalDistribution.cpp", "max_issues_repo_name": "chunyuyuan/My-Solution-for-C-Programming-for-Financial-Engineering", "max_issues_repo_head_hexsha": "478b414714edbea1ebdc2f565baad6f04f54bc70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Level8/Level8/Level8/Exercise5/TestNormalDistribution.cpp", "max_forks_repo_name": "chunyuyuan/My-Solution-for-C-Programming-for-Financial-Engineering", "max_forks_repo_head_hexsha": "478b414714edbea1ebdc2f565baad6f04f54bc70", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6779661017, "max_line_length": 91, "alphanum_fraction": 0.658392435, "num_tokens": 983, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966717067252, "lm_q2_score": 0.8633916222765629, "lm_q1q2_score": 0.8172836360264645}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n\nusing namespace std;\nusing namespace Eigen;\n\n// Evaluate the Legendre polynomials and its derivatives in the vector x using the 3-term recursion formulae. The outputs are the matrices Lx and DLx.\nvoid legvals(const VectorXd &x, MatrixXd &Lx, MatrixXd &DLx)\n{\n    int n = Lx.cols()-1;\n    int N = x.size();\n    for (int j=0; j<N; j++) {\n        Lx(j,0) = 1.;\n        Lx(j,1) = x(j);\n        DLx(j,0) = 0;\n        DLx(j,1) = 1.;\n        for (int k=2; k<n+1; k++) {\n            Lx(j,k) = (2*k-1.)/k*x(j)*Lx(j,k-1)-(k-1.)/k*Lx(j,k-2);\n            DLx(j,k) = (2*k-1.)/k*Lx(j,k-1)+(2*k-1.)/k*x(j)*DLx(j,k-1)-(k-1.)/k*DLx(j,k-2);\n        }\n    }\n}\n\n// Evaluate P_n(x), for a scalar x and integer n.\ndouble Pnx(double x, int n) {\n    VectorXd Px(n+1);\n    Px(0) = 1.; Px(1) = x;\n    for (int k=2; k<n+1; k++)\n        Px(k) = (2*k-1.)/k*x*Px(k-1)-(k-1.)/k*Px(k-2);\n    return Px(n);\n}\n\n// Find the Gauss points using the secant method with regula falsi. The standard secant method may be obtained by commenting out lines 50 and 52.\nMatrixXd gaussPts(int n, double rtol=1e-10, double atol=1e-12) {\n    MatrixXd zeros(n,n);\n    double x0, x1, f0, f1, s;\n    for (int k=1; k<n+1; k++) {\n        for (int j=1; j<k+1; j++) {\n            // Initialise initial guesses.\n            if (j==1) x0 = -1.;\n            else      x0 = zeros(j-2,k-2);\n            if (j==k) x1 = 1.;\n            else      x1 = zeros(j-1,k-2);\n            \n            // Secant method\n            f0 = Pnx(x0,k);\n            for (int i=0; i<1e4; i++) {\n                f1 = Pnx(x1,k);\n                s = f1*(x1-x0)/(f1-f0);\n                if (Pnx(x1 - s,k)*f1<0) {\n                    x0 = x1; f0 = f1;\n                }\n                x1 = x1 - s;\n                if ((abs(s)<max(atol,rtol*min(abs(x0),abs(x1)))))  {\n                    zeros(j-1,k-1) = x1;\n                    break;\n                }\n            }\n        }\n    }\n    return zeros;\n}\n\n// Test the implementation.\nint main(){\n    int n = 8;\n    MatrixXd zeros = gaussPts(n);\n    cout<<\"Zeros: \"<<endl<< zeros <<endl;\n    \n    for (int k=1; k<n+1; k++) {\n        VectorXd xi = zeros.block(0, k-1, k, 1);\n        MatrixXd Lx(k,n+1), DLx(k,n+1);\n        legvals(xi, Lx, DLx);\n        cout<<\"Values of the \"<<k<<\"-th polynomial in the calculated zeros: \"<<endl;\n        cout<<Lx.col(k).transpose() <<endl;\n    }\n}\n", "meta": {"hexsha": "921917d6ceb5dc49747b656ff55e3cd7ead13994", "size": 2386, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/solutions/solutions_ps10/legendre.cpp", "max_stars_repo_name": "valentinjacot/backupETHZ", "max_stars_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:21:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:21:30.000Z", "max_issues_repo_path": "Nummerical Methods for CSE/solutions/solutions_ps10/legendre.cpp", "max_issues_repo_name": "valentinjacot/backupETHZ", "max_issues_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Nummerical Methods for CSE/solutions/solutions_ps10/legendre.cpp", "max_forks_repo_name": "valentinjacot/backupETHZ", "max_forks_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5897435897, "max_line_length": 150, "alphanum_fraction": 0.4673093043, "num_tokens": 827, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067163548471, "lm_q2_score": 0.867035752930664, "lm_q1q2_score": 0.8171870204569326}}
{"text": "#include <vector>\n#include <Eigen/Dense>\n#include \"univariate.h\"\n#include \"multivariate.h\"\n\nnamespace numerical_optimization {\n\n// homework1 univariate optimization problems\nnamespace uni {\nconstexpr int number_functions = 5;\n\nstd::vector<function_t> construct_functions() {\n\n    std::vector<function_t> functions;\n    functions.resize(number_functions);\n    functions[0] = [](float x){ return std::pow(x, 4)/4 + std::pow(x, 3) + std::pow(x, 2)*(9/2) - 10*x; };\n    functions[1] = [](float x){ return std::sin(x) +x*x-10; };\n    functions[2] = [](float x){ return -std::exp((-1*x*x)/(1.4*1.4)); };\n\n    // not differentiable cases\n    functions[3] = [](float x){ return std::abs(x-0.3); };\n    functions[4] = [](float x){ return std::abs(std::log(x)); };\n\n    return functions;\n};\n\nstd::vector<Univariate> construct_methods(const std::vector<function_t> functions) {\n    std::vector<Univariate> methods;\n    for(auto func : functions) {\n        methods.emplace_back(Univariate(func));\n    }\n    return methods;\n};\n/////////////////////////////////\n} // the end of namespace uni //\n////////////////////////////////\n\nnamespace multi {\ntemplate<typename Multi>\nstd::vector<Multi> construct_methods(std::vector<std::function<double(const Vector2d&)>> functions) {\n    std::vector<Multi> methods;\n    for(const auto& func:functions) {\n        methods.emplace_back(Multi(func));\n    }\n    return methods;\n};\n///////////////////////////////////\n} // the end of namespace multi ///\n//////////////////////////////////\n\nnamespace hw2 {\nconstexpr int number_functions = 3;\n\nusing namespace multi;\nusing namespace Eigen;\nusing function_t = std::function<double(const Vector2d&)>;\n\nstd::vector<function_t> construct_functions() {\n    std::vector<function_t> functions(number_functions);\n\n    functions[0] = [](Vector2d var) {\n        return std::pow((var[0]+2*var[1]-6), 2)\n        + std::pow((2*var[0]+var[1]-6), 2);\n    };\n\n    functions[1] = [](Vector2d var) {\n        return 50*std::pow((var[1]-var[0]*var[0]), 2) \n        + std::pow((1.0-var[0]), 2);\n    };\n\n    functions[2] = [](Vector2d var) {\n        return std::pow((1.5-var[0]+var[0]*var[1]), 2) \n        + std::pow((2.25-var[0]+var[0]*var[1]*var[1]), 2)\n        + std::pow((2.625-var[0]+var[0]*var[1]*var[1]*var[1]), 2);\n    };\n\n    return functions;\n};\n//////////////////////////////////\n} // the end of namespace hw2  ///\n//////////////////////////////////\n\nnamespace hw5 {\nconstexpr int number_functions = 3;\n\nusing namespace multi;\nusing namespace Eigen;\nusing function_t = std::function<double(const Vector2d&)>;\n\nstd::vector<function_t> construct_functions() {\n    std::vector<function_t> functions(number_functions);\n\n    functions[0] = [](Vector2d var) {\n        return std::pow((var[0]+2*var[1]-7), 2)\n        + std::pow((2*var[0]+var[1]-5), 2);\n    };\n\n    functions[1] = [](Vector2d var) {\n        return 40*std::pow((var[1]-var[0]*var[0]), 2) \n        + std::pow((1.0-var[0]), 2);\n    };\n\n    functions[2] = [](Vector2d var) {\n        return std::pow((1.5-var[0]+var[0]*var[1]), 2) \n        + std::pow((2.25-var[0]+var[0]*var[1]*var[1]), 2)\n        + std::pow((2.625-var[0]+var[0]*var[1]*var[1]*var[1]), 2);\n    };\n\n    return functions;\n};\n//////////////////////////////////\n}/// the end of namespace hw5 ////\n//////////////////////////////////\n\nnamespace hw6 {\nconstexpr int number_functions = 2;\n\nusing namespace Eigen;\nusing function_t = std::function<double(const Vector4d&, const Vector3d&)>;\n\nstd::vector<function_t> construct_functions() {\n    std::vector<function_t> functions(number_functions);\n\n    functions[0] = [](Vector4d coeff, Vector3d vars) {\n        return coeff[0]*vars[0] + coeff[1]*vars[1] + coeff[2]*vars[2] + coeff[3];\n    };\n\n    functions[1] = [](Vector4d coeff, Vector3d vars) {\n        double value = -(pow(vars[0]-coeff[0], 2) + pow(vars[1]-coeff[1], 2) + pow(vars[2]-coeff[2], 2))/pow(coeff[3], 2);\n        return std::exp(value);\n    };\n\n    return functions;\n}\n//////////////////////////////////\n}/// the end of namespace hw6 ////\n//////////////////////////////////\n\nnamespace hw7 {\n// 1. $f(x) = 2(x-0.5)^2 + 1$\n// 2. $f(x) = |x-0.5|(cos(12\\phi[x-0.5])+1) + 1$\nconstexpr int number_functions = 2;\n\nusing namespace Eigen;\nusing function_t = std::function<double(const double&)>;\n\nstd::vector<function_t> construct_functions() {\n    std::vector<function_t> functions(number_functions);\n\n    functions[0] = [](double var) {\n        return std::pow((var-0.5),2) + 1;\n    };\n\n    functions[1] = [](double var) {\n        auto x = var - 0.5;\n        return std::abs(x)*(std::cos(12*3.14*x)+1.2);\n    };\n\n    return functions;\n}\n//////////////////////////////////\n}/// the end of namespace hw7 ////\n//////////////////////////////////\n\n/////////////////////////////////////////////////////\n} // the end of namespace numerical_optimization ////\n/////////////////////////////////////////////////////", "meta": {"hexsha": "f9812c87421f6e6ad3787a3e42ac8947fc58a60f", "size": 4882, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/function.hpp", "max_stars_repo_name": "hyeonjang/numerical-optimization", "max_stars_repo_head_hexsha": "39ab4f75056acf5f7c0779bf3330046f29430bd0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/function.hpp", "max_issues_repo_name": "hyeonjang/numerical-optimization", "max_issues_repo_head_hexsha": "39ab4f75056acf5f7c0779bf3330046f29430bd0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/function.hpp", "max_forks_repo_name": "hyeonjang/numerical-optimization", "max_forks_repo_head_hexsha": "39ab4f75056acf5f7c0779bf3330046f29430bd0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2335329341, "max_line_length": 122, "alphanum_fraction": 0.5434248259, "num_tokens": 1375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769413, "lm_q2_score": 0.8947894604912848, "lm_q1q2_score": 0.8164382597659017}}
{"text": "#include <iostream>\n#include <vector>\n\n#include <Eigen/Dense>\n\ndouble f1(const Eigen::Vector2d &x) {\n\treturn x(0) * x(0) + 2. * x(1) * x(1) - 1.;\n}\n\ndouble f2(const Eigen::Vector2d &x) {\n\treturn x(1) - x(0) * x(0);\n}\n\nEigen::Vector2d f(const Eigen::Vector2d &x) {\n\treturn Eigen::Vector2d(f1(x), f2(x));\n}\n\nEigen::Matrix2d Jacobian(const Eigen::Vector2d &x) {\n\tEigen::Matrix2d J;\n\tJ <<  2*x(0), 4*x(1),\n\t     -2*x(0), \t  1;\n\treturn J;\n}\n\nEigen::Vector2d Newton(Eigen::Vector2d x, int n) {\n\tfor(int i = 0; i < n; i++) {\n\t\tx += Jacobian(x).fullPivLu().solve(-f(x));\n\t}\t\n\n\treturn x;\n}\n\nEigen::IOFormat ShortFmt(Eigen::StreamPrecision, Eigen::DontAlignCols, \", \", \", \", \"\", \"\", \"[\", \"]\");\n\nint main() {\n\tint n = 100;\n\tstd::vector<Eigen::Vector2d> startingPoints(3);\n\n\tstartingPoints[0] = Eigen::Vector2d(-1., 1.);\n\tstartingPoints[1] = Eigen::Vector2d(1., 1.);\n\tstartingPoints[2] = Eigen::Vector2d(-2., -2.);\n\n\tstd::cout << \"---------------------------\" << std::endl;\n\tfor (const Eigen::Vector2d &x : startingPoints) {\n\t\tEigen::Vector2d y = Newton(x, n);\n\t\tstd::cout << \"   x = \" << x.format(ShortFmt) << std::endl;\n\t\tstd::cout << \"   y = \" << y.format(ShortFmt) << std::endl;\n\t\tstd::cout << \"f(y) = \" << f(y).format(ShortFmt) << std::endl;\n\t\tstd::cout << \"---------------------------\" << std::endl;\n\t}\n\n\treturn 0;\n}\n", "meta": {"hexsha": "d96341a71331cb6d7c1d109f92305267ba733926", "size": 1311, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "exercise_6/newton.cpp", "max_stars_repo_name": "azurite/numCSE18-code", "max_stars_repo_head_hexsha": "f7104305375954a0528d366f8460bf8033d20f0a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-13T19:08:32.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-13T19:08:32.000Z", "max_issues_repo_path": "exercise_6/newton.cpp", "max_issues_repo_name": "azurite/numCSE18-code", "max_issues_repo_head_hexsha": "f7104305375954a0528d366f8460bf8033d20f0a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exercise_6/newton.cpp", "max_forks_repo_name": "azurite/numCSE18-code", "max_forks_repo_head_hexsha": "f7104305375954a0528d366f8460bf8033d20f0a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.2777777778, "max_line_length": 101, "alphanum_fraction": 0.5514874142, "num_tokens": 468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693645535724, "lm_q2_score": 0.8596637541053281, "lm_q1q2_score": 0.8163963310909456}}
{"text": "//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\file Operations.cpp\n/// \\brief Implementation file for the SO3 Lie Group math functions.\n/// \\details These namespace functions provide implementations of the special orthogonal (SO)\n///          Lie group functions that we commonly use in robotics.\n///\n/// \\author Sean Anderson\n//////////////////////////////////////////////////////////////////////////////////////////////\n\n#include <lgmath/so3/Operations.hpp>\n\n#include <Eigen/Dense>\n#include <stdexcept>\n#include <stdio.h>\n\nnamespace lgmath {\nnamespace so3 {\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Builds the 3x3 skew symmetric matrix\n///\n/// The hat (^) operator, builds the 3x3 skew symmetric matrix from the 3x1 vector:\n///\n/// v^ = [0.0  -v3   v2]\n///      [ v3  0.0  -v1]\n///      [-v2   v1  0.0]\n///\n/// See eq. 5 in Barfoot-TRO-2014 for more information.\n//////////////////////////////////////////////////////////////////////////////////////////////\nEigen::Matrix3d hat(const Eigen::Vector3d& vector) {\n  Eigen::Matrix3d mat;\n  mat <<       0.0,  -vector[2],   vector[1],\n         vector[2],         0.0,  -vector[0],\n        -vector[1],   vector[0],         0.0;\n  return mat;\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Builds a rotation matrix using the exponential map\n///\n/// This function builds a rotation matrix, C_ab, using the exponential map (from an axis-\n/// angle parameterization).\n///\n///   C_ab = exp(aaxis_ba^),\n///\n/// where aaxis_ba is a 3x1 axis-angle vector, the magnitude of the angle of rotation\n/// can be recovered by finding the norm of the vector, and the axis of rotation is the unit-\n/// length vector that arises from normalization. Note that the angle around the axis,\n/// aaxis_ba, is a right-hand-rule (counter-clockwise positive) angle from 'a' to 'b'.\n///\n/// Alternatively, we that note that\n///\n///   C_ba = exp(-aaxis_ba^) = exp(aaxis_ab^).\n///\n/// Typical robotics convention has some oddity when it comes using this exponential map in\n/// practice. For example, if we wish to integrate the kinematics:\n///\n///   d/dt C = omega^ * C,\n///\n/// where omega is the 3x1 angular velocity, we employ the convention:\n///\n///   C_20 = exp(deltaTime*-omega^) * C_10,\n///\n/// Noting that omega is negative (left-hand-rule).\n/// For more information see eq. 97 in Barfoot-TRO-2014.\n//////////////////////////////////////////////////////////////////////////////////////////////\nEigen::Matrix3d vec2rot(const Eigen::Vector3d& aaxis_ba, unsigned int numTerms) {\n\n  // Get angle\n  const double phi_ba = aaxis_ba.norm();\n\n  // If angle is very small, return Identity\n  if(phi_ba < 1e-12) {\n    return Eigen::Matrix3d::Identity();\n  }\n\n  if (numTerms == 0) {\n\n    // Analytical solution\n    Eigen::Vector3d axis = aaxis_ba/phi_ba;\n    const double sinphi_ba = sin(phi_ba);\n    const double cosphi_ba = cos(phi_ba);\n    return cosphi_ba*Eigen::Matrix3d::Identity() +\n           (1.0 - cosphi_ba)*axis*axis.transpose() +\n           sinphi_ba*so3::hat(axis);\n\n  } else {\n\n    // Numerical solution (good for testing the analytical solution)\n    Eigen::Matrix3d C_ab = Eigen::Matrix3d::Identity();\n\n    // Incremental variables\n    Eigen::Matrix3d x_small = so3::hat(aaxis_ba);\n    Eigen::Matrix3d x_small_n = Eigen::Matrix3d::Identity();\n\n    // Loop over sum up to the specified numTerms\n    for (unsigned int n = 1; n <= numTerms; n++) {\n      x_small_n = x_small_n*x_small/double(n);\n      C_ab += x_small_n;\n    }\n    return C_ab;\n  }\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Builds and returns both the rotation matrix and SO(3) Jacobian\n///\n/// Similar to the function 'vec2rot', this function builds a rotation matrix, C_ab, using an\n/// equivalent expression to the exponential map, but allows us to simultaneously extract\n/// the Jacobian of SO(3), which is also required in some cases.\n///\n///   J_ab = jac(aaxis_ba)\n///   C_ab = exp(aaxis_ba^) = identity + aaxis_ba^ * J_ab\n///\n/// For more information see eq. 97 in Barfoot-TRO-2014.\n//////////////////////////////////////////////////////////////////////////////////////////////\nvoid vec2rot(const Eigen::Vector3d& aaxis_ba, Eigen::Matrix3d* out_C_ab,\n             Eigen::Matrix3d* out_J_ab) {\n\n  // Check pointers\n  if (out_C_ab == NULL) {\n    throw std::invalid_argument(\"Null pointer out_C_ab in vec2rot\");\n  }\n  if (out_J_ab == NULL) {\n    throw std::invalid_argument(\"Null pointer out_J_ab in vec2rot\");\n  }\n\n  // Set Jacobian term\n  *out_J_ab = so3::vec2jac(aaxis_ba);\n\n  // Set rotation matrix\n  *out_C_ab = Eigen::Matrix3d::Identity() + so3::hat(aaxis_ba) * (*out_J_ab);\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Compute the matrix log of a rotation matrix\n///\n/// Compute the inverse of the exponential map (the logarithmic map). This lets us go from\n/// a 3x3 rotation matrix back to a 3x1 axis angle parameterization. In some cases, when the\n/// rotation matrix is 'numerically off', this involves some 'projection' back to SO(3).\n///\n///   aaxis_ba = ln(C_ab)\n///\n/// where aaxis_ba is a 3x1 axis angle, where the axis is normalized and the magnitude of\n/// the rotation can be recovered by finding the norm of the axis angle. Note that the\n/// angle around the axis, aaxis_ba, is a right-hand-rule (counter-clockwise positive)\n/// angle from 'a' to 'b'.\n///\n/// Alternatively, we that note that\n///\n///   aaxis_ab = -aaxis_ba = ln(C_ba) = ln(C_ab^T)\n///\n/// See Barfoot-TRO-2014 Appendix B2 for more information.\n//////////////////////////////////////////////////////////////////////////////////////////////\nEigen::Vector3d rot2vec(const Eigen::Matrix3d& C_ab) {\n\n  // Get angle\n  const double phi_ba = acos(0.5*(C_ab.trace()-1.0));\n  const double sinphi_ba = sin(phi_ba);\n\n  if (fabs(sinphi_ba) > 1e-9) {\n\n    // General case, angle is NOT near 0, pi, or 2*pi\n    Eigen::Vector3d axis;\n    axis << C_ab(2,1) - C_ab(1,2),\n            C_ab(0,2) - C_ab(2,0),\n            C_ab(1,0) - C_ab(0,1);\n    return (0.5*phi_ba/sinphi_ba)*axis;\n\n  } else if (fabs(phi_ba) > 1e-9) {\n\n    // Angle is near pi or 2*pi\n    // ** Note with this method we do not know the sign of 'phi', however since we know phi is\n    //    close to pi or 2*pi, the sign is unimportant..\n\n    // Find the eigenvalues and eigenvectors\n    Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d > eigenSolver(C_ab);\n\n    // Try each eigenvalue\n    for (int i = 0; i < 3; i++) {\n\n      // Check if eigen value is near +1.0\n      if ( fabs(eigenSolver.eigenvalues()[i] - 1.0) < 1e-6 ) {\n\n        // Get corresponding angle-axis\n        Eigen::Vector3d aaxis_ba = phi_ba*eigenSolver.eigenvectors().col(i);\n        return aaxis_ba;\n      }\n    }\n\n    // Runtime error\n    throw std::runtime_error(\"so3 logarithmic map failed to find an axis-angle, \"\n                             \"angle was near pi, or 2*pi, but no eigenvalues were near 1\");\n\n  } else {\n\n    // Angle is near zero\n    return Eigen::Vector3d::Zero();\n  }\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Builds the 3x3 Jacobian matrix of SO(3)\n///\n/// Build the 3x3 left Jacobian of SO(3).\n///\n/// For the sake of a notation, we assign subscripts consistence with the rotation,\n///\n///   J_ab = J(aaxis_ba),\n///\n/// although we note to the SO(3) novice that this Jacobian is not a rotation matrix, and\n/// should be used with care.\n///\n/// For more information see eq. 98 in Barfoot-TRO-2014.\n//////////////////////////////////////////////////////////////////////////////////////////////\nEigen::Matrix3d vec2jac(const Eigen::Vector3d& aaxis_ba, unsigned int numTerms) {\n\n  // Get angle\n  const double phi_ba = aaxis_ba.norm();\n  if(phi_ba < 1e-12) {\n\n    // If angle is very small, return Identity\n    return Eigen::Matrix3d::Identity();\n  }\n\n  if (numTerms == 0) {\n\n    // Analytical solution\n    Eigen::Vector3d axis = aaxis_ba/phi_ba;\n    const double sinTerm = sin(phi_ba)/phi_ba;\n    const double cosTerm = (1.0-cos(phi_ba))/phi_ba;\n    return sinTerm*Eigen::Matrix3d::Identity() +\n           (1.0 - sinTerm)*axis*axis.transpose() +\n           cosTerm*so3::hat(axis);\n  } else {\n\n    // Numerical solution (good for testing the analytical solution)\n    Eigen::Matrix3d J_ab = Eigen::Matrix3d::Identity();\n\n    // Incremental variables\n    Eigen::Matrix3d x_small = so3::hat(aaxis_ba);\n    Eigen::Matrix3d x_small_n = Eigen::Matrix3d::Identity();\n\n    // Loop over sum up to the specified numTerms\n    for (unsigned int n = 1; n <= numTerms; n++) {\n      x_small_n = x_small_n*x_small/double(n+1);\n      J_ab += x_small_n;\n    }\n    return J_ab;\n  }\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Builds the 3x3 inverse Jacobian matrix of SO(3)\n///\n/// Build the 3x3 inverse left Jacobian of SO(3).\n///\n/// For the sake of a notation, we assign subscripts consistence with the rotation,\n///\n///   J_ab_inverse = J(aaxis_ba)^{-1},\n///\n/// although we note to the SO(3) novice that this Jacobian is not a rotation matrix, and\n/// should be used with care. Also, please note that J_ab_inverse is not equivalent to J_ba:\n///\n///   J(aaxis_ba)^{-1} != J(-aaxis_ba)\n///\n/// For more information see eq. 99 in Barfoot-TRO-2014.\n//////////////////////////////////////////////////////////////////////////////////////////////\nEigen::Matrix3d vec2jacinv(const Eigen::Vector3d& aaxis_ba, unsigned int numTerms) {\n\n  // Get angle\n  const double phi_ba = aaxis_ba.norm();\n  if(phi_ba < 1e-12) {\n\n    // If angle is very small, return Identity\n    return Eigen::Matrix3d::Identity();\n  }\n\n  if (numTerms == 0) {\n\n    // Analytical solution\n    Eigen::Vector3d axis = aaxis_ba/phi_ba;\n    const double halfphi = 0.5*phi_ba;\n    const double cotanTerm = halfphi/tan(halfphi);\n    return cotanTerm*Eigen::Matrix3d::Identity() +\n           (1.0 - cotanTerm)*axis*axis.transpose() -\n           halfphi*so3::hat(axis);\n  } else {\n\n    // Logic error\n    if (numTerms > 20) {\n      throw std::invalid_argument(\"Numerical vec2jacinv does not support numTerms > 20\");\n    }\n\n    // Numerical solution (good for testing the analytical solution)\n    Eigen::Matrix3d J_ab_inverse = Eigen::Matrix3d::Identity();\n\n    // Incremental variables\n    Eigen::Matrix3d x_small = so3::hat(aaxis_ba);\n    Eigen::Matrix3d x_small_n = Eigen::Matrix3d::Identity();\n\n    // Boost has a bernoulli package... but we shouldn't need more than 20\n    Eigen::Matrix<double,21,1> bernoulli;\n    bernoulli << 1.0, -0.5, 1.0/6.0, 0.0, -1.0/30.0, 0.0, 1.0/42.0, 0.0, -1.0/30.0,\n                 0.0, 5.0/66.0, 0.0, -691.0/2730.0, 0.0, 7.0/6.0, 0.0, -3617.0/510.0,\n                 0.0, 43867.0/798.0, 0.0, -174611.0/330.0;\n\n    // Loop over sum up to the specified numTerms\n    for (unsigned int n = 1; n <= numTerms; n++) {\n      x_small_n = x_small_n*x_small/double(n);\n      J_ab_inverse += bernoulli(n)*x_small_n;\n    }\n    return J_ab_inverse;\n  }\n}\n\n} // so3\n} // lgmath\n", "meta": {"hexsha": "ee34aea917774ec0dff0999738139d427da955c3", "size": 11192, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/so3/Operations.cpp", "max_stars_repo_name": "utiasASRL/lgmath", "max_stars_repo_head_hexsha": "d767997cc183f13f5d77ef3056f0c78af37547ae", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2019-11-18T11:56:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T15:55:11.000Z", "max_issues_repo_path": "src/so3/Operations.cpp", "max_issues_repo_name": "utiasASRL/lgmath", "max_issues_repo_head_hexsha": "d767997cc183f13f5d77ef3056f0c78af37547ae", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-05-06T21:31:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-08T15:23:38.000Z", "max_forks_repo_path": "src/so3/Operations.cpp", "max_forks_repo_name": "utiasASRL/lgmath", "max_forks_repo_head_hexsha": "d767997cc183f13f5d77ef3056f0c78af37547ae", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-11-18T11:56:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-12T15:15:09.000Z", "avg_line_length": 35.0846394984, "max_line_length": 94, "alphanum_fraction": 0.5715689778, "num_tokens": 3049, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297941266013, "lm_q2_score": 0.9059898165759307, "lm_q1q2_score": 0.8158708230019202}}
{"text": "#include \"L2_norm.hpp\"\r\n#include \"integrate.hpp\"\r\n#include <Eigen/Core>\r\n#include <Eigen/Sparse>\r\n#include <gtest/gtest.h>\r\n#include <gtest/gtest.h>\r\n\r\nTEST(TestL2Norm, ConstantTest) {\r\n\t// In this test, we check that the L2-norm function\r\n\t// is able to get a simple constant right\r\n\r\n\tconst double constant = 4.0;\r\n\tauto         f = [=](double, double) {\r\n\t\treturn constant;\r\n\t};\r\n\r\n\t// We only add one triangle:\r\n\r\n\tEigen::MatrixXd vertices(3, 3);\r\n\tvertices << 0, 0, 0,\r\n\t    1, 0, 0,\r\n\t    0, 1, 0;\r\n\r\n\tEigen::MatrixXi triangles(1, 3);\r\n\ttriangles << 0, 1, 2;\r\n\r\n\tEigen::VectorXd u(3);\r\n\tu << constant, constant, constant;\r\n\r\n\tconst double error = computeL2Difference(vertices, triangles, u, f);\r\n\r\n\tASSERT_EQ(0.0, error) << \"L2-norm does not give 0 = ||C-C||_2\";\r\n}\r\n\r\nTEST(TestL2Norm, ShapeFunctionTest) {\r\n\t// In this test, we check that the L2-norm function\r\n\t// is able to destinguish the shape functions\r\n\r\n\tfor (int i = 0; i < 3; ++i) {\r\n\t\t// We only add one triangle:\r\n\r\n\t\tEigen::MatrixXd vertices(3, 3);\r\n\t\tvertices << 0, 0, 0,\r\n\t\t    1, 0, 0,\r\n\t\t    0, 1, 0;\r\n\r\n\t\tEigen::MatrixXi triangles(1, 3);\r\n\t\ttriangles << 0, 1, 2;\r\n\r\n\t\tEigen::VectorXd u(3);\r\n\t\tu << (i == 0), (i == 1), (i == 2);\r\n\r\n\t\tauto f = [i](double x, double y) {\r\n\t\t\treturn lambda(i, x, y);\r\n\t\t};\r\n\r\n\t\tconst double error = computeL2Difference(vertices, triangles, u, f);\r\n\r\n\t\tASSERT_EQ(0.0, error) << \"L2-norm does not give 0 = ||lambda_\" << i << \"-lambda_\" << i << \"||_2\";\r\n\t}\r\n}\r\n", "meta": {"hexsha": "9cd199a92a651a55b03cb1174047537f7016803c", "size": 1461, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "series2/2d-linFEM/unittest/TestL2Norm.cpp", "max_stars_repo_name": "westernmagic/NumPDE", "max_stars_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "series2/2d-linFEM/unittest/TestL2Norm.cpp", "max_issues_repo_name": "westernmagic/NumPDE", "max_issues_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2017-04-01T22:52:16.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-30T16:21:55.000Z", "max_forks_repo_path": "series2/2d-linFEM/unittest/TestL2Norm.cpp", "max_forks_repo_name": "westernmagic/NumPDE", "max_forks_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.564516129, "max_line_length": 100, "alphanum_fraction": 0.5859000684, "num_tokens": 486, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363293639213, "lm_q2_score": 0.8791467643431002, "lm_q1q2_score": 0.8152884389734745}}
{"text": "#include <iostream>\r\n#include <Eigen/Dense>\r\n\r\nusing namespace std;\r\nusing namespace Eigen;\r\n\r\nint main()\r\n{\r\n   Matrix2d A;\r\n   A << 2, 1,\r\n        2, 0.9999999999;\r\n   FullPivLU<Matrix2d> lu(A);\r\n   cout << \"By default, the rank of A is found to be \" << lu.rank() << endl;\r\n   lu.setThreshold(1e-5);\r\n   cout << \"With threshold 1e-5, the rank of A is found to be \" << lu.rank() << endl;\r\n}\r\n", "meta": {"hexsha": "70f15444eba5d48a7abf263e1b062c9a702e1b5b", "size": 393, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/eigen-eigen-323c052e1731/doc/examples/TutorialLinAlgSetThreshold.cpp", "max_stars_repo_name": "k4rth33k/dnnc-operators", "max_stars_repo_head_hexsha": "a7fe3f1240c12b3438558def71fbfcd4520446c3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-08-16T14:35:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-11T23:59:22.000Z", "max_issues_repo_path": "packages/eigen-eigen-323c052e1731/doc/examples/TutorialLinAlgSetThreshold.cpp", "max_issues_repo_name": "k4rth33k/dnnc-operators", "max_issues_repo_head_hexsha": "a7fe3f1240c12b3438558def71fbfcd4520446c3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-08-12T04:38:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T16:32:13.000Z", "max_forks_repo_path": "packages/eigen-eigen-323c052e1731/doc/examples/TutorialLinAlgSetThreshold.cpp", "max_forks_repo_name": "k4rth33k/dnnc-operators", "max_forks_repo_head_hexsha": "a7fe3f1240c12b3438558def71fbfcd4520446c3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-08-15T13:29:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-09T17:08:04.000Z", "avg_line_length": 23.1176470588, "max_line_length": 86, "alphanum_fraction": 0.5877862595, "num_tokens": 124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.9005297847831082, "lm_q1q2_score": 0.814664756308289}}
{"text": "/**\n * This file contains summary statistics template functions for Eigen::Matrix data types.\n *\n * More functions are added once a need for the particular function necessitates their development. In other words,\n * until there is a use for developing a summary statistic, I will not implement it. For example, as of right now, there\n * is no kurtosis function, because there are no clients nor any other functions within the library requiring a kurtosis\n * function.\n */\n\n#ifndef PROMETHEUS_SUMMARY_STATISTICS_HPP\n#define PROMETHEUS_SUMMARY_STATISTICS_HPP\n\n#include <Eigen/Dense>\n\n// zach's-attempt-at-math\nnamespace zaamath {\n    /**\n     * computes the sample mean of a given dataset represented by a matrix whose columns represent different populations\n     * @tparam T the datatype of the input matrix (int, float, double, custom, etc.)\n     * @tparam RowIndexType the number of rows of the input datatype\n     * @tparam ColIndexType the number of columns of the input datatype\n     * @param data the data represented by an Eigen::Matrix (vector or matrix)\n     * @return the sample mean of the data\n     */\n    template <class T, int RowIndexType, int ColIndexType>\n    Eigen::Matrix<T, 1, ColIndexType> sample_mean(const Eigen::Matrix<T, RowIndexType, ColIndexType>& data) {\n        return data.colwise().mean();\n    }\n\n    /**\n     * computes the sample variance of a given dataset represented by a matrix whose columns represent different\n     * populations\n     * @tparam T the datatype of the input matrix (int, float, double, custom, etc.)\n     * @tparam RowIndexType the number of rows of the input datatype\n     * @tparam ColIndexType the number of columns of the input datatype\n     * @param data the data represented by an Eigen::Matrix (vector or matrix)\n     * @return the sample variance of the data\n     */\n    template <class T, int RowIndexType, int ColIndexType>\n    Eigen::Matrix<T, 1, ColIndexType> sample_var(const Eigen::Matrix<T, RowIndexType, ColIndexType>& data) {\n        auto means = data.colwise().mean();\n        return (data.rowwise() - means).colwise().squaredNorm() / (data.rows() - 1);\n    }\n\n    /**\n     * computes the sample standard deviation of a given dataset represented by a matrix whose columns represent\n     * different populations\n     * @tparam T the datatype of the input matrix (int, float, double, custom, etc.)\n     * @tparam RowIndexType the number of rows of the input datatype\n     * @tparam ColIndexType the number of columns of the input datatype\n     * @param data the data represented by an Eigen::Matrix (vector or matrix)\n     * @return the sample standard deviation of the data\n     */\n    template <class T, int RowIndexType, int ColIndexType>\n    Eigen::Matrix<T, 1, ColIndexType> sample_std_dev(const Eigen::Matrix<T, RowIndexType, ColIndexType>& data) {\n        auto var = sample_var(data);\n        return var.array().sqrt();\n    }\n\n    /**\n     * computes the range of a given dataset represented by a matrix whose columns represent different populations\n     * @tparam T the datatype of the input matrix (int, float, double, custom, etc.)\n     * @tparam RowIndexType the number of rows of the input datatype\n     * @tparam ColIndexType the number of columns of the input datatype\n     * @param data the data represnted by an Eigen::Matrix (vector or matrix)\n     * @return the range of each column (max element - min element)\n     */\n    template <class T, int RowIndexType, int ColIndexType>\n    Eigen::Matrix<T, 1, ColIndexType> range(const Eigen::Matrix<T, RowIndexType, ColIndexType>& data) {\n        return data.colwise().maxCoeff() - data.colwise().minCoeff();\n    }\n\n};\n\n#endif //PROMETHEUS_SUMMARY_STATISTICS_HPP\n", "meta": {"hexsha": "cbc1fe46b403b5aa715f8540fa718fd068838e59", "size": 3692, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "tools/math/summary_statistics.hpp", "max_stars_repo_name": "zborffs/AsterionEngine", "max_stars_repo_head_hexsha": "029624cba19cd7fbc407bb24b9beb33efd089c5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tools/math/summary_statistics.hpp", "max_issues_repo_name": "zborffs/AsterionEngine", "max_issues_repo_head_hexsha": "029624cba19cd7fbc407bb24b9beb33efd089c5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tools/math/summary_statistics.hpp", "max_forks_repo_name": "zborffs/AsterionEngine", "max_forks_repo_head_hexsha": "029624cba19cd7fbc407bb24b9beb33efd089c5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.5789473684, "max_line_length": 120, "alphanum_fraction": 0.7104550379, "num_tokens": 871, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475715065793, "lm_q2_score": 0.8633916082162403, "lm_q1q2_score": 0.8144783768699503}}
{"text": "//  Diagonalizing tridiagonal Toeplitz matrix  with Lapack functions\n//  Compile as c++ -O3 -o Tridiag.x TridiagToeplitz.cpp -larmadillo -llapack -lblas\n#include <cmath>\n#include <iostream>\n#include <fstream>\n#include <iomanip>\n#include <armadillo>\n\nusing namespace  std;\nusing namespace  arma;\n\n// Begin of main program   \n\nint main(int argc, char* argv[])\n{\n  int       i, j, Dim;\n  double    RMin, RMax, Step, DiagConst, NondiagConst; \n  RMin = 0.0; RMax = 1.0; Dim =20;  \n  mat Hamiltonian = zeros<mat>(Dim,Dim);\n  // Integration step length\n  Step    = RMax/ Dim;\n  DiagConst = 2.0 / (Step*Step);\n  NondiagConst =  -1.0 / (Step*Step);\n  \n  // Setting up tridiagonal matrix and diagonalization using Armadillo\n  Hamiltonian(0,0) = DiagConst;\n  Hamiltonian(0,1) = NondiagConst;\n  for(i = 1; i < Dim-1; i++) {\n    Hamiltonian(i,i-1)    = NondiagConst;\n    Hamiltonian(i,i)    = DiagConst;\n    Hamiltonian(i,i+1)    = NondiagConst;\n  }\n  Hamiltonian(Dim-1,Dim-2) = NondiagConst;\n  Hamiltonian(Dim-1,Dim-1) = DiagConst;\n  // diagonalize and obtain eigenvalues\n  vec Eigval(Dim);\n  eig_sym(Eigval, Hamiltonian);\n  double pi = acos(-1.0);\n  cout << \"RESULTS:\" << endl;\n  cout << setiosflags(ios::showpoint | ios::uppercase);\n  cout <<\"Number of Eigenvalues = \" << setw(15) << Dim << endl;  \n  cout << \"Exact versus numerical eigenvalues:\" << endl;\n  for(int i = 0; i < Dim; i++) {\n    double Exact = DiagConst+2*NondiagConst*cos((i+1)*pi/(Dim+1));\n    cout << setw(15) << setprecision(8) << fabs(Eigval[i]-Exact) << endl;\n  }\n  return 0;\n}  //  end of main function\n\n", "meta": {"hexsha": "e14afc914301504d508178b6923291fc8a08ff92", "size": 1565, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/Projects/2018/Project2/CodeExample/TridiagToeplitz.cpp", "max_stars_repo_name": "kimrojas/ComputationalPhysicsMSU", "max_stars_repo_head_hexsha": "a47cfc18b3ad6adb23045b3f49fab18c0333f556", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 220.0, "max_stars_repo_stars_event_min_datetime": "2016-08-25T09:18:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:09:16.000Z", "max_issues_repo_path": "doc/Projects/2018/Project2/CodeExample/TridiagToeplitz.cpp", "max_issues_repo_name": "dnhdang94/ComputationalPhysicsMSU", "max_issues_repo_head_hexsha": "16990c74cf06eb5b933982137f0536d669567259", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-12-04T12:55:10.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-04T12:55:10.000Z", "max_forks_repo_path": "doc/Projects/2018/Project2/CodeExample/TridiagToeplitz.cpp", "max_forks_repo_name": "dnhdang94/ComputationalPhysicsMSU", "max_forks_repo_head_hexsha": "16990c74cf06eb5b933982137f0536d669567259", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 136.0, "max_forks_repo_forks_event_min_datetime": "2016-08-25T09:04:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T09:54:21.000Z", "avg_line_length": 31.3, "max_line_length": 83, "alphanum_fraction": 0.6466453674, "num_tokens": 534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172587090974, "lm_q2_score": 0.8577681104440172, "lm_q1q2_score": 0.8139509639706192}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include <math.h>\n#include <string>\n#include <fstream>\n#include <service.cpp>\n#include <profiler.h>\n\nconst static Eigen::IOFormat CSVFormat(Eigen::StreamPrecision, Eigen::DontAlignCols, \"\\t\", \"\\n\");\n\nint main()\n{\n\t// Ex. 1\n    // Load and store data\n    Eigen::MatrixXd matA(512,512);\n    std::string filename = \"data/Bild\";\n    size_t row = 512;\n    size_t col = 512;\n    int load = loadData(matA, filename, row, col);\n    std::ofstream file;\n    file.open(\"output/data.txt\", std::ofstream::out | std::ofstream::trunc);\n\tfile << \"# Picture with k:\\n\" << matA.format(CSVFormat) << std::endl; \n\tfile.close();\n\n    // Compute U, W, V matrix \n    Eigen::JacobiSVD<Eigen::MatrixXd> svd(matA, Eigen::ComputeThinU | Eigen::ComputeThinV);\n    Eigen::MatrixXd W = svd.singularValues().asDiagonal();\n    Eigen::MatrixXd U = svd.matrixU();\n    Eigen::MatrixXd V = svd.matrixV().transpose();\n\n    // Perform k-approx with values in range array\n    int range[3]={10,20,50};\n\tfor(int i : range){\n        // Use Eigen::seq to decrease dimension of W, and of U and V respectively\n        Eigen::MatrixXd W_new = W(Eigen::seq(0,i), Eigen::seq(0,i));\n        Eigen::MatrixXd U_new = U(Eigen::all, Eigen::seq(0,i));\n        Eigen::MatrixXd V_new = V(Eigen::seq(0,i), Eigen::all);\n        Eigen::MatrixXd mat_new = U_new * W_new* V_new;\n        // Save new picture in txt file, to make a simple read out in python\n        std::ofstream file;\n        file.open(\"output/data\"+std::to_string(i)+\".txt\", std::ofstream::out | std::ofstream::trunc);\n        file << \"# Picture with k:\"+std::to_string(i)+\"\\n\" << mat_new.format(CSVFormat) << std::endl; \n        file.close();\n    }\n\n    // Ex. 2\n\n    // Number of dimension N linear from 1 to 1000\n    Profiler::init(3);\n    int anzahl = 1000;\n    int start = 1;\n\n    // Vectors for the building of the random NxN matrix, for the LU decomposition and the solve function\n    Eigen::VectorXd random_times(anzahl - start);\n    Eigen::VectorXd LU_times(anzahl - start);\n    Eigen::VectorXd solve_times(anzahl - start);\n\n    for (int N = start; N < anzahl; N++)\n    {\n        //All timers are reseted\n        Profiler::resetAll();\n        //Timer for random initialisation and saving\n        Profiler::start(0);\n        Eigen::MatrixXd M = Eigen::MatrixXd::Random(N, N);\n          Profiler::stop(0);\n        random_times[N - start] = Profiler::getTimeInS(0);\n        Eigen::VectorXd b = Eigen::VectorXd::Random(N);\n        //Timer for LU decomposition without saving\n        Profiler::start(1);\n        M.partialPivLu();\n        Profiler::stop(1);\n        LU_times[N - start] = Profiler::getTimeInS(1);\n        Eigen::PartialPivLU<Eigen::MatrixXd> mat(M);\n        //Timer for solve function without saving\n        Profiler::start(2);\n        Eigen::VectorXd x = mat.solve(b);\n        Profiler::stop(2);\n        solve_times[N - start] = Profiler::getTimeInS(2);\n    }\n    // Store vectors in file\n    Eigen::MatrixXd store(anzahl-start, 3);\n    store << random_times, LU_times, solve_times;\n    std::ofstream file2;\n    file2.open(\"output/times.txt\", std::ofstream::out | std::ofstream::trunc);\n\tfile2 << \"# Times: Random, LU, Solve\\n\" << store.format(CSVFormat) << std::endl; \n\tfile2.close();\n\n    //Ex. 3\n    // Initialize Matrix A with a1 - a10 as vector space\n    Eigen::VectorXd a1(4), a2(4), a3(4), a4(4), a5(4), a6(4), a7(4), a8(4), a9(4), a10(4);\n    a1 << 4., 1., 2., 4.;\n    a2 << 1., 2., 6., 2.;\n    a3 << 2., 6., 9., 8.;\n    a4 << 5., 3., 8., 6.;\n    a5 << 8., 2., 4., 8.;\n    a6 << 6., 7., 11., 12.;\n    a7 << 3., 8., 15., 10.; \n    a8 << -2., 5., 7., 4.;\n    a9 << 12,  3., 6., 12.;\n    a10 << 3., -1., -4., 2.; \n\n    Eigen::MatrixXd A(4, 10);\n    A << a1, a2, a3, a4, a5, a6, a7, a8, a9, a10;\n\n    // find orthonormal basis of a1-a10 with singular value decomposition\n    Eigen::JacobiSVD<Eigen::MatrixXd> svd2(A, Eigen::ComputeThinU | Eigen::ComputeThinV);\n    Eigen::MatrixXd W2 = svd2.singularValues().asDiagonal();\n    Eigen::MatrixXd U2 = svd2.matrixU();\n    Eigen::MatrixXd V2 = svd2.matrixV().transpose();\n\n    std::ofstream file3;\n    file3.open(\"output/basis.txt\", std::ofstream::trunc);\n    // basis vectors are the columns of U with w_i != 0\n    for (int i = 0; i< 4; i++){\n        if(W2(i,i) >= 1e-10){\n            file3 << \"Value W_\" << i << \" is not zero. The corresponding vector is\\n\" << U2.col(i).format(CSVFormat) << \"\\n\\n\";\n        }\n    }\n    file3 << \"\\nDie U-Matrix\" << U2.format(CSVFormat) << std::endl;\n    file3 << \"\\nDie W-Matrix\" << W2.format(CSVFormat) << std::endl;\n    file3.close();\n\n    return 0;\n}", "meta": {"hexsha": "c0d020bdd38e26b9504ed7532863f541ebe32694", "size": 4606, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Blatt2/src/main.cpp", "max_stars_repo_name": "lewis206/Computational_Physics", "max_stars_repo_head_hexsha": "06ad6126685eaf65f5834bfe70ebd91b33314395", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Blatt2/src/main.cpp", "max_issues_repo_name": "lewis206/Computational_Physics", "max_issues_repo_head_hexsha": "06ad6126685eaf65f5834bfe70ebd91b33314395", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Blatt2/src/main.cpp", "max_forks_repo_name": "lewis206/Computational_Physics", "max_forks_repo_head_hexsha": "06ad6126685eaf65f5834bfe70ebd91b33314395", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.1451612903, "max_line_length": 127, "alphanum_fraction": 0.5924880591, "num_tokens": 1445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305297023094, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.8128655228651118}}
{"text": "#include <iostream>\n#include <set>\n\n#include <Eigen/Core>\n\n#include <cannon/math/primes.hpp>\n#include <cannon/log/registry.hpp>\n\nusing namespace cannon::math;\nusing namespace cannon::log;\n\n/*!\n * The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be\n *\n *     1, 3, 6, 10, 15, 21, 28, 36, 45, 55\n *\n * Let us list the factors of the first seven triangle numbers:\n *\n *     1: 1\n *     3: 1, 3\n *     6: 1, 2, 3, 6\n *     10: 1, 2, 5, 10\n *     15: 1, 3, 5, 15\n *     21: 1, 3, 7, 21\n *     28: 1, 2, 4, 7, 14, 28\n *\n * We can see that 28 is the first triangle number to have over five divisors. \n *\n * What is the value of the first triangle number to have over five hundred divisors?\n */\n\nunsigned int get_num_factors(unsigned long n) {\n  auto prime_factors = get_prime_factorization(n);\n  unsigned int num_factors = 1;\n\n  for (auto it = prime_factors.begin(); it != prime_factors.end(); ) {\n    unsigned long factor = *it;\n\n    // Given a prime factorization of the input number, all possible factors\n    // are all possible products of the factors\n    num_factors *= prime_factors.count(factor) + 1;\n\n    // Go to next unique entry\n    do {\n      ++it;\n    } while (it != prime_factors.end() && *it == factor);\n  }\n\n  return num_factors;\n}\n\nunsigned long find_triangle_number_with_divisors(unsigned int num_divisors) {\n  unsigned long prime_upper = 100;\n  auto primes = get_primes_up_to(prime_upper);\n\n  unsigned int n = 1;\n  while (true) {\n    unsigned int triangle = n * (n + 1) / 2;\n\n    unsigned int n_factors = get_num_factors(triangle);\n\n    if (n_factors > num_divisors) {\n      return triangle;\n    }\n\n    ++n;\n  }\n\n}\n\nint main(int argc, char** argv) {\n  if (argc != 2) {\n    std::cerr << \"This script takes only one argument: the number of divisors to search for.\"  << std::endl;\n    return 1;\n  }\n\n  std::cout << find_triangle_number_with_divisors(std::stoul(argv[1])) << std::endl;\n}\n", "meta": {"hexsha": "5fce73033036d4464ce32578a3b165f371a776ce", "size": 2018, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scripts/project_euler/euler_problem_12.cpp", "max_stars_repo_name": "cannontwo/cannon", "max_stars_repo_head_hexsha": "4be79f3a6200d1a3cd26c28c8f2250dbdf08f267", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/project_euler/euler_problem_12.cpp", "max_issues_repo_name": "cannontwo/cannon", "max_issues_repo_head_hexsha": "4be79f3a6200d1a3cd26c28c8f2250dbdf08f267", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 46.0, "max_issues_repo_issues_event_min_datetime": "2021-01-12T23:03:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-01T17:29:01.000Z", "max_forks_repo_path": "scripts/project_euler/euler_problem_12.cpp", "max_forks_repo_name": "cannontwo/cannon", "max_forks_repo_head_hexsha": "4be79f3a6200d1a3cd26c28c8f2250dbdf08f267", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5443037975, "max_line_length": 176, "alphanum_fraction": 0.6422200198, "num_tokens": 614, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475715065793, "lm_q2_score": 0.8615382112085969, "lm_q1q2_score": 0.8127299793037522}}
{"text": "// C++ includes\n#include <iostream>\nusing namespace std;\n\n// Eigen includes\n#include <Eigen/Core>\nusing namespace Eigen;\n\n// autodiff include\n#include <autodiff/forward.hpp>\n#include <autodiff/forward/eigen.hpp>\nusing namespace autodiff;\n\n// The scalar function for which the gradient is needed\ndual f(const VectorXdual& x)\n{\n    return x.cwiseProduct(x).sum(); // sum([x(i) * x(i) for i = 1:5])\n}\n\nint main()\n{\n    VectorXdual x(5);    // the input vector x with 5 variables\n    x << 1, 2, 3, 4, 5;  // x = [1, 2, 3, 4, 5]\n\n    dual u;  // the output scalar u = f(x) evaluated together with gradient below\n\n    VectorXd g = gradient(f, wrt(x), at(x), u);  // evaluate the function value u and its gradient vector g = du/dx\n\n    cout << \"u = \" << u << endl;    // print the evaluated output u\n    cout << \"g = \\n\" << g << endl;  // print the evaluated gradient vector g = du/dx\n}\n", "meta": {"hexsha": "d2056c44db3df1df72817a6a268af23982594b64", "size": 880, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/forward/example-forward-gradient-derivatives-using-eigen.cpp", "max_stars_repo_name": "ram-nad/autodiff", "max_stars_repo_head_hexsha": "a4ea49d15ae730ddfa79c3615807285006d5e7d7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-09-21T04:02:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-21T04:02:38.000Z", "max_issues_repo_path": "examples/forward/example-forward-gradient-derivatives-using-eigen.cpp", "max_issues_repo_name": "gayatri-a-b/autodiff", "max_issues_repo_head_hexsha": "98bdfea087cb67dd6e2a1a399e90bbd7ac4eb326", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-06-22T07:15:49.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-22T07:15:49.000Z", "max_forks_repo_path": "examples/forward/example-forward-gradient-derivatives-using-eigen.cpp", "max_forks_repo_name": "gayatri-a-b/autodiff", "max_forks_repo_head_hexsha": "98bdfea087cb67dd6e2a1a399e90bbd7ac4eb326", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-02-26T13:14:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-25T03:52:45.000Z", "avg_line_length": 27.5, "max_line_length": 115, "alphanum_fraction": 0.6340909091, "num_tokens": 271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810511092411, "lm_q2_score": 0.8577681086260461, "lm_q1q2_score": 0.8126332523581292}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include \"../Optimizer/optimizer\"\nusing namespace std;\nusing namespace Eigen;\nusing namespace Optimizer;\n\ndouble func (double x) {\n    // This function will return the square after adding 10 to the given number.\n    return pow(x + 10, 2);\n}\n\ndouble SumSquares (VectorXd x) {\n    return x.squaredNorm();\n}\n\ndouble Matyas (Vector2d x) {\n    return 0.26 * (pow(x(0),2) + pow(x(1),2)) - 0.48 * x(0) * x(1);\n}\n\ndouble Dixon (VectorXd x) {\n\tdouble val = 0;\n\tfor (int i = 0; i < x.size() - 1; ++i)\n\t\tval += 100 * pow(x(i + 1) - pow(x(i), 2), 2) + pow(x(i) - 1, 2);\n\treturn val;\n}\n\ndouble Himmelblau(Vector2d x)\n{\n    return pow((pow(x(0),2) + x(1) -11),2) + pow((x(0) + pow(x(1),2) - 7),2);\n}\n\ndouble func_cust(Vector2d x) {\n    return pow(x(0)-10, 3) + pow(x(1)-20, 3);\n}\n\ndouble ineq1(Vector2d x){\n    return - (pow(x(0)-5, 2) + pow(x(1)-5, 2) + 100);\n}\n\ndouble ineq2(Vector2d x){\n    return - (pow(x(0)-5, 2) + pow(x(1)-5, 2) - 82.81);\n}\n\nint main () {\n\n    cout << \"Using Function: (x + 10)^2 for single variable algorithms testing.\" << endl;\n    double ipt = 5.4;\n\n    cout << \"Test Bounding Phase:\" << endl;\n    Vector2d range = BoundingPhase(func, ipt);\n    cout << \"Range from bounding Phase for initial point :\" << ipt << endl;\n    cout << range << endl;\n\n    cout << \"Test Exhaustive Search:\" << endl;\n    range = Exhaustive(func, ipt);\n    cout << \"Range from Exhaustive Search for initial point :\" << ipt << endl;\n    cout << range << endl;\n\n    cout << \"Derivatives at \" << ipt << endl;\n    cout << Derivative(func, ipt) << endl;\n\n    cout << \"Finding optimal point using above range for Newton Rapshon Method.\" << endl;\n    cout << \"Optimal Point is: \";\n    cout << NewtonRapshon (func, range) << endl;\n\n    cout << \"Finding optimal point using above range for Secant Method.\" << endl;\n    cout << \"Optimal Point is: \";\n    cout << Secant (func, range) << endl;\n\n    cout << \"Finding optimal point using above range for Golden Section Search Method.\" << endl;\n    cout << \"Optimal Point is: \";\n    cout << GoldenSection (func, range) << endl;\n\n    cout << \"Finding optimal point using above range for Interval Halving Method.\" << endl;\n    cout << \"Optimal Point is: \";\n    cout << IntervalHalving (func, range) << endl;\n\n    cout << \"Finding optimal point using above range for Fibonnaci Search Method.\" << endl;\n    cout << \"Optimal Point is: \";\n    cout << Fibonacci (func, range) << endl;\n\n    cout << \"Testing SVOptimize on (x + 10)^2 with initial point 5.4.\" << endl;\n    cout << \"The Optimal Point obtained is: \";\n    cout << SVOptimize(func, 5.4) << endl;\n\n    cout << \"Testing Bisection method on (x + 10)^2\" << endl;\n    cout << \"The Optimal Point obtained is: \";\n    cout << Bisection(func, Eigen::Vector2d(-20,1) ,0.001, 10000) << endl;\n\n    cout << \"Testing Gradient function using SumSquares with 3 variables\" << endl;\n    cout << Gradient(SumSquares, Vector3d(3, 3, 4)) << endl;\n\n    cout << \"Testing Hessian function using SumSquares with 3 variables\" << endl;\n    cout << Hessian(SumSquares, Vector3d(3, 3, 4)) << endl;\n\n    Vector3d x(4, -3, 7);\n\n    cout << \"Testing MVOptimize on SumSquares with initial point (4, -3, 7).\" << endl;\n    cout << \"The Optimal Point obtained is: \";\n    cout << MVOptimize(SumSquares, x, 200,  MVO::NEWTON) << endl;\n\n    cout << \"Testing DFP on sum squared function with 3 variables and initial point (4, -3, 7).\" << endl;\n    cout << \"The Optimal Point obtained is: \" << endl;\n    cout << DFP(SumSquares, x) << endl;\n\n    cout << \"Testing Newton's method on sum squared function with 3 variables and initial point (4, -3, 7).\" << endl;\n    cout << \"The Optimal Point obtained is: \" << endl;\n    cout << Newton(SumSquares, x) << endl;\n\n    cout << \"Testing Cauchy's method on sum squared function with 3 variables and initial point (4, -3, 7).\" << endl;\n    cout << \"The Optimal Point obtained is: \" << endl;\n    cout << Cauchy(SumSquares, x) << endl;\n\n    cout << \"Testing Marquardt's method on sum squared function with 3 variables and initial point (4, -3, 7).\" << endl;\n    cout << \"The Optimal Point obtained is: \" << endl;\n    cout << Marquardt(SumSquares, x) << endl;\n\n    cout << \"Testing Conjugate Gradient method on sum squared function with 3 variables and initial point (4, -3, 7).\" << endl;\n    cout << \"The Optimal Point obtained is: \" << endl;\n    cout << ConjugateGradient(SumSquares, x) << endl;\n\n    cout << \"Testing Conjugate Gradient method on Matyas function with 2 variables and initial point (-3, 7).\" << endl;\n    cout << \"The Optimal Point obtained is: \" << endl;\n    cout << ConjugateGradient(Matyas, Vector2d(-3, 7)) << endl;\n\n    cout << \"Testing Conjugate Gradient method on Dixon function with initial point (-3, 8, 0).\" << endl;\n    cout << \"The Optimal Point obtained is: \" << endl;\n    cout << ConjugateGradient(Dixon, Vector3d(-3, 8, 0), 30000) << endl;\n\n    cout << \"Testing Simplex method on the Himmelblau function with two variables\" << endl;\n    cout << \"The Optimal Point obtained is: \" << endl;\n    VectorXd vec(2);\n    vec(0) = 1;\n    vec(1) = 2;\n    cout << Simplex(Himmelblau,vec,10000, 2, 0.5) << endl;\n\n    cout << \"Testing Penalty Function Method with custom function\" << endl;\n    cout << \"The Optimal Point obtained is: \" << endl;\n    Vector2d x1(2, 2);\n    vector<std::function<double (Eigen::VectorXd)>> eq_const;\n    vector<std::function<double (Eigen::VectorXd)>> ineq_const{[](Vector2d x) { return pow(x(0) - 5, 2) + pow(x(1), 2) - 26; },\n    [](Vector2d x) { return x(0); }, [](Vector2d x) { return x(1); }};\n    cout << PenaltyConstrained(Himmelblau, x1, ineq_const, eq_const) << endl;\n\n    cout << \"Testing Multiplier Constrained Method with custom function\" << endl;\n    cout << \"The Optimal Point obtained is: \" << endl;\n    cout << MultiplierConstrained(Himmelblau, x1, ineq_const, eq_const) << endl;\n\n    cout << \"Testing Data Save Methods\" << endl;\n    Optimum point1;\n    point1.path = Hessian(SumSquares, Vector3d(3, 3, 4));\n    point1.SaveAsTxt();\n    point1.SaveAsCsv();\n    cout << \"TEST SUCCESSFUL\" << endl;\n}\n", "meta": {"hexsha": "db4f694e187399383e1792eaa268e87838bc563d", "size": 6077, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tests/test.cpp", "max_stars_repo_name": "ayerhs7/Optimizer", "max_stars_repo_head_hexsha": "c29900dfb5a7b8471898822c4fb257f546ec519e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2018-10-07T11:33:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T09:20:57.000Z", "max_issues_repo_path": "Tests/test.cpp", "max_issues_repo_name": "ayerhs7/Optimizer", "max_issues_repo_head_hexsha": "c29900dfb5a7b8471898822c4fb257f546ec519e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 70.0, "max_issues_repo_issues_event_min_datetime": "2018-10-07T08:47:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-15T01:17:01.000Z", "max_forks_repo_path": "Tests/test.cpp", "max_forks_repo_name": "ayerhs7/Optimizer", "max_forks_repo_head_hexsha": "c29900dfb5a7b8471898822c4fb257f546ec519e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 63.0, "max_forks_repo_forks_event_min_datetime": "2018-10-07T09:06:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T20:02:26.000Z", "avg_line_length": 38.7070063694, "max_line_length": 127, "alphanum_fraction": 0.6239921014, "num_tokens": 1855, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947132556618, "lm_q2_score": 0.8596637559030338, "lm_q1q2_score": 0.8123777045058727}}
{"text": "#pragma once\n\n#include <boost/math/constants/constants.hpp>\n\n#include \"fmmtl/meta/integer_sequence.hpp\"\n\n/** Computes the ith Chebyshev node of an N-sized quadrature on [-1/2, 1/2] */\ntemplate <typename T>\nconstexpr T chebyshev_node(std::size_t i, std::size_t N) {\n  using boost::math::constants::pi;\n  return\n      (i     == 0  ) ? -0.5 :    // left point\n      (i     == N-1) ?  0.5 :    // right point\n      (2*i+1 == N  ) ?  0.0 :    // N is odd and i is middle\n      (i     <  N/2) ? -std::cos(     i  * pi<T>()/(N-1)) / 2 :  // Force symmetry\n      (i     >= N/2) ?  std::cos((N-1-i) * pi<T>()/(N-1)) / 2 :\n      T();\n}\n\n\ntemplate <typename T, typename Seq>\nstruct ChebyshevImpl;\n\ntemplate <typename T, std::size_t... Is>\nstruct ChebyshevImpl<T,fmmtl::index_sequence<Is...>> {\n  static constexpr std::size_t N = sizeof...(Is);\n  static constexpr T x[N] = { chebyshev_node<T>(Is, N)... };\n};\ntemplate <typename T, std::size_t... Is>\nconstexpr T ChebyshevImpl<T,fmmtl::index_sequence<Is...>>::x[];\n\n/** Precompute N Chebyshev nodes of type T in the range [-1/2, 1/2] */\ntemplate <typename T, std::size_t N>\nstruct Chebyshev : ChebyshevImpl<T,fmmtl::make_index_sequence<N>> {};\n", "meta": {"hexsha": "42a72021c55f181c9bb0cfe0e7d8028854a164e2", "size": 1181, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "extern/magnetic-force/fmmtl_minimum/kernel/Util/Chebyshev.hpp", "max_stars_repo_name": "hg2120223/SPlisHSPlasH", "max_stars_repo_head_hexsha": "b1596c6dfde914533367f7d3124b46997a833af2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "extern/magnetic-force/fmmtl_minimum/kernel/Util/Chebyshev.hpp", "max_issues_repo_name": "hg2120223/SPlisHSPlasH", "max_issues_repo_head_hexsha": "b1596c6dfde914533367f7d3124b46997a833af2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "extern/magnetic-force/fmmtl_minimum/kernel/Util/Chebyshev.hpp", "max_forks_repo_name": "hg2120223/SPlisHSPlasH", "max_forks_repo_head_hexsha": "b1596c6dfde914533367f7d3124b46997a833af2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7428571429, "max_line_length": 82, "alphanum_fraction": 0.6037256562, "num_tokens": 403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750387190131, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.8121453366998055}}
{"text": "#include <iostream>\n#include <cmath>\n#include <Eigen/Dense>\n#include \"descentmethods.h\"\n\ndouble F(Eigen::VectorXd x) {\n    return pow(x(0), 4.0) + pow(x(0), 2.0) * x(1) + 0.5 * pow(x(0), 2.0) + 3 * x(0) * x(1) + pow(x(1), 2.0);\n}\n\nEigen::VectorXd J(Eigen::VectorXd x) {\n    int x_size = x.size();\n\n    Eigen::VectorXd jacobian(x_size);\n\n    jacobian(0) = 4 * pow(x(0), 3.0) + 2 * x(0) * x(1) + x(0) + 3 * x(1);\n    jacobian(1) = pow(x(0), 2.0) + 3 * x(0) + 2 * x(1);\n\n    return jacobian;\n}\n\nEigen::MatrixXd H(Eigen::VectorXd x) {\n    int x_size = x.size();\n\n    Eigen::MatrixXd hessian(x_size, x_size);\n\n    hessian(0, 0) = 12 * pow(x(0), 2.0) + 2 * x(1) + 1;\n    hessian(0, 1) = 2 * x(0) + 3;\n    hessian(1, 0) = 2 * x(0) + 3;\n    hessian(1, 1) = 2;\n\n    return hessian;\n}\n\nint main() {\n    Eigen::Vector2d x0;\n\n    x0(0) = -0.5;\n    x0(1) = -0.5;\n\n    double epsilon = 0.00001;\n    double alpha = 0.3;\n    double beta = 0.5;\n\n    Eigen::VectorXd x = DM::Newton(x0, epsilon, alpha, beta, F, J, H);\n\n    std::cout << \"The solution is: \" << x << std::endl;\n    std::cout << \"The objective is: \" << F(x) << std::endl;\n}\n", "meta": {"hexsha": "a86d6869e1075d1ebcde3cbb2bf2a6f1a3416d46", "size": 1119, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "jameshskoh/DescentMethods-CPP", "max_stars_repo_head_hexsha": "0e0ad532b8de01a8d511489b97ddde6b234e7e48", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "jameshskoh/DescentMethods-CPP", "max_issues_repo_head_hexsha": "0e0ad532b8de01a8d511489b97ddde6b234e7e48", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.cpp", "max_forks_repo_name": "jameshskoh/DescentMethods-CPP", "max_forks_repo_head_hexsha": "0e0ad532b8de01a8d511489b97ddde6b234e7e48", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8367346939, "max_line_length": 108, "alphanum_fraction": 0.5218945487, "num_tokens": 467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214450208031, "lm_q2_score": 0.8418256432832332, "lm_q1q2_score": 0.8117905207864545}}
{"text": "/*\n *  (C) Copyright Nick Thompson 2018.\n *  Use, modification and distribution are subject to the\n *  Boost Software License, Version 1.0. (See accompanying file\n *  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#include <iostream>\n#include <iomanip>\n#include <vector>\n#include <array>\n#include <forward_list>\n#include <algorithm>\n#include <random>\n#include <boost/core/lightweight_test.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/statistics/univariate_statistics.hpp>\n#include <boost/math/statistics/bivariate_statistics.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#include <boost/multiprecision/cpp_complex.hpp>\n\nusing boost::multiprecision::cpp_bin_float_50;\nusing boost::multiprecision::cpp_complex_50;\n\n/*\n * Test checklist:\n * 1) Does it work with multiprecision?\n * 2) Does it work with .cbegin()/.cend() if the data is not altered?\n * 3) Does it work with ublas and std::array? (Checking Eigen and Armadillo will make the CI system really unhappy.)\n * 4) Does it work with std::forward_list if a forward iterator is all that is required?\n * 5) Does it work with complex data if complex data is sensible?\n */\n\nusing  boost::math::statistics::means_and_covariance;\nusing  boost::math::statistics::covariance;\n\ntemplate<class Real>\nvoid test_covariance()\n{\n    std::cout << std::setprecision(std::numeric_limits<Real>::digits10+1);\n    Real tol = std::numeric_limits<Real>::epsilon();\n    using std::abs;\n\n    // Covariance of a single thing is zero:\n    std::array<Real, 1> u1{8};\n    std::array<Real, 1> v1{17};\n    auto [mu_u1, mu_v1, cov1] = means_and_covariance(u1, v1);\n\n    BOOST_TEST(abs(cov1) < tol);\n    BOOST_TEST(abs(mu_u1 - 8) < tol);\n    BOOST_TEST(abs(mu_v1 - 17) < tol);\n\n\n    std::array<Real, 2> u2{8, 4};\n    std::array<Real, 2> v2{3, 7};\n    auto [mu_u2, mu_v2, cov2] = means_and_covariance(u2, v2);\n\n    BOOST_TEST(abs(cov2+4) < tol);\n    BOOST_TEST(abs(mu_u2 - 6) < tol);\n    BOOST_TEST(abs(mu_v2 - 5) < tol);\n\n    std::vector<Real> u3{1,2,3};\n    std::vector<Real> v3{1,1,1};\n\n    auto [mu_u3, mu_v3, cov3] = means_and_covariance(u3, v3);\n\n    // Since v is constant, covariance(u,v) = 0 against everything any u:\n    BOOST_TEST(abs(cov3) < tol);\n    BOOST_TEST(abs(mu_u3 - 2) < tol);\n    BOOST_TEST(abs(mu_v3 - 1) < tol);\n    // Make sure we pull the correct symbol out of means_and_covariance:\n    cov3 = covariance(u3, v3);\n    BOOST_TEST(abs(cov3) < tol);\n\n    cov3 = covariance(v3, u3);\n    // Covariance is symmetric: cov(u,v) = cov(v,u)\n    BOOST_TEST(abs(cov3) < tol);\n\n    // cov(u,u) = sigma(u)^2:\n    cov3 = covariance(u3, u3);\n    Real expected = Real(2)/Real(3);\n\n    BOOST_TEST(abs(cov3 - expected) < tol);\n\n    std::mt19937 gen(15);\n    // Can't template standard library on multiprecision, so use double and cast back:\n    std::uniform_real_distribution<double> dis(-1.0, 1.0);\n    std::vector<Real> u(500);\n    std::vector<Real> v(500);\n    for(size_t i = 0; i < u.size(); ++i)\n    {\n        u[i] = (Real) dis(gen);\n        v[i] = (Real) dis(gen);\n    }\n\n    Real mu_u = boost::math::statistics::mean(u);\n    Real mu_v = boost::math::statistics::mean(v);\n    Real sigma_u_sq = boost::math::statistics::variance(u);\n    Real sigma_v_sq = boost::math::statistics::variance(v);\n\n    auto [mu_u_, mu_v_, cov_uv] = means_and_covariance(u, v);\n    BOOST_TEST(abs(mu_u - mu_u_) < tol);\n    BOOST_TEST(abs(mu_v - mu_v_) < tol);\n\n    // Cauchy-Schwartz inequality:\n    BOOST_TEST(cov_uv*cov_uv <= sigma_u_sq*sigma_v_sq);\n    // cov(X, X) = sigma(X)^2:\n    Real cov_uu = covariance(u, u);\n    BOOST_TEST(abs(cov_uu - sigma_u_sq) < tol);\n    Real cov_vv = covariance(v, v);\n    BOOST_TEST(abs(cov_vv - sigma_v_sq) < tol);\n\n}\n\ntemplate<class Real>\nvoid test_correlation_coefficient()\n{\n    using boost::math::statistics::correlation_coefficient;\n\n    Real tol = std::numeric_limits<Real>::epsilon();\n    std::vector<Real> u{1};\n    std::vector<Real> v{1};\n    Real rho_uv = correlation_coefficient(u, v);\n    BOOST_TEST(abs(rho_uv - 1) < tol);\n\n    u = {1,1};\n    v = {1,1};\n    rho_uv = correlation_coefficient(u, v);\n    BOOST_TEST(abs(rho_uv - 1) < tol);\n\n    u = {1, 2, 3};\n    v = {1, 2, 3};\n    rho_uv = correlation_coefficient(u, v);\n    BOOST_TEST(abs(rho_uv - 1) < tol);\n\n    u = {1, 2, 3};\n    v = {-1, -2, -3};\n    rho_uv = correlation_coefficient(u, v);\n    BOOST_TEST(abs(rho_uv + 1) < tol);\n\n    rho_uv = correlation_coefficient(v, u);\n    BOOST_TEST(abs(rho_uv + 1) < tol);\n\n    u = {1, 2, 3};\n    v = {0, 0, 0};\n    rho_uv = correlation_coefficient(v, u);\n    BOOST_TEST(abs(rho_uv) < tol);\n\n    u = {1, 2, 3};\n    v = {0, 0, 3};\n    rho_uv = correlation_coefficient(v, u);\n    // mu_u = 2, sigma_u^2 = 2/3, mu_v = 1, sigma_v^2 = 2, cov(u,v) = 1.\n    BOOST_TEST(abs(rho_uv - sqrt(Real(3))/Real(2)) < tol);\n}\n\nint main()\n{\n    test_covariance<float>();\n    test_covariance<double>();\n    test_covariance<long double>();\n    test_covariance<cpp_bin_float_50>();\n\n    test_correlation_coefficient<float>();\n    test_correlation_coefficient<double>();\n    test_correlation_coefficient<long double>();\n    test_correlation_coefficient<cpp_bin_float_50>();\n\n    return boost::report_errors();\n}\n", "meta": {"hexsha": "82feeb727efd834ecaec93434b3d3ba95fe7c726", "size": 5243, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/math/test/bivariate_statistics_test.cpp", "max_stars_repo_name": "uosorio/heroku_face", "max_stars_repo_head_hexsha": "7d6465e71dba17a15d8edaef520adb2fcd09d91e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-04-28T15:15:28.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-28T15:15:28.000Z", "max_issues_repo_path": "3rdparty/boost_1_73_0/libs/math/test/bivariate_statistics_test.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-05-23T08:01:11.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-06T20:49:05.000Z", "max_forks_repo_path": "3rdparty/boost_1_73_0/libs/math/test/bivariate_statistics_test.cpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T14:12:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-22T19:20:54.000Z", "avg_line_length": 30.6608187135, "max_line_length": 116, "alphanum_fraction": 0.650963189, "num_tokens": 1592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240142763573, "lm_q2_score": 0.8652240825770432, "lm_q1q2_score": 0.8116874895957542}}
{"text": "#include <iostream>\nusing namespace std;\n#include <ctime>\n// Eigen \u90e8\u5206\n#include <Eigen/Core>\n// \u7a20\u5bc6\u77e9\u9635\u7684\u4ee3\u6570\u8fd0\u7b97\uff08\u9006\uff0c\u7279\u5f81\u503c\u7b49\uff09\n#include <Eigen/Dense>\n\n#define MATRIX_SIZE 50\n\n/****************************\n* \u672c\u7a0b\u5e8f\u6f14\u793a\u4e86 Eigen \u57fa\u672c\u7c7b\u578b\u7684\u4f7f\u7528\n****************************/\n\nint main( int argc, char** argv )\n{\n    // Eigen \u4e2d\u6240\u6709\u5411\u91cf\u548c\u77e9\u9635\u90fd\u662fEigen::Matrix\uff0c\u5b83\u662f\u4e00\u4e2a\u6a21\u677f\u7c7b\u3002\u5b83\u7684\u524d\u4e09\u4e2a\u53c2\u6570\u4e3a\uff1a\u6570\u636e\u7c7b\u578b\uff0c\u884c\uff0c\u5217\n    // \u58f0\u660e\u4e00\u4e2a2*3\u7684float\u77e9\u9635\n    Eigen::Matrix<float, 2, 3> matrix_23;\n\n    // \u540c\u65f6\uff0cEigen \u901a\u8fc7 typedef \u63d0\u4f9b\u4e86\u8bb8\u591a\u5185\u7f6e\u7c7b\u578b\uff0c\u4e0d\u8fc7\u5e95\u5c42\u4ecd\u662fEigen::Matrix\n    // \u4f8b\u5982 Vector3d \u5b9e\u8d28\u4e0a\u662f Eigen::Matrix<double, 3, 1>\uff0c\u5373\u4e09\u7ef4\u5411\u91cf\n    Eigen::Vector3d v_3d;\n\t// \u8fd9\u662f\u4e00\u6837\u7684\n    Eigen::Matrix<float,3,1> vd_3d;\n\n    // Matrix3d \u5b9e\u8d28\u4e0a\u662f Eigen::Matrix<double, 3, 3>\n    Eigen::Matrix3d matrix_33 = Eigen::Matrix3d::Zero(); //\u521d\u59cb\u5316\u4e3a\u96f6\n    // \u5982\u679c\u4e0d\u786e\u5b9a\u77e9\u9635\u5927\u5c0f\uff0c\u53ef\u4ee5\u4f7f\u7528\u52a8\u6001\u5927\u5c0f\u7684\u77e9\u9635\n    Eigen::Matrix< double, Eigen::Dynamic, Eigen::Dynamic > matrix_dynamic;\n    // \u66f4\u7b80\u5355\u7684\n    Eigen::MatrixXd matrix_x;\n    // \u8fd9\u79cd\u7c7b\u578b\u8fd8\u6709\u5f88\u591a\uff0c\u6211\u4eec\u4e0d\u4e00\u4e00\u5217\u4e3e\n\n    // \u4e0b\u9762\u662f\u5bf9Eigen\u9635\u7684\u64cd\u4f5c\n    // \u8f93\u5165\u6570\u636e\uff08\u521d\u59cb\u5316\uff09\n    matrix_23 << 1, 2, 3, 4, 5, 6;\n    // \u8f93\u51fa\n    cout << matrix_23 << endl;\n\n    // \u7528()\u8bbf\u95ee\u77e9\u9635\u4e2d\u7684\u5143\u7d20\n    for (int i=0; i<2; i++) {\n        for (int j=0; j<3; j++)\n            cout<<matrix_23(i,j)<<\"\\t\";\n        cout<<endl;\n    }\n\n    // \u77e9\u9635\u548c\u5411\u91cf\u76f8\u4e58\uff08\u5b9e\u9645\u4e0a\u4ecd\u662f\u77e9\u9635\u548c\u77e9\u9635\uff09\n    v_3d << 3, 2, 1;\n    vd_3d << 4,5,6;\n    // \u4f46\u662f\u5728Eigen\u91cc\u4f60\u4e0d\u80fd\u6df7\u5408\u4e24\u79cd\u4e0d\u540c\u7c7b\u578b\u7684\u77e9\u9635\uff0c\u50cf\u8fd9\u6837\u662f\u9519\u7684\n    // Eigen::Matrix<double, 2, 1> result_wrong_type = matrix_23 * v_3d;\n    // \u5e94\u8be5\u663e\u5f0f\u8f6c\u6362\n    Eigen::Matrix<double, 2, 1> result = matrix_23.cast<double>() * v_3d;\n    cout << result << endl;\n\n    Eigen::Matrix<float, 2, 1> result2 = matrix_23 * vd_3d;\n    cout << result2 << endl;\n\n    // \u540c\u6837\u4f60\u4e0d\u80fd\u641e\u9519\u77e9\u9635\u7684\u7ef4\u5ea6\n    // \u8bd5\u7740\u53d6\u6d88\u4e0b\u9762\u7684\u6ce8\u91ca\uff0c\u770b\u770bEigen\u4f1a\u62a5\u4ec0\u4e48\u9519\n    // Eigen::Matrix<double, 2, 3> result_wrong_dimension = matrix_23.cast<double>() * v_3d;\n\n    // \u4e00\u4e9b\u77e9\u9635\u8fd0\u7b97\n    // \u56db\u5219\u8fd0\u7b97\u5c31\u4e0d\u6f14\u793a\u4e86\uff0c\u76f4\u63a5\u7528+-*/\u5373\u53ef\u3002\n    matrix_33 = Eigen::Matrix3d::Random();      // \u968f\u673a\u6570\u77e9\u9635\n    cout << matrix_33 << endl << endl;\n\n    cout << matrix_33.transpose() << endl;      // \u8f6c\u7f6e\n    cout << matrix_33.sum() << endl;            // \u5404\u5143\u7d20\u548c\n    cout << matrix_33.trace() << endl;          // \u8ff9\n    cout << 10*matrix_33 << endl;               // \u6570\u4e58\n    cout << matrix_33.inverse() << endl;        // \u9006\n    cout << matrix_33.determinant() << endl;    // \u884c\u5217\u5f0f\n\n    // \u7279\u5f81\u503c\n    // \u5b9e\u5bf9\u79f0\u77e9\u9635\u53ef\u4ee5\u4fdd\u8bc1\u5bf9\u89d2\u5316\u6210\u529f\n    Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> eigen_solver ( matrix_33.transpose()*matrix_33 );\n    cout << \"Eigen values = \\n\" << eigen_solver.eigenvalues() << endl;\n    cout << \"Eigen vectors = \\n\" << eigen_solver.eigenvectors() << endl;\n\n    // \u89e3\u65b9\u7a0b\n    // \u6211\u4eec\u6c42\u89e3 matrix_NN * x = v_Nd \u8fd9\u4e2a\u65b9\u7a0b\n    // N\u7684\u5927\u5c0f\u5728\u524d\u8fb9\u7684\u5b8f\u91cc\u5b9a\u4e49\uff0c\u5b83\u7531\u968f\u673a\u6570\u751f\u6210\n    // \u76f4\u63a5\u6c42\u9006\u81ea\u7136\u662f\u6700\u76f4\u63a5\u7684\uff0c\u4f46\u662f\u6c42\u9006\u8fd0\u7b97\u91cf\u5927\n\n    Eigen::Matrix< double, MATRIX_SIZE, MATRIX_SIZE > matrix_NN;\n    matrix_NN = Eigen::MatrixXd::Random( MATRIX_SIZE, MATRIX_SIZE );\n    Eigen::Matrix< double, MATRIX_SIZE,  1> v_Nd;\n    v_Nd = Eigen::MatrixXd::Random( MATRIX_SIZE,1 );\n\n    clock_t time_stt = clock(); // \u8ba1\u65f6\n    // \u76f4\u63a5\u6c42\u9006\n    Eigen::Matrix<double,MATRIX_SIZE,1> x = matrix_NN.inverse()*v_Nd;\n    cout <<\"time use in normal invers is \" << 1000* (clock() - time_stt)/(double)CLOCKS_PER_SEC << \"ms\"<< endl;\n    \n\t// \u901a\u5e38\u7528\u77e9\u9635\u5206\u89e3\u6765\u6c42\uff0c\u4f8b\u5982QR\u5206\u89e3\uff0c\u901f\u5ea6\u4f1a\u5feb\u5f88\u591a\n    time_stt = clock();\n    x = matrix_NN.colPivHouseholderQr().solve(v_Nd);\n    cout <<\"time use in Qr compsition is \" <<1000*  (clock() - time_stt)/(double)CLOCKS_PER_SEC <<\"ms\" << endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "b44ff8c28f926e94eb2689b6a299cb392b6de372", "size": 3236, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch3/useEigen/eigenMatrix.cpp", "max_stars_repo_name": "amourlee123/slambook", "max_stars_repo_head_hexsha": "36c7fc944a39fd4b88aafc2ebe7bf3c1f380e791", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-03-07T19:29:41.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-03T14:39:41.000Z", "max_issues_repo_path": "ch3/useEigen/eigenMatrix.cpp", "max_issues_repo_name": "amourlee123/slambook", "max_issues_repo_head_hexsha": "36c7fc944a39fd4b88aafc2ebe7bf3c1f380e791", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch3/useEigen/eigenMatrix.cpp", "max_forks_repo_name": "amourlee123/slambook", "max_forks_repo_head_hexsha": "36c7fc944a39fd4b88aafc2ebe7bf3c1f380e791", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-07-07T07:18:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-15T11:52:23.000Z", "avg_line_length": 31.1153846154, "max_line_length": 111, "alphanum_fraction": 0.5970333745, "num_tokens": 1378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475730993028, "lm_q2_score": 0.8596637487122111, "lm_q1q2_score": 0.8109617110291133}}
{"text": "/*\n * MIT License\n * Copyright (c) 2020 Anirudh Topiwala\n * Author: Anirudh Topiwala\n * Create Date: 2020-08\n * Last Edit Date: 2020-08\n *\n * @brief Check if a Point is Inside , On or Outside a given Polygon\n *        Implements two funtions:\n *        1) Check if a point is inside a polygon using windinding number\n *            algorithm.\n *        2) A simpler way to check if a point is inside a convex polygon.\n *\n * A more detailed explanation can be found on my blog post\n * \"Is the Point Inside the Polygon\"\n * (https://medium.com/@topiwala.anirudh/is-the-point-inside-the-polygon-574b86472119)\n *\n */\n\n#include <Eigen/Dense>\n#include <cmath>\n#include <iostream>\n#include <unordered_map>\n#include <vector>\n\n/**\n * @brief The result can be used to test if the query point lies on the left or\n *        right side of the line formed by pt1 and pt2 when viewed in\n *        anticlockwise  direction.\n *\n * @param pt1: First point to form equation of line.\n * @param pt2: Second point to form equation of line.\n * @param query_point: Query point\n * @return: > 0: Query point lies on left of the line.\n *          = 0: Query point lies on the line.\n *          < 0: Query point lies on right of the line.\n */\ndouble substitute_point_in_line(const Eigen::Vector2d &pt1,\n                                const Eigen::Vector2d &pt2,\n                                const Eigen::Vector2d &query_point) {\n    return ((query_point.y() - pt1.y()) * (pt2.x() - pt1.x())) -\n           ((query_point.x() - pt1.x()) * (pt2.y() - pt1.y()));\n};\n\n/**\n * @brief Check if a point lies inside, on or outside a convex polygon.\n *\n * For a convex polygon, if the sides of the polygon can be considered as a path\n * from first vertex. Then, a query point is said to be inside the polygon if it\n * lies on the same side of all the line segments making up the path.\n *\n * @param query_point Point to check.\n * @param vertices Vertices making up the polygon.\n * @return  = 1: query_point lies inside the polygon.\n *          = 0: query_point lies on the polygon.\n *          =-1: query_point lies outside the polygon.\n */\nint is_point_inside_convex_polygon(const Eigen::Vector2d &query_point,\n                                   std::vector<Eigen::Vector2d> &vertices) {\n    const int num_sides_of_polygon = vertices.size();\n    int count_same_side_results = 0;\n    // Iterate over each side.\n    for (size_t i = 0; i < num_sides_of_polygon; ++i) {\n        const auto point_in_line = substitute_point_in_line(\n            vertices[i], vertices[(i + 1) % num_sides_of_polygon], query_point);\n\n        // Check if the point lies on the polygon.\n        if (point_in_line == 0) {\n            return point_in_line;\n        }\n\n        count_same_side_results += point_in_line > 0;\n    }\n    return (std::abs(count_same_side_results) == num_sides_of_polygon) ? 1 : -1;\n}\n\n/**\n * @brief Check if a point lies inside, on or outside any polygon.\n *\n * Winding number algorithm can be used to check if any point lies inside a\n * polygon. A more detailed explanation can be found in the blog post. The link\n * is attached at the top of the file.\n *\n *\n * @param query_point Point to check.\n * @param vertices Vertices making up the polygon in anticlockwise direction.\n * @return  = 1: query_point lies inside the polygon.\n *          = 0: query_point lies on the polygon.\n *          =-1: query_point lies outside the polygon.\n */\nint is_point_inside_polygon(const Eigen::Vector2d &query_point,\n                            std::vector<Eigen::Vector2d> &vertices) {\n    int wn = 0;  // the  winding number counter\n    const int num_sides_of_polygon = vertices.size();\n\n    for (size_t i = 0; i < num_sides_of_polygon; ++i) {\n        const auto point_in_line = substitute_point_in_line(\n            vertices[i], vertices[(i + 1) % num_sides_of_polygon], query_point);\n\n        // Check if the point lies on the polygon.\n        if (point_in_line == 0) {\n            return 0;\n        }\n        if (vertices[i].y() <= query_point.y()) {\n            // Upward crossing.\n            if (vertices[(i + 1) % num_sides_of_polygon].y() >\n                query_point.y()) {\n                if (point_in_line > 0) {\n                    ++wn;  // query point is left of edge\n                }\n            }\n        } else {\n            // Downward crossing.\n            if (vertices[(i + 1) % num_sides_of_polygon].y() <\n                query_point.y()) {\n                if (point_in_line < 0) {\n                    --wn;  // query point is right of edge\n                }\n            }\n        }\n    }\n    return (wn != 0) ? 1 : -1;  // Point is inside polygon only if wn != 0\n}\n\nint main() {\n    // Map to make printing easier.\n    std::unordered_map<int, std::string> get_value{\n        {-1, \"outisde\"}, {0, \"on\"}, {1, \"inside\"}};\n    // Non Convex Polygon\n    {\n        std::cout << \"For Non Convex Polygon...\\n\" << std::endl;\n        // Vetices need to be in anticlockwise direction to fix the notion of\n        // left and right of edges made in the comments.\n        std::vector<Eigen::Vector2d> vertices{{0, 0}, {3, 1}, {6, 0}, {3, 5}};\n        std::vector<Eigen::Vector2d> query_points{\n            {3, 2}, {3, 6}, {3, 1}, {0, 0}, {15, 20}};\n        for (const auto &point : query_points) {\n            std::cout << \"Point: \" << point.transpose() << \" lies \"\n                      << get_value[is_point_inside_polygon(point, vertices)]\n                      << \" the polygon.\" << std::endl;\n        }\n    }\n\n    std::cout << \"\\n\";\n\n    // Convex Polygons\n    std::cout << \"For Convex Polygon...\" << std::endl;\n    // Triangle\n    {\n        std::cout << \"For Triangle\\n\" << std::endl;\n        std::vector<Eigen::Vector2d> vertices{{0, 0}, {6, 0}, {3, 5}};\n        std::vector<Eigen::Vector2d> query_points{\n            {3, 2}, {3, 6}, {3, 5}, {0, 0}, {15, 20}};\n        for (const auto &point : query_points) {\n            std::cout << \"Point: \" << point.transpose() << \" lies \"\n                      << get_value[is_point_inside_polygon(point, vertices)]\n                      << \" the polygon.\" << std::endl;\n        }\n    }\n\n    std::cout << \"\\n\";\n\n    // Quadrilateral\n    {\n        std::cout << \"For convex Quadrilateral\\n\" << std::endl;\n        std::vector<Eigen::Vector2d> vertices{{0, 0}, {6, 0}, {6, 6}, {-1, 10}};\n        std::vector<Eigen::Vector2d> query_points{\n            {3, 2}, {3, 6}, {3, 5}, {0, 0}, {15, 20}};\n        for (const auto &point : query_points) {\n            std::cout << \"Point: \" << point.transpose() << \" lies \"\n                      << get_value[is_point_inside_polygon(point, vertices)]\n                      << \" the polygon.\" << std::endl;\n        }\n    }\n}\n", "meta": {"hexsha": "9b0978ceffd93cb0f5194ce8dc5542dade809416", "size": 6662, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Point_In_Polygon/src/point_in_polygon.cpp", "max_stars_repo_name": "anirudhtopiwala/OpenSource_Problems", "max_stars_repo_head_hexsha": "2482bf6d999d468bc56c15c3c0bf01f7da945858", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 39.0, "max_stars_repo_stars_event_min_datetime": "2020-05-05T16:30:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T21:18:03.000Z", "max_issues_repo_path": "Point_In_Polygon/src/point_in_polygon.cpp", "max_issues_repo_name": "anirudhtopiwala/OpenSource_Problems", "max_issues_repo_head_hexsha": "2482bf6d999d468bc56c15c3c0bf01f7da945858", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-05-05T18:36:27.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-27T10:08:41.000Z", "max_forks_repo_path": "Point_In_Polygon/src/point_in_polygon.cpp", "max_forks_repo_name": "anirudhtopiwala/OpenSource_Problems", "max_forks_repo_head_hexsha": "2482bf6d999d468bc56c15c3c0bf01f7da945858", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2020-05-27T03:00:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-03T22:58:47.000Z", "avg_line_length": 37.8522727273, "max_line_length": 86, "alphanum_fraction": 0.5706994896, "num_tokens": 1780, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248140158416, "lm_q2_score": 0.8633916047011594, "lm_q1q2_score": 0.8107461410273452}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include <Eigen/Jacobi>\n#include <cmath>\n#include <math.h> \n\nusing namespace Eigen;\n\nvoid calc_V(const Eigen::Matrix2f& C, Eigen::Matrix2f& V) {\n\n\tEigen::Matrix2f Sigma;\n\tfloat tau, t_2, c_2, s_2;\n\n\ttau = (C(1, 1) - C(0, 0)) / (2 * C(1, 0));\n\tif (tau>0) {\n\t\tt_2 = tau - sqrt(1 + tau*tau);\n\t}\n\telse {\n\t\tt_2 = tau + sqrt(1 + tau*tau);\n\t}\n\tc_2 = 1 / sqrt(1 + t_2*t_2);\n\ts_2 = t_2*c_2;\n\tV << c_2, -s_2, s_2, c_2;\n}\n\n\nvoid signconvention(Matrix2f& U, Matrix2f& V, Vector2f& sigma) {\n\tVector2f tempvec;\n\tfloat tempf;\n\tif (sigma(0)<0 && sigma(1)<0) {\n\t\tU = -U;\n\t\tsigma = -sigma;\n\t}\n\tif (sigma(0)<0) {\n\t\ttempvec = U.col(0);\n\t\tU.col(0) << U.col(1);\n\t\tU.col(1) = tempvec;\n\t\ttempf = sigma(0);\n\t\tsigma(0) = sigma(1);\n\t\tsigma(1) = tempf;\n\t\ttempvec = V.col(0);\n\t\tV.col(0) << V.col(1);\n\t\tV.col(1) = tempvec;\n\n\t}\n\telse if (sigma(0) >= 0 && sigma(1) >= 0) {\n\t\tif (sigma(1) > sigma(0)) {\n\t\t\ttempvec = U.col(0);\n\t\t\tU.col(0) << U.col(1);\n\t\t\tU.col(1) = tempvec;\n\t\t\ttempf = sigma(0);\n\t\t\tsigma(0) = sigma(1);\n\t\t\tsigma(1) = tempf;\n\t\t\ttempvec = V.col(0);\n\t\t\tV.col(0) << V.col(1);\n\t\t\tV.col(1) = tempvec;\n\t\t}\n\t}\n\n\n\n}\n\nvoid My_SVD(const Eigen::Matrix2f& F, Eigen::Matrix2f& U, Eigen::Matrix2f& sigma, Eigen::Matrix2f& V)\n{\n\tEigen::Matrix2f C,A,Sigma;\n\tEigen::Vector2f b,v,sigma_vec;\n\tEigen::JacobiRotation<float> G;\n\tfloat a, c_U, s_U;\n\n\t\n\n\tC = F.transpose()*F;\n\tcalc_V(C,V);\n\t\n\tA = F*V;\n\t\n\tG.makeGivens(A(0,0),A(1,0));\n\tv<<1,0;\n    v.applyOnTheLeft(0,1,G);\n    c_U = v(0);\n    s_U = -v(1);\n    U<<c_U,s_U,-s_U,c_U;\n    Sigma = A;\n    Sigma.applyOnTheLeft(0,1,G.adjoint());\n    //std::cout<<Sigma;\n\tsigma_vec(0) = Sigma(0,0);\n\tsigma_vec(1) = Sigma(1,1);\n\n\tsignconvention(U, V, sigma_vec);\n\n\tsigma << sigma_vec(0), 0,\n\t\t0, sigma_vec(1);\n\n\t\n\t\n}\n\nint main() {\n\n\tEigen::Matrix2f F, U, sigma, V;\n\n\n\tF << 10, 2,\n\t\t3, 4;\n\n\tMy_SVD(F, U, sigma, V);\n\n\t\n\n\n\n\tstd::cout << U << std::endl << std::endl;\n\n\tstd::cout << U*U.transpose() << std::endl << std::endl;\n\n\tstd::cout << V << std::endl << std::endl;\n\n\tstd::cout << V*V.transpose() << std::endl << std::endl;\n\n\tstd::cout << sigma << std::endl << std::endl;\n\n\tstd::cout << U*sigma*V.adjoint() << std::endl << std::endl;\n\n\tstd::cout << F << std::endl;\n\n\tsystem(\"pause\");\n\n\treturn 0;\n}\n", "meta": {"hexsha": "43abb426632f51a3327bd960d142f7960668aa0a", "size": 2238, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "HW1/HW1_1.cpp", "max_stars_repo_name": "ShyrSheaChang/Math_270A_Fall_2016_HW", "max_stars_repo_head_hexsha": "470767cccf25319ee713481004ac0a5a65129cc4", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HW1/HW1_1.cpp", "max_issues_repo_name": "ShyrSheaChang/Math_270A_Fall_2016_HW", "max_issues_repo_head_hexsha": "470767cccf25319ee713481004ac0a5a65129cc4", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HW1/HW1_1.cpp", "max_forks_repo_name": "ShyrSheaChang/Math_270A_Fall_2016_HW", "max_forks_repo_head_hexsha": "470767cccf25319ee713481004ac0a5a65129cc4", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.0839694656, "max_line_length": 101, "alphanum_fraction": 0.5527256479, "num_tokens": 908, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947086083138, "lm_q2_score": 0.8577681122619883, "lm_q1q2_score": 0.810586327300521}}
{"text": "////\n//// Copyright (C) 2016 SAM (D-MATH) @ ETH Zurich\n//// Author(s): lfilippo <filippo.leonardi@sam.math.ethz.ch>\n//// Contributors: tille, jgacon, dcasati\n//// This file is part of the NumCSE repository.\n////\n#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace Eigen;\n\n/* \\brief Performs Gram-Schidt orthonormalization\n * Given a matrix $\\mathbf{A}$ of linearly independent columns,\n * returns the result of a Gram-Schmidt orthonormalization.\n * Unstable GS algorithm: output is prone to cancellation issues.\n * \\param[in] $\\mathbf{A}$ Matrix of linearly independent columns\n * \\return Matrix with ONB of $span(a_1, \\cdots, a_n)$ as columns\n */\n\nMatrixXd gram_schmidt(const MatrixXd &A) {\n\t// We create a matrix Q with the same size and data of A\n\tMatrixXd Q(A);\n\n\tfor(int k = 0; k < A.cols(); k++) {\n\t\tVectorXd sum = VectorXd::Zero(A.cols());\n\n\t\tfor(int j = 0; j < k; j++) {\n\t\t\tsum += (Q.col(j).dot(A.col(k))) * Q.col(j);\n\t\t}\n\n\t\tQ.col(k) = A.col(k) - sum;\n\t\tQ.col(k).normalize();\n\t}\n\n\treturn Q;\n}\n\nint main(void) {\n\n\t// Orthonormality test\n\tunsigned int n = 4;\n\tMatrixXd A = MatrixXd::Random(n, n);\n\tMatrixXd Q = gram_schmidt(A);\n\n\t// \"How far is Q from being orthonormal?\"\n\tMatrixXd I =  Q.transpose() * Q ; \t// for orthogonal matrices this should be the identity\n\tstd::cout << I << std::endl;\n\n\t// Error has to be small, but not zero (why?)\n\tdouble err = (I - MatrixXd::Identity(n, n)).norm();\n\tstd::cout << \"Error is: \" << err << std::endl;\n\n\treturn 0;\n}\n", "meta": {"hexsha": "7a956d8dce367b1fb0c1ab31ce871acdc5c2e06e", "size": 1470, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "misc/gramschmidt.cpp", "max_stars_repo_name": "azurite/numCSE18-code", "max_stars_repo_head_hexsha": "f7104305375954a0528d366f8460bf8033d20f0a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-13T19:08:32.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-13T19:08:32.000Z", "max_issues_repo_path": "misc/gramschmidt.cpp", "max_issues_repo_name": "azurite/numCSE18-code", "max_issues_repo_head_hexsha": "f7104305375954a0528d366f8460bf8033d20f0a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "misc/gramschmidt.cpp", "max_forks_repo_name": "azurite/numCSE18-code", "max_forks_repo_head_hexsha": "f7104305375954a0528d366f8460bf8033d20f0a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.7272727273, "max_line_length": 90, "alphanum_fraction": 0.6496598639, "num_tokens": 442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172630429475, "lm_q2_score": 0.8539127473751341, "lm_q1q2_score": 0.8102925471166962}}
{"text": "/*\n * prime_test.cpp: Math Utility #6. Determine if the given integer is prime, then\n * find and output the next prime starting from the same integer.\n *\n * Version:     1.0.0\n * License:     MIT License (see LICENSE.txt for more details)\n * Author:      Joshua Morrison (MrM21632)\n * Last Edited: 1/17/2018, 5:00pm\n */\n\n#include <cstdint>\n#include <cstdio>\n#include <cstdlib>\n#include <ctime>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/random_device.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n\n// Constant value used for testing primality; ensures we won't run into any\n// unepxected results.\n#define TEST_NUM (30)\n\n// Constants for random number generation\nboost::random::random_device rd;\nboost::random::mt19937 mt(rd());\n\n\n/**\n *  @brief Modular Addition\n *  \n *  @param [in] a Summand\n *  @param [in] b Summand\n *  @param [in] n Modulus\n *  @return (a + b) mod n.\n *  \n *  @details Performs modular addition on two integers with a given modulus.\n *           This implementation is written so as to avoid integer overflow.\n */\nuint64_t mod_add(uint64_t a, uint64_t b, uint64_t n) {\n    return ((a % n) + (b % n)) % n;\n}\n\n/**\n *  @brief Modular Multiplication\n *  \n *  @param [in] a Multiplicand\n *  @param [in] b Multiplier\n *  @param [in] n Modulus\n *  @return ab mod n.\n *  \n *  @details Performs modular multiplication on two integers with a given\n *           modulus. This implementation is written so as to avoid integer\n *           overflow.\n */\nuint64_t mod_mult(uint64_t a, uint64_t b, uint64_t n) {\n    uint64_t r = 0;  // Remainder, to be returned\n\n    // If a is larger than the modulus, we need to reduce it in order to avoid\n    // integer overflow.\n    if (a >= n) a %= n;\n\n    // This loop performs modular addition on r until the multiplier is 0.\n    while (b > 0) {\n        if (b & 1)  // Equivalent to \"b % 2 == 1\"\n            r = mod_add(r, a, n);\n\n        a = (a * 2) % n;\n        b >>= 1;    // Equivalent to \"b /= 2\"\n    }\n\n    // (a * b) mod n == ((a mod n) * (b mod n)) mod n. At this point, we have\n    // calculated r = (a mod n) * (b mod n), so we now need to reduce r by mod\n    // n, then return that result.\n    return r % n;\n}\n\n/**\n *  @brief Modular Exponentiation\n *  \n *  @param [in] a Base\n *  @param [in] b Exponent\n *  @param [in] n Modulus\n *  @return a^b mod n.\n *  \n *  @details Performs modular exponentiation on two integers with a given\n *           modulus. This implementation is written so as to avoid integer\n *           overflow.\n */\nuint64_t mod_pow(uint64_t a, uint64_t b, uint64_t n) {\n    uint64_t r = 1;  // Remainder, to be returned\n\n    // If a is larger than the modulus, we need to reduce it in order to avoid\n    // integer overflow.\n    if (a >= n) a %= n;\n\n    // This loop performs modular multiplication on both the remainder and the\n    // base, until our exponent is 0.\n    while (b > 0) {\n        if (b & 1)  // Equivalent to \"b % 2 == 1\"\n            r = mod_mult(r, a, n);\n\n        a = mod_mult(a, a, n);\n        b >>= 1;    // Equivalent to \"b /= 2\"\n    }\n\n    return r;\n}\n\n/**\n *  @brief Miller-Rabin Primality Test\n *  \n *  @param [in] n Number to test for primality; must be odd\n *  @param [in] d A divisor of n-1; must be odd\n *  @return Returns true if n is likely prime, or false otherwise.\n *  \n *  @details Performs a non-deterministic primality test on a given integer to\n *           determine if it is composite or (likely) prime.\n */\nbool miller_rabin(uint64_t n, uint64_t d) {\n    boost::random::uniform_int_distribution<uint64_t> dist(2, n - 2);\n\n    uint64_t a = dist(mt);          // Randomly select a from [2, n-2]\n    uint64_t x = mod_pow(a, d, n);  // Let x = a^d mod n\n\n    // Base Case: if a^d mod n is 1 or n-1, then we can already assume n is\n    // prime, so we can return true.\n    if (x == 1 || x == n - 1)\n        return true;\n\n    // This loop performs modular multiplication on x until d is equal to n-1.\n    while (d != (n - 1)) {\n        x = mod_mult(x, x, n);\n        d <<= 1;  // Equivalent to \"d *= 2\"\n\n        if (x == 1) return false;\n        if (x == (n - 1)) return true;\n    }\n\n    // If we reach this point, we can safely say that n is not prime, so we\n    // return false.\n    return false;\n}\n\n/**\n *  @brief Main Primality Test Algorithm\n *  \n *  @param [in] n Number to test for primality; must be odd\n *  @param [in] k Number of times to repeat the test\n *  @return Returns true if n is likely prime, or false otherwise.\n *  \n *  @details Performs a series of non-deterministic primality tests on a given\n *           integer to determine if it is composite or (likely) prime. If any\n *           test fails, we immediately assume compositeness.\n */\nbool is_prime(uint64_t n, uint64_t k) {\n    // Base cases\n    if (n <= 1) return false;\n    if (n <= 3) return true;\n    if (!(n & 1)) return false;  // Equivalent to \"n % 2 == 0\"\n\n    // At this point, we know n is odd and greater than 1. Now, our goal is to\n    // find an integer d such that n-1 = d * 2^r, where r >= 1. The loop divides\n    // d by 2 until it is no longer even - at that point, we will have the value\n    // we desire.\n    uint64_t d = n - 1;\n    while (!(d & 1))  // Equivalent to \"d % 2 == 0\"\n        d >>= 1;      // Equivalent to \"d /= 2\"\n\n    // This loop calls miller_rabin(n, d) k times. If any of the tests fail, we\n    // know that n is not prime, so we return false.\n    for (uint64_t i = 0; i < k; ++i) {\n        if (!miller_rabin(n, d))\n            return false;\n    }\n\n    // If we reach this point, we can safely assume (NOT guarantee!) n is prime,\n    // so we return true.\n    return true;\n}\n\n/**\n *  @brief Find the Next Prime\n *  \n *  @param [in] n Start point for prime search\n *  @return The next prime number after n.\n *  \n *  @details Looks for the next prime number to occur after the given integer.\n */\nuint64_t next_prime(uint64_t n) {\n    // This loop runs for all i in [n+1, inf).\n    // \n    // Because there is consistently a marginal number of integers between any\n    // two primes, this process will execute quickly.\n    for (uint64_t i = n + 1; ; ++i) {\n        if (is_prime(i, TEST_NUM))\n            return i;\n    }\n}\n\n\nint main(int argc, char **argv) {\n    if (argc != 2) {\n        std::printf(\"Usage: prime_test n\\n\");\n        std::printf(\"Test the given number for primality, then find the next prime number.\\n\\n\");\n        std::printf(\"n\\t\\tNumber to test; in range [0, 2^64)\\n\");\n        std::exit(EXIT_FAILURE);\n    }\n\n    char *e;\n    uint64_t n = std::strtoull(argv[1], &e, 10);\n\n    clock_t start = std::clock();\n    bool is_n_prime = is_prime(n, TEST_NUM);\n    uint64_t next = next_prime(n);\n    clock_t end = std::clock();\n    double time = static_cast<double>(end - start) / CLOCKS_PER_SEC;\n\n    std::printf(\"%llu is %s.\\n\", n, (is_n_prime ? \"PRIME\" : \"NOT PRIME\"));\n    std::printf(\"The next prime is %llu.\\n\", next);\n    std::printf(\"Process took %.6f seconds.\\n\", time);\n}\n", "meta": {"hexsha": "05d7d06b74609c99228db85bf2fd0f4ee73cfac4", "size": 6952, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "math_utils/prime_test.cpp", "max_stars_repo_name": "MrM21632/WinUtils", "max_stars_repo_head_hexsha": "1f8597ffbbea7ec8684fa723831cec2dc37900d0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "math_utils/prime_test.cpp", "max_issues_repo_name": "MrM21632/WinUtils", "max_issues_repo_head_hexsha": "1f8597ffbbea7ec8684fa723831cec2dc37900d0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "math_utils/prime_test.cpp", "max_forks_repo_name": "MrM21632/WinUtils", "max_forks_repo_head_hexsha": "1f8597ffbbea7ec8684fa723831cec2dc37900d0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3153153153, "max_line_length": 97, "alphanum_fraction": 0.6034234753, "num_tokens": 2060, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240142763573, "lm_q2_score": 0.8633916222765627, "lm_q1q2_score": 0.8099684145826654}}
{"text": "#include <Eigen/Geometry>\n#include \"Kabsch.hpp\"\n// Given two sets of 3D points, find the rotation + translation + scale\n// which best maps the first set to the second.\n// Source: http://en.wikipedia.org/wiki/Kabsch_algorithm\n\n// The input 3D points are stored as columns.\nEigen::Affine3d Find3DAffineTransform(Eigen::Matrix3Xd in, Eigen::Matrix3Xd out) {\n\n  // Default output\n  Eigen::Affine3d A;\n  A.linear() = Eigen::Matrix3d::Identity(3, 3);\n  A.translation() = Eigen::Vector3d::Zero();\n\n  if (in.cols() != out.cols())\n    throw \"Find3DAffineTransform(): input data mis-match\";\n\n  // First find the scale, by finding the ratio of sums of some distances,\n  // then bring the datasets to the same scale.\n  double dist_in = 0, dist_out = 0;\n  for (int col = 0; col < in.cols()-1; col++) {\n    dist_in  += (in.col(col+1) - in.col(col)).norm();\n    dist_out += (out.col(col+1) - out.col(col)).norm();\n  }\n  if (dist_in <= 0 || dist_out <= 0)\n    return A;\n  double scale = dist_out/dist_in;\n  out /= scale;\n    \n  //  printf(\"scale %lf\\n\", scale);\n\n  // Find the centroids then shift to the origin\n  Eigen::Vector3d in_ctr = Eigen::Vector3d::Zero();\n  Eigen::Vector3d out_ctr = Eigen::Vector3d::Zero();\n  for (int col = 0; col < in.cols(); col++) {\n    in_ctr  += in.col(col);\n    out_ctr += out.col(col);\n  }\n  in_ctr /= in.cols();\n  out_ctr /= out.cols();\n  for (int col = 0; col < in.cols(); col++) {\n    in.col(col)  -= in_ctr;\n    out.col(col) -= out_ctr;\n  }\n\n  // SVD\n  Eigen::MatrixXd Cov = in * out.transpose();\n  Eigen::JacobiSVD<Eigen::MatrixXd> svd(Cov, Eigen::ComputeThinU | Eigen::ComputeThinV);\n\n  // Find the rotation\n  double d = (svd.matrixV() * svd.matrixU().transpose()).determinant();\n  if (d > 0)\n    d = 1.0;\n  else\n    d = -1.0;\n  Eigen::Matrix3d I = Eigen::Matrix3d::Identity(3, 3);\n  I(2, 2) = d;\n  Eigen::Matrix3d R = svd.matrixV() * I * svd.matrixU().transpose();\n\n  // The final transform\n  A.linear() = scale * R;\n  A.translation() = scale*(out_ctr - R*in_ctr);\n\n  return A;\n}\n\nEigen::Affine3d Find3DAffineTransformSameScale(Eigen::Matrix3Xd in, Eigen::Matrix3Xd out)\n{\n    // Default output\n    Eigen::Affine3d A;\n    A.linear() = Eigen::Matrix3d::Identity(3, 3);\n    A.translation() = Eigen::Vector3d::Zero();\n    \n    if (in.cols() != out.cols())\n        throw \"Find3DAffineTransform(): input data mis-match\";\n    \n    // Find the centroids then shift to the origin\n    Eigen::Vector3d in_ctr = Eigen::Vector3d::Zero();\n    Eigen::Vector3d out_ctr = Eigen::Vector3d::Zero();\n    for (int col = 0; col < in.cols(); col++) {\n        in_ctr  += in.col(col);\n        out_ctr += out.col(col);\n    }\n    in_ctr /= in.cols();\n    out_ctr /= out.cols();\n    for (int col = 0; col < in.cols(); col++) {\n        in.col(col)  -= in_ctr;\n        out.col(col) -= out_ctr;\n    }\n    \n    // SVD\n    Eigen::MatrixXd Cov = in * out.transpose();\n    Eigen::JacobiSVD<Eigen::MatrixXd> svd(Cov, Eigen::ComputeThinU | Eigen::ComputeThinV);\n    \n    // Find the rotation\n    double d = (svd.matrixV() * svd.matrixU().transpose()).determinant();\n    if (d > 0)\n        d = 1.0;\n    else\n        d = -1.0;\n    Eigen::Matrix3d I = Eigen::Matrix3d::Identity(3, 3);\n    I(2, 2) = d;\n    Eigen::Matrix3d R = svd.matrixV() * I * svd.matrixU().transpose();\n    \n    // The final transform\n    A.linear() = R;\n    A.translation() = (out_ctr - R*in_ctr);\n    \n    return A;\n}\n\n\n// A function to test Find3DAffineTransform()\n\nvoid TestFind3DAffineTransform(){\n\n  // Create datasets with known transform\n  Eigen::Matrix3Xd in(3, 100), out(3, 100);\n  Eigen::Quaternion<double> Q(1, 3, 5, 2);\n  Q.normalize();\n  Eigen::Matrix3d R = Q.toRotationMatrix();\n  double scale = 2.0;\n  for (int row = 0; row < in.rows(); row++) {\n    for (int col = 0; col < in.cols(); col++) {\n      in(row, col) = log(2*row + 10.0)/sqrt(1.0*col + 4.0) + sqrt(col*1.0)/(row + 1.0);\n    }\n  }\n  Eigen::Vector3d S;\n  S << -5, 6, -27;\n  for (int col = 0; col < in.cols(); col++)\n    out.col(col) = scale*R*in.col(col) + S;\n\n  Eigen::Affine3d A = Find3DAffineTransform(in, out);\n\n  // See if we got the transform we expected\n  if ( (scale*R-A.linear()).cwiseAbs().maxCoeff() > 1e-13 ||\n       (S-A.translation()).cwiseAbs().maxCoeff() > 1e-13)\n    throw \"Could not determine the affine transform accurately enough\";\n}\n", "meta": {"hexsha": "0d9842cbceb2432c92e9e688bdfda737b392739e", "size": 4286, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pose_estimation/Kabsch.cpp", "max_stars_repo_name": "LiliMeng/btrf", "max_stars_repo_head_hexsha": "c13da164b11c5ada522fa40deeaffc32192c4bf9", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2017-10-28T15:24:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-28T13:51:05.000Z", "max_issues_repo_path": "src/pose_estimation/Kabsch.cpp", "max_issues_repo_name": "LiliMeng/btrf", "max_issues_repo_head_hexsha": "c13da164b11c5ada522fa40deeaffc32192c4bf9", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pose_estimation/Kabsch.cpp", "max_forks_repo_name": "LiliMeng/btrf", "max_forks_repo_head_hexsha": "c13da164b11c5ada522fa40deeaffc32192c4bf9", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-11-08T16:10:39.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-21T03:40:02.000Z", "avg_line_length": 30.6142857143, "max_line_length": 90, "alphanum_fraction": 0.6028931405, "num_tokens": 1370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768557238084, "lm_q2_score": 0.8577681068080748, "lm_q1q2_score": 0.8098847940262119}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n//      Copyright Christopher Kormanyos 2020.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n//\n\n// This example exercises Boost.Multiprecision in concurrent\n// multi-threaded environments. To do so a loop involving\n// non-trivial calculations of numerous function values\n// has been set up within both concurrent as well as\n// sequential running environments. In particular,\n// this example uses an AGM method to do a \"from the ground up\"\n// calculation of logarithms. The logarithm functions values\n// are compared with the values from Boost.Multiprecision's\n// specific log functions for the relevant backends.\n// The log GM here is not optimized or intended for\n// high-performance work, but can be taken as an\n// interesting example of an AGM iteration if helpful.\n\n// This example has been initially motivated in part\n// by discussions in:\n// https://github.com/boostorg/multiprecision/pull/211\n\n// We find the following performance data here:\n// https://github.com/boostorg/multiprecision/pull/213\n//\n// cpp_dec_float:\n// result_is_ok_concurrent: true, calculation_time_concurrent: 18.1s\n// result_is_ok_sequential: true, calculation_time_sequential: 48.5s\n//\n// cpp_bin_float:\n// result_is_ok_concurrent: true, calculation_time_concurrent: 18.7s\n// result_is_ok_sequential: true, calculation_time_sequential: 50.4s\n//\n// gmp_float:\n// result_is_ok_concurrent: true, calculation_time_concurrent: 3.3s\n// result_is_ok_sequential: true, calculation_time_sequential: 12.4s\n//\n// mpfr_float:\n// result_is_ok_concurrent: true, calculation_time_concurrent: 0.6s\n// result_is_ok_sequential: true, calculation_time_sequential: 1.9s\n\n#include <array>\n#include <atomic>\n#include <cstddef>\n#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n#include <thread>\n#include <vector>\n\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/special_functions/prime.hpp>\n\n#define BOOST_MULTIPRECISION_EXERCISE_THREADING_BACKEND_CPP_DEC_FLOAT 101\n#define BOOST_MULTIPRECISION_EXERCISE_THREADING_BACKEND_GMP_FLOAT 102\n#define BOOST_MULTIPRECISION_EXERCISE_THREADING_BACKEND_CPP_BIN_FLOAT 103\n#define BOOST_MULTIPRECISION_EXERCISE_THREADING_BACKEND_MPFR_FLOAT 104\n\n#if !defined(BOOST_MULTIPRECISION_EXERCISE_THREADING_BACKEND_TYPE)\n#define BOOST_MULTIPRECISION_EXERCISE_THREADING_BACKEND_TYPE \\\n    BOOST_MULTIPRECISION_EXERCISE_THREADING_BACKEND_CPP_DEC_FLOAT\n//#define BOOST_MULTIPRECISION_EXERCISE_THREADING_BACKEND_TYPE\n//BOOST_MULTIPRECISION_EXERCISE_THREADING_BACKEND_CPP_BIN_FLOAT #define\n//BOOST_MULTIPRECISION_EXERCISE_THREADING_BACKEND_TYPE BOOST_MULTIPRECISION_EXERCISE_THREADING_BACKEND_GMP_FLOAT #define\n//BOOST_MULTIPRECISION_EXERCISE_THREADING_BACKEND_TYPE BOOST_MULTIPRECISION_EXERCISE_THREADING_BACKEND_MPFR_FLOAT\n#endif\n\n#if (BOOST_MULTIPRECISION_EXERCISE_THREADING_BACKEND_TYPE == \\\n     BOOST_MULTIPRECISION_EXERCISE_THREADING_BACKEND_CPP_DEC_FLOAT)\n#include <nil/crypto3/multiprecision/cpp_dec_float.hpp>\n\nusing big_float_type = nil::crypto3::multiprecision::number<nil::crypto3::multiprecision::cpp_dec_float<501>,\n                                                            nil::crypto3::multiprecision::et_off>;\n\n#elif (BOOST_MULTIPRECISION_EXERCISE_THREADING_BACKEND_TYPE == \\\n       BOOST_MULTIPRECISION_EXERCISE_THREADING_BACKEND_CPP_BIN_FLOAT)\n#include <nil/crypto3/multiprecision/cpp_bin_float.hpp>\n\nusing big_float_type = nil::crypto3::multiprecision::number<nil::crypto3::multiprecision::cpp_bin_float<501>,\n                                                            nil::crypto3::multiprecision::et_off>;\n\n#elif (BOOST_MULTIPRECISION_EXERCISE_THREADING_BACKEND_TYPE == \\\n       BOOST_MULTIPRECISION_EXERCISE_THREADING_BACKEND_GMP_FLOAT)\n#include <nil/crypto3/multiprecision/gmp.hpp>\n\nusing big_float_type = nil::crypto3::multiprecision::number<nil::crypto3::multiprecision::gmp_float<501>,\n                                                            nil::crypto3::multiprecision::et_off>;\n\n#elif (BOOST_MULTIPRECISION_EXERCISE_THREADING_BACKEND_TYPE == \\\n       BOOST_MULTIPRECISION_EXERCISE_THREADING_BACKEND_MPFR_FLOAT)\n#include <nil/crypto3/multiprecision/mpfr.hpp>\n\nusing big_float_type = nil::crypto3::multiprecision::number<nil::crypto3::multiprecision::mpfr_float_backend<501>,\n                                                            nil::crypto3::multiprecision::et_off>;\n\n#else\n#error BOOST_MULTIPRECISION_EXERCISE_THREADING_BACKEND_TYPE is undefined.\n#endif\n\nnamespace boost {\n    namespace multiprecision {\n        namespace exercise_threading {\n\n            namespace detail {\n\n                namespace my_concurrency {\n                    template<typename index_type, typename callable_function_type>\n                    void parallel_for(index_type start, index_type end, callable_function_type parallel_function) {\n                        // Estimate the number of threads available.\n                        static const unsigned int number_of_threads_hint = std::thread::hardware_concurrency();\n\n                        static const unsigned int number_of_threads_total =\n                            ((number_of_threads_hint == 0U) ? 4U : number_of_threads_hint);\n\n                        // Use only 3/4 of the available cores.\n                        static const unsigned int number_of_threads =\n                            number_of_threads_total - (number_of_threads_total / 8U);\n\n                        std::cout << \"Executing with \" << number_of_threads << \" threads\" << std::endl;\n\n                        // Set the size of a slice for the range functions.\n                        index_type n = index_type(end - start) + index_type(1);\n\n                        index_type slice =\n                            static_cast<index_type>(std::round(n / static_cast<float>(number_of_threads)));\n\n                        slice = (std::max)(slice, index_type(1));\n\n                        // Inner loop.\n                        auto launch_range = [&parallel_function](index_type index_lo, index_type index_hi) {\n                            for (index_type i = index_lo; i < index_hi; ++i) {\n                                parallel_function(i);\n                            }\n                        };\n\n                        // Create the thread pool and launch the jobs.\n                        std::vector<std::thread> pool;\n\n                        pool.reserve(number_of_threads);\n\n                        index_type i1 = start;\n                        index_type i2 = (std::min)(index_type(start + slice), end);\n\n                        for (index_type i = 0U; ((index_type(i + index_type(1U)) < number_of_threads) && (i1 < end));\n                             ++i) {\n                            pool.emplace_back(launch_range, i1, i2);\n\n                            i1 = i2;\n\n                            i2 = (std::min)(index_type(i2 + slice), end);\n                        }\n\n                        if (i1 < end) {\n                            pool.emplace_back(launch_range, i1, end);\n                        }\n\n                        // Wait for the jobs to finish.\n                        for (std::thread& thread_in_pool : pool) {\n                            if (thread_in_pool.joinable()) {\n                                thread_in_pool.join();\n                            }\n                        }\n                    }\n                }    // namespace my_concurrency\n\n                template<typename FloatingPointType, typename UnsignedIntegralType>\n                FloatingPointType pown(const FloatingPointType& b, const UnsignedIntegralType& p) {\n                    // Calculate (b ^ p).\n\n                    using local_floating_point_type = FloatingPointType;\n                    using local_unsigned_integral_type = UnsignedIntegralType;\n\n                    local_floating_point_type result;\n\n                    if (p == local_unsigned_integral_type(0U)) {\n                        result = local_floating_point_type(1U);\n                    } else if (p == local_unsigned_integral_type(1U)) {\n                        result = b;\n                    } else if (p == local_unsigned_integral_type(2U)) {\n                        result = b;\n                        result *= b;\n                    } else {\n                        result = local_floating_point_type(1U);\n\n                        local_floating_point_type y(b);\n\n                        for (local_unsigned_integral_type p_local(p); p_local != local_unsigned_integral_type(0U);\n                             p_local >>= 1U) {\n                            if ((static_cast<unsigned>(p_local) & 1U) != 0U) {\n                                result *= y;\n                            }\n\n                            y *= y;\n                        }\n                    }\n\n                    return result;\n                }\n\n                const std::vector<std::uint32_t>& primes() {\n                    static const std::vector<std::uint32_t> my_primes = []() -> std::vector<std::uint32_t> {\n                        std::vector<std::uint32_t> local_primes(10000U);\n\n                        // Get exactly 10,000 primes.\n                        for (auto i = 0U; i < local_primes.size(); ++i) {\n                            local_primes[i] = boost::math::prime(i);\n                        }\n\n                        return local_primes;\n                    }();\n\n                    return my_primes;\n                }\n\n            }    // namespace detail\n\n            template<typename FloatingPointType>\n            FloatingPointType log(const FloatingPointType& x) {\n                // Use an AGM method to compute the logarithm of x.\n\n                // For values less than 1 invert the argument and\n                // remember (in this case) to negate the result below.\n                const bool b_negate = (x < 1);\n\n                const FloatingPointType xx = ((b_negate == false) ? x : 1 / x);\n\n                // Set a0 = 1\n                // Set b0 = 4 / (x * 2^m) = 1 / (x * 2^(m - 2))\n\n                FloatingPointType ak(1U);\n\n                const float n_times_factor =\n                    static_cast<float>(static_cast<float>(std::numeric_limits<FloatingPointType>::digits10) * 1.67F);\n                const float lgx_over_lg2 = std::log(static_cast<float>(xx)) / std::log(2.0F);\n\n                std::int32_t m = static_cast<std::int32_t>(n_times_factor - lgx_over_lg2);\n\n                // Ensure that the resulting power is non-negative.\n                // Also enforce that m >= 8.\n                m = (std::max)(m, static_cast<std::int32_t>(8));\n\n                FloatingPointType bk = detail::pown(FloatingPointType(2), static_cast<std::uint32_t>(m));\n\n                bk *= xx;\n                bk = 4 / bk;\n\n                FloatingPointType ak_tmp(0U);\n\n                using std::sqrt;\n\n                // Determine the requested precision of the upcoming iteration in units of digits10.\n                const FloatingPointType target_tolerance =\n                    sqrt(std::numeric_limits<FloatingPointType>::epsilon()) / 100;\n\n                for (std::int32_t k = static_cast<std::int32_t>(0); k < static_cast<std::int32_t>(64); ++k) {\n                    using std::fabs;\n\n                    // Check for the number of significant digits to be\n                    // at least half of the requested digits. If at least\n                    // half of the requested digits have been achieved,\n                    // then break after the upcoming iteration.\n                    const bool break_after_this_iteration =\n                        ((k > static_cast<std::int32_t>(4)) && (fabs(1 - fabs(ak / bk)) < target_tolerance));\n\n                    ak_tmp = ak;\n                    ak += bk;\n                    ak /= 2;\n\n                    if (break_after_this_iteration) {\n                        break;\n                    }\n\n                    bk *= ak_tmp;\n                    bk = sqrt(bk);\n                }\n\n                // We are now finished with the AGM iteration for log(x).\n\n                // Compute log(x) = {pi / [2 * AGM(1, 4 / 2^m)]} - (m * ln2)\n                // Note at this time that (ak = bk) = AGM(...)\n\n                // Retrieve the value of pi, divide by (2 * a) and subtract (m * ln2).\n                const FloatingPointType result = boost::math::constants::pi<FloatingPointType>() / (ak * 2) -\n                                                 (boost::math::constants::ln_two<FloatingPointType>() * m);\n\n                return ((b_negate == true) ? -result : result);\n            }\n\n        }    // namespace exercise_threading\n    }        // namespace multiprecision\n}    // namespace boost\n\ntemplate<typename FloatingPointType>\nbool log_agm_concurrent(float& calculation_time) {\n    const std::size_t count = nil::crypto3::multiprecision::exercise_threading::detail::primes().size();\n\n    std::vector<FloatingPointType> log_results(count);\n    std::vector<FloatingPointType> log_control(count);\n\n    std::atomic_flag log_agm_lock = ATOMIC_FLAG_INIT;\n\n    std::size_t concurrent_log_agm_count = 0U;\n\n    const std::clock_t start = std::clock();\n\n    nil::crypto3::multiprecision::exercise_threading::detail::my_concurrency::parallel_for(\n        std::size_t(0U),\n        log_results.size(),\n        [&log_results, &log_control, &concurrent_log_agm_count, &log_agm_lock](std::size_t i) {\n            while (log_agm_lock.test_and_set()) {\n                ;\n            }\n            ++concurrent_log_agm_count;\n            if ((concurrent_log_agm_count % 100U) == 0U) {\n                std::cout << \"log agm concurrent at index \" << concurrent_log_agm_count << \" of \" << log_results.size()\n                          << \". Total processed so far: \" << std::fixed << std::setprecision(1)\n                          << (100.0F * float(concurrent_log_agm_count)) / float(log_results.size()) << \"%.\"\n                          << \"\\r\";\n            }\n            log_agm_lock.clear();\n\n            const FloatingPointType dx =\n                (FloatingPointType(1U) / (nil::crypto3::multiprecision::exercise_threading::detail::primes()[i]));\n            const FloatingPointType x = boost::math::constants::catalan<FloatingPointType>() + dx;\n\n            const FloatingPointType lr = nil::crypto3::multiprecision::exercise_threading::log(x);\n            const FloatingPointType lc = nil::crypto3::multiprecision::log(x);\n\n            log_results[i] = lr;\n            log_control[i] = lc;\n        });\n\n    calculation_time = static_cast<float>(std::clock() - start) / static_cast<float>(CLOCKS_PER_SEC);\n\n    std::cout << std::endl;\n\n    std::cout << \"Checking results concurrent: \";\n\n    bool result_is_ok = true;\n\n    for (std::size_t i = 0U; i < log_results.size(); ++i) {\n        using std::fabs;\n\n        const FloatingPointType close_fraction = fabs(1 - (log_results[i] / log_control[i]));\n\n        result_is_ok &= (close_fraction < std::numeric_limits<FloatingPointType>::epsilon() * 1000000U);\n    }\n\n    std::cout << std::boolalpha << result_is_ok << std::endl;\n\n    return result_is_ok;\n}\n\ntemplate<typename FloatingPointType>\nbool log_agm_sequential(float& calculation_time) {\n    const std::size_t count = nil::crypto3::multiprecision::exercise_threading::detail::primes().size();\n\n    std::vector<FloatingPointType> log_results(count);\n    std::vector<FloatingPointType> log_control(count);\n\n    std::atomic_flag log_agm_lock = ATOMIC_FLAG_INIT;\n\n    const std::clock_t start = std::clock();\n\n    for (std::size_t i = 0U; i < log_results.size(); ++i) {\n        const std::size_t sequential_log_agm_count = i + 1U;\n\n        if ((sequential_log_agm_count % 100U) == 0U) {\n            std::cout << \"log agm sequential at index \" << sequential_log_agm_count << \" of \" << log_results.size()\n                      << \". Total processed so far: \" << std::fixed << std::setprecision(1)\n                      << (100.0F * float(sequential_log_agm_count)) / float(log_results.size()) << \"%.\"\n                      << \"\\r\";\n        }\n\n        const FloatingPointType dx =\n            (FloatingPointType(1U) / (nil::crypto3::multiprecision::exercise_threading::detail::primes()[i]));\n        const FloatingPointType x = boost::math::constants::catalan<FloatingPointType>() + dx;\n\n        log_results[i] = nil::crypto3::multiprecision::exercise_threading::log(x);\n        log_control[i] = nil::crypto3::multiprecision::log(x);\n    }\n\n    calculation_time = static_cast<float>(std::clock() - start) / static_cast<float>(CLOCKS_PER_SEC);\n\n    std::cout << std::endl;\n\n    std::cout << \"Checking results sequential: \";\n\n    bool result_is_ok = true;\n\n    for (std::size_t i = 0U; i < log_results.size(); ++i) {\n        using std::fabs;\n\n        const FloatingPointType close_fraction = fabs(1 - (log_results[i] / log_control[i]));\n\n        result_is_ok &= (close_fraction < std::numeric_limits<FloatingPointType>::epsilon() * 1000000U);\n    }\n\n    std::cout << std::boolalpha << result_is_ok << std::endl;\n\n    return result_is_ok;\n}\n\nint main() {\n    std::cout << \"Calculating \" << nil::crypto3::multiprecision::exercise_threading::detail::primes().size()\n              << \" primes\" << std::endl;\n\n    float calculation_time_concurrent;\n    const bool result_is_ok_concurrent = log_agm_concurrent<big_float_type>(calculation_time_concurrent);\n\n    float calculation_time_sequential;\n    const bool result_is_ok_sequential = log_agm_sequential<big_float_type>(calculation_time_sequential);\n\n    std::cout << std::endl;\n\n    std::cout << \"result_is_ok_concurrent: \" << std::boolalpha << result_is_ok_concurrent\n              << \", calculation_time_concurrent: \" << std::fixed << std::setprecision(1) << calculation_time_concurrent\n              << \"s\" << std::endl;\n\n    std::cout << \"result_is_ok_sequential: \" << std::boolalpha << result_is_ok_sequential\n              << \", calculation_time_sequential: \" << std::fixed << std::setprecision(1) << calculation_time_sequential\n              << \"s\" << std::endl;\n}\n", "meta": {"hexsha": "28c85bc855d23739e8c530df26f76c7e22afdd21", "size": 18136, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "snark-logic/libs-source/multiprecision/example/exercise_threading_log_agm.cpp", "max_stars_repo_name": "podlodkin/podlodkin-freeton-year-control", "max_stars_repo_head_hexsha": "e394c11f2414804d2fbde93a092ae589d4359739", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-14T18:09:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-14T18:09:38.000Z", "max_issues_repo_path": "snark-logic/libs-source/multiprecision/example/exercise_threading_log_agm.cpp", "max_issues_repo_name": "podlodkin/podlodkin-freeton-year-control", "max_issues_repo_head_hexsha": "e394c11f2414804d2fbde93a092ae589d4359739", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "snark-logic/libs-source/multiprecision/example/exercise_threading_log_agm.cpp", "max_forks_repo_name": "podlodkin/podlodkin-freeton-year-control", "max_forks_repo_head_hexsha": "e394c11f2414804d2fbde93a092ae589d4359739", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-31T06:27:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-31T06:27:19.000Z", "avg_line_length": 42.4730679157, "max_line_length": 120, "alphanum_fraction": 0.5917512131, "num_tokens": 4001, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632936392131, "lm_q2_score": 0.8723473630627234, "lm_q1q2_score": 0.8089829238073296}}
{"text": "#include <iostream>\r\n#include <Eigen/Dense>\r\n\r\nusing namespace Eigen;\r\nusing namespace std;\r\nint main()\r\n{\r\n  Vector3d v(1,2,3);\r\n  Vector3d w(0,1,2);\r\n\r\n  cout << \"Dot product: \" << v.dot(w) << endl;\r\n  double dp = v.adjoint()*w; // automatic conversion of the inner product to a scalar\r\n  cout << \"Dot product via a matrix product: \" << dp << endl;\r\n  cout << \"Cross product:\\n\" << v.cross(w) << endl;\r\n}\r\n", "meta": {"hexsha": "bd47108b459452a050e827576bd0bf374a6aa5a9", "size": 408, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/eigen-eigen-323c052e1731/doc/examples/tut_arithmetic_dot_cross.cpp", "max_stars_repo_name": "k4rth33k/dnnc-operators", "max_stars_repo_head_hexsha": "a7fe3f1240c12b3438558def71fbfcd4520446c3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-08-16T14:35:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-11T23:59:22.000Z", "max_issues_repo_path": "packages/eigen-eigen-323c052e1731/doc/examples/tut_arithmetic_dot_cross.cpp", "max_issues_repo_name": "k4rth33k/dnnc-operators", "max_issues_repo_head_hexsha": "a7fe3f1240c12b3438558def71fbfcd4520446c3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-08-12T04:38:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T16:32:13.000Z", "max_forks_repo_path": "packages/eigen-eigen-323c052e1731/doc/examples/tut_arithmetic_dot_cross.cpp", "max_forks_repo_name": "k4rth33k/dnnc-operators", "max_forks_repo_head_hexsha": "a7fe3f1240c12b3438558def71fbfcd4520446c3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-08-15T13:29:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-09T17:08:04.000Z", "avg_line_length": 25.5, "max_line_length": 86, "alphanum_fraction": 0.6102941176, "num_tokens": 118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582632076909, "lm_q2_score": 0.8688267745399465, "lm_q1q2_score": 0.8084070516667786}}
{"text": "#include <Eigen/Dense>\n\n#include <iostream>\n#include <vector>\n\n#include \"timer.h\"\n\n//! \\brief build A*x using array of ranges and of ones.\n//! \\param[in] x vector x for A*x = y\n//! \\param[out] y y = A*x\nvoid multAminSlow(const Eigen::VectorXd & x, Eigen::VectorXd & y) {\n    unsigned int n = x.size();\n    \n    Eigen::VectorXd one = Eigen::VectorXd::Ones(n);\n    Eigen::VectorXd linsp = Eigen::VectorXd::LinSpaced(n,1,n);\n    y = ( (one * linsp.transpose()).cwiseMin(linsp * one.transpose()) ) *x;\n}\n\n//! \\brief build A*x using a simple for loop\n//! \\param[in] x vector x for A*x = y\n//! \\param[out] y y = A*x\nvoid multAminLoops(const Eigen::VectorXd & x, Eigen::VectorXd & y) {\n    unsigned int n = x.size();\n    \n    Eigen::MatrixXd A(n,n);\n    \n    for(unsigned int i = 0; i < n; ++i) {\n        for(unsigned int j = 0; j < n; ++j) {\n            A(i,j) = std::min(i+1,j+1);\n        }\n    }\n    y = A * x;\n}\n\n//! \\brief build A*x using a clever representation\n//! \\param[in] x vector x for A*x = y\n//! \\param[out] y y = A*x\nvoid multAmin(const Eigen::VectorXd & x, Eigen::VectorXd & y) {\n    unsigned int n = x.size();\n    y = Eigen::VectorXd::Zero(n);\n    Eigen::VectorXd v = Eigen::VectorXd::Zero(n);\n    Eigen::VectorXd w = Eigen::VectorXd::Zero(n);\n    \n    v(0) = x(n-1);\n    w(0) = x(0);\n    \n    for(unsigned int j = 1; j < n; ++j) {\n        v(j) = v(j-1) + x(n-j-1);\n        w(j) = w(j-1) + (j+1)*x(j);\n    }\n    for(unsigned int j = 0; j < n-1; ++j) {\n        y(j) = w(j) + v(n-j-2)*(j+1);\n    }\n    y(n-1) = w(n-1);\n}\n\nint main(void) {\n    // Build Matrix B with 10x10 dimensions such that B = inv(A)\n    unsigned int n = 10;\n    Eigen::MatrixXd B = Eigen::MatrixXd::Zero(n,n);\n    for(unsigned int i = 0; i < n; ++i) {\n        B(i,i) = 2;\n        if(i < n-1) B(i+1,i) = -1;\n        if(i > 0) B(i-1,i) = -1;\n    }\n    B(n-1,n-1) = 1;\n    std::cout << \"B = \" << B << std::endl;\n    \n    // Check that B = inv(A) (up to machine precision)\n    Eigen::VectorXd x = Eigen::VectorXd::Random(n), y;\n    multAmin(B*x, y);\n    std::cout << \"|y-x| = \" << (y - x).norm() << std::endl;\n    multAminSlow(B*x, y);\n    std::cout << \"|y-x| = \" << (y - x).norm() << std::endl;\n    multAminLoops(B*x, y);\n    std::cout << \"|y-x| = \" << (y - x).norm() << std::endl;\n    \n    // Timing from 2^4 to 2^13 repeating nruns times\n    timer<> tm_slow, tm_slow_loops, tm_fast;\n    std::vector<int> times_slow, times_slow_loops, times_fast;\n    unsigned int nruns = 10;\n    for(unsigned int p = 4; p <= 13; ++p) {\n        tm_slow.reset();\n        tm_slow_loops.reset();\n        tm_fast.reset();\n        for(unsigned int r = 0; r < nruns; ++r) {\n            x = Eigen::VectorXd::Random(pow(2,p));\n        \n            tm_slow.start();\n            multAminSlow(x, y);\n            tm_slow.stop();\n            \n            tm_slow_loops.start();\n            multAminLoops(x, y);\n            tm_slow_loops.stop();\n            \n            tm_fast.start();\n            multAmin(x, y);\n            tm_fast.stop();\n        }\n        times_slow.push_back( tm_slow.avg().count() );\n        times_slow_loops.push_back( tm_slow_loops.avg().count() );\n        times_fast.push_back( tm_fast.avg().count() );\n    }\n    \n    for(auto it = times_slow.begin(); it != times_slow.end(); ++it) {\n        std::cout << *it << \" \";\n    }\n    std::cout << std::endl;\n    for(auto it = times_slow_loops.begin(); it != times_slow_loops.end(); ++it) {\n        std::cout << *it << \" \";\n    }\n    std::cout << std::endl;\n    for(auto it = times_fast.begin(); it != times_fast.end(); ++it) {\n        std::cout << *it << \" \";\n    }\n    std::cout << std::endl;\n}\n", "meta": {"hexsha": "b7f03df8b519c9e03e14d92038e35775f4b21903", "size": 3613, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/PS1/solutions_ps1/C++/multAmin.cpp", "max_stars_repo_name": "valentinjacot/backupETHZ", "max_stars_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:21:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:21:30.000Z", "max_issues_repo_path": "Nummerical Methods for CSE/PS1/solutions_ps1/C++/multAmin.cpp", "max_issues_repo_name": "valentinjacot/backupETHZ", "max_issues_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Nummerical Methods for CSE/PS1/solutions_ps1/C++/multAmin.cpp", "max_forks_repo_name": "valentinjacot/backupETHZ", "max_forks_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3613445378, "max_line_length": 81, "alphanum_fraction": 0.5095488514, "num_tokens": 1145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802507195635, "lm_q2_score": 0.8791467738423874, "lm_q1q2_score": 0.8074789492580514}}
{"text": "#pragma once\n#include <Eigen/Core>\n#include \"mtao/eigen/shape_checks.hpp\"\n#include <cmath>\n#include <type_traits>\n#include <iostream>\n\n\nnamespace mtao::geometry {\n\n    //The Solid Angle of a Plane Triangle\n    //A. Van Oosterom, J. Strackee\n    // divided by 2*M_PI to make the solid angle from the interior of a closed geometry 1\n    \n\n\n\n\n\n\n\n    //The actual implementations\n    template <typename AType, typename BType, typename CType>\n        auto solid_angle(const Eigen::MatrixBase<AType>& a, const Eigen::MatrixBase<BType>& b, const Eigen::MatrixBase<CType>& c) -> typename AType::Scalar {\n            if(eigen::shape_check<3,1>(a) && eigen::shape_check<3,1>(b) && eigen::shape_check<3,1>(c)) {\n                auto num = a.cross(b).dot(c);\n                auto aN = a.norm();\n                auto bN = b.norm();\n                auto cN = c.norm();\n                return std::atan2<typename AType::Scalar>(num,\n                        aN*bN*cN\n                        + aN * b.dot(c)\n                        + bN * a.dot(c)\n                        + cN * a.dot(b)\n                        ) / (2 * M_PI);\n\n            } else {\n                assert(false);\n                return 0;\n            }\n        }\n    template <typename MType>\n        auto solid_angle(const Eigen::MatrixBase<MType>& M) -> typename MType::Scalar {\n            if(eigen::shape_check<3,3>(M)) {\n                auto num = M.determinant();\n                auto B = M.transpose() * M;\n                auto C = B.diagonal().cwiseSqrt().eval();\n                return std::atan2<typename MType::Scalar>(num,\n                        C.prod() \n                        +C(0) * B(1,2)\n                        +C(1) * B(0,2)\n                        +C(2) * B(0,1)\n                        ) / (2 * M_PI);\n\n            } else {\n                assert(false);\n                return 0;\n            }\n        }\n\n    //NOTE: this is going to be pretty slow for large meshes...\n    template <typename VType, typename FType>\n        auto solid_angle_mesh(const Eigen::MatrixBase<VType>& V, const Eigen::MatrixBase<FType>& F) {\n            static_assert(std::is_integral_v<typename FType::Scalar>);\n            if(eigen::row_check<3>(V) && eigen::row_check<3>(F)) {\n                typename VType::Scalar ret = 0;\n                for(int i = 0; i < F.cols(); ++i) {\n                    auto f = F.col(i);\n                    ret += solid_angle(V.col(f(0)), V.col(f(1)), V.col(f(2)));\n                }\n                return ret;\n            } else {\n                assert(false);\n                return typename VType::Scalar(0);\n            }\n        }\n\n    //Some convenience versions for when passing in a point to check\n    template <typename VType, typename FType, typename PType>\n        auto solid_angle_mesh(const Eigen::MatrixBase<VType>& V, const Eigen::MatrixBase<FType>& F, const Eigen::MatrixBase<PType>& p) {\n            return solid_angle_mesh((V.colwise() - p).eval(), F);\n        }\n\n    template <typename AType, typename BType, typename CType, typename PType>\n        auto solid_angle(const Eigen::MatrixBase<AType>& a, const Eigen::MatrixBase<BType>& b, const Eigen::MatrixBase<CType>& c, const Eigen::MatrixBase<PType>& p) {\n            return solid_angle(a-p,b-p,c-p);\n        }\n\n    template <typename MType, typename PType>\n        auto solid_angle(const Eigen::MatrixBase<MType>& M, const Eigen::MatrixBase<PType>& p) {\n            static_assert(std::is_floating_point_v<typename PType::Scalar>);\n            return solid_angle((M.colwise()-p).eval());\n        }\n}\n", "meta": {"hexsha": "b24ff55d32f223f9f7add9894932ba0f49832427", "size": 3556, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mtao/geometry/solid_angle.hpp", "max_stars_repo_name": "mtao/core", "max_stars_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/mtao/geometry/solid_angle.hpp", "max_issues_repo_name": "mtao/core", "max_issues_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-04-18T16:16:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-18T16:17:36.000Z", "max_forks_repo_path": "include/mtao/geometry/solid_angle.hpp", "max_forks_repo_name": "mtao/core", "max_forks_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.4315789474, "max_line_length": 166, "alphanum_fraction": 0.5202474691, "num_tokens": 866, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660936744719, "lm_q2_score": 0.8459424334245618, "lm_q1q2_score": 0.8070003986875063}}
{"text": "#include <iostream>\n#include <cmath>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include \"sophus/se3.hpp\"\n\nusing namespace std;\nusing namespace Eigen;\n\n/// This program demonstrates the basic usage of sophus\n\nint main(int argc, char **argv) {\n\n  // Rotation matrix rotated 90 degrees along the Z axis\n  Matrix3d R = AngleAxisd(M_PI / 2, Vector3d(0, 0, 1)).toRotationMatrix();\n  // Or quaternion\n  Quaterniond q(R);\n  Sophus::SO3d SO3_R(R); // Sophus::SO(3) can be constructed directly from the rotation matrix\n  Sophus::SO3d SO3_q(q); // can also be constructed from a rotation vector\n  // \u4e8c\u8005\u662f\u7b49\u4ef7\u7684\n  cout << \"SO(3) from matrix:\\n\" << SO3_R.matrix() << endl;\n  cout << \"SO(3) from quaternion:\\n\" << SO3_q.matrix() << endl;\n  cout << \"they are equal\" << endl;\n\n  // Use the logarithmic map to get its Lie algebra\n  Vector3d so3 = SO3_R.log();\n  cout << \"so3 = \" << so3.transpose() << endl;\n  // hat is vector to antisymmetric matrix\n  cout << \"so3 hat=\\n\" << Sophus::SO3d::hat(so3) << endl;\n  // Relative, vee is the objection vector\n  cout << \"so3 hat vee= \" << Sophus::SO3d::vee(Sophus::SO3d::hat(so3)).transpose() << endl;\n\n  // Update of the incremental disturbance model\n  Vector3d update_so3(1e-4, 0, 0); //assuming the update is so much\n  Sophus::SO3d SO3_updated = Sophus::SO3d::exp(update_so3) * SO3_R;\n  cout << \"SO3 updated = \\n\" << SO3_updated.matrix() << endl;\n\n  cout << \"*******************************\" << endl;\n  // The operation of SE(3) is similar\n  Vector3d t(1, 0, 0);           // translate 1 along the X axis\n  Sophus::SE3d SE3_Rt(R, t);           // Construct SE(3) from R, t\n  Sophus::SE3d SE3_qt(q, t);            // Construct SE(3) from q,t\n  cout << \"SE3 from R,t= \\n\" << SE3_Rt.matrix() << endl;\n  cout << \"SE3 from q,t= \\n\" << SE3_qt.matrix() << endl;\n  // The Lie algebra se(3) is a six-dimensional vector, which is convenient for typedef first.\n  typedef Eigen::Matrix<double, 6, 1> Vector6d;\n  Vector6d se3 = SE3_Rt.log();\n  cout << \"se3 = \" << se3.transpose() << endl;\n  //Observe the output, you will find that in Sophus, the translation of se(3) is in front and the rotation is in the back.\n  // Same, there are two operators of hat and vee\n  cout << \"se3 hat = \\n\" << Sophus::SE3d::hat(se3) << endl;\n  cout << \"se3 hat vee = \" << Sophus::SE3d::vee(Sophus::SE3d::hat(se3)).transpose() << endl;\n\n  //  Finally, demonstrate the update\n  Vector6d update_se3; //update volume\n  update_se3.setZero();\n  update_se3(0, 0) = 1e-4;\n  Sophus::SE3d SE3_updated = Sophus::SE3d::exp(update_se3) * SE3_Rt;\n  cout << \"SE3 updated = \" << endl << SE3_updated.matrix() << endl;\n\n  return 0;\n}", "meta": {"hexsha": "e1993f627008dcf703b75daaeea26fe147b47bd1", "size": 2612, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch4/useSophus.cpp", "max_stars_repo_name": "salahkhan94/slambook2", "max_stars_repo_head_hexsha": "9a2f1694268d5dfd3dbabfbcfb1ada858e62ed33", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-28T18:05:53.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-28T18:05:53.000Z", "max_issues_repo_path": "ch4/useSophus.cpp", "max_issues_repo_name": "salahkhan94/slambook2", "max_issues_repo_head_hexsha": "9a2f1694268d5dfd3dbabfbcfb1ada858e62ed33", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch4/useSophus.cpp", "max_forks_repo_name": "salahkhan94/slambook2", "max_forks_repo_head_hexsha": "9a2f1694268d5dfd3dbabfbcfb1ada858e62ed33", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.1290322581, "max_line_length": 123, "alphanum_fraction": 0.6397396631, "num_tokens": 861, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947117065458, "lm_q2_score": 0.8539127603871312, "lm_q1q2_score": 0.8069430428245777}}
{"text": "/*\n * Copyright Nick Thompson, 2019\n * Use, modification and distribution are subject to the\n * Boost Software License, Version 1.0. (See accompanying file\n * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#include \"math_unit_test.hpp\"\n#include <vector>\n#include <random>\n#include <boost/math/statistics/linear_regression.hpp>\n\nusing boost::math::statistics::simple_ordinary_least_squares;\nusing boost::math::statistics::simple_ordinary_least_squares_with_R_squared;\n\ntemplate<typename Real>\nvoid test_line()\n{\n    std::vector<Real> x(128);\n    std::vector<Real> y(128);\n    Real expected_c0 = 7;\n    Real expected_c1 = 12;\n    for (size_t i = 0; i < x.size(); ++i) {\n        x[i] = i;\n        y[i] = expected_c0 + expected_c1*x[i];\n    }\n\n    auto [computed_c0, computed_c1] = simple_ordinary_least_squares(x, y);\n\n    CHECK_ULP_CLOSE(expected_c0, computed_c0, 0);\n    CHECK_ULP_CLOSE(expected_c1, computed_c1, 0);\n\n    auto [computed_c0_R, computed_c1_R, Rsquared] = simple_ordinary_least_squares_with_R_squared(x, y);\n\n    Real expected_Rsquared = 1;\n    CHECK_ULP_CLOSE(expected_c0, computed_c0, 0);\n    CHECK_ULP_CLOSE(expected_c1, computed_c1, 0);\n    CHECK_ULP_CLOSE(expected_Rsquared, Rsquared, 0);\n\n}\n\ntemplate<typename Real>\nvoid test_constant()\n{\n    std::vector<Real> x(128);\n    std::vector<Real> y(128);\n    Real expected_c0 = 7;\n    Real expected_c1 = 0;\n    for (size_t i = 0; i < x.size(); ++i) {\n        x[i] = i;\n        y[i] = expected_c0 + expected_c1*x[i];\n    }\n\n    auto [computed_c0, computed_c1] = simple_ordinary_least_squares(x, y);\n\n    CHECK_ULP_CLOSE(expected_c0, computed_c0, 0);\n    CHECK_ULP_CLOSE(expected_c1, computed_c1, 0);\n\n    auto [computed_c0_R, computed_c1_R, Rsquared] = simple_ordinary_least_squares_with_R_squared(x, y);\n\n    Real expected_Rsquared = 1;\n    CHECK_ULP_CLOSE(expected_c0, computed_c0, 0);\n    CHECK_ULP_CLOSE(expected_c1, computed_c1, 0);\n    CHECK_ULP_CLOSE(expected_Rsquared, Rsquared, 0);\n\n}\n\ntemplate<typename Real>\nvoid test_permutation_invariance()\n{\n    std::vector<Real> x(256);\n    std::vector<Real> y(256);\n    std::mt19937_64 gen{123456};\n    std::normal_distribution<Real> dis(0, 0.1);\n\n    Real expected_c0 = -7.2;\n    Real expected_c1 = -13.5;\n\n    x[0] = 0;\n    y[0] = expected_c0 + dis(gen);\n    for(size_t i = 1; i < x.size(); ++i) {\n        Real t = dis(gen);\n        x[i] = x[i-1] + t*t;\n        y[i] = expected_c0 + expected_c1*x[i] + dis(gen);\n    }\n\n    auto [c0, c1, Rsquared] = simple_ordinary_least_squares_with_R_squared(x, y);\n    CHECK_MOLLIFIED_CLOSE(expected_c0, c0, 0.002);\n    CHECK_MOLLIFIED_CLOSE(expected_c1, c1, 0.002);\n\n    int j = 0;\n    std::mt19937_64 gen1{12345};\n    std::mt19937_64 gen2{12345};\n    while(j++ < 10) {\n        std::shuffle(x.begin(), x.end(), gen1);\n        std::shuffle(y.begin(), y.end(), gen2);\n        auto [c0_, c1_, Rsquared_] = simple_ordinary_least_squares_with_R_squared(x, y);\n\n        CHECK_ULP_CLOSE(c0, c0_, 100);\n        CHECK_ULP_CLOSE(c1, c1_, 100);\n        CHECK_ULP_CLOSE(Rsquared, Rsquared_, 65);\n    }\n}\n\ntemplate<typename Real>\nvoid test_scaling_relations()\n{\n    std::vector<Real> x(256);\n    std::vector<Real> y(256);\n    std::mt19937_64 gen{123456};\n    std::normal_distribution<Real> dis(0, 0.1);\n\n    Real expected_c0 = 3.2;\n    Real expected_c1 = -13.5;\n\n    x[0] = 0;\n    y[0] = expected_c0 + dis(gen);\n    for(size_t i = 1; i < x.size(); ++i) {\n        Real t = dis(gen);\n        x[i] = x[i-1] + t*t;\n        y[i] = expected_c0 + expected_c1*x[i] + dis(gen);\n    }\n\n    auto [c0, c1, Rsquared] = simple_ordinary_least_squares_with_R_squared(x, y);\n    CHECK_MOLLIFIED_CLOSE(expected_c0, c0, 0.005);\n    CHECK_MOLLIFIED_CLOSE(expected_c1, c1, 0.005);\n\n    // If y -> lambda y, then c0 -> lambda c0 and c1 -> lambda c1.\n    Real lambda = 6;\n\n    for (auto& s : y) {\n        s *= lambda;\n    }\n\n    auto [c0_lambda, c1_lambda, Rsquared_lambda] = simple_ordinary_least_squares_with_R_squared(x, y);\n\n    CHECK_ULP_CLOSE(lambda*c0, c0_lambda, 30);\n    CHECK_ULP_CLOSE(lambda*c1, c1_lambda, 30);\n    CHECK_ULP_CLOSE(Rsquared, Rsquared_lambda, 3);\n\n    // If x -> lambda x, then c0 -> c0 and c1 -> c1/lambda\n    for (auto& s : x) {\n        s *= lambda;\n    }\n    // Put y back into it's original state:\n    for (auto& s : y) {\n        s /= lambda;\n    }\n    auto [c0_, c1_, Rsquared_] = simple_ordinary_least_squares_with_R_squared(x, y);\n\n    CHECK_ULP_CLOSE(c0, c0_, 50);\n    CHECK_ULP_CLOSE(c1, c1_*lambda, 50);\n    CHECK_ULP_CLOSE(Rsquared, Rsquared_, 50);\n\n}\n\n\nint main()\n{\n    test_line<float>();\n    test_line<double>();\n    test_line<long double>();\n\n    test_constant<float>();\n    test_constant<double>();\n    test_constant<long double>();\n\n    test_permutation_invariance<float>();\n    test_permutation_invariance<double>();\n    test_permutation_invariance<long double>();\n\n    test_scaling_relations<float>();\n    test_scaling_relations<double>();\n    test_scaling_relations<long double>();\n    return boost::math::test::report_errors();\n}\n", "meta": {"hexsha": "fb5bc6473cc3ecad4f8915153e8b8f493d1bf097", "size": 5016, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/math/test/linear_regression_test.cpp", "max_stars_repo_name": "uosorio/heroku_face", "max_stars_repo_head_hexsha": "7d6465e71dba17a15d8edaef520adb2fcd09d91e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-04-28T15:15:28.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-28T15:15:28.000Z", "max_issues_repo_path": "3rdparty/boost_1_73_0/libs/math/test/linear_regression_test.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-05-23T08:01:11.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-06T20:49:05.000Z", "max_forks_repo_path": "3rdparty/boost_1_73_0/libs/math/test/linear_regression_test.cpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T14:12:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-22T19:20:54.000Z", "avg_line_length": 28.3389830508, "max_line_length": 103, "alphanum_fraction": 0.6527113238, "num_tokens": 1537, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545392102523, "lm_q2_score": 0.8499711699569787, "lm_q1q2_score": 0.8059040229925583}}
{"text": "// Copyright Christopher Kormanyos 2013.\n// Copyright Paul A. Bristow 2013.\n// Copyright John Maddock 2013.\n\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or\n// copy at http://www.boost.org/LICENSE_1_0.txt).\n\n#ifdef _MSC_VER\n#  pragma warning (disable : 4512) // assignment operator could not be generated.\n#  pragma warning (disable : 4996) // assignment operator could not be generated.\n#endif\n\n#include <iostream>\n#include <limits>\n#include <vector>\n#include <algorithm>\n#include <iomanip>\n#include <iterator>\n\n//[bessel_zeros_iterator_example_1\n\n/*`[h5 Using Output Iterator to sum zeros of Bessel Functions]\n\nThis example demonstrates summing zeros of the Bessel functions.\nTo use the functions for finding zeros of the functions we need\n */\n\n#include <boost/math/special_functions/bessel.hpp>\n\n/*`We use the `cyl_bessel_j_zero` output iterator parameter `out_it`\nto create a sum of ['1/zeros[super 2]] by defining a custom output iterator:\n*/\n\ntemplate <class T>\nstruct output_summation_iterator\n{\n   output_summation_iterator(T* p) : p_sum(p)\n   {}\n   output_summation_iterator& operator*()\n   { return *this; }\n    output_summation_iterator& operator++()\n   { return *this; }\n   output_summation_iterator& operator++(int)\n   { return *this; }\n   output_summation_iterator& operator = (T const& val)\n   {\n     *p_sum += 1./ (val * val); // Summing 1/zero^2.\n     return *this;\n   }\nprivate:\n   T* p_sum;\n};\n\n//] [/bessel_zeros_iterator_example_1]\n\nint main()\n{\n  try\n  {\n//[bessel_zeros_iterator_example_2\n\n/*`The sum is calculated for many values, converging on the analytical exact value of `1/8`.\n*/\n    using boost::math::cyl_bessel_j_zero;\n    double nu = 1.;\n    double sum = 0;\n    output_summation_iterator<double> it(&sum);  // sum of 1/zeros^2\n    cyl_bessel_j_zero(nu, 1, 10000, it);\n\n    double s = 1/(4 * (nu + 1)); // 0.125 = 1/8 is exact analytical solution.\n    std::cout << std::setprecision(6) << \"nu = \" << nu << \", sum = \" << sum\n      << \", exact = \" << s << std::endl;\n    // nu = 1.00000, sum = 0.124990, exact = 0.125000\n//] [/bessel_zeros_iterator_example_2]\n   }\n  catch (std::exception const& ex)\n  {\n    std::cout << \"Thrown exception \" << ex.what() << std::endl;\n  }\n  return 0;\n  } // int_main()\n\n/*\n Output:\n\n nu = 1, sum = 0.12499, exact = 0.125\n*/\n", "meta": {"hexsha": "a92a2704acbcd36d3be24e7bec227d8db0e5a6ff", "size": 2346, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/math/example/bessel_zeros_interator_example.cpp", "max_stars_repo_name": "rajeev02101987/arangodb", "max_stars_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "3rdParty/boost/1.71.0/libs/math/example/bessel_zeros_interator_example.cpp", "max_issues_repo_name": "rajeev02101987/arangodb", "max_issues_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "3rdParty/boost/1.71.0/libs/math/example/bessel_zeros_interator_example.cpp", "max_forks_repo_name": "rajeev02101987/arangodb", "max_forks_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 26.3595505618, "max_line_length": 92, "alphanum_fraction": 0.6747655584, "num_tokens": 683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898229217591, "lm_q2_score": 0.8887587920192298, "lm_q1q2_score": 0.8052064206016586}}
{"text": "#include <Eigen/Dense>\n#include <Eigen/IterativeLinearSolvers>\n\n#include <algorithm>\n#include <iostream>\n#include <random>\n#include <vector>\n\nstd::pair<Eigen::MatrixXf, Eigen::MatrixXf> GenerateData(size_t n) {\n  std::vector<float> x_data(n);\n  std::iota(x_data.begin(), x_data.end(), 0);\n  std::vector<float> y_data(n);\n  std::iota(y_data.begin(), y_data.end(), 0);\n\n  // mutate data\n  std::random_device rd;\n  std::mt19937 re(rd());\n  std::uniform_real_distribution<float> dist(-1.5f, 1.5f);\n\n  for (auto& x : x_data) {\n    x += dist(re);  // add noise\n  }\n\n  for (auto& y : y_data) {\n    y += dist(re);  // add noise\n  }\n\n  // Make result\n  Eigen::Map<Eigen::MatrixXf> x(x_data.data(), static_cast<Eigen::Index>(n), 1);\n  Eigen::Map<Eigen::MatrixXf> y(y_data.data(), static_cast<Eigen::Index>(n), 1);\n\n  return {x, y};\n}\n\nint main() {\n  size_t n = 1000;\n  // generate training data\n  Eigen::MatrixXf x1, y;\n  std::tie(x1, y) = GenerateData(n);\n  Eigen::MatrixXf x0 = Eigen::MatrixXf::Ones(n, 1);\n  // setup line coeficients y = b(4) + k(0.3)*x\n  y.array() *= 0.3f;\n  y.array() += 4.f;\n  Eigen::MatrixXf x(n, 2);\n  x << x0, x1;\n\n  // train estimator\n  Eigen::LeastSquaresConjugateGradient<Eigen::MatrixXf> gd;\n  gd.setMaxIterations(100);\n  gd.setTolerance(0.001f);\n  gd.compute(x);\n  Eigen::VectorXf b = gd.solve(y);\n  std::cout << \"Estimated parameters vector : \" << b << std::endl;\n\n  // normal equations\n  Eigen::VectorXf b_norm = (x.transpose() * x).ldlt().solve(x.transpose() * y);\n  std::cout << \"Estimated with normal equation parameters vector : \" << b_norm\n            << std::endl;\n\n  // predict\n  Eigen::MatrixXf new_x(5, 2);\n  new_x << 1, 1, 1, 2, 1, 3, 1, 4, 1, 5;\n  auto new_y = new_x.array().rowwise() * b.transpose().array();\n  std::cout << \"Predicted values : \\n\" << new_y << std::endl;\n\n  auto new_y_norm = new_x.array().rowwise() * b_norm.transpose().array();\n  std::cout << \"Predicted(norm) values : \\n\" << new_y_norm << std::endl;\n\n  return 0;\n};\n", "meta": {"hexsha": "72911c71897fd00b380a5bba164fc7e209b13f27", "size": 1970, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Chapter01/eigen_samples/linreg_eigen.cc", "max_stars_repo_name": "bdonkey/Hands-On-Machine-Learning-with-CPP", "max_stars_repo_head_hexsha": "d2b17abeb48db3d45369fdb1be806682ab9819ed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 201.0, "max_stars_repo_stars_event_min_datetime": "2020-05-13T12:50:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T20:56:11.000Z", "max_issues_repo_path": "Chapter01/eigen_samples/linreg_eigen.cc", "max_issues_repo_name": "bdonkey/Hands-On-Machine-Learning-with-CPP", "max_issues_repo_head_hexsha": "d2b17abeb48db3d45369fdb1be806682ab9819ed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-12T10:01:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-14T19:35:05.000Z", "max_forks_repo_path": "Chapter01/eigen_samples/linreg_eigen.cc", "max_forks_repo_name": "bdonkey/Hands-On-Machine-Learning-with-CPP", "max_forks_repo_head_hexsha": "d2b17abeb48db3d45369fdb1be806682ab9819ed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 63.0, "max_forks_repo_forks_event_min_datetime": "2020-06-05T15:03:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T02:07:09.000Z", "avg_line_length": 27.7464788732, "max_line_length": 80, "alphanum_fraction": 0.6228426396, "num_tokens": 667, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147438, "lm_q2_score": 0.8824278649085117, "lm_q1q2_score": 0.8051590887526916}}
{"text": "/** \\file matrix_utils.hpp\n*  \\brief Miscellaneous math functions\n*\n*  Miscellaneous math functions used in FDCL are defined here\n*/\n\n#ifndef FDCL_MATRIX_UTILS_HPP\n#define FDCL_MATRIX_UTILS_HPP\n\n#include <iostream>\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n\n#include \"fdcl/common_types.hpp\"\n\nnamespace fdcl\n{\n\n/** \\fn Matrix3 hat(const Vector3 v)\n* Returns the hat map of a given 3x1 vector. This is the inverse of vee map.\n* @param v vector which the hat map is needed to be operated on\n* @return hat map of the input vector\n*/\nMatrix3 hat(const Vector3 v);\n\n\n/** \\fn Vector3 vee(const Matrix3 V)\n* Returns the vee map of a given 3x3 matrix. This is the inverse of hat map.\n* @param V matrix which the vee map is needed to be operated on\n* @return vee map of the input matrix\n*/\nVector3 vee(const Matrix3 V);\n\n\n/** \\fn double sinx_over_x(const double x)\n * Calculates and returns the value of sin(x)/x, dealing with the case where\n * x = 0.\n * @param  x input value\n * @return   the value of sin(x)/x\n */\ndouble sinx_over_x(const double x);\n\n\n/** \\fn Matrix3 expm_SO3(const Vector3 r)\n * Calculates and returns the rotation matrix in SO(3) from rotation vector.\n * This is the inverse of logm_som3.\n * @param  r rotation vector (angle * axis)\n * @return   rotation matrix in SO(3) which corresponds to the input vector\n */\nMatrix3 expm_SO3(const Vector3 r);\n\n\n/** \\fn Vector3 logm_SO3(const Matrix3 R)\n * Calculates and returns the rotation vector from rotation matrix in SO(3).\n * This is the inverse of expm_SO3.\n * @param  R rotation matrix in SO(3)\n * @return rotation vector (angle * axis)\n */\nVector3 logm_SO3(const Matrix3 R);\n\n\n/** \\fn bool assert_SO3(Matrix3 R,const char *R_name)\n * Check and returns if a given matrix is in SO(3)\n * @param  R      rotation matrix\n * @param  R_name name of the rotation matrix\n * @return        true if the input matrix is true, false otherwise\n */\nbool assert_SO3(Matrix3 R,const char *R_name);\n\n/** \\fn void saturate(Vector3 &x, const double x_min, const double x_max)\n * Saturate the elements of a given 3x1 vector between a minimum and a maximum\n * velue.\n * @param x     vector which the elements needed to be saturated\n * @param x_min minimum value for each element\n * @param x_max maximum value for each element\n */\nvoid saturate(Vector3 &x, const double x_min, const double x_max);\n\n\n/** \\fn void saturate(Vector4 &x, const double x_min, const double x_max)\n * Saturate the elements of a given 4x1 vector between a minimum and a maximum\n * velue.\n * @param x     vector which the elements needed to be saturated\n * @param x_min minimum value for each element\n * @param x_max maximum value for each element\n */\nvoid saturate(Vector4 &x, const double x_min, const double x_max);\n\n\n/** \\fn void saturate(Vector6 &x, const double x_min, const double x_max)\n * Saturate the elements of a given 6x1 vector between a minimum and a maximum\n * velue.\n * @param x     vector which the elements needed to be saturated\n * @param x_min minimum value for each element\n * @param x_max maximum value for each element\n */\nvoid saturate(Vector6 &x, const double x_min, const double x_max);\n\n\n/** \\fn void saturate(int &x, const int x_min, const int x_max)\n * Saturate the elements of a given integer between a minimum and a maximum\n * velue.\n * @param x     integer which needed to be saturated\n * @param x_min minimum value for x\n * @param x_max maximum value for x\n */\nvoid saturate(int &x, const int x_min, const int x_max);\n\n\n/** \\fn void saturate(double &x, const double x_min, const double x_max)\n * Saturate the elements of a given integer between a minimum and a maximum\n * velue.\n * @param x     double which needed to be saturated\n * @param x_min minimum value for x\n * @param x_max maximum value for x\n */\nvoid saturate(double &x, const double x_min, const double x_max);\n\n\n/** \\fn void deriv_unit_vector(Vector3 B, Vector3 B_dot, Vector3 &q, \n * Vector3 &q_dot)\n * finds derivative q = -B/norm(B)\n */\nvoid deriv_unit_vector(Vector3 B, Vector3 B_dot, Vector3 &q, Vector3 &q_dot);\n\n\n/** \\fn void deriv_unit_vector(Vector3 B, Vector3 B_dot, Vector3 B_ddot, \n * Vector3 &q, Vector3 &q_dot, Vector3 &q_ddot)\n * finds first and second derivatives of q = -B/norm(B)\n */\nvoid deriv_unit_vector(Vector3 B, Vector3 B_dot, Vector3 B_ddot, Vector3 &q, \\\n    Vector3 &q_dot, Vector3 &q_ddot);\n\n}  // end of namespace fdcl\n#endif\n", "meta": {"hexsha": "da75342bdc9dc46739cbe21b32859d858795aeb2", "size": 4373, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/uav_plugins/include/fdcl/matrix_utils.hpp", "max_stars_repo_name": "fdcl-gwu/uav_simulator", "max_stars_repo_head_hexsha": "a31855babfe633ae326ecb36c4ff714066cdb269", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2021-02-11T08:26:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T00:41:12.000Z", "max_issues_repo_path": "src/uav_plugins/include/fdcl/matrix_utils.hpp", "max_issues_repo_name": "fdcl-gwu/uav_simulator", "max_issues_repo_head_hexsha": "a31855babfe633ae326ecb36c4ff714066cdb269", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-07-29T05:23:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-08T13:15:17.000Z", "max_forks_repo_path": "src/uav_plugins/include/fdcl/matrix_utils.hpp", "max_forks_repo_name": "fdcl-gwu/uav_simulator", "max_forks_repo_head_hexsha": "a31855babfe633ae326ecb36c4ff714066cdb269", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2021-03-17T13:03:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T00:41:20.000Z", "avg_line_length": 32.1544117647, "max_line_length": 78, "alphanum_fraction": 0.7237594329, "num_tokens": 1178, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.934395157060208, "lm_q2_score": 0.86153820232079, "lm_q1q2_score": 0.8050171238709039}}
{"text": "#include <iostream>\n#include <math.h>\n#include <vector>\n#include <Eigen/Dense>\n\nusing namespace std;\n\n//Evaluate the Chebyshev polynomials up to order n in x.\nvector<double> chebpolmult(const int &n,const double &x)\n{\n    vector<double> V={1,x};\n    for (int k=1; k<n; k++)\n        V.push_back(2*x*V[k]-V[k-1]);\n    return V;\n}\n\n// Compute the best approximation of the function f with Chebyshev polynomials. alpha is the output vector of coefficients.\ntemplate <typename Function>\nvoid bestpolchebnodes(const Function &f, Eigen::VectorXd &alpha) {\n    int n=alpha.size()-1;\n    Eigen::VectorXd fn(n+1);\n    for (int k=0; k<n+1; k++) {\n        double temp=cos(M_PI*(2*k+1)/2/(n+1));\n        fn(k)=f(temp);\n    }\n    \n    vector<double> V;\n    Eigen::MatrixXd scal(n+1,n+1);\n    for (int j=0; j<n+1; j++) {\n        V=chebpolmult(n,cos(M_PI*(2*j+1)/2/(n+1)));\n        for (int k=0; k<n+1; k++) scal(j,k)=V[k];\n    }\n    \n    for (int k=0; k<n+1; k++) {\n        alpha(k)=0;\n        for (int j=0; j<n+1; j++) {\n            alpha(k)+=2*fn(j)*scal(j,k)/(n+1);\n        }\n    }\n        alpha(0)=alpha(0)/2;\n}\n\n// Test the implementation.\nint main(){\n    auto f = [] (double & x) {return 1/(pow(5*x,2)+1);};\n    int n=20;\n    Eigen::VectorXd alpha(n+1);\n    bestpolchebnodes(f, alpha);\n    \n    //Compute the error\n    Eigen::VectorXd X = Eigen::VectorXd::LinSpaced(1e6,-1,1);\n    auto qn = [&alpha,&n] (double & x) {\n        double temp;\n        vector<double> V=chebpolmult(n,x);\n        for (int k=0; k<n+1; k++) temp+=alpha(k)*V[k];\n        return temp;\n    };\n    double err_max=abs(f(X(0))-qn(X(0)));\n    for (int i=1; i<1e6; i++) err_max=std::max(err_max,abs(f(X(i))-qn(X(i))));\n    cout<<\"Error: \"<< err_max <<endl;\n}", "meta": {"hexsha": "b92f655cfa3a061416e0f93a58af8ffc7e84366a", "size": 1716, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/PS9/solutions_ps9/ChebBest.cpp", "max_stars_repo_name": "valentinjacot/backupETHZ", "max_stars_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:21:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:21:30.000Z", "max_issues_repo_path": "Nummerical Methods for CSE/PS9/solutions_ps9/ChebBest.cpp", "max_issues_repo_name": "valentinjacot/backupETHZ", "max_issues_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Nummerical Methods for CSE/PS9/solutions_ps9/ChebBest.cpp", "max_forks_repo_name": "valentinjacot/backupETHZ", "max_forks_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.131147541, "max_line_length": 123, "alphanum_fraction": 0.5536130536, "num_tokens": 576, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305360354471, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.804763259238667}}
{"text": "/**\n * Authors:\n *      Marcelo Jacinto (marcelo.jacinto@tecnico.ulisboa.pt)\n *      Andre Potes (andre.potes@tecnico.ulisboa.pt)\n * Maintained by: Marcelo Fialho Jacinto (marcelo.jacinto@tecnico.ulisboa.pt)\n * Last Update: 14/12/2021\n * License: MIT\n * File: rotations.hpp \n * Brief: Defines all functions related to angle wrapping, rotation matrices, \n * euler angles, convertion to quaternions, etc.\n */\n#pragma once\n\n#include <Eigen/Core>\n#include <cmath>\n\nnamespace DSOR {\n\n/**\n * @brief Function to convert from quaternion to (roll, pitch and yaw), according to Z-Y-X convention\n * This function is from: https://github.com/mavlink/mavros/issues/444\n * and the logic is also available at: https://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles\n * @param q An eigen quaternion\n * @return A Vector<T, 3> with the [roll, pitch, yaw] obtained according to Z-Y-X convention\n */\ntemplate <typename T>\ninline Eigen::Matrix<T, 3, 1> quaternion_to_euler(const Eigen::Quaternion<T> &q) {\n    /* NOTE: The Eigen standard way of doing it is not used because for the order YPR the output range would be:\n    [Eigen EulerAngles implementation] yaw, pitch, roll in the ranges [0:pi]x[-pi:pi]x[-pi:pi] */\n\n    Eigen::Matrix<T, 3, 1> rpy;\n\n    /* Compute roll */\n    rpy.x() = std::atan2(2 * (q.w() * q.x() + q.y() * q.z()), 1 - 2 * (q.x() * q.x() + q.y()*q.y()));\n    T sin_pitch = 2 * (q.w()*q.y() - q.z()*q.x());\n    sin_pitch = sin_pitch >  1 ?  1 : sin_pitch;\n    sin_pitch = sin_pitch < -1 ? -1 : sin_pitch;\n\n    /* Compute pitch */\n    rpy.y() = std::asin(sin_pitch);\n\n    /* Compute yaw */\n    rpy.z() = std::atan2(2 * (q.w() * q.z() + q.x() * q.y()), 1 - 2 * (q.y() * q.y() + q.z() * q.z()));\n\n    return rpy;\n}\n\n/**\n * @brief Converts a vector of euler angles according to Z-Y-X convention\n * into a quaternion\n * @param v An eigen vector of either floats or doubles [roll, pitch, yaw]\n * @return An Eigen Quaternion\n */\ntemplate <typename T>\ninline Eigen::Quaternion<T> euler_to_quaternion(const Eigen::Matrix<T, 3, 1> &v) {\n    \n    // Create the Eigen quaternion\n    Eigen::Quaternion<T> orientation;\n\n    // Obtain the orientation according to Z-Y-X convention\n    orientation = Eigen::AngleAxis<T>(v.z(), Eigen::Matrix<T, 3, 1>::UnitZ()) *\n            Eigen::AngleAxis<T>(v.y(), Eigen::Matrix<T, 3, 1>::UnitY()) *\n            Eigen::AngleAxis<T>(v.x(), Eigen::Matrix<T, 3, 1>::UnitX());\n\n    return orientation;\n}\n\n/**\n * @brief Gets the yaw angle from a quaternion (assumed a Z-Y-X rotation)\n * NOTE: this function is based on: \n * https://github.com/mavlink/mavros/blob/ros2/mavros/src/lib/ftf_quaternion_utils.cpp\n * which in turn has the theory explained in:\n * https://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles\n * @param q A eigen quaternion\n * @return The yaw angle in radians (assumed a Z-Y-X rotation)\n */\ntemplate <typename T>\ninline T yaw_from_quaternion(const Eigen::Quaternion<T> &q) {\n    return std::atan2(2 * (q.w() * q.z() + q.x() * q.y()), 1 - 2 * (q.y() * q.y() + q.z() * q.z()));\n}\n\n/**\n * @brief Wrap angle between [0, 2PI] \n * \n * @param angle angle in radians\n * @return The wraped angle\n */\ntemplate <typename T>\ninline T wrapTo2pi(T angle) {\n\n    double wrapped_angle = std::fmod(angle, 2 * M_PI);\n\n    if(wrapped_angle < 0) \n        wrapped_angle += 2 * M_PI;\n    return wrapped_angle;\n}\n\n/**\n * @brief Wrap angle between [-PI, PI] \n * \n * @param angle angle in radians\n * @return The wraped angle\n */\ntemplate <typename T>\ninline T wrapTopi(T angle) {\n\n    double wrapped_angle = std::fmod(angle + M_PI, 2 * M_PI);\n\n    if (wrapped_angle < 0)\n        wrapped_angle += 2 * M_PI;\n\n    return wrapped_angle - M_PI;\n}\n\n/**\n * @brief Convert an angle in radian to degrees\n * \n * @param angle in radians\n * @return angle in degrees\n */\ntemplate <typename T>\ninline T radToDeg(T angle) {\n    return angle * 180 / M_PI;\n}\n\n/**\n * @brief Convert an angle in degrees to radians\n * \n * @param angle in degrees\n * @return angle in radians\n */\ntemplate <typename T>\ninline T degToRad(T angle) {\n    return angle * M_PI / 180;\n}\n\n/**\n * @brief Method to calculate the diference between angles correctly even if they wrap between -pi and pi\n * \n * @param a angle 1 in radians \n * @param b angle 2 in radians\n * @return The minimum difference between the two angles \n */\ntemplate <typename T>\ninline T angleDiff(T a, T b) {\n    double aux = std::fmod(a - b + M_PI, 2 * M_PI);\n    if (aux < 0) aux += (2 * M_PI);\n    aux = aux - M_PI;\n    return aux;\n}\n\n\n/**\n * @brief Compute the 3x3 skew-symmetric matrix from a vector 3x1\n * @param v A vector with 3 elements\n * @return A 3x3 skew-symmetric matrix\n */\ntemplate <typename T>\ninline Eigen::Matrix<T, 3, 3> computeSkewSymmetric3(const Eigen::Matrix<T, 3, 1> &v) {\n\n    Eigen::Matrix<T, 3, 3> skew_symmetric;\n    skew_symmetric <<    0, -v(2),  v(1),\n                      v(2),     0, -v(0),\n                     -v(1),  v(0),     0;\n\n    return skew_symmetric;\n}\n\n/**\n * @brief Compute the 2x2 skew-symmetric matrix from a constant (int, float or double)\n * @param v A constant\n * @return A 2x2 skew-symmetric matrix\n */\ntemplate <typename T>\ninline Eigen::Matrix<T, 2, 2> computeSkewSymmetric2(T c) {\n\n    Eigen::Matrix<T, 2, 2> skew_symmetric;\n    skew_symmetric << 0, -c,\n                      c,  0;\n\n    return skew_symmetric;\n}\n\n/**\n * @brief Compute the rotation matrix that converts angular velocities expressed in the body frame\n * to angular velocities expressed in the inertial frame (according to Z-Y-X convention) - makes use of small angle approximation\n * @param v A vector with 3 elements (roll, pitch, yaw)\n * @return A 3x3 rotation matrix\n */\ntemplate <typename T>\ninline Eigen::Matrix<T, 3, 3> rotationAngularBodyToInertial(const Eigen::Matrix<T, 3, 1> &v) {\n    Eigen::Matrix<T, 3, 3> transformation_matrix;\n    transformation_matrix << 1, sin(v(0)) * tan(v(1)), cos(v(0)) * tan(v(1)),\n                             0, cos(v(0)), -sin(v(0)),\n                             0, sin(v(0)) / cos(v(1)), cos(v(0)) / cos(v(1));\n    return transformation_matrix;\n}\n\n/**\n * @brief Method that returns a rotation matrix from body frame to inertial frame, assuming a Z-Y-X convention\n * @param v A vector with euler angles (roll, pith, yaw) according to Z-Y-X convention\n * @return A 3x3 rotation matrix\n */\ntemplate <typename T>\ninline Eigen::Matrix<T, 3, 3> rotationBodyToInertial(const Eigen::Matrix<T, 3, 1> &v) {\n    \n    // Create a quaternion\n    Eigen::Matrix<T, 3, 3> m;\n\n    // Obtain the orientation according to Z-Y-X convention\n    m = (Eigen::AngleAxis<T>(v.z(), Eigen::Matrix<T, 3, 1>::UnitZ()) *\n         Eigen::AngleAxis<T>(v.y(), Eigen::Matrix<T, 3, 1>::UnitY()) *\n         Eigen::AngleAxis<T>(v.x(), Eigen::Matrix<T, 3, 1>::UnitX())).toRotationMatrix();\n    \n    return m;\n}\n\n}", "meta": {"hexsha": "91da557810ba40a01d2f9991b91837dd177c5a69", "size": 6818, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dsor_utils/include/dsor_utils/rotations.hpp", "max_stars_repo_name": "dsor-isr/dsor_utils", "max_stars_repo_head_hexsha": "9e0c47701340b18da423a6badfb698673179f6bd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dsor_utils/include/dsor_utils/rotations.hpp", "max_issues_repo_name": "dsor-isr/dsor_utils", "max_issues_repo_head_hexsha": "9e0c47701340b18da423a6badfb698673179f6bd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dsor_utils/include/dsor_utils/rotations.hpp", "max_forks_repo_name": "dsor-isr/dsor_utils", "max_forks_repo_head_hexsha": "9e0c47701340b18da423a6badfb698673179f6bd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2752293578, "max_line_length": 129, "alphanum_fraction": 0.636550308, "num_tokens": 2023, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818864, "lm_q2_score": 0.8856314753275017, "lm_q1q2_score": 0.8047006129526343}}
{"text": "#include <stdio.h>\n\n#include <cmath>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <numeric>\n#include <string>\n#include <utility>\n#include <vector>\n\n\nusing std::cout;\nusing std::endl;\nusing std::fixed;\nusing std::ifstream;\nusing std::left;\nusing std::pair;\nusing std::right;\nusing std::scientific;\nusing std::setw;\nusing std::setprecision;\nusing std::string;\nusing std::vector;\n\n#include <boost/math/distributions/students_t.hpp>\n\nusing boost::math::students_t;\n\npair<double, double> get_mean_and_standard_deviation(const vector<double> &vv) {\n  const double sum = std::accumulate(vv.begin(), vv.end(), 0.0);\n  const double mean = sum / vv.size();\n  double A = 0;\n  std::for_each(vv.begin(), vv.end(), [&mean, &A](const double v) {\n\t\t\t\t\tA += (v - mean) * (v - mean);\n\t\t\t\t      });\n  return std::make_pair(mean, std::sqrt(A / (vv.size() - 1)));\n}\n\nvector<double> get_data_set(const string &fn) {\n  ifstream fin(fn);\n  if (!fin.good()) {\n    fprintf(stderr, \"Open file error: %s\\n\", fn.c_str());\n    return vector<double>();\n  }\n  vector<double> result;\n  for (string line; std::getline(fin, line) ; ) {\n    result.push_back(std::stof(line));\n  }\n  return result;\n}\n\n\nvoid two_samples_t_test_equal_sd(\n        double Sm1, // Sm1 = Sample Mean 1.\n        double Sd1,   // Sd1 = Sample Standard Deviation 1.\n        unsigned Sn1,   // Sn1 = Sample Size 1.\n        double Sm2,   // Sm2 = Sample Mean 2.\n        double Sd2,   // Sd2 = Sample Standard Deviation 2.\n        unsigned Sn2,   // Sn2 = Sample Size 2.\n        double alpha)   // alpha = Significance Level.\n{\n   // A Students t test applied to two sets of data.\n   // We are testing the null hypothesis that the two\n   // samples have the same mean and that any difference\n   // if due to chance.\n   // See http://www.itl.nist.gov/div898/handbook/eda/section3/eda353.htm\n   //\n   using namespace std;\n   // using namespace boost::math;\n\n   using boost::math::students_t;\n\n   double v = (Sn1 + Sn2 - 2) ;\n   double sp = sqrt(((Sn1-1) * Sd1 * Sd1 + (Sn2-1) * Sd2 * Sd2) / v);\n   // t-statistic:\n   double t_stat = (Sm1 - Sm2) / (sp * sqrt(1.0 / Sn1 + 1.0 / Sn2));\n   cout << setw(20) << left << \"T Statistic\" << \"=  \" << t_stat << \"\\n\";\n   students_t dist(v);\n   double q = cdf(complement(dist, fabs(t_stat)));\n   cout << setw(20) << left << \"P-value\" << \"=  \"\n\t<< setprecision(3) << scientific << 2 * q << \"\\n\";\n   if(q < alpha / 2) {\n      cout << \"Sample 1 Mean != Sample 2 Mean\\n\";\n   } else {\n     printf(\"Sample 1 Mean = %.2f\\n\", Sm1);\n     printf(\"Sample 2 Mean = %.2f\\n\", Sm2);\n     cout << \"Sample 1 Mean == Sample 2 Mean\\n\";\n     return;\n   }\n   printf(\"Sample 1 Mean = %.2f\\n\", Sm1);\n   printf(\"Sample 2 Mean = %.2f\\n\", Sm2);\n\n   if(cdf(dist, t_stat) < alpha) {\n     printf(\"Sample 1 Mean <  Sample 2 Mean\\n\");\n     printf(\"Sample improvement = %.2f%%\\n\", (Sm2 - Sm1) / Sm1 * 100);\n   }\n   if(cdf(complement(dist, t_stat)) < alpha) {\n     printf(\"Sample 1 Mean >  Sample 2 Mean\\n\");\n     printf(\"Sample regression = %.2f%%\\n\", (Sm1 - Sm2) / Sm1 * 100);\n   }\n}\n\ndouble confidence_interval(const vector<double> &data) {\n  students_t dist(data.size() - 1);\n  double t_star = quantile(complement(dist, 0.05 / 2));\n  auto mean_and_standard_deviation = get_mean_and_standard_deviation(data);\n  return t_star * mean_and_standard_deviation.second / sqrt(data.size());\n}\n\nint main(const int argc, const char *argv[]) {\n\n  if (argc < 3) {\n    fprintf(stderr, \"Missing argument\\n\");\n    return 1;\n  }\n  \n   vector<double> data_1 = get_data_set(argv[1]);\n   vector<double> data_2 = get_data_set(argv[2]);\n\n   if (data_1.empty() || data_2.empty()) {\n     fprintf(stderr, \"Empty data set(s).\\n\");\n     return 1;\n   }\n\n   if (data_1.size() != data_2.size()) {\n     fprintf(stderr, \"Data sets have different number of data points.\\n\");\n     return 1;\n   }\n\n   vector<double> diff_set;\n   for(vector<double>::iterator i = data_1.begin(),\n\t j = data_2.begin(), e = data_1.end(); i != e; ++i, ++j)\n     diff_set.push_back(*j - *i);\n\n   auto p1 = get_mean_and_standard_deviation(data_1);\n   auto p2 = get_mean_and_standard_deviation(data_2);\n   auto p3 = get_mean_and_standard_deviation(diff_set);\n   double diff_standard_error = p3.second / sqrt(diff_set.size());\n   // T value\n   double diff_t = p3.first / diff_standard_error;\n   students_t dist(data_1.size() - 1);\n   // P = 2 * q;\n   double q = cdf(complement(dist, fabs(diff_t)));\n\n   fprintf(stderr, \"Group 1 mean = %.2f \u00b1 %.2f\\n\", p1.first, confidence_interval(data_1));\n   fprintf(stderr, \"Group 2 mean = %.2f \u00b1 %.2f\\n\", p2.first, confidence_interval(data_2));\n   if (q * 2 <= 0.01) {\n     fprintf(stderr, \"P value      = %.2e\\n\", q * 2);\n   } else {\n     fprintf(stderr, \"P value      = %.2f\\n\", q * 2);\n   }\n   if (q * 2 > 0.05) {\n     fprintf(stderr, \"Difference is not significant.\\n\");\n     return 0;\n   }\n   double w = confidence_interval(diff_set);\n   fprintf(stderr, \"Diff mean (95%% CI)  = %.2f \u00b1 %.2f\\n\", p3.first, w);\n   fprintf(stderr, \"Percent   (95%% CI) = %.2f%% (\u00b1 %.2f%%)\\n\", p3.first / p1.first * 100, w / p1.first * 100);\n\n   return 0;\n} // int main()\n", "meta": {"hexsha": "48b908b8b1c799ba5ed3074111069fd398e05d89", "size": 5094, "ext": "cc", "lang": "C++", "max_stars_repo_path": "plo/t-test.cc", "max_stars_repo_name": "google/llvm-propeller", "max_stars_repo_head_hexsha": "45c226984fe8377ebfb2ad7713c680d652ba678d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 305.0, "max_stars_repo_stars_event_min_datetime": "2019-09-14T17:16:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:05:20.000Z", "max_issues_repo_path": "plo/t-test.cc", "max_issues_repo_name": "houchen/llvm-propeller", "max_issues_repo_head_hexsha": "45c226984fe8377ebfb2ad7713c680d652ba678d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2019-10-17T21:11:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-17T20:10:00.000Z", "max_forks_repo_path": "plo/t-test.cc", "max_forks_repo_name": "houchen/llvm-propeller", "max_forks_repo_head_hexsha": "45c226984fe8377ebfb2ad7713c680d652ba678d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2019-10-03T11:22:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T09:59:30.000Z", "avg_line_length": 31.2515337423, "max_line_length": 111, "alphanum_fraction": 0.6091480173, "num_tokens": 1563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750440288019, "lm_q2_score": 0.8438950966654772, "lm_q1q2_score": 0.8044641354294728}}
{"text": "#ifndef MLT_UTILS_LOSS_FUNCTIONS_HPP\n#define MLT_UTILS_LOSS_FUNCTIONS_HPP\n\n#include <tuple>\n\n#include <Eigen/Core>\n\n#include \"../defs.hpp\"\n\nnamespace mlt {\nnamespace utils {\nnamespace loss_functions {\n\tclass SquaredLoss {\n\tpublic:\n\t\tauto loss(MatrixXdRef pred, MatrixXdRef target) const {\n\t\t\treturn (pred - target).array().pow(2).sum() / (2 * pred.cols());\n\t\t}\n\n\t\tauto gradient(MatrixXdRef pred, MatrixXdRef target) const {\n\t\t\treturn MatrixXd{ (pred - target) / pred.cols() };\n\t\t}\n\n\t\tauto loss_and_gradient(MatrixXdRef pred, MatrixXdRef target) const {\n\t\t\tint size = pred.cols();\n\t\t\tauto residuals = (pred - target).eval();\n\n\t\t\treturn make_tuple(residuals.array().pow(2).sum() / (2 * size), (residuals / size).eval());\n\t\t}\n\t};\n\n\tclass HingeLoss {\n\tpublic:\n\t\tHingeLoss (double threshold = 1.0) : _threshold(threshold) {}\n\n\t\tauto loss(MatrixXdRef pred, MatrixXdRef target) const {\n\t\t\treturn (((pred.rowwise() - pred.cwiseProduct(target).colwise().sum()) - target).array() + _threshold).max(0).sum() / pred.cols();\n\t\t}\n\n\t\tauto gradient(MatrixXdRef pred, MatrixXdRef target) const {\n\t\t\tauto margin_mask = ((((pred.rowwise() - pred.cwiseProduct(target).colwise().sum()) - target).array() + _threshold).max(0) > 0).cast<double>().eval();\n\t\t\tmargin_mask = margin_mask + (target.array().rowwise() * -margin_mask.colwise().sum().array());\n\t\t\treturn (margin_mask / pred.cols()).eval();\n\t\t}\n\n\t\tauto loss_and_gradient(MatrixXdRef pred, MatrixXdRef target) const {\n\t\t\tint size = pred.cols();\n\t\t\tauto hinge_loss = ((((pred.rowwise() - pred.cwiseProduct(target).colwise().sum()) - target).array() + _threshold).max(0)).eval();\n\t\t\tauto margin_mask = (hinge_loss.array() > 0).cast<double>().eval();\n\t\t\tmargin_mask = margin_mask + (target.array().rowwise() * -margin_mask.colwise().sum().array());\n\t\t\treturn make_tuple(hinge_loss.sum() / size, (margin_mask / size).eval());\n\t\t}\n\tprotected:\n\t\tdouble _threshold;\n\t};\n\n\tclass SoftmaxLoss {\n\tpublic:\n\t\tauto loss(MatrixXdRef pred, MatrixXdRef target) const {\n\t\t\treturn -_softmax(pred).cwiseProduct(target).colwise().sum().array().log().sum() / pred.cols();\n\t\t}\n\n\t\tauto gradient(MatrixXdRef pred, MatrixXdRef target) const {\n\t\t\treturn ((_softmax(pred) - target) / pred.cols()).eval();\n\t\t}\n\n\t\tauto loss_and_gradient(MatrixXdRef pred, MatrixXdRef target) const {\n\t\t\tint size = pred.cols();\n\t\t\tauto softmax_output = _softmax(pred);\n\t\t\tdouble l = softmax_output.cwiseProduct(target).colwise().sum().array().log().sum() / size;\n\t\t\treturn make_tuple(l, ((_softmax(pred) - target) / size).eval());\n\t\t}\n\n\tprotected:\n\t\tinline MatrixXd _softmax(MatrixXdRef x) const {\n\t\t\tauto result = (x.rowwise() - x.colwise().maxCoeff()).array().exp().eval();\n\t\t\treturn (result.array().rowwise() / result.colwise().sum().array());\n\t\t}\n\t};\n}\n}\n}\n#endif", "meta": {"hexsha": "a8e2b196cba1c99c8cd90669eb83a247bc3ab581", "size": 2753, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/mlt/utils/loss_functions.hpp", "max_stars_repo_name": "fedeallocati/MachineLearningToolkit", "max_stars_repo_head_hexsha": "8614ee2c8c5211a3eefceb10a50576e0485cefd9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-08-31T11:43:19.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-22T11:03:47.000Z", "max_issues_repo_path": "src/mlt/utils/loss_functions.hpp", "max_issues_repo_name": "fedeallocati/MachineLearningToolkit", "max_issues_repo_head_hexsha": "8614ee2c8c5211a3eefceb10a50576e0485cefd9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlt/utils/loss_functions.hpp", "max_forks_repo_name": "fedeallocati/MachineLearningToolkit", "max_forks_repo_head_hexsha": "8614ee2c8c5211a3eefceb10a50576e0485cefd9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5731707317, "max_line_length": 152, "alphanum_fraction": 0.674900109, "num_tokens": 741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731158685838, "lm_q2_score": 0.8354835371034369, "lm_q1q2_score": 0.8042975399202712}}
{"text": "/*  Legendre polynomials\n\n\tAn in-class exercise using equations for the Polynomials and solvers as\n\tshown in the lecture/manuscript for Numerical Methods for CSE\n\tby Prof. R. Hiptmair, ETH Z\u00fcrich\n\n\tInclude the Eigen3 library as shown in documentation for Eigen3.\n\n\tuse piping to store the .m file. Example call:\n\tlegendre >legendre.m\n\n \tThis program calculates\n \t- Legendre Polynomials P0 to P8 and their derivatives in interval [-1,1]\n \t  -> plots them using MatlabPlotter\n \t- Gauss points / zero points for P1 to P8\n \t  - using secant method as solver\n \t  - using secant falsi method as solver\n \t  -> plots them using MatlabPlotter\n \t- uses these Gauss points to calculate the weights for GL quadrature\n \t- applies this GL quadrature to a function f(x) = e^(x^2) over an interval [a,b] = [3,6]\n \t- plots the relative error (comparison of P1 to P8 vs reference result by Wolfram|Alpha)\n\n\tv1.0.3 2015-11-22 / 2015-11-29 Pirmin Schmid\n*/\n\n//#define _USE_MATH_DEFINES\n#include <cmath>\n#include <vector>\n#include <Eigen/Dense>\n#include \"matlab_plotter.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\n//------------------------------------------------------------------------------\n\n// 3-term recursion for sequences (Pn)n  and (Pn')n for n in 0 to (N-1)\n// evaluation of multiple x_i values in parallel\n// input:        vector x in R^n with x_0 to x_{n-1}\n// input/output: Lx and DLx in R^Nxn\n//               thus, number of given rows N eq. number of elements desired\n//               of the sequences (Pn)n  and (Pn')n\nvoid legvals(const VectorXd& x, MatrixXd& Lx, MatrixXd& DLx) {\n\t// check input\n\tlong n = x.size();\n\tlong N = Lx.rows();\n\tif(Lx.cols() != n || DLx.rows() != N || DLx.cols() != n) {\n\t\tcout << \"Error in legvals(): Dimensions mismatch.\" << endl;\n\t\texit(1);\n\t}\n\n\tdouble denominator_inv = 0.0;\n\tdouble numerator1 = 0.0;\n\tdouble numerator2 = 0.0;\n\n\t// we need a row vector for the calculations below (otherwise Eigen assertion fails)\n\t// this seemed the easiest way for me to get one.\n\tRowVectorXd xr = x;\n\n\tDLx.row(0) = MatrixXd::Zero(1, n);\n\tLx.row(0) = MatrixXd::Ones(1, n);\n\n\tDLx.row(1) = MatrixXd::Ones(1, n);\n\tLx.row(1) = x;\n\n\tfor(long i = 2; i < N; i++) {\n\t\t// these values are calculated fresh for each iteration to avoid any accumulating rounding error\n\t\t// when calculated iteratively from prior values\n\t\tdenominator_inv = 1.0 / (double)i; // one division here -> many much faster multiplications than divisions later\n\t\tnumerator1 = (double)(2 * i - 1);\n\t\tnumerator2 = (double)(i - 1);\n\n\t\tDLx.row(i) = denominator_inv * (numerator1 * (Lx.row(i-1) + DLx.row(i-1).cwiseProduct(xr)) - numerator2 * DLx.row(i-2));\n\t\tLx.row(i)  = denominator_inv * (numerator1 * Lx.row(i-1).cwiseProduct(xr) - numerator2 * Lx.row(i-2));\n\t}\n}\n\n//------------------------------------------------------------------------------\n\nusing EvalFunction = function<double (const double, const int)>;\n\n// computes Pk(x) for scalar x\ndouble Pkx(const double x, const int k) {\n\tif(k < 2) {\n\t\tif(k == 0) {\n\t\t\treturn 1.0;\n\t\t}\n\n\t\tif(k == 1) {\n\t\t\treturn x;\n\t\t}\n\n\t\tcout << \"Error in Pkx(): Negative k values are not valid.\" << endl;\n\t\texit(1);\n\t}\n\n\tdouble denominator = 0.0;\n\tdouble numerator1 = 0.0;\n\tdouble numerator2 = 0.0;\n\n\tdouble result_minus2 = 1.0;\n\tdouble result_minus1 = x;\n\tdouble result = 0.0;\n\n\tfor(int i = 2; i <= k; i++) {\n\t\tdenominator = (double)i;\n\t\tnumerator1 = (double)(2 * i - 1);\n\t\tnumerator2 = (double)(i - 1);\n\n\t\tresult = (numerator1 * result_minus1 * x - numerator2 * result_minus2) / denominator;\n\t\tresult_minus2 = result_minus1;\n\t\tresult_minus1 = result;\n\t}\n\treturn result;\n}\n\n//------------------------------------------------------------------------------\n\nusing Solver = function<double (double, double, EvalFunction, int, const double, const double, const int)>;\n\n// translation of the Matlab function secant 2.3.25 in the manuscript\n// modified to include the additional parameter k\ndouble secant(double x0, double x1, EvalFunction f, int k, const double rtol, const double atol, const int maxIterations) {\n\tdouble f0 = f(x0, k);\n\tdouble fn = 0.0;\n\tdouble s = 0.0;\n\tfor(int i=0; i < maxIterations; i++) {\n\t\tfn = f(x1, k);\n\t\ts = fn * (x1-x0) / (fn-f0); // correction\n\t\tx0 = x1;\n\t\tx1 = x1 - s;\n\t\tif( abs(s) < max(atol, rtol * min(abs(x0), abs(x1))) ) {\n\t\t\treturn x1;\n\t\t}\n\t\tf0 = fn;\n\t}\n\n\t// default, best guess after maxIterations\n\treturn x1;\n}\n\n// translation of the Matlab function secant_falsi on the exercise sheet\n// modified to include the additional parameter k\ndouble secant_falsi(double x0, double x1, EvalFunction f, int k, const double rtol, const double atol, const int maxIterations) {\n\tdouble f0 = f(x0, k);\n\tdouble fn = 0.0;\n\tdouble s = 0.0;\n\tfor(int i=0; i < maxIterations; i++) {\n\t\tfn = f(x1, k);\n\t\ts = fn * (x1-x0) / (fn-f0); // correction\n\t\tif(f(x1 - s, k) * fn < 0.0) {\n\t\t\tx0 = x1;\n\t\t\tf0 = fn;\n\t\t}\n\t\tx1 = x1 - s;\n\t\tif( abs(s) < max(atol, rtol * min(abs(x0), abs(x1))) ) {\n\t\t\treturn x1;\n\t\t}\n\t}\n\n\t// default, best guess after maxIterations\n\treturn x1;\n}\n\n//------------------------------------------------------------------------------\n\n#define MAX_ITERATIONS 100\n\n// calculate zeros of Pk, k in 1 to n using the secant rule for end points {-1, 1} of the interval [-1, 1] and the zeros\n// of the previous Legendre polynomial as initial guesses. Correction based termination criterion\n// input:  n size\n//         rtol and atol relative and absolute tolerance\n// return: nxn upper triangular matrix, to actually get such an upper triangular\n//         I assume that row j indicates the j-th zero for j in 1 to k\n//                       column k indicates the solutions for Pk (thus, we will have column vectors of solutions)\n//         note: for C++, index 0 will refer to j=1 and k=1 respectively, and so on.\nMatrixXd gaussPts(const int n, Solver z, const double rtol = 1e-10, const double atol = 1e-12) {\n\tMatrixXd zeros = MatrixXd::Zero(n, n);\n\n\t// find the first for P1 -> will be in [0,0]\n\tzeros(0,0) = z(-1.0, 1.0, Pkx, 1, rtol, atol, MAX_ITERATIONS);\n\n\t// get the zeros for P2 to Pn (will be in columns 1 to (n-1)\n\tfor(int i = 1; i < n; i++) {\n\t\t// get first zero\n\t\tzeros(0, i) = z(-1.0, zeros(0, i-1), Pkx, i+1, rtol, atol, MAX_ITERATIONS);\n\n\t\t// get last zero\n\t\tzeros(i, i) = z(zeros(i-1, i-1), 1.0, Pkx, i+1, rtol, atol, MAX_ITERATIONS);\n\n\t\t// get the zeros in-between\n\t\tfor(int j = 1; j < i; j++) {\n\t\t\tzeros(j, i) = z(zeros(j-1, i-1), zeros(j, i-1), Pkx, i+1, rtol, atol, MAX_ITERATIONS);\n\t\t}\n\t}\n\n\treturn zeros;\n}\n\n//------------------------------------------------------------------------------\n\n#define A 3\n#define B 6\n\nusing Function = function<double (const double)>;\n\n// just a simple function that does not have a primitive (Stammfunktion) that can be expressed\n// in R space. thus: suitable for numerical integration / quadrature\ndouble test_function_for_quadrature(const double x) {\n\treturn exp(x * x);\n}\n\n// Wolfram|Alpha calculated the quadrature of this function in [3,6] to be\n// 3.644831077835569048422984645481051411815484722480248338949090926023254915628803401963716304967305392 10^14\n// change this reference value if you change the function or A, B\n\n#define REFERENCE_RESULT 3.6448310778355690e14\n\n// applies the Gauss-Legendre quadrature for the given function over a defined interval [a,b]\n// input:  f     a function that fits the type definition of Function\n//         a, b  define interval [a,b]\n//         w, x  weights and Gauss points for the given Legendre Polynomial in standard interval [-1,1]\n//               size of both arrays must match, of course\n// return: quadrature approximation for this function in interval [a,b]\ndouble GLquadrature(const Function f, const double a, const double b, const ArrayXd& w, const ArrayXd& x) {\n\tint n = w.size();\n\tif(n != x.size()) {\n\t\tcout << \"vectors of weights and Gauss points must have the same size\" << endl;\n\t\texit(1);\n\t}\n\n\tdouble half_delta = 0.5 * (b-a);\n\tdouble avg = 0.5 * (a+b);\n\tArrayXd weights = half_delta * w;\n\tArrayXd xs = half_delta * x;\n\txs += avg;\n\n\tArrayXd ys = xs.unaryExpr(f);\n\tys *= weights;\n\treturn ys.sum();\n}\n\n//------------------------------------------------------------------------------\n\n#define MIN -1\n#define MAX 1\n#define MAX_K 8\n#define N_X 600\n\nint main() {\n\t// initialization\n\tMatlabPlotter p;\n\tp.comment(\"Legendre polynomials\");\n\tp.comment(\"Code generated by legendre.cpp\");\n\n\tvector<string> colors = {\"k-\", \"b-\", \"g-\", \"r-\", \"c-\", \"m-\", \"y-\"};\n\tvector<string> colors2 = {\"ko\", \"bo\", \"go\", \"ro\", \"co\", \"mo\", \"yo\"};\n\tint n_colors = colors.size();\n\n\tvector<string> description = {\"P_{0}\", \"P_{1}\", \"P_{2}\", \"P_{3}\", \"P_{4}\", \"P_{5}\", \"P_{6}\", \"P_{7}\", \"P_{8}\"};\n\n\n\t// (1) get a visual impression -> plot the Legendre polynomials up to k = MAX_K\n\tVectorXd xx = VectorXd::LinSpaced(N_X, MIN, MAX);\n\tMatrixXd Lx(MAX_K+1, N_X);\n\tMatrixXd DLx(MAX_K+1, N_X);\n\tlegvals(xx, Lx, DLx);\n\n\tp.figure(\"Legendre polynomials 0 to 8\");\n\tVectorXd yy = Lx.row(0);\n\tp.plot(xx, yy, colors[0]);\n\tp.hold();\n\tp.title(\"Legendre polynomials 0 to 8\");\n\tfor(int i=1; i <= MAX_K; i++) {\n\t\tyy = Lx.row(i);\n\t\tp.plot(xx, yy, colors[i % n_colors]);\n\t}\n\tp.xylabels(\"x\", \"P_{i}(x) for i={0, 1, ..., 8}\");\n\tp.legend(\"P_{0}\", \"P_{1}\", \"P_{2}\", \"P_{3}\", \"P_{4}\", \"P_{5}\", \"P_{6}\", \"P_{7}\", \"P_{8}\");\n\tp.hold(false);\n\n\t// (2) get a visual impression -> plot the derivatives of the Legendre polynomials up to k = MAX_K\n\tp.figure(\"Derivatives of Legendre polynomials 0 to 8\");\n\tyy = DLx.row(0);\n\tp.plot(xx, yy, colors[0]);\n\tp.hold();\n\tp.title(\"Derivatives of Legendre polynomials 0 to 8\");\n\tfor(int i=1; i <= MAX_K; i++) {\n\t\tyy = DLx.row(i);\n\t\tp.plot(xx, yy, colors[i % n_colors]);\n\t}\n\tp.xylabels(\"x\", \"dP_{i}(x)/dx for i={0, 1, ..., 8}\");\n\tp.legend(\"dP_{0}/dx\", \"dP_{1}/dx\", \"dP_{2}/dx\", \"dP_{3}/dx\", \"dP_{4}/dx\", \"dP_{5}/dx\", \"dP_{6}/dx\", \"dP_{7}/dx\", \"dP_{8}/dx\");\n\tp.hold(false);\n\n\t// (3) Find zeros with secant and secant falsi methods\n\t//     and since we are iterating thru the Legendre polynomials and their Gauss points\n\t//     -> use the gained insight to apply GL quadrature to a given function and interval\n\t//        and measure the error of approximation\n\tMatrixXd zeros_x = gaussPts(MAX_K, secant);\n\tMatrixXd zeros_x_falsi = gaussPts(MAX_K, secant_falsi);\n\tVectorXd zeros_y = VectorXd::Zero(MAX_K);\n\n\tvector<double> x = {MIN, MAX};\n\tvector<double> y = {0.0, 0.0};\n\n\tArrayXd i_values(MAX_K+1);\n\ti_values[0] = 0.0;\n\tArrayXd areas(MAX_K+1);\n\tareas[0] = 0.0; // P0 is not tested\n\n\tfor(int i=1; i <= MAX_K; i++) {\n\t\tp.figure(\"Legendre polynomial \" + description[i] + \" Zeros / Gauss points by secant and secant falsi methods.\");\n\t\tyy = Lx.row(i);\n\t\tp.plot(xx, yy, colors[i % n_colors]);\n\t\tp.hold();\n\t\tp.title(\"Legendre polynomial \" + description[i] + \" Zeros / Gauss points by secant and secant falsi methods.\");\n\t\t// secant\n\t\tVectorXd gyy = zeros_y.head(i);\n\t\tVectorXd gxx = zeros_x.col(i-1);\n\t\tgxx = gxx.head(i);\n\t\tp.plot(gxx, gyy, \"ko\");\n\t\t// true position of these \"zeros\"\n\t\tMatrixXd Lgx(i+1, i);\n\t\tMatrixXd DLgx(i+1, i);\n\t\tlegvals(gxx, Lgx, DLgx);\n\t\tVectorXd true_gyy = Lgx.row(i);\n\t\tp.plot(gxx, true_gyy, \"b*\"); // note: This may not be visible if secant falsi gets the same result\n\t\t                             // but P8 shows a clear difference\n\t\tp.comment(\"zeros for \" + description[i] + \" by secant method\");\n\t\tfor(int j=0; j < i; j++) {\n\t\t\tp.comment(\"x = \" + to_string(gxx[j]) + \" y = \" + to_string(true_gyy[j]) + \" expected 0.0\");\n\t\t}\n\n\t\t// falsi\n\t\tgxx = zeros_x_falsi.col(i-1);\n\t\tgxx = gxx.head(i);\n\t\tp.plot(gxx, gyy, \"r*\");\n\t\t// true position of these \"zeros\"\n\t\tlegvals(gxx, Lgx, DLgx);\n\t\ttrue_gyy = Lgx.row(i);\n\t\tp.comment(\"zeros for \" + description[i] + \" by secant falsi method\");\n\t\tfor(int j=0; j < i; j++) {\n\t\t\tp.comment(\"x = \" + to_string(gxx[j]) + \" y = \" + to_string(true_gyy[j]) + \" expected 0.0\");\n\t\t}\n\t\t// calculation of weights for GL-quadrature on standard interval [-1,1]\n\t\tp.comment(\"\");\n\t\tp.comment(description[i] + \": Weights w_i and gauss points x_i needed for Gauss-Legendre quadrature\");\n\t\tp.comment(\"(integration approximation) on interval [-1, 1]. Use appropriate scaling for other intervals.\");\n\t\tArrayXd DLgx_squared = DLgx.row(i).array();\n\t\tDLgx_squared *= DLgx_squared;\n\t\tArrayXd gww = gxx.cwiseProduct(gxx).array();\n\t\tgww = -gww; // intermediary step since - seems not to be defined in combination with scalars\n\t\tgww = gww + 1.0;\n\t\tgww = gww.cwiseProduct(DLgx_squared);\n\t\tgww = 2.0 / gww;\n\t\tfor(int j=0; j < i; j++) {\n\t\t\tstring index = to_string(j);\n\t\t\tp.comment(\"w_\" + index + \" = \" + to_string(gww[j]) +\" x_\" + index + \" = \" + to_string(gxx[j]) );\n\t\t}\n\n\t\t// let's test this on an effective quadrature\n\t\tdouble area = GLquadrature(test_function_for_quadrature, A, B, gww, gxx.array());\n\t\tp.comment(\"-> quadrature of f(x)=e^(x^2) in [\" + to_string(A) + \",\" + to_string(B) + \"] approx. = \" + to_string(area));\n\t\tareas[i] = area;\n\t\ti_values[i] = (double)i;\n\n\t\t// null line\n\t\tp.plot(x, y, \"k:\");\n\t\t// info\n\t\tp.xylabels(\"x\", description[i] + \"(x)\");\n\t\tp.legend(description[i], \"zeros by secant\", \"true y value of these zeros\", \"zeros by secant falsi\");\n\t\tp.hold(false);\n\t}\n\n\t// show relative errors (P1 to P8 vs reference result)\n\tdouble negReference = -REFERENCE_RESULT;\n\tArrayXd error = areas + negReference; // workaround since - is not accepted with scalars (while + is)\n\terror = error.cwiseAbs() / REFERENCE_RESULT;\n\n\t// do not show P0\n\ti_values = i_values.tail(MAX_K);\n\terror = error.tail(MAX_K);\n\n\tp.figure(\"Relative errors of P1 to P8 vs reference result from Wolfram|Alpha\", MatlabPlotter::LINEAR);\n\tp.plot(i_values, error, \"r*-\");\n\tp.xylabels(\"P_{i}\", \"Relative error vs reference result (lin scale)\");\n\tp.title(\"Relative errors of P1 to P8 vs reference result from Wolfram|Alpha\");\n\n\tp.figure(\"Relative errors of P1 to P8 vs reference result from Wolfram|Alpha\", MatlabPlotter::SEMILOGY);\n\tp.plot(i_values, error, \"r*-\");\n\tp.xylabels(\"P_{i}\", \"Relative error vs reference result (log scale)\");\n\tp.title(\"Relative errors of P1 to P8 vs reference result from Wolfram|Alpha\");\n\n\treturn 0;\n}", "meta": {"hexsha": "58bb6829d85013d3f24fa231f2aa1caebebfc428", "size": 13948, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example2/legendre.cpp", "max_stars_repo_name": "pirminschmid/MatlabPlotter", "max_stars_repo_head_hexsha": "6cdc3954ee4a065d978c0248b00406366eafe237", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-11-09T13:21:08.000Z", "max_stars_repo_stars_event_max_datetime": "2015-11-09T15:54:38.000Z", "max_issues_repo_path": "example2/legendre.cpp", "max_issues_repo_name": "pirminschmid/MatlabPlotter", "max_issues_repo_head_hexsha": "6cdc3954ee4a065d978c0248b00406366eafe237", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example2/legendre.cpp", "max_forks_repo_name": "pirminschmid/MatlabPlotter", "max_forks_repo_head_hexsha": "6cdc3954ee4a065d978c0248b00406366eafe237", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.2222222222, "max_line_length": 129, "alphanum_fraction": 0.628477201, "num_tokens": 4326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.9032942080055513, "lm_q1q2_score": 0.8041976126181865}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include <math.h>\n#include <fstream>\n\nconst static Eigen::IOFormat CSVFormat(Eigen::StreamPrecision, Eigen::DontAlignCols, \"\\t\", \"\\n\");\n\nint main()\n{\n\t// Initialization of vectors and matrices\n    Eigen::VectorXd a_1(3), a_2(3), a_3(3), x(3), y(3);\n\tEigen::MatrixXd matA(3,3);\n\n\t// Definition of vectors and matrices\n    a_1 << 1./2., sqrt(3.)/2., 0.;\n    a_2 << -1./2., sqrt(3.)/2., 0.;\n    a_3 << 0., 0., 1.;\n    matA << a_1, a_2, a_3;\n\n    // b), c) \n    x << 2., 0., 2.;\n    y << 1., 2.*sqrt(3.), 3;\n\n\t// Use PartialPivLU as it was told in the exercise. \n\tEigen::PartialPivLU<Eigen::MatrixXd> matPivLU(matA);\n\tEigen::VectorXd x_new = matPivLU.solve(x);\n\tEigen::VectorXd y_new = matPivLU.solve(y);\n\n\t// Produce U, L, P matrices and check if everything works as expected. \n\tEigen::MatrixXd U = matPivLU.matrixLU().triangularView<Eigen::Upper>();\n    Eigen::MatrixXd L = matPivLU.matrixLU().triangularView<Eigen::UnitLower>();\n    Eigen::MatrixXd P = matPivLU.permutationP();\n    Eigen::MatrixXd P_inv = P.inverse();\n    Eigen::MatrixXd matA_new = P_inv * L * U;\n\n\t// d) Do the same with the reversed (rev) basis vectors in the matrix.  \n\tEigen::MatrixXd matA_rev(3,3);\n    matA_rev << a_3, a_2, a_1;\n\n\t// Everything is done as before. \n\tEigen::PartialPivLU<Eigen::MatrixXd> matPivLU_rev(matA_rev);\n\tEigen::VectorXd x_new_rev = matPivLU_rev.solve(x);\n\tEigen::VectorXd y_new_rev = matPivLU_rev.solve(y);\n\n\tEigen::MatrixXd U_rev = matPivLU_rev.matrixLU().triangularView<Eigen::Upper>();\n    Eigen::MatrixXd L_rev = matPivLU_rev.matrixLU().triangularView<Eigen::UnitLower>();\n    Eigen::MatrixXd P_rev = matPivLU_rev.permutationP();\n    Eigen::MatrixXd P_inv_rev = P_rev.inverse();\n    Eigen::MatrixXd matA_new_rev = P_inv_rev * L_rev * U_rev;\n\n\tstd::ofstream output;\n\toutput.open(\"bin/Aufgabe1.txt\", std::ofstream::out | std::ofstream::trunc);\n\toutput << \"Matrix U:\\n\" << U << std::endl;\n\toutput << \"Matrix L:\\n\" <<L << std::endl;\n\toutput << \"Matrix P:\\n\" << P.format(CSVFormat) << std::endl;\n\toutput << \"Matrix A:\\n\" << matA.format(CSVFormat) << std::endl;\n\toutput << \"Matrix A_new:\\n\" << matA_new.format(CSVFormat) << std::endl;\n\toutput << \"Vector x:\\n\" << x.format(CSVFormat) << std::endl;\n\toutput << \"Vector x_new:\\n\" << x_new.format(CSVFormat) << std::endl;\n\toutput << \"Vector y:\\n\" << y.format(CSVFormat) << std::endl;\n\toutput << \"Vector y_new:\\n\" << y_new.format(CSVFormat) << std::endl;\n\n\n\toutput << \"Matrix U_rev:\\n\" << U_rev.format(CSVFormat) << std::endl;\n\toutput << \"Matrix L_rev:\\n\" <<L_rev.format(CSVFormat) << std::endl;\n\toutput << \"Matrix P_rev:\\n\" << P_rev.format(CSVFormat) << std::endl;\n\toutput << \"Matrix A_rev:\\n\" << matA_rev.format(CSVFormat) << std::endl;\n\toutput << \"Matrix A_new_rev:\\n\" << matA_new_rev.format(CSVFormat) << std::endl;\n\toutput << \"Vector x_rev:\\n\" << x.format(CSVFormat) << std::endl;\n\toutput << \"Vector x_new_rev:\\n\" << x_new_rev.format(CSVFormat) << std::endl;\n\toutput << \"Vector y_rev:\\n\" << y.format(CSVFormat) << std::endl;\n\toutput << \"Vector y_new_rev:\\n\" << y_new_rev.format(CSVFormat) << std::endl;\n\toutput.close();\n\n\t// Aufgabe 2 \n\n\t// Initialization of the vector and the matrix.\n\tEigen::VectorXd x2(10), y2(10);\n\tEigen::MatrixXd A(10, 2);\n\t\n\t// x2 and y2 are the input vectors. A is the matrix resulting from the original minimization problem.\n\tx2 <<  0., 2.5, -6.3, 4., -3.2, 5.3, 10.1, 9.5, -5.4, 12.7;\n\tA << x2, Eigen::VectorXd::Ones(10);\n\ty2 << 4., 4.3, -3.9, 6.5, 0.7, 8.6, 13., 9.9, -3.6, 15.1;\n\n\t// Transform A to a pseudo quadratic matrix as explained in the lecture and transform y2 as well. \n\tEigen::MatrixXd mat = A.transpose() * A;\n\tEigen::VectorXd b = A.transpose() * y2;\n\n\t// Use the same calculation as in Exercise 1 to solve the problem.\n\tEigen::PartialPivLU<Eigen::MatrixXd> matPivLU2(mat);\n\tEigen::Vector2d alpha = matPivLU2.solve(b);\n\n\tEigen::VectorXd result = A * alpha;\n\t// Save everything in a file to copy the results into an output file and to use it as input for a visualization script in python.\n\n\tEigen::MatrixXd xy(10, 2);\n\txy << x2, y2;\n\tstd::ofstream file;\n\tfile.open(\"bin/python_Aufgabe2.txt\", std::ofstream::out | std::ofstream::trunc);\n\tfile << \"# x, y\\n\" << xy.format(CSVFormat) << std::endl; \n\tfile << \"#m, n\\n \" << alpha.transpose().format(CSVFormat);\n\tfile.close();\n\n\n\t// std::ofstream file2;\n\t// file2.open(\"bin/python_result.txt\", std::ofstream::out | std::ofstream::trunc);\n\t\n\t// file2.close();\n    return 0;\n}", "meta": {"hexsha": "08bef1c0a71f3af9590bc420efbc58357517826c", "size": 4444, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Blatt1/src/main.cpp", "max_stars_repo_name": "lewis206/Computational_Physics", "max_stars_repo_head_hexsha": "06ad6126685eaf65f5834bfe70ebd91b33314395", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Blatt1/src/main.cpp", "max_issues_repo_name": "lewis206/Computational_Physics", "max_issues_repo_head_hexsha": "06ad6126685eaf65f5834bfe70ebd91b33314395", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Blatt1/src/main.cpp", "max_forks_repo_name": "lewis206/Computational_Physics", "max_forks_repo_head_hexsha": "06ad6126685eaf65f5834bfe70ebd91b33314395", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.036036036, "max_line_length": 130, "alphanum_fraction": 0.6563906391, "num_tokens": 1444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012686491107, "lm_q2_score": 0.8499711737573762, "lm_q1q2_score": 0.8039038144549001}}
{"text": "//\n// Created by Vlad Argunov on 13/11/2021.\n//\n\n#include \"nonuniform_grid.h\"\n\n#include <Eigen/Dense>\n#include <string>\n\nvoid create_nonuniform_grid(Eigen::VectorXd & x_range, double x_min, double x_max, double alpha, double beta, int m) {\n    /*The function transforms the grid in the non-uniform manner concentrating around the beta.\n     * Parameter alpha is responsible for the fraction of points lying in the neighbourhood of the beta.\n     * Important! The length of x_range must be of m + 1 exactly.*/\n\n    double xi;\n    double dxi = (asinh((x_max - beta)/alpha) - asinh((x_min - beta)/alpha)) / m;\n\n    for (int i = 0; i < m + 1; ++i) {\n        xi = asinh(- beta / alpha) + i * dxi;\n        x_range(i,0) = beta + alpha * sinh(xi);\n    }\n}\n", "meta": {"hexsha": "5b2e9d170b120c917861987f5f8aaadff0f0fddf", "size": 748, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/nonuniform_grid.cpp", "max_stars_repo_name": "vladargunov/QuantKit", "max_stars_repo_head_hexsha": "858f58f6ed6f3ed2b55a618639bcbb82e9ef5bb9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/nonuniform_grid.cpp", "max_issues_repo_name": "vladargunov/QuantKit", "max_issues_repo_head_hexsha": "858f58f6ed6f3ed2b55a618639bcbb82e9ef5bb9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/nonuniform_grid.cpp", "max_forks_repo_name": "vladargunov/QuantKit", "max_forks_repo_head_hexsha": "858f58f6ed6f3ed2b55a618639bcbb82e9ef5bb9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5217391304, "max_line_length": 118, "alphanum_fraction": 0.6524064171, "num_tokens": 210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338079816758, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.8033456728452399}}
{"text": "/**\n * @file contourplot.cc\n * @brief NPDE homework ContourPlot code\n * @author Unknown, Oliver Rietmann\n * @date 25.03.2021\n * @copyright Developed at ETH Zurich\n */\n\n#include \"contourplot.h\"\n\n#include <Eigen/Core>\n\nnamespace ContourPlot {\n\n/* SAM_LISTING_BEGIN_0 */\nEigen::Matrix<double, 2, Eigen::Dynamic> crookedEgg() {\n#if SOLUTION\n  auto gradF = [](Eigen::Vector2d x) -> Eigen::Vector2d {\n    return 4.0 * x.squaredNorm() * x - 3.0 * x.cwiseAbs2();\n  };\n  Eigen::Vector2d y0(1.0, 0.0);\n  double T = 4.0;\n  return computeIsolinePoints(gradF, y0, T);\n#else\n  //====================\n  // Your code goes here\n  // Replace the following dummy return value\n  // by the matrix containing the isoline points:\n  return Eigen::Matrix<double, 2, 42>::Zero();\n  //====================\n#endif\n}\n/* SAM_LISTING_END_0 */\n\n}  // namespace ContourPlot\n", "meta": {"hexsha": "ef47eabee91bda76107e867cecdb8321573eaaa2", "size": 841, "ext": "cc", "lang": "C++", "max_stars_repo_path": "developers/ContourPlot/mastersolution/contourplot.cc", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "developers/ContourPlot/mastersolution/contourplot.cc", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "developers/ContourPlot/mastersolution/contourplot.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 23.3611111111, "max_line_length": 59, "alphanum_fraction": 0.6373365042, "num_tokens": 255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765187126078, "lm_q2_score": 0.8791467595934565, "lm_q1q2_score": 0.8032557507428192}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n// Solves an eigenvalue problem, print out the solution plus some checks:\n\nint main(int argc, char **argv) {\n\n  Eigen::VectorXd Y(2);\n  Y(0)= 1.0;\n  Y(1)= 3.0;\n\n  Eigen::MatrixXd A(2,2);\n  A(0,0)= 1.0; A(0,1)=2.0;\n  A(1,0)= 2.0; A(1,1)=9.0;\n\n  Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> s(A);\n  Eigen::VectorXd  val=s.eigenvalues();\n  Eigen::MatrixXd  vec=s.eigenvectors();\n\n  std::cout << \"Eigenvalues:\\n \"  << val << std::endl;\n  std::cout << std::endl;\n\n  std::cout << \"Eigenvectors A:\\n \" << vec << std::endl;\n  std::cout << std::endl;\n\n  std::cout << \"A\u1d40\u22c5A:\\n\" << vec.transpose()*vec << std::endl;\n  std::cout << std::endl;\n\n  std::cout << \"Reconstituted original matrix:\\n\" <<  vec*val.asDiagonal()*vec.transpose() << std::endl;\n  std::cout << std::endl;\n\n\n\n}\n", "meta": {"hexsha": "0b1f264cb6d32ddc1529f3e513d982624d0957e6", "size": 813, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CH3/EIGENEX1/eigenEx1.cpp", "max_stars_repo_name": "acastellanos95/AppCompPhys", "max_stars_repo_head_hexsha": "920a7ba707e92f1ef92fba9d97323863994f0b1a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CH3/EIGENEX1/eigenEx1.cpp", "max_issues_repo_name": "acastellanos95/AppCompPhys", "max_issues_repo_head_hexsha": "920a7ba707e92f1ef92fba9d97323863994f0b1a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CH3/EIGENEX1/eigenEx1.cpp", "max_forks_repo_name": "acastellanos95/AppCompPhys", "max_forks_repo_head_hexsha": "920a7ba707e92f1ef92fba9d97323863994f0b1a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.9117647059, "max_line_length": 104, "alphanum_fraction": 0.6014760148, "num_tokens": 293, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799410139922, "lm_q2_score": 0.8333245891029456, "lm_q1q2_score": 0.8031415233311462}}
{"text": "// compile with: g++ template_structured_matrix_vector.cpp -I/usr/include/eigen3 -lmgl\n\n//#include <chrono>\n#include <iostream>\n#include <iomanip>\n//#include <limits>\n//#include <ratio>\n#include <vector>\n\n#include <Eigen/Dense>\n#include <mgl2/mgl.h>\n\nusing namespace Eigen;\n\n/* \\brief compute $\\mathbf{A}\\mathbf{x}$\n * \\mathbf{A} is defined by $(\\mathbf{A})_{i,j} := \\min {i,j}$\n * \\param[in] x vector x for computation of A*x = y\n * \\param[out] y = A*x\n */\nvoid multAminSlow(const VectorXd & x, VectorXd & y) {\n    unsigned int n = x.size();\n\n    VectorXd one = VectorXd::Ones(n);\n    VectorXd linsp = VectorXd::LinSpaced(n,1,n);\n    y = ( ( one * linsp.transpose() )\n          .cwiseMin( linsp * one.transpose()) ) * x;\n}\n\n/* \\brief compute $\\mathbf{A}\\mathbf{x}$\n * \\mathbf{A} is defined by $(\\mathbf{A})_{i,j} := \\min {i,j}$\n * Instead of a \"Matlab style\" construcion of the product,\n * we use simple loops.\n * \\param[in] x vector x for computation of A*x = y\n * \\param[out] y = A*x\n */\nvoid multAminLoops(const VectorXd & x, VectorXd & y) {\n    unsigned int n = x.size();\n\n    MatrixXd A(n,n);\n\n    for(unsigned int i = 0; i < n; ++i) {\n        for(unsigned int j = 0; j < n; ++j) {\n            A(i,j) = std::min(i+1,j+1);\n        }\n    }\n    y = A * x;\n}\n\n/* \\brief compute $\\mathbf{A}\\mathbf{x}$\n * This function has optimal complexity.\n * \\mathbf{A} is defined by $(\\mathbf{A})_{i,j} := \\min {i,j}$\n * \\param[in] x vector x for computation of A*x = y\n * \\param[out] y = A*x\n */\nvoid multAmin(const VectorXd & x, VectorXd & y) {\n    unsigned int n = x.size();\n    y = VectorXd::Zero(n);\n\n    VectorXd sum_left(n);\n    VectorXd sum_right(n);\n\n    sum_left(0) = 0;\n    for(int i = 1; i < n; i++) {\n      sum_left(i) = sum_left(i - 1) + i * x(i - 1);\n    }\n\n    sum_right(n - 1) = x(n - 1);\n    for(int i = n - 2; i >= 0; i--) {\n      sum_right(i) = sum_right(i + 1) + x(i);\n    }\n\n    for(int i = 0; i < n; i++) {\n      y(i) = sum_left(i) + (i + 1) * sum_right(i);\n    }\n}\n\nint main(void) {\n    // Testing correctness of the code\n    unsigned int M = 10;\n    VectorXd xa = VectorXd::Random(M);\n    VectorXd ys, yf;\n\n    multAmin(xa, yf);\n    multAminSlow(xa, ys);\n    // Error should be small\n    std::cout << \"||ys-yf|| = \" << (ys - yf).norm() << std::endl;\n\n\n    unsigned int nLevels = 9;\n  \tunsigned int *n = new unsigned int[nLevels];\n  \tdouble *minTime = new double[nLevels];\n  \tdouble *minTimeLoops = new double[nLevels];\n  \tdouble *minTimeEff = new double[nLevels];\n\n  \tn[0] = 4;\n  \tfor (unsigned int i=1; i<nLevels; i++)\n  \t\tn[i] = 2*n[i-1];\n\n  \t//TODO: Point (c)\n\n    // Plotting with MathGL\n    double nMgl[nLevels];\n    double ref1[nLevels], ref2[nLevels];\n    for (int i=0; i<nLevels; i++) {\n    \tnMgl[i] = n[i];\n    \tref1[i] = 1e-8*pow(n[i],2);\n    \tref2[i] = 1e-7*n[i];\n    }\n\n    mglData matSize;\n    matSize.Link(nMgl, nLevels);\n\n    mglData data1, data2;\n    mglData dataRef1, dataRef2;\n  \tdata1.Link(minTime, nLevels);\n  \tdata2.Link(minTimeEff, nLevels);\n  \tdataRef1.Link(ref1,nLevels);\n  \tdataRef2.Link(ref2,nLevels);\n\n  \tmglGraph *gr = new mglGraph;\n    gr->Title(\"Runtime of multAmin\");\n  \tgr->SetRanges(n[0],n[0]*pow(2,nLevels-1),1e-6,1e+1);  gr->SetFunc(\"lg(x)\",\"lg(y)\");\n  \tgr->Axis();\n  \tgr->Plot(matSize,data1,\"k +\"); gr->AddLegend(\"slow\",\"k +\");\n  \tgr->Plot(matSize,data2,\"r +\"); gr->AddLegend(\"efficient\",\"r +\");\n  \tgr->Plot(matSize,dataRef1,\"k\"); gr->AddLegend(\"O(n^2)\",\"k\");\n  \tgr->Plot(matSize,dataRef2,\"r\"); gr->AddLegend(\"O(n)\",\"r\");\n  \tgr->Label('x',\"Matrix size [n]\",0);\n  \tgr->Label('y', \"Runtime [s]\",0);\n    gr->Legend(2);\n\t  gr->WriteFrame(\"multAmin_comparison.eps\");\n\n\n    // The following code is just for demonstration purposes.\n    // Build Matrix B with dimension 10x10\n    unsigned int nn = 10;\n    MatrixXd B = MatrixXd::Zero(nn,nn);\n    for(unsigned int i = 0; i < nn; ++i) {\n        B(i,i) = 2;\n        if(i < nn-1) B(i+1,i) = -1;\n        if(i > 0) B(i-1,i) = -1;\n    }\n    B(nn-1,nn-1) = 1;\n\n    // Point (e)\n    MatrixXd A(nn, nn);\n    for(unsigned int i = 0; i < nn; ++i) {\n        for(unsigned int j = 0; j < nn; ++j) {\n            A(i,j) = std::min(i + 1, j + 1);\n        }\n    }\n\n    // We observe that A is the Inverse of B since AB = I\n    std::cout << A * B << std::endl;\n}\n", "meta": {"hexsha": "52916b4a11dd303f18cab1472c2398b45aab27c4", "size": 4236, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "exercise_1/structured_matrix_vector.cpp", "max_stars_repo_name": "azurite/numCSE18-code", "max_stars_repo_head_hexsha": "f7104305375954a0528d366f8460bf8033d20f0a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-13T19:08:32.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-13T19:08:32.000Z", "max_issues_repo_path": "exercise_1/structured_matrix_vector.cpp", "max_issues_repo_name": "azurite/numCSE18-code", "max_issues_repo_head_hexsha": "f7104305375954a0528d366f8460bf8033d20f0a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exercise_1/structured_matrix_vector.cpp", "max_forks_repo_name": "azurite/numCSE18-code", "max_forks_repo_head_hexsha": "f7104305375954a0528d366f8460bf8033d20f0a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1538461538, "max_line_length": 86, "alphanum_fraction": 0.5583097262, "num_tokens": 1472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418137109956, "lm_q2_score": 0.8688267898240861, "lm_q1q2_score": 0.8029191653487329}}
{"text": "\r\n// Copyright Christopher Kormanyos 2013.\r\n// Copyright Paul A. Bristow 2013.\r\n// Copyright John Maddock 2013.\r\n\r\n// Distributed under the Boost Software License, Version 1.0.\r\n// (See accompanying file LICENSE_1_0.txt or\r\n// copy at http://www.boost.org/LICENSE_1_0.txt).\r\n\r\n#ifdef _MSC_VER\r\n#  pragma warning (disable : 4512) // assignment operator could not be generated.\r\n#  pragma warning (disable : 4996) // assignment operator could not be generated.\r\n#endif\r\n\r\n#include <iostream>\r\n#include <limits>\r\n#include <vector>\r\n#include <algorithm>\r\n#include <iomanip>\r\n#include <iterator>\r\n\r\n//[neumann_zeros_example_1\r\n\r\n/*`[h5 Calculating zeros of the Neumann function.]\r\nThis example also shows how Boost.Math and Boost.Multiprecision can be combined to provide\r\na many decimal digit precision. For 50 decimal digit precision we need to include\r\n*/\r\n\r\n  #include <boost/multiprecision/cpp_dec_float.hpp>\r\n\r\n/*`and a `typedef` for `float_type` may be convenient\r\n(allowing a quick switch to re-compute at built-in `double` or other precision)\r\n*/\r\n  typedef boost::multiprecision::cpp_dec_float_50 float_type;\r\n\r\n//`To use the functions for finding zeros of the `cyl_neumann` function we need:\r\n\r\n  #include <boost/math/special_functions/bessel.hpp>\r\n//] [/neumann_zerso_example_1]\r\n\r\nint main()\r\n{\r\n  try\r\n  {\r\n    {\r\n//[neumann_zeros_example_2\r\n/*`The Neumann (Bessel Y) function zeros are evaluated very similarly:\r\n*/\r\n    using boost::math::cyl_neumann_zero;\r\n    double zn = cyl_neumann_zero(2., 1);\r\n    std::cout << \"cyl_neumann_zero(2., 1) = \" << zn << std::endl;\r\n\r\n    std::vector<float> nzeros(3); // Space for 3 zeros.\r\n    cyl_neumann_zero<float>(2.F, 1, nzeros.size(), nzeros.begin());\r\n\r\n    std::cout << \"cyl_neumann_zero<float>(2.F, 1, \";\r\n    // Print the zeros to the output stream.\r\n    std::copy(nzeros.begin(), nzeros.end(),\r\n              std::ostream_iterator<float>(std::cout, \", \"));\r\n\r\n    std::cout << \"\\n\"\"cyl_neumann_zero(static_cast<float_type>(220)/100, 1) = \" \r\n      << cyl_neumann_zero(static_cast<float_type>(220)/100, 1) << std::endl;\r\n    // 3.6154383428745996706772556069431792744372398748422\r\n\r\n//] //[/neumann_zeros_example_2]\r\n    }\r\n  }\r\n  catch (std::exception ex)\r\n  {\r\n    std::cout << \"Thrown exception \" << ex.what() << std::endl;\r\n  }\r\n} // int main()\r\n\r\n/*\r\n Output:\r\n\r\ncyl_neumann_zero(2., 1) = 3.38424\r\ncyl_neumann_zero<float>(2.F, 1,\r\n3.38424\r\n6.79381\r\n10.0235\r\n3.61544\r\n*/\r\n\r\n\r\n", "meta": {"hexsha": "741d2946d0af21b2ca251428a6f7845d7457155b", "size": 2437, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/math/example/neumann_zeros_example_1.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 85.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T20:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T20:38:31.000Z", "max_issues_repo_path": "libs/boost/libs/math/example/neumann_zeros_example_1.cpp", "max_issues_repo_name": "flingone/frameworks_base_cmds_remoted", "max_issues_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/boost/libs/math/example/neumann_zeros_example_1.cpp", "max_forks_repo_name": "flingone/frameworks_base_cmds_remoted", "max_forks_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T16:33:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T05:04:39.000Z", "avg_line_length": 28.3372093023, "max_line_length": 91, "alphanum_fraction": 0.6745999179, "num_tokens": 679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.921921841290738, "lm_q2_score": 0.8705972650509008, "lm_q1q2_score": 0.8026226336184071}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n#include <ctime>\n#define     N   7\n\n//! \\brief Compute an ONB of the space orthogonal to $v$\n//! \\param[in] v vector $ v \\in \\mathbb{R}^n \\setminus \\{ 0 \\} $\n//! \\param[out] Z matrix $ Z \\in \\mathbb{R}^{n-1 \\times n} $\nvoid houserefl(const Eigen::VectorXd & v, Eigen::MatrixXd & Z)\n{\n    unsigned int n = v.size();\n    Eigen::VectorXd w = v.normalized();\n    Eigen::VectorXd u=w;\n    u(0) += 1;\n    Eigen::VectorXd  q=u.normalized();\n    Eigen::MatrixXd X = Eigen::MatrixXd::Identity(n, n) - 2*q*q.transpose();\n    Z = X.rightCols(n-1);\n}\n\n\nint main(int argc, char ** argv) {\n    // Check what houserefl does to random vector\n    srand((unsigned int) time(0));\n    unsigned int n = N;\n    if(argc >= 2) n = std::atoi(argv[1]);\n    \n    Eigen::VectorXd v = Eigen::VectorXd::Random(n); // Not truly random if missing srand\n    Eigen::MatrixXd Z;\n    \n    houserefl(v, Z);\n    \n    std::cout << \"v = \" << v << std::endl;\n    std::cout << \"Z = \" << Z << std::endl;\n}\n", "meta": {"hexsha": "315cdd8736c7028e73531350dc6a25d9975769bf", "size": 1006, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/solutions/solution_0/houserefl.cpp", "max_stars_repo_name": "valentinjacot/backupETHZ", "max_stars_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:21:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:21:30.000Z", "max_issues_repo_path": "Nummerical Methods for CSE/solutions/solution_0/houserefl.cpp", "max_issues_repo_name": "valentinjacot/backupETHZ", "max_issues_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Nummerical Methods for CSE/solutions/solution_0/houserefl.cpp", "max_forks_repo_name": "valentinjacot/backupETHZ", "max_forks_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7428571429, "max_line_length": 88, "alphanum_fraction": 0.5795228628, "num_tokens": 310, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.944176852582231, "lm_q2_score": 0.8499711832583695, "lm_q1q2_score": 0.802523116594482}}
{"text": "#include <iostream>\n#include <armadillo>\n#include <stdlib.h>\n\n#define CLOSE_TO_ZERO 0.00001\n\nusing namespace std;\nusing namespace arma;\n\n/**\n * Gauss Elimination Without Pivoting\n * @param  aug_mat Augmented Matrix\n * @return         Solution Vector\n */\nvec gauss_elimination(mat aug_mat) {\n    //: Check for Singularity\n    mat coeff_matrix = aug_mat.submat(0, 0, aug_mat.n_rows - 1, aug_mat.n_cols - 2);\n    double determinant_coeff_mat = det(coeff_matrix);\n\n    if (abs(determinant_coeff_mat) < CLOSE_TO_ZERO) {\n        cout << \"[ERR] Singular Coeffecient Matrix.\";\n        exit (EXIT_FAILURE);\n    }\n\n    //: Row Eliminations\n    for (int i = 0; i < aug_mat.n_rows - 1; ++i) {\n        for (int j = i+1; j < aug_mat.n_rows; ++j) {\n            double ratio = aug_mat(j, i) / aug_mat(i, i);\n            aug_mat.row(j) = aug_mat.row(j) - ratio * aug_mat.row(i);\n        }\n    }\n\n    for (int i = aug_mat.n_rows - 1; i > 0; --i) {\n        for (int j = i-1; j >= 0; --j) {\n            double ratio = aug_mat(j, i) / aug_mat(i, i);\n            aug_mat.row(j) = aug_mat.row(j) - ratio * aug_mat.row(i);\n        }\n    }\n\n    // Calculating the X. Divide the last column (B) of the Augmented Matrix by the\n    // Diagonal of the Augmenterd matrix.\n    vec x = aug_mat.col(aug_mat.n_cols - 1) / aug_mat.diag();\n\n    return x;\n}\n\n/**\n * Gauss Elimination With Pivoting\n * @param  aug_mat Augmented Matrix\n * @return         Solution Vector\n */\nvec gauss_elimination_pivoted(mat aug_mat) {\n    //: Check for Singularity\n    mat coeff_matrix = aug_mat.submat(0, 0, aug_mat.n_rows - 1, aug_mat.n_cols - 2);\n    double determinant_coeff_mat = det(coeff_matrix);\n\n    if (abs(determinant_coeff_mat) < CLOSE_TO_ZERO) {\n        cout << \"[ERR] Singular Coeffecient Matrix.\";\n        exit (EXIT_FAILURE);\n    }\n\n    //: Pivoting\n    for (int i = 0; i < aug_mat.n_cols-1; ++i) {\n        uword r;\n        aug_mat.col(i).max(r);\n        aug_mat.swap_rows(r, i);\n    }\n\n    //: Row Eliminations\n    for (int i = 0; i < aug_mat.n_rows - 1; ++i) {\n        for (int j = i+1; j < aug_mat.n_rows; ++j) {\n            double ratio = aug_mat(j, i) / aug_mat(i, i);\n            aug_mat.row(j) = aug_mat.row(j) - ratio * aug_mat.row(i);\n        }\n    }\n\n    for (int i = aug_mat.n_rows - 1; i > 0; --i) {\n        for (int j = i-1; j >= 0; --j) {\n            double ratio = aug_mat(j, i) / aug_mat(i, i);\n            aug_mat.row(j) = aug_mat.row(j) - ratio * aug_mat.row(i);\n        }\n    }\n\n    // Calculating the X. Divide the last column (B) of the Augmented Matrix by the\n    // Diagonal of the Augmenterd matrix.\n    vec x = aug_mat.col(aug_mat.n_cols - 1) / aug_mat.diag();\n\n    return x;\n}\n\n/**\n * L U Decomposition\n * @param  aug_mat Augmented Matrix\n * @return         Solution Vector\n */\nvec l_u_decomposition(mat aug_mat) {\n    mat coeff_matrix = aug_mat.submat(0, 0, aug_mat.n_rows - 1, aug_mat.n_cols - 2);\n\n    //: Declare l and u matrices.\n    mat l(size(coeff_matrix)), u(size(coeff_matrix));\n\n    //: Declare column vectors.\n    colvec b, x, y;\n\n    //: Decompose B from Augmented Matrix.\n    b = aug_mat.col(aug_mat.n_cols - 1);\n\n    //: Check for Singularity\n    double determinant_coeff_mat = det(coeff_matrix);\n\n    if (abs(determinant_coeff_mat) < CLOSE_TO_ZERO) {\n        cout << \"[ERR] Singular Coeffecient Matrix.\";\n        exit (EXIT_FAILURE);\n    }\n\n    //: Identity matrix\n    l.eye();\n    //: Prepare U\n    u = coeff_matrix;\n\n    //: Calculate L and U\n    for (int i = 0; i < coeff_matrix.n_rows-1; ++i) {\n        for (int j = i+1; j < coeff_matrix.n_rows; ++j) {\n            double ratio = u(j, i) / u(i, i);\n\n            u.row(j) = u.row(j) - ratio*u.row(i);\n            l(j, i) = ratio;\n        }\n    }\n\n    //: b is B vector for y\n    y = (l.i()) * b;\n\n    //: y is B vector for x\n    x = (u.i()) * y;\n\n    return x;\n}\n\n/**\n * Gauss Jacobi Method\n * NOTE: This method does NOT guarantee a solution.\n * @param  aug_mat Augmented Matrix\n * @return         Solution Vector\n */\nvec gauss_jacobi(mat aug_mat) {\n    mat coeff_matrix = aug_mat.submat(0, 0, aug_mat.n_rows - 1, aug_mat.n_cols - 2);\n\n    //: Declare column vectors.\n    colvec x, xi, b;\n\n    x.resize(coeff_matrix.n_cols);\n    x.zeros();\n    xi.resize(coeff_matrix.n_cols);\n    xi.zeros();\n\n    //: Decompose B from Augmented Matrix.\n    b = aug_mat.col(aug_mat.n_cols - 1);\n\n    //: Check for Singularity\n    double determinant_coeff_mat = det(coeff_matrix);\n\n    if (abs(determinant_coeff_mat) < CLOSE_TO_ZERO) {\n        cout << \"[ERR] Singular Coeffecient Matrix.\";\n        exit (EXIT_FAILURE);\n    }\n\n    int count=0;\n    while(++count < 50) {\n        for (int i = 0 ; i < coeff_matrix.n_cols ; ++i) {\n            double sigma = 0;\n            for (int j = 0; j < coeff_matrix.n_cols ; ++j) {\n                if (i != j) {\n                    sigma = sigma + coeff_matrix(i, j) * x(j);\n                }\n            }\n            xi(i) = (b(i) - sigma) / coeff_matrix(i, i);\n        }\n        //: Update X\n        x = xi;\n    }\n\n    return x;\n}\n\n/**\n * Gauss Seidel Method\n * NOTE: This method does NOT guarantee a solution.\n * @param  aug_mat Augmented Matrix\n * @return         Solution Vector\n */\nvec gauss_seidel(mat aug_mat) {\n    mat coeff_matrix = aug_mat.submat(0, 0, aug_mat.n_rows - 1, aug_mat.n_cols - 2);\n\n    //: Declare column vectors.\n    colvec x, xi, b;\n\n    x.resize(coeff_matrix.n_cols);\n    x.zeros();\n    xi.resize(coeff_matrix.n_cols);\n    xi.zeros();\n\n    //: Decompose B from Augmented Matrix.\n    b = aug_mat.col(aug_mat.n_cols - 1);\n\n    //: Check for Singularity\n    double determinant_coeff_mat = det(coeff_matrix);\n\n    if (abs(determinant_coeff_mat) < CLOSE_TO_ZERO) {\n        cout << \"[ERR] Singular Coeffecient Matrix.\";\n        exit (EXIT_FAILURE);\n    }\n\n    int count=0;\n    while(++count < 50) {\n        for (int i = 0 ; i < coeff_matrix.n_cols ; ++i) {\n            double sigma = 0;\n            for (int j = 0; j < coeff_matrix.n_cols ; ++j) {\n                if (i != j) {\n                    sigma = sigma + coeff_matrix(i, j) * xi(j);\n                }\n            }\n            xi(i) = (b(i) - sigma) / coeff_matrix(i, i);\n        }\n        //: Update X\n        x = xi;\n    }\n\n    return x;\n}\n\n/**\n * Main Function\n * @param  argc Commandline Argument Counts\n * @param  argv Commandline Argument Vectors\n * @return      Exit Status\n */\nint main(int argc, char** argv) {\n\n    //: The Augmented Matrix needs to be put here.\n    mat aug_mat = {\n        {2, 1, 11},\n        {5, 7, 13}\n    };\n\n    gauss_elimination(aug_mat).print(\"Gauss Elimination Without Pivoting:\");\n    gauss_elimination_pivoted(aug_mat).print(\"Pivoted Gaussian Elimination\");\n    l_u_decomposition(aug_mat).print(\"L U Decomposition\");\n    gauss_jacobi(aug_mat).print(\"Gauss Jacobi\");\n    gauss_seidel(aug_mat).print(\"Gauss Seidel\");\n\n    return 0;\n}\n", "meta": {"hexsha": "85ee61f10b9becaf58e9b83b20417e07633062e9", "size": 6822, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gauss_elimination/system.cpp", "max_stars_repo_name": "PrashntS/numerical-methods", "max_stars_repo_head_hexsha": "5aeb2573bdfd464200ad7dbf14e6a29fd496e7fd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gauss_elimination/system.cpp", "max_issues_repo_name": "PrashntS/numerical-methods", "max_issues_repo_head_hexsha": "5aeb2573bdfd464200ad7dbf14e6a29fd496e7fd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gauss_elimination/system.cpp", "max_forks_repo_name": "PrashntS/numerical-methods", "max_forks_repo_head_hexsha": "5aeb2573bdfd464200ad7dbf14e6a29fd496e7fd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8582677165, "max_line_length": 84, "alphanum_fraction": 0.5690413369, "num_tokens": 1978, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625031628428, "lm_q2_score": 0.8615382147637196, "lm_q1q2_score": 0.8024905420942612}}
{"text": "// arcsine_example.cpp\n\n// Copyright John Maddock 2014.\n// Copyright  Paul A. Bristow 2014.\n\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n// Example for the arcsine Distribution.\n\n// Note: Contains Quickbook snippets in comments.\n\n//[arcsine_snip_1\n#include <boost/math/distributions/arcsine.hpp> // For arcsine_distribution.\n//] [/arcsine_snip_1]\n\n#include <iostream>\n#include <exception>\n#include <boost/math/tools/assert.hpp>\n\nint main()\n{\n  std::cout << \"Examples of Arcsine distribution.\" << std::endl;\n  std::cout.precision(3);  // Avoid uninformative decimal digits.\n\n  using boost::math::arcsine;\n\n  arcsine as; // Construct a default `double` standard [0, 1] arcsine distribution.\n\n//[arcsine_snip_2\n  std::cout << pdf(as, 1. / 2) << std::endl; // 0.637\n  // pdf has a minimum at x = 0.5\n//]  [/arcsine_snip_2]\n\n//[arcsine_snip_3\n  std::cout << pdf(as, 1. / 4) << std::endl; // 0.735\n//]  [/arcsine_snip_3]\n\n\n//[arcsine_snip_4\n  std::cout << cdf(as, 0.05) << std::endl; // 0.144\n//] [/arcsine_snip_4]\n\n//[arcsine_snip_5\n  std::cout << 2 * cdf(as, 1 - 0.975) << std::endl; // 0.202\n//] [/arcsine_snip_5]\n\n\n//[arcsine_snip_6\n  std::cout << 2 * cdf(complement(as, 0.975)) << std::endl; // 0.202\n//] [/arcsine_snip_6]\n\n//[arcsine_snip_7\n  std::cout << quantile(as, 1 - 0.2 / 2) << std::endl; //  0.976\n\n  std::cout << quantile(complement(as, 0.2 / 2)) << std::endl; // 0.976\n//] [/arcsine_snip_7]\n\n{\n//[arcsine_snip_8\n  using boost::math::arcsine_distribution;\n\n  arcsine_distribution<> as(2, 5); // Constructs a double arcsine distribution.\n  BOOST_MATH_ASSERT(as.x_min() == 2.);  // as.x_min() returns 2.\n  BOOST_MATH_ASSERT(as.x_max() == 5.);   // as.x_max()  returns 5.\n//] [/arcsine_snip_8]\n}\n    return 0;\n\n} // int main()\n\n/*\n[arcsine_output\n\nExample of Arcsine distribution\n0.637\n0.735\n0.144\n0.202\n0.202\n0.976\n0.976\n\n] [/arcsine_output]\n*/\n\n\n", "meta": {"hexsha": "3bea6d0ed52f05f0c5b94bc6d20db3d0fad04ac2", "size": 2002, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/arcsine_example.cpp", "max_stars_repo_name": "oleg-alexandrov/math", "max_stars_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 233.0, "max_stars_repo_stars_event_min_datetime": "2015-01-12T19:26:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T09:21:47.000Z", "max_issues_repo_path": "example/arcsine_example.cpp", "max_issues_repo_name": "oleg-alexandrov/math", "max_issues_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 626.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T18:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:19:18.000Z", "max_forks_repo_path": "example/arcsine_example.cpp", "max_forks_repo_name": "oleg-alexandrov/math", "max_forks_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 243.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T17:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T12:56:26.000Z", "avg_line_length": 22.2444444444, "max_line_length": 83, "alphanum_fraction": 0.6573426573, "num_tokens": 717, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026482819236, "lm_q2_score": 0.8740772466456689, "lm_q1q2_score": 0.8017933731510443}}
{"text": "#include <iostream>\n\nusing namespace std;\n\n#include <ctime>\n// Eigen core\n#include <Eigen/Core>\n// For operations on dense matrices (inverse, eigenvals, etc)\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\n#define MATRIX_SIZE 50\n\n/****************************\n * This program demonstrates the use of basic Eigen types\n ****************************/\n\nint main(int argc, char **argv) {\n  // All vectors and matrices in Eigen are Eigen::Matrix, which is a template\n  // class. Its first three parameters are: data type, row, column Declare a 2\u22173\n  // float matrix\n  Matrix<float, 2, 3> matrix_23;\n\n  // At the same time, Eigen provides many built\u2212in types via typedef, but the\n  // bottom layer is still Eigen::Matrix. For example, Vector3d is essentially\n  // Eigen::Matrix<double, 3, 1>, which is a three\u2212dimensional vector.\n  Vector3d v_3d;\n  // This is the same as above\n  Matrix<float, 3, 1> vd_3d;\n\n  // Matrix3d is essentially Eigen::Matrix<double, 3, 3>\n  Matrix3d matrix_33 = Matrix3d::Zero();  // Initialized to 0\n  // If you are not sure about the size of the matrix, you can use a matrix of\n  // dynamic size\n  Matrix<double, Dynamic, Dynamic> matrix_dynamic;\n  // Simpler way to define the same\n  MatrixXd matrix_x;\n  // There are still many types of this kind. We don't list them one by one.\n\n  // Here is the operation of the Eigen matrix\n  // input data (initialization)\n  matrix_23 << 1, 2, 3, 4, 5, 6;\n  // Initialize\n  cout << \"matrix 2x3 from 1 to 6: \\n\" << matrix_23 << endl;\n\n  // Use () to access the elements\n  cout << \"print matrix 2x3: \" << endl;\n  for (int i = 0; i < 2; i++) {\n    for (int j = 0; j < 3; j++) cout << matrix_23(i, j) << \"\\t\";\n    cout << endl;\n  }\n\n  // We can easily multiply a matrix with a vector (but actually still matrices and\n  // matrices)\n  v_3d << 3, 2, 1;\n  vd_3d << 4, 5, 6;\n\n  // In Eigen you can't mix two different types of matrices, like this is\n  // wrong Matrix<double, 2, 1> result_wrong_type = matrix_23 \u2217 v_3d;\n  // It should be explicitly converted\n  Matrix<double, 2, 1> result = matrix_23.cast<double>() * v_3d;\n  cout << \"[1,2,3;4,5,6]*[3,2,1]=\" << result.transpose() << endl;\n\n  Matrix<float, 2, 1> result2 = matrix_23 * vd_3d;\n  cout << \"[1,2,3;4,5,6]*[4,5,6]: \" << result2.transpose() << endl;\n\n  // Also you can't misjudge the dimensions of the matrix\n  // Try canceling the comments below to see what Eigen will report.\n  // Eigen::Matrix<double, 2, 3> result_wrong_dimension =\n  // matrix_23.cast<double>() \u2217 v_3d;\n\n  // Basic operations\n  matrix_33 = Matrix3d::Random();  // Random\n  cout << \"random matrix: \\n\" << matrix_33 << endl;\n  cout << \"transpose: \\n\" << matrix_33.transpose() << endl;  // Transpose\n  cout << \"sum: \" << matrix_33.sum() << endl;                // Sum of the elements\n  cout << \"trace: \" << matrix_33.trace() << endl;            // Trace\n  cout << \"times 10: \\n\" << 10 * matrix_33 << endl;          // Scalar\n  cout << \"inverse: \\n\" << matrix_33.inverse() << endl;      // Inverse\n  cout << \"det: \" << matrix_33.determinant() << endl;        // Matrix determinant\n\n  // Eigenvalues\n  // Real symmetric matrix can guarantee successful diagonalization\n  Matrix3d sym_mat = matrix_33.transpose() * matrix_33;\n  SelfAdjointEigenSolver<Matrix3d> eigen_solver(sym_mat);\n  cout << \"Eigen values = \\n\" << eigen_solver.eigenvalues() << endl;\n  cout << \"Eigen vectors = \\n\" << eigen_solver.eigenvectors() << endl;\n\n  // Solving equations\n  // We solve the equation of matrix_NN \u2217 x = v_Nd\n  // The size of N is defined in the previous macro, which is generated by a\n  // random number Direct inversion is the most direct, but the amount of\n  // inverse operations is large.\n\n  Matrix<double, MATRIX_SIZE, MATRIX_SIZE> matrix_NN =\n      MatrixXd::Random(MATRIX_SIZE, MATRIX_SIZE);\n  matrix_NN = matrix_NN * matrix_NN.transpose();  // Guarantee semi\u2212positive definite\n  Matrix<double, MATRIX_SIZE, 1> v_Nd = MatrixXd::Random(MATRIX_SIZE, 1);\n\n  clock_t time_stt = clock();  // timing\n  // Direct inversion\n  Matrix<double, MATRIX_SIZE, 1> x = matrix_NN.inverse() * v_Nd;\n  cout << \"time of normal inverse is \" << 1000 * (clock() - time_stt) / (double)CLOCKS_PER_SEC\n       << \"ms\" << endl;\n  cout << \"x = \" << x.transpose() << endl;\n\n  // Usually solved by matrix decomposition, such as QR decomposition, the speed\n  // will be much faster\n  time_stt = clock();\n  x = matrix_NN.colPivHouseholderQr().solve(v_Nd);\n  cout << \"time of Qr decomposition is \"\n       << 1000 * (clock() - time_stt) / (double)CLOCKS_PER_SEC << \"ms\" << endl;\n  cout << \"x = \" << x.transpose() << endl;\n\n  // For positive definite matrices, you can also use cholesky decomposition to\n  // solve equations.\n  time_stt = clock();\n  x = matrix_NN.ldlt().solve(v_Nd);\n  cout << \"time of ldlt decomposition is \"\n       << 1000 * (clock() - time_stt) / (double)CLOCKS_PER_SEC << \"ms\" << endl;\n  cout << \"x = \" << x.transpose() << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "c988a417ec1f445cd2b917bd93eaa411045f92f1", "size": 4904, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch3/useEigen/eigenMatrix.cpp", "max_stars_repo_name": "RachitB11/slambook2", "max_stars_repo_head_hexsha": "71364203ecd0bd0f2dd6e9d9bd4bd80f049bbfc4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch3/useEigen/eigenMatrix.cpp", "max_issues_repo_name": "RachitB11/slambook2", "max_issues_repo_head_hexsha": "71364203ecd0bd0f2dd6e9d9bd4bd80f049bbfc4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch3/useEigen/eigenMatrix.cpp", "max_forks_repo_name": "RachitB11/slambook2", "max_forks_repo_head_hexsha": "71364203ecd0bd0f2dd6e9d9bd4bd80f049bbfc4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.9206349206, "max_line_length": 94, "alphanum_fraction": 0.6443719413, "num_tokens": 1467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533126145179, "lm_q2_score": 0.8596637541053281, "lm_q1q2_score": 0.8015963152501456}}
{"text": "//NormalFunction.hpp\n//purpose: source file for normal distribution functions \n//author: bondxue\n//version: 1.0 11/18/2017\n\n#ifndef NORMALFUNCTION_HPP\n#define NORMALFUNCTION_HPP\n\n#include <cmath>\n#include <iostream>\n#include <boost/math/distributions/normal.hpp>\n#include <boost/math/distributions.hpp> // For non-member functions of distributions\nusing namespace boost::math;\n\nnamespace OPTION\n{\n\tnamespace EUROPEANOPTION\n\t{\n\t\t// standard Normal Cumulative Distribution Function\n\t\tdouble N(const double x)\n\t\t{\n\t\t\tnormal_distribution<double> myNormal(0.0, 1.0);\n\n\t\t\treturn cdf(myNormal, x);\n\t\t}\n\n\t\t// standard Normal Probability Distribution Function\n\t\tdouble n(const double x)\n\t\t{\n\t\t\tnormal_distribution<double> myNormal(0.0, 1.0);\n\n\t\t\treturn pdf(myNormal, x);\n\t\t}\n\t}\n}\n\n#endif\n\n\n", "meta": {"hexsha": "07c6de54e733858b8e6cb4737517df1402e4959c", "size": 781, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Part F Finite Difference Methods/Exercise F Finite Difference Methods/Level9/Level9Code/Level9Code/UtilitiesDJD/ExcelDriver/NormalFunction.hpp", "max_stars_repo_name": "bondxue/Option-Pricing-Model", "max_stars_repo_head_hexsha": "5f22df0ff31e90fd536eb216c5af19c697fb87b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Part F Finite Difference Methods/Exercise F Finite Difference Methods/Level9/Level9Code/Level9Code/UtilitiesDJD/ExcelDriver/NormalFunction.hpp", "max_issues_repo_name": "bondxue/Option-Pricing-Model", "max_issues_repo_head_hexsha": "5f22df0ff31e90fd536eb216c5af19c697fb87b2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Part F Finite Difference Methods/Exercise F Finite Difference Methods/Level9/Level9Code/Level9Code/UtilitiesDJD/ExcelDriver/NormalFunction.hpp", "max_forks_repo_name": "bondxue/Option-Pricing-Model", "max_forks_repo_head_hexsha": "5f22df0ff31e90fd536eb216c5af19c697fb87b2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.525, "max_line_length": 84, "alphanum_fraction": 0.7400768246, "num_tokens": 202, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897442783527, "lm_q2_score": 0.8519528057272543, "lm_q1q2_score": 0.8015084622373687}}
{"text": "#include <Eigen/Dense>\r\n#include <iostream>\r\n\r\nusing namespace Eigen;\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n  ArrayXXf a(3,3);\r\n  ArrayXXf b(3,3);\r\n  a << 1,2,3,\r\n       4,5,6,\r\n       7,8,9;\r\n  b << 1,2,3,\r\n       1,2,3,\r\n       1,2,3;\r\n       \r\n  // Adding two arrays\r\n  cout << \"a + b = \" << endl << a + b << endl << endl;\r\n\r\n  // Subtracting a scalar from an array\r\n  cout << \"a - 2 = \" << endl << a - 2 << endl;\r\n}\r\n", "meta": {"hexsha": "bba1cdbf28bf65eec51d0af2f9f3f67ca0fde757", "size": 423, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/eigen-eigen-323c052e1731/doc/examples/Tutorial_ArrayClass_addition.cpp", "max_stars_repo_name": "k4rth33k/dnnc-operators", "max_stars_repo_head_hexsha": "a7fe3f1240c12b3438558def71fbfcd4520446c3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-08-16T14:35:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-11T23:59:22.000Z", "max_issues_repo_path": "packages/eigen-eigen-323c052e1731/doc/examples/Tutorial_ArrayClass_addition.cpp", "max_issues_repo_name": "k4rth33k/dnnc-operators", "max_issues_repo_head_hexsha": "a7fe3f1240c12b3438558def71fbfcd4520446c3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-08-12T04:38:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T16:32:13.000Z", "max_forks_repo_path": "packages/eigen-eigen-323c052e1731/doc/examples/Tutorial_ArrayClass_addition.cpp", "max_forks_repo_name": "k4rth33k/dnnc-operators", "max_forks_repo_head_hexsha": "a7fe3f1240c12b3438558def71fbfcd4520446c3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-08-15T13:29:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-09T17:08:04.000Z", "avg_line_length": 17.625, "max_line_length": 55, "alphanum_fraction": 0.4657210402, "num_tokens": 152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628702, "lm_q2_score": 0.8652240860523328, "lm_q1q2_score": 0.8014603019709772}}
{"text": "#include <gtest/gtest.h>\n\n#include <opencv2/core.hpp>\n#include <opencv2/highgui.hpp>\n#include <opencv2/features2d/features2d.hpp>\n\n#include <libutils/timer.h>\n#include <phg/matching/gms_matcher.h>\n#include <phg/sfm/fmatrix.h>\n#include <phg/sfm/ematrix.h>\n#include <phg/sfm/sfm_utils.h>\n#include <phg/sfm/defines.h>\n#include <Eigen/SVD>\n#include <phg/sfm/triangulation.h>\n#include <phg/sfm/resection.h>\n#include <phg/utils/point_cloud_export.h>\n\n#include \"utils/test_utils.h\"\n\nnamespace {\n\n    void filterMatchesF(const std::vector<cv::DMatch> &matches, const std::vector<cv::KeyPoint> keypoints_query,\n                        const std::vector<cv::KeyPoint> keypoints_train, const cv::Matx33d &F, std::vector<cv::DMatch> &result, double threshold_px)\n    {\n        result.clear();\n\n        for (const cv::DMatch &match : matches) {\n            cv::Vec2f pt1 = keypoints_query[match.queryIdx].pt;\n            cv::Vec2f pt2 = keypoints_train[match.trainIdx].pt;\n\n            if (phg::epipolarTest(pt1, pt2, F, threshold_px)) {\n                result.push_back(match);\n            }\n        }\n    }\n\n    // Fundamental matrix has to be of rank 2. See Hartley & Zisserman, p.243\n    bool checkFmatrixSpectralProperty(const matrix3d &Fcv)\n    {\n        Eigen::MatrixXd F;\n        copy(Fcv, F);\n\n        Eigen::JacobiSVD<Eigen::MatrixXd> svd(F, Eigen::ComputeFullU | Eigen::ComputeFullV);\n        Eigen::VectorXd s = svd.singularValues();\n\n        std::cout << \"checkFmatrixSpectralProperty: s: \" << s.transpose() << std::endl;\n\n        double thresh = 1e10;\n        return s[0] > thresh * s[2] && s[1] > thresh * s[2];\n    }\n\n    // Essential matrix has to be of rank 2, and two non-zero singular values have to be equal. See Hartley & Zisserman, p.257\n    bool checkEmatrixSpectralProperty(const matrix3d &Fcv)\n    {\n        Eigen::MatrixXd F;\n        copy(Fcv, F);\n\n        Eigen::JacobiSVD<Eigen::MatrixXd> svd(F, Eigen::ComputeFullU | Eigen::ComputeFullV);\n        Eigen::VectorXd s = svd.singularValues();\n\n        std::cout << \"checkEmatrixSpectralProperty: s: \" << s.transpose() << std::endl;\n\n        double thresh = 1e10;\n\n        bool rank2 = s[0] > thresh * s[2] && s[1] > thresh * s[2];\n        bool equal = (s[0] < (1.0 + thresh) * s[1]) && (s[1] < (1.0 + thresh) * s[0]);\n\n        return rank2 && equal;\n    }\n\n    template <typename MAT>\n    double matRMS(const MAT &a, const MAT &b)\n    {\n        MAT d = (a - b);\n        d = d.mul(d);\n        double rms = std::sqrt(cv::sum(d)[0] / (a.cols * a.rows));\n        return rms;\n    }\n\n    vector3d relativeOrientationAngles(const matrix3d &R0, const vector3d &O0, const matrix3d &R1, const vector3d &O1)\n    {\n        vector3d a = R0 * vector3d{0, 0, 1};\n        vector3d b = O0 - O1;\n        vector3d c = R1 * vector3d{0, 0, 1};\n\n        double norma = cv::norm(a);\n        double normb = cv::norm(b);\n        double normc = cv::norm(c);\n\n        if (norma == 0 || normb == 0 || normc == 0) {\n            throw std::runtime_error(\"norma == 0 || normb == 0 || normc == 0\");\n        }\n\n        a /= norma;\n        b /= normb;\n        c /= normc;\n\n        vector3d cos_vals;\n\n        cos_vals[0] = a.dot(c);\n        cos_vals[1] = a.dot(b);\n        cos_vals[2] = b.dot(c);\n\n        return cos_vals;\n    }\n\n}\n\n#define TEST_EPIPOLAR_LINE(pt0, pt1, F, t, eps) \\\nEXPECT_FALSE(phg::epipolarTest(pt0, pt1, F, std::max(0.0, t - eps))); \\\nEXPECT_TRUE(phg::epipolarTest(pt0, pt1, F, t + eps));\n\nTEST (SFM, EpipolarDist) {\n\n    const vector2d pt0 = {0, 0};\n    const double eps = 1e-5;\n\n    {\n        // line: y = 0\n        const double l[3] = {0, 1, 0};\n        const matrix3d F = {0, 0, l[0], 0, 0, l[1], 0, 0, l[2]};\n\n        vector2d pt1;\n        double t;\n\n        pt1 = {0, 0};\n        t = 0;\n        TEST_EPIPOLAR_LINE(pt0, pt1, F, t, eps)\n\n        pt1 = {1000, 0};\n        t = 0;\n        TEST_EPIPOLAR_LINE(pt0, pt1, F, t, eps)\n\n        pt1 = {0, 1000};\n        t = 1000;\n        TEST_EPIPOLAR_LINE(pt0, pt1, F, t, eps)\n    }\n\n    {\n        // line: y = x\n        const double l[3] = {1, -1, 0};\n        const matrix3d F = {0, 0, l[0], 0, 0, l[1], 0, 0, l[2]};\n\n        vector2d pt1;\n        double t;\n\n        pt1 = {0, 0};\n        t = 0;\n        TEST_EPIPOLAR_LINE(pt0, pt1, F, t, eps)\n\n        pt1 = {1, 1};\n        t = 0;\n        TEST_EPIPOLAR_LINE(pt0, pt1, F, t, eps)\n\n        pt1 = {-1, -1};\n        t = 0;\n        TEST_EPIPOLAR_LINE(pt0, pt1, F, t, eps)\n\n        pt1 = {-1, 1};\n        t = std::sqrt(2);\n        TEST_EPIPOLAR_LINE(pt0, pt1, F, t, eps)\n\n        pt1 = {10, 0};\n        t = 10 / std::sqrt(2);\n        TEST_EPIPOLAR_LINE(pt0, pt1, F, t, eps)\n    }\n\n    {\n        // line: y = x + 1\n        const double l[3] = {1, -1, 1};\n        const matrix3d F = {0, 0, l[0], 0, 0, l[1], 0, 0, l[2]};\n\n        vector2d pt1;\n        double t;\n\n        pt1 = {0, 1};\n        t = 0;\n        TEST_EPIPOLAR_LINE(pt0, pt1, F, t, eps)\n\n        pt1 = {1, 2};\n        t = 0;\n        TEST_EPIPOLAR_LINE(pt0, pt1, F, t, eps)\n\n        pt1 = {-1, 0};\n        t = 0;\n        TEST_EPIPOLAR_LINE(pt0, pt1, F, t, eps)\n\n        pt1 = {-1, 2};\n        t = std::sqrt(2);\n        TEST_EPIPOLAR_LINE(pt0, pt1, F, t, eps)\n\n        pt1 = {10, 1};\n        t = 10 / std::sqrt(2);\n        TEST_EPIPOLAR_LINE(pt0, pt1, F, t, eps)\n    }\n}\n\nTEST (SFM, FmatrixSimple) {\n\n    std::vector<cv::Vec2d> pts0, pts1;\n    std::srand(1);\n    for (int i = 0; i < 8; ++i) {\n        pts0.push_back({(double) (std::rand() % 100), (double) (std::rand() % 100)});\n        pts1.push_back({(double) (std::rand() % 100), (double) (std::rand() % 100)});\n    }\n\n    matrix3d F = phg::findFMatrix(pts0, pts1);\n    matrix3d Fcv = phg::findFMatrixCV(pts0, pts1);\n\n    EXPECT_TRUE(checkFmatrixSpectralProperty(F));\n    EXPECT_TRUE(checkFmatrixSpectralProperty(Fcv));\n}\n\nTEST (SFM, EmatrixSimple) {\n\n    phg::Calibration calib(360, 240);\n    std::cout << \"EmatrixSimple: calib: \\n\" << calib.K() << std::endl;\n\n    std::vector<cv::Vec2d> pts0, pts1;\n    std::srand(1);\n    for (int i = 0; i < 8; ++i) {\n        pts0.push_back({(double) (std::rand() % calib.width()), (double) (std::rand() % calib.height())});\n        pts1.push_back({(double) (std::rand() % calib.width()), (double) (std::rand() % calib.height())});\n    }\n\n    matrix3d F = phg::findFMatrix(pts0, pts1, 10);\n    matrix3d E = phg::fmatrix2ematrix(F, calib, calib);\n\n    EXPECT_TRUE(checkEmatrixSpectralProperty(E));\n}\n\nTEST (SFM, EmatrixDecomposeSimple) {\n\n    phg::Calibration calib(360, 240);\n    std::cout << \"EmatrixSimple: calib: \\n\" << calib.K() << std::endl;\n\n    std::vector<cv::Vec2d> pts0, pts1;\n    std::srand(1);\n    for (int i = 0; i < 8; ++i) {\n        pts0.push_back({(double) (std::rand() % calib.width()), (double) (std::rand() % calib.height())});\n        pts1.push_back({(double) (std::rand() % calib.width()), (double) (std::rand() % calib.height())});\n    }\n\n    matrix3d F = phg::findFMatrix(pts0, pts1, 10);\n    matrix3d E = phg::fmatrix2ematrix(F, calib, calib);\n\n    matrix34d P0, P1;\n    phg::decomposeEMatrix(P0, P1, E, pts0, pts1, calib, calib);\n\n    matrix3d R;\n    R = P1.get_minor<3, 3>(0, 0);\n    vector3d T;\n    T(0) = P1(0, 3);\n    T(1) = P1(1, 3);\n    T(2) = P1(2, 3);\n\n    matrix3d E1 = phg::composeEMatrixRT(R, T);\n    matrix3d E2 = phg::composeFMatrix(P0, P1);\n\n    EXPECT_NE(E(2, 2), 0);\n    EXPECT_NE(E1(2, 2), 0);\n    EXPECT_NE(E2(2, 2), 0);\n\n    E /= E(2, 2);\n    E1 /= E1(2, 2);\n    E2 /= E2(2, 2);\n\n    double rms1 = matRMS(E, E1);\n    double rms2 = matRMS(E, E2);\n    double rms3 = matRMS(E1, E2);\n\n    std::cout << \"E: \\n\" << E << std::endl;\n    std::cout << \"E1: \\n\" << E1 << std::endl;\n    std::cout << \"E2: \\n\" << E2 << std::endl;\n    std::cout << \"RMS1: \" << rms1 << std::endl;\n    std::cout << \"RMS2: \" << rms2 << std::endl;\n    std::cout << \"RMS3: \" << rms3 << std::endl;\n\n    double eps = 1e-10;\n    EXPECT_LT(rms1, eps);\n    EXPECT_LT(rms2, eps);\n    EXPECT_LT(rms3, eps);\n}\n\nTEST (SFM, TriangulationSimple) {\n\n    vector4d X = {0, 0, 2, 1};\n\n    matrix34d P0 = matrix34d::eye();\n    vector3d x0 = {0, 0, 1};\n\n    // P1\n    vector3d O = {2, 0, 0};\n    double alpha = M_PI_4;\n    double s = std::sin(alpha);\n    double c = std::cos(alpha);\n    matrix3d R = { c, 0, s,\n                   0, 1, 0,\n                  -s, 0, c};\n    vector3d T = -R * O;\n    matrix34d P1 = {\n             R(0, 0), R(0, 1), R(0, 2), T[0],\n             R(1, 0), R(1, 1), R(1, 2), T[1],\n             R(2, 0), R(2, 1), R(2, 2), T[2]\n    };\n\n    // x1\n    vector3d x1 = {0, 0, 1};\n\n    std::cout << \"P1:\\n\" << P1 << std::endl;\n    std::cout << \"x2:\\n\" << P0 * X << std::endl;\n    std::cout << \"x3:\\n\" << P1 * X << std::endl;\n\n    matrix34d Ps[2] = {P0, P1};\n    vector3d xs[2] = {x0, x1};\n\n    vector4d X1 = phg::triangulatePoint(Ps, xs, 2);\n    std::cout << \"X1:\\n\" << X1 << std::endl;\n\n    EXPECT_NE(X1[3], 0);\n    X1 /= X1[3];\n\n    vector4d d = X - X1;\n    std::cout << \"|X - X1| = \" << cv::norm(d) << std::endl;\n\n    double eps = 1e-10;\n    EXPECT_LT(cv::norm(d), eps);\n}\n\nTEST (SFM, FmatrixMatchFiltering) {\n\n    using namespace cv;\n\n    cv::Mat img1 = cv::imread(\"data/src/test_sfm/saharov/IMG_3023.JPG\");\n    cv::Mat img2 = cv::imread(\"data/src/test_sfm/saharov/IMG_3024.JPG\");\n\n    std::cout << \"detecting points...\" << std::endl;\n    cv::Ptr<cv::FeatureDetector> detector = cv::SIFT::create();\n    std::vector<cv::KeyPoint> keypoints1, keypoints2;\n    cv::Mat descriptors1, descriptors2;\n    detector->detectAndCompute( img1, cv::noArray(), keypoints1, descriptors1 );\n    detector->detectAndCompute( img2, cv::noArray(), keypoints2, descriptors2 );\n\n    std::cout << \"matching points...\" << std::endl;\n    std::vector<std::vector<DMatch>> knn_matches;\n\n    Ptr<DescriptorMatcher> matcher = DescriptorMatcher::create(DescriptorMatcher::FLANNBASED);\n    matcher->knnMatch( descriptors1, descriptors2, knn_matches, 2 );\n\n    std::vector<DMatch> good_matches(knn_matches.size());\n    for (int i = 0; i < (int) knn_matches.size(); ++i) {\n        good_matches[i] = knn_matches[i][0];\n    }\n\n    std::cout << \"filtering matches GMS...\" << std::endl;\n    std::vector<DMatch> good_matches_gms;\n    phg::filterMatchesGMS(good_matches, keypoints1, keypoints2, img1.size(), img2.size(), good_matches_gms);\n\n    std::cout << \"filtering matches F...\" << std::endl;\n    std::vector<DMatch> good_matches_gms_plus_f;\n    std::vector<DMatch> good_matches_f;\n    double threshold_px = 3;\n    {\n        std::vector<cv::Vec2d> points1, points2;\n        for (const cv::DMatch &match : good_matches) {\n            cv::Vec2f pt1 = keypoints1[match.queryIdx].pt;\n            cv::Vec2f pt2 = keypoints2[match.trainIdx].pt;\n            points1.push_back(pt1);\n            points2.push_back(pt2);\n        }\n        matrix3d F = phg::findFMatrix(points1, points2, threshold_px);\n        filterMatchesF(good_matches, keypoints1, keypoints2, F, good_matches_f, threshold_px);\n    }\n    {\n        std::vector<cv::Vec2d> points1, points2;\n        for (const cv::DMatch &match : good_matches_gms) {\n            cv::Vec2f pt1 = keypoints1[match.queryIdx].pt;\n            cv::Vec2f pt2 = keypoints2[match.trainIdx].pt;\n            points1.push_back(pt1);\n            points2.push_back(pt2);\n        }\n        matrix3d F = phg::findFMatrix(points1, points2, threshold_px);\n        filterMatchesF(good_matches_gms, keypoints1, keypoints2, F, good_matches_gms_plus_f, threshold_px);\n    }\n\n    drawMatches(img1, img2, keypoints1, keypoints2, good_matches_gms, \"data/debug/test_sfm/matches_GMS.jpg\");\n    drawMatches(img1, img2, keypoints1, keypoints2, good_matches_f, \"data/debug/test_sfm/matches_F.jpg\");\n    drawMatches(img1, img2, keypoints1, keypoints2, good_matches_gms_plus_f, \"data/debug/test_sfm/matches_GMS_plus_F.jpg\");\n\n    std::cout << \"n matches gms: \" << good_matches_gms.size() << std::endl;\n    std::cout << \"n matches F: \" << good_matches_f.size() << std::endl;\n    std::cout << \"n matches gms + F: \" << good_matches_gms_plus_f.size() << std::endl;\n\n    EXPECT_GT(good_matches_gms_plus_f.size(), 0.5 * good_matches_gms.size());\n    EXPECT_GT(good_matches_f.size(), 0.5 * good_matches_gms.size());\n\n    EXPECT_GT(good_matches_f.size(), 0.5 * good_matches_gms_plus_f.size());\n    EXPECT_GT(good_matches_gms_plus_f.size(), 0.5 * good_matches_f.size());\n}\n\nnamespace {\n\n    void transform(matrix3d &R, vector3d &O)\n    {\n        matrix4d H = matrix4d::diag({1, -1, -1, 1});\n        matrix3d Rinv = H.inv().get_minor<3, 3>(0, 0);\n\n        auto tmp = H * vector4d({O[0], O[1], O[2], 1.0});\n        O = {tmp[0] / tmp[3], tmp[1] / tmp[3], tmp[2] / tmp[3]};\n        R = R * Rinv;\n    }\n\n}\n\nTEST (SFM, RelativePosition2View) {\n\n    using namespace cv;\n\n    const cv::Mat img1 = cv::imread(\"data/src/test_sfm/saharov/IMG_3023.JPG\");\n    const cv::Mat img2 = cv::imread(\"data/src/test_sfm/saharov/IMG_3024.JPG\");\n\n    const phg::Calibration calib0(img1.cols, img1.rows);\n    const phg::Calibration calib1(img2.cols, img2.rows);\n\n    std::cout << \"detecting points...\" << std::endl;\n    cv::Ptr<cv::FeatureDetector> detector = cv::SIFT::create();\n    std::vector<cv::KeyPoint> keypoints1, keypoints2;\n    cv::Mat descriptors1, descriptors2;\n    detector->detectAndCompute( img1, cv::noArray(), keypoints1, descriptors1 );\n    detector->detectAndCompute( img2, cv::noArray(), keypoints2, descriptors2 );\n\n    std::cout << \"matching points...\" << std::endl;\n    std::vector<std::vector<DMatch>> knn_matches;\n\n    Ptr<DescriptorMatcher> matcher = DescriptorMatcher::create(DescriptorMatcher::FLANNBASED);\n    matcher->knnMatch( descriptors1, descriptors2, knn_matches, 2 );\n\n    std::vector<DMatch> good_matches(knn_matches.size());\n    for (int i = 0; i < (int) knn_matches.size(); ++i) {\n        good_matches[i] = knn_matches[i][0];\n    }\n\n    std::cout << \"filtering matches GMS...\" << std::endl;\n    std::vector<DMatch> good_matches_gms;\n    phg::filterMatchesGMS(good_matches, keypoints1, keypoints2, img1.size(), img2.size(), good_matches_gms);\n\n    std::vector<cv::Vec2d> points1, points2;\n    for (const cv::DMatch &match : good_matches_gms) {\n        cv::Vec2f pt1 = keypoints1[match.queryIdx].pt;\n        cv::Vec2f pt2 = keypoints2[match.trainIdx].pt;\n        points1.push_back(pt1);\n        points2.push_back(pt2);\n    }\n\n    matrix3d F = phg::findFMatrix(points1, points2);\n    matrix3d E = phg::fmatrix2ematrix(F, calib0, calib1);\n\n    matrix34d P0, P1;\n    phg::decomposeEMatrix(P0, P1, E, points1, points2, calib0, calib1);\n\n    matrix3d R0, R1;\n    vector3d O0, O1;\n    phg::decomposeUndistortedPMatrix(R0, O0, P0);\n    phg::decomposeUndistortedPMatrix(R1, O1, P1);\n    transform(R0, O0);\n    transform(R1, O1);\n    P0 = phg::composeCameraMatrixRO(R0, O0);\n    P1 = phg::composeCameraMatrixRO(R1, O1);\n\n    std::cout << \"Camera positions: \" << std::endl;\n    std::cout << \"R0:\\n\" << R0 << std::endl;\n    std::cout << \"O0: \" << O0.t() << std::endl;\n    std::cout << \"R1:\\n\" << R1 << std::endl;\n    std::cout << \"O1: \" << O1.t() << std::endl;\n\n    {\n        vector3d relative_cos_vals = relativeOrientationAngles(R0, O0, R1, O1);\n        std::cout << \"relative_cos_vals: \" << relative_cos_vals << std::endl;\n        vector3d relative_cos_vals_expected = {0.966827, -0.141921, 0.115634};\n        EXPECT_LT(cv::norm(relative_cos_vals - relative_cos_vals_expected), 0.05);\n    }\n\n    std::cout << \"exporting point cloud...\" << std::endl;\n    std::vector<vector3d> point_cloud;\n    std::vector<cv::Vec3b> point_cloud_colors;\n\n    matrix34d Ps[2] = {P0, P1};\n    for (int i = 0; i < (int) good_matches_gms.size(); ++i) {\n        vector3d ms[2] = {calib0.unproject(points1[i]), calib1.unproject(points2[i])};\n        vector4d X = phg::triangulatePoint(Ps, ms, 2);\n\n        if (X(3) == 0) {\n            std::cerr << \"infinite point\" << std::endl;\n            continue;\n        }\n\n        point_cloud.push_back(vector3d{X(0) / X(3), X(1) / X(3), X(2) / X(3)});\n        point_cloud_colors.push_back(img1.at<cv::Vec3b>(points1[i][1], points1[i][0]));\n    }\n\n    point_cloud.push_back(O0);\n    point_cloud_colors.push_back(cv::Vec3b{0, 0, 255});\n    point_cloud.push_back(O0 + R0 * cv::Vec3d(0, 0, 1));\n    point_cloud_colors.push_back(cv::Vec3b(255, 0, 0));\n\n    point_cloud.push_back(O1);\n    point_cloud_colors.push_back(cv::Vec3b{0, 0, 255});\n    point_cloud.push_back(O1 + R1 * cv::Vec3d(0, 0, 1));\n    point_cloud_colors.push_back(cv::Vec3b(255, 0, 0));\n\n    std::cout << \"exporting \" << point_cloud.size() << \" points...\" << std::endl;\n    phg::exportPointCloud(point_cloud, \"data/debug/test_sfm/point_cloud_2_cameras.ply\", point_cloud_colors);\n}\n\nTEST (SFM, Resection) {\n\n    using namespace cv;\n\n    const cv::Mat img1 = cv::imread(\"data/src/test_sfm/saharov/IMG_3023.JPG\");\n    const cv::Mat img2 = cv::imread(\"data/src/test_sfm/saharov/IMG_3024.JPG\");\n\n    const phg::Calibration calib0(img1.cols, img1.rows);\n    const phg::Calibration calib1(img2.cols, img2.rows);\n\n    std::cout << \"detecting points...\" << std::endl;\n    cv::Ptr<cv::FeatureDetector> detector = cv::SIFT::create();\n    std::vector<cv::KeyPoint> keypoints1, keypoints2;\n    cv::Mat descriptors1, descriptors2;\n    detector->detectAndCompute( img1, cv::noArray(), keypoints1, descriptors1 );\n    detector->detectAndCompute( img2, cv::noArray(), keypoints2, descriptors2 );\n\n    std::cout << \"matching points...\" << std::endl;\n    std::vector<std::vector<DMatch>> knn_matches;\n\n    Ptr<DescriptorMatcher> matcher = DescriptorMatcher::create(DescriptorMatcher::FLANNBASED);\n    matcher->knnMatch( descriptors1, descriptors2, knn_matches, 2 );\n\n    std::vector<DMatch> good_matches(knn_matches.size());\n    for (int i = 0; i < (int) knn_matches.size(); ++i) {\n        good_matches[i] = knn_matches[i][0];\n    }\n\n    std::cout << \"filtering matches GMS...\" << std::endl;\n    std::vector<DMatch> good_matches_gms;\n    phg::filterMatchesGMS(good_matches, keypoints1, keypoints2, img1.size(), img2.size(), good_matches_gms);\n\n    std::vector<cv::Vec2d> points1, points2;\n    for (const cv::DMatch &match : good_matches_gms) {\n        cv::Vec2f pt1 = keypoints1[match.queryIdx].pt;\n        cv::Vec2f pt2 = keypoints2[match.trainIdx].pt;\n        points1.push_back(pt1);\n        points2.push_back(pt2);\n    }\n\n    matrix3d F = phg::findFMatrix(points1, points2);\n    matrix3d E = phg::fmatrix2ematrix(F, calib0, calib1);\n\n    matrix34d P0, P1;\n    phg::decomposeEMatrix(P0, P1, E, points1, points2, calib0, calib1);\n\n    matrix3d R0, R1;\n    vector3d O0, O1;\n    phg::decomposeUndistortedPMatrix(R0, O0, P0);\n    phg::decomposeUndistortedPMatrix(R1, O1, P1);\n    transform(R0, O0);\n    transform(R1, O1);\n    P0 = phg::composeCameraMatrixRO(R0, O0);\n    P1 = phg::composeCameraMatrixRO(R1, O1);\n\n    std::cout << \"Camera positions: \" << std::endl;\n    std::cout << \"R0:\\n\" << R0 << std::endl;\n    std::cout << \"O0: \" << O0.t() << std::endl;\n    std::cout << \"R1:\\n\" << R1 << std::endl;\n    std::cout << \"O1: \" << O1.t() << std::endl;\n\n    std::vector<cv::Vec3d> Xs;\n    std::vector<cv::Vec2d> x0s;\n    std::vector<cv::Vec2d> x1s;\n\n    matrix34d Ps[2] = {P0, P1};\n    for (int i = 0; i < (int) good_matches_gms.size(); ++i) {\n        vector3d ms[2] = {calib0.unproject(points1[i]), calib1.unproject(points2[i])};\n        vector4d X = phg::triangulatePoint(Ps, ms, 2);\n\n        if (X(3) == 0) {\n            std::cerr << \"infinite point\" << std::endl;\n            continue;\n        }\n\n        Xs.push_back(vector3d{X(0) / X(3), X(1) / X(3), X(2) / X(3)});\n        x0s.push_back(points1[i]);\n        x1s.push_back(points2[i]);\n    }\n\n    matrix34d P0res = phg::findCameraMatrix(calib0, Xs, x0s);\n    matrix34d P1res = phg::findCameraMatrix(calib1, Xs, x1s);\n\n    double rms0 = matRMS(P0res, P0);\n    double rms1 = matRMS(P1res, P1);\n    double rms2 = matRMS(P0, P1);\n\n    EXPECT_LT(rms0, 0.005);\n    EXPECT_LT(rms1, 0.005);\n    EXPECT_LT(rms0, 0.05 * rms2);\n    EXPECT_LT(rms1, 0.05 * rms2);\n}\n\nTEST (SFM, ReconstructNViews) {\n\n    using namespace cv;\n\n    std::vector<cv::Mat> imgs;\n    imgs.push_back(cv::imread(\"data/src/test_sfm/saharov/IMG_3023.JPG\"));\n    imgs.push_back(cv::imread(\"data/src/test_sfm/saharov/IMG_3024.JPG\"));\n    imgs.push_back(cv::imread(\"data/src/test_sfm/saharov/IMG_3025.JPG\"));\n\n    std::vector<vector3d> expected_orientations;\n    expected_orientations.push_back({0.966827, -0.141921, 0.115634});\n    expected_orientations.push_back({0.972914, -0.0489595, 0.183026});\n\n    std::vector<phg::Calibration> calibs;\n    for (const auto &img : imgs) {\n        calibs.push_back(phg::Calibration(img.cols, img.rows));\n    }\n\n    const int n_imgs = imgs.size();\n\n    std::cout << \"detecting points...\" << std::endl;\n    std::vector<std::vector<cv::KeyPoint>> keypoints(n_imgs);\n    std::vector<std::vector<int>> track_ids(n_imgs);\n    std::vector<cv::Mat> descriptors(n_imgs);\n    cv::Ptr<cv::FeatureDetector> detector = cv::SIFT::create();\n    for (int i = 0; i < (int) imgs.size(); ++i) {\n        detector->detectAndCompute(imgs[i], cv::noArray(), keypoints[i], descriptors[i]);\n        track_ids[i].resize(keypoints[i].size(), -1);\n    }\n\n    std::cout << \"matching points...\" << std::endl;\n    using Matches = std::vector<cv::DMatch>;\n    std::vector<std::vector<Matches>> matches(n_imgs);\n    for (int i = 0; i < n_imgs; ++i) {\n        matches[i].resize(n_imgs);\n        for (int j = 0; j < n_imgs; ++j) {\n            if (i == j) {\n                continue;\n            }\n\n            std::vector<std::vector<DMatch>> knn_matches;\n            std::cout << \"flann matching...\" << std::endl;\n            Ptr<DescriptorMatcher> matcher = DescriptorMatcher::create(DescriptorMatcher::FLANNBASED);\n            matcher->knnMatch( descriptors[i], descriptors[j], knn_matches, 2 );\n            std::vector<DMatch> good_matches(knn_matches.size());\n            for (int k = 0; k < (int) knn_matches.size(); ++k) {\n                good_matches[k] = knn_matches[k][0];\n            }\n\n            std::cout << \"filtering matches GMS...\" << std::endl;\n            std::vector<DMatch> good_matches_gms;\n            phg::filterMatchesGMS(good_matches, keypoints[i], keypoints[j], imgs[i].size(), imgs[j].size(), good_matches_gms);\n\n            matches[i][j] = good_matches_gms;\n        }\n    }\n\n    std::vector<phg::Track> tracks;\n    std::vector<vector3d> tie_points;\n    std::vector<matrix34d> cameras(n_imgs);\n    std::vector<char> aligned(n_imgs);\n\n    // align first two cameras\n    {\n        // matches from first to second image in specified sequence\n        const Matches &good_matches_gms = matches[0][1];\n        const std::vector<cv::KeyPoint> &keypoints0 = keypoints[0];\n        const std::vector<cv::KeyPoint> &keypoints1 = keypoints[1];\n        const phg::Calibration &calib0 = calibs[0];\n        const phg::Calibration &calib1 = calibs[1];\n\n        std::vector<cv::Vec2d> points0, points1;\n        for (const cv::DMatch &match : good_matches_gms) {\n            cv::Vec2f pt1 = keypoints0[match.queryIdx].pt;\n            cv::Vec2f pt2 = keypoints1[match.trainIdx].pt;\n            points0.push_back(pt1);\n            points1.push_back(pt2);\n        }\n\n        matrix3d F = phg::findFMatrix(points0, points1);\n        matrix3d E = phg::fmatrix2ematrix(F, calib0, calib1);\n\n        matrix34d P0, P1;\n        phg::decomposeEMatrix(P0, P1, E, points0, points1, calib0, calib1);\n\n        {\n            matrix3d R0, R1;\n            vector3d O0, O1;\n            phg::decomposeUndistortedPMatrix(R0, O0, P0);\n            phg::decomposeUndistortedPMatrix(R1, O1, P1);\n            transform(R0, O0);\n            transform(R1, O1);\n            P0 = phg::composeCameraMatrixRO(R0, O0);\n            P1 = phg::composeCameraMatrixRO(R1, O1);\n        }\n\n        cameras[0] = P0;\n        cameras[1] = P1;\n        aligned[0] = true;\n        aligned[1] = true;\n\n        matrix34d Ps[2] = {P0, P1};\n        for (int i = 0; i < (int) good_matches_gms.size(); ++i) {\n            vector3d ms[2] = {calib0.unproject(points0[i]), calib1.unproject(points1[i])};\n            vector4d X = phg::triangulatePoint(Ps, ms, 2);\n\n            if (X(3) == 0) {\n                std::cerr << \"infinite point\" << std::endl;\n                continue;\n            }\n\n            vector3d X3d{X(0) / X(3), X(1) / X(3), X(2) / X(3)};\n\n            tie_points.push_back(X3d);\n\n            phg::Track track;\n            track.img_kpt_pairs.push_back({0, good_matches_gms[i].queryIdx});\n            track.img_kpt_pairs.push_back({1, good_matches_gms[i].trainIdx});\n            track_ids[0][good_matches_gms[i].queryIdx] = tracks.size();\n            track_ids[1][good_matches_gms[i].trainIdx] = tracks.size();\n            tracks.push_back(track);\n        }\n    }\n\n    // append remaining cameras one by one\n    for (int i_camera = 2; i_camera < n_imgs; ++i_camera) {\n\n        const std::vector<cv::KeyPoint> &keypoints0 = keypoints[i_camera];\n        const phg::Calibration &calib0 = calibs[i_camera];\n\n        std::vector<vector3d> Xs;\n        std::vector<vector2d> xs;\n        for (int i_camera_prev = 0; i_camera_prev < i_camera; ++i_camera_prev) {\n            const Matches &good_matches_gms = matches[i_camera][i_camera_prev];\n            for (const cv::DMatch &match : good_matches_gms) {\n                int track_id = track_ids[i_camera_prev][match.trainIdx];\n                if (track_id != -1) {\n                    Xs.push_back(tie_points[track_id]);\n                    cv::Vec2f pt = keypoints0[match.queryIdx].pt;\n                    xs.push_back(pt);\n                }\n            }\n        }\n\n        matrix34d P = phg::findCameraMatrix(calib0, Xs, xs);\n\n        cameras[i_camera] = P;\n        aligned[i_camera] = true;\n\n        for (int i_camera_prev = 0; i_camera_prev < i_camera; ++i_camera_prev) {\n            const std::vector<cv::KeyPoint> &keypoints1 = keypoints[i_camera_prev];\n            const phg::Calibration &calib1 = calibs[i_camera_prev];\n            const Matches &good_matches_gms = matches[i_camera][i_camera_prev];\n            for (const cv::DMatch &match : good_matches_gms) {\n                int track_id = track_ids[i_camera_prev][match.trainIdx];\n                if (track_id == -1) {\n                    matrix34d Ps[2] = {P, cameras[i_camera_prev]};\n                    cv::Vec2f pts[2] = {keypoints0[match.queryIdx].pt, keypoints1[match.trainIdx].pt};\n                    vector3d ms[2] = {calib0.unproject(pts[0]), calib1.unproject(pts[1])};\n                    vector4d X = phg::triangulatePoint(Ps, ms, 2);\n\n                    if (X(3) == 0) {\n                        std::cerr << \"infinite point\" << std::endl;\n                        continue;\n                    }\n\n                    tie_points.push_back({X(0) / X(3), X(1) / X(3), X(2) / X(3)});\n\n                    phg::Track track;\n                    track.img_kpt_pairs.push_back({i_camera, match.queryIdx});\n                    track.img_kpt_pairs.push_back({i_camera_prev, match.trainIdx});\n                    track_ids[i_camera][match.queryIdx] = tracks.size();\n                    track_ids[i_camera_prev][match.trainIdx] = tracks.size();\n                    tracks.push_back(track);\n                } else {\n                    phg::Track &track = tracks[track_id];\n                    track.img_kpt_pairs.push_back({i_camera, match.queryIdx});\n                    track_ids[i_camera][match.queryIdx] = track_id;\n                }\n            }\n        }\n    }\n\n    if (tie_points.size() != tracks.size()) {\n        throw std::runtime_error(\"tie_points.size() != tracks.size()\");\n    }\n\n    std::vector<cv::Vec3b> tie_points_colors;\n    for (int i = 0; i < (int) tie_points.size(); ++i) {\n        const phg::Track &track = tracks[i];\n        int img = track.img_kpt_pairs.front().first;\n        int kpt = track.img_kpt_pairs.front().second;\n        cv::Vec2f px = keypoints[img][kpt].pt;\n        tie_points_colors.push_back(imgs[img].at<cv::Vec3b>(px[1], px[0]));\n    }\n\n    for (int i_camera = 0; i_camera < n_imgs; ++i_camera) {\n        if (!aligned[i_camera]) {\n            throw std::runtime_error(\"camera \" + std::to_string(i_camera) + \" is not aligned\");\n        }\n\n        matrix3d R;\n        vector3d O;\n        phg::decomposeUndistortedPMatrix(R, O, cameras[i_camera]);\n\n        tie_points.push_back(O);\n        tie_points_colors.push_back(cv::Vec3b(0, 0, 255));\n        tie_points.push_back(O + R * cv::Vec3d(0, 0, 1));\n        tie_points_colors.push_back(cv::Vec3b(255, 0, 0));\n    }\n\n    for (int i = 1; i < n_imgs; ++i) {\n        matrix3d R0, R1;\n        vector3d O0, O1;\n        phg::decomposeUndistortedPMatrix(R0, O0, cameras[i - 1]);\n        phg::decomposeUndistortedPMatrix(R1, O1, cameras[i]);\n\n        vector3d relative_cos_vals = relativeOrientationAngles(R0, O0, R1, O1);\n        std::cout << \"relative_cos_vals: \" << relative_cos_vals << std::endl;\n        vector3d relative_cos_vals_expected = expected_orientations[i - 1];\n        EXPECT_LT(cv::norm(relative_cos_vals - relative_cos_vals_expected), 0.05);\n    }\n\n    std::cout << \"exporting \" << tie_points.size() << \" points...\" << std::endl;\n    phg::exportPointCloud(tie_points, \"data/debug/test_sfm/point_cloud_N_cameras.ply\", tie_points_colors);\n\n}\n", "meta": {"hexsha": "adf1ba1c55a0f0b51127e7e3a4c105b9f001b23c", "size": 29051, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_sfm.cpp", "max_stars_repo_name": "kpilyugin/PhotogrammetryTasks2021", "max_stars_repo_head_hexsha": "7da69f04909075340a220a7021efeeb42283d9dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/test_sfm.cpp", "max_issues_repo_name": "kpilyugin/PhotogrammetryTasks2021", "max_issues_repo_head_hexsha": "7da69f04909075340a220a7021efeeb42283d9dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/test_sfm.cpp", "max_forks_repo_name": "kpilyugin/PhotogrammetryTasks2021", "max_forks_repo_head_hexsha": "7da69f04909075340a220a7021efeeb42283d9dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7916167665, "max_line_length": 148, "alphanum_fraction": 0.5804963685, "num_tokens": 9320, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802395624257, "lm_q2_score": 0.8723473614033683, "lm_q1q2_score": 0.8012338134834157}}
{"text": "#include <Eigen/Dense>\n\ndouble mse(Eigen::MatrixXd X, Eigen::VectorXd W, Eigen::VectorXd Y);\n\nEigen::VectorXd _derivative(Eigen::MatrixXd X, Eigen::VectorXd W,\n                            Eigen::VectorXd Y) {\n  /*\n  Computes the jth derivative given W, X, Y\n  by following gradient descent where\n       D_j J(W,X) = (Y - X * W) * X_j\n  */\n  return -1 * X.transpose() * (Y - X * W);\n}\n\nEigen::VectorXd _gradient_descent_step(Eigen::MatrixXd X, Eigen::VectorXd W,\n                                       Eigen::VectorXd Y, double alpha) {\n  /*\n  Runs gradient descent for each row in the dataset X\n  */\n  Eigen::VectorXd W_temp = W;\n  for (int j = 0; j < X.rows(); j++) {\n    W_temp -= alpha * _derivative(X, W, Y);\n  }\n\n  return W_temp;\n}\n\nEigen::VectorXd gradient_descent(Eigen::MatrixXd X, Eigen::MatrixXd Y,\n                                 int *iter, bool *converged,\n                                 int max_iterations, double threshold,\n                                 double learning_rate) {\n  Eigen::VectorXd W;\n  /*\n    Starting from a random set of weights W, use\n    gradient descent to determine the optimal W. Stop\n    when either the max iterations (not converged)\n    or the error threshold (converged) is reached.\n  */\n  *converged = true;\n  W = Eigen::MatrixXd::Random(X.cols(), 1);\n\n  for (*iter = 0; *iter < max_iterations; *iter = *iter + 1) {\n    W = _gradient_descent_step(X, W, Y, learning_rate);\n\n    double error = mse(X, W, Y);\n    if (error < threshold) {\n      *converged = true;\n      break;\n    }\n  }\n\n  return W;\n}", "meta": {"hexsha": "ea03b84ece42767e529e38791be6276b07e3c621", "size": 1544, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/gradient_descent.cpp", "max_stars_repo_name": "dsherma7/LinearRegression", "max_stars_repo_head_hexsha": "ce0827bfe7b98cfaf1d6df3c736694ae7ea3a8c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/gradient_descent.cpp", "max_issues_repo_name": "dsherma7/LinearRegression", "max_issues_repo_head_hexsha": "ce0827bfe7b98cfaf1d6df3c736694ae7ea3a8c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gradient_descent.cpp", "max_forks_repo_name": "dsherma7/LinearRegression", "max_forks_repo_head_hexsha": "ce0827bfe7b98cfaf1d6df3c736694ae7ea3a8c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1320754717, "max_line_length": 76, "alphanum_fraction": 0.5796632124, "num_tokens": 402, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.942506716354847, "lm_q2_score": 0.8499711718571775, "lm_q1q2_score": 0.8011035381833896}}
{"text": "#include<iostream>\n#include <bits/stdc++.h>\n#include <boost/bind.hpp>\nusing namespace std;\n \nstruct point\n{\n    int x, y;\n};\n\nint orientation(point p, point q, point r)\n{\n    int val = (q.y - p.y) * (r.x - q.x) -\n              (q.x - p.x) * (r.y - q.y);\n \n    if (val == 0) return 0;  // colinear\n    return (val > 0)? 1: 2; // clock or counterclock wise\n}\n\nint pointLocation(point A, point B, point P)\n    {\n        int cp1 = (B.x - A.x) * (P.y - A.y) - (B.y - A.y) * (P.x - A.x);\n        if (cp1 > 0)\n            return 1;\n        else if (cp1 == 0)\n            return 0;\n        else\n            return -1;\n    }\n    \n int distance(point A, point B, point C)\n    {\n        int ABx = B.x - A.x;\n        int ABy = B.y - A.y;\n        int num = ABx * (A.y - C.y) - ABy * (A.x - C.x);\n        if (num < 0)\n            num = -num;\n        return num;\n    }\n    \n  void hullSet(point A, point B, vector<point>set,vector<point>&hull)\n  {\n  \tvector<point>::iterator it;\n  \tpoint alpha=B;\n  \t it=find_if(hull.begin(),hull.end(),boost::bind (&point::x, _1 ) == alpha.x );\n  \t \n  \t \n  \tif (set.size() == 0)\n            return;\n            \n    if (set.size() == 1)\n        {\n            point p = set[0];\n            set.erase(set.begin()+0);\n            hull.insert(it, p);\n            return;\n        }\n        \n    int dist = INT_MIN;\n        int furthestPoint = -1;\n        for (int i = 0; i <set.size(); i++)\n        {\n            point p = set[i];\n            int distan = distance(A, B, p);\n            if (distan > dist)\n            {\n                dist = distan;\n                furthestPoint = i;\n            }\n        }\n    \n     point P = set[furthestPoint];\n        set.erase(set.begin()+furthestPoint-1);\n        hull.insert(it, P);\n        \n    // Determine who's to the left of AP\n        vector<point>leftSetAP;\n        for (int i = 0;i < set.size(); i++)\n        {\n            point M = set[i];\n            if (pointLocation(A, P, M) == 1)\n            {\n                leftSetAP.push_back(M);\n            }\n        }\n \n        // Determine who's to the left of PB\n        vector<point>leftSetPB;\n        for (int i = 0; i < set.size(); i++)\n        {\n            point M = set[i];\n            if (pointLocation(P, B, M) == 1)\n            {\n                leftSetPB.push_back(M);\n            }\n        }\n        hullSet(A, P, leftSetAP, hull);\n        hullSet(P, B, leftSetPB, hull);\n    \n  }\n\nvoid convexHull(point sample[], int n)\n{\n\t\n\tif(n<3) return;\n\t// Initialize Result\n    vector<point> hull;\n    vector<point> Lefthull;\n    vector<point> Righthull;\n\t\n\t int minPoint = -1, maxPoint = -1;\n        int minX = INT_MAX;\n        int maxX = INT_MIN;\n        for (int i=0;i<n; i++)\n        {\n            if (sample[i].x < minX)\n            {\n                minX = sample[i].x;\n                minPoint = i;\n            }\n            if (sample[i].x > maxX)\n            {\n                maxX =sample[i].x;\n                maxPoint = i;\n            }\n        }\n        \n         hull.push_back(sample[minPoint]);\n         hull.push_back(sample[maxPoint]);\n         \n        point A = sample[minPoint];\n        point B = sample[maxPoint];\n         \n          for(int i=0;i<n; i++)\n        {\n            point p = sample[i];\n            if (pointLocation(A, B, p) == -1)\n               Lefthull.push_back(p);\n            else if (pointLocation(A, B, p) == 1)\n                 Righthull.push_back(p);\n        }\n         \n        hullSet(A, B, Righthull, hull);\n        hullSet(B, A, Lefthull, hull); \n        \n        \n    // Print Result\n    for (int i = 0; i < hull.size(); i++)\n        cout << \"(\" << hull[i].x << \", \"\n              << hull[i].y << \")\\n\";   \n              \n}\n\nint main() {\n\t int N;\ncout << \"Enter no of points N \"<<endl;\ncin>>N;\npoint sample[N];\n\nfor (int i = 0; i < N; i++)\n{  \n  cin>>sample[i].x>>sample[i].y;\n}  \n//add timer here to calculate execution time\nclock_t start;\ndouble duration;\nstart = clock();\n\ncout << \"The points in the convex hull are: \"<<endl;\nconvexHull(sample, N);\n\nduration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;\ncout<<\"time: \"<<duration <<\" seconds\"<<endl;\nreturn 0;\n}\n\n", "meta": {"hexsha": "1aaf99045da14db6b2f91eb117f240746677dbd9", "size": 4138, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Quickhull.cpp", "max_stars_repo_name": "raj808569/CSN-212-Assignment-4", "max_stars_repo_head_hexsha": "7540392c475ef1436b0bb9117eec8282bb39b55a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-06-08T17:51:04.000Z", "max_stars_repo_stars_event_max_datetime": "2017-06-08T17:51:04.000Z", "max_issues_repo_path": "Quickhull.cpp", "max_issues_repo_name": "raj808569/CSN-212-Assignment-4", "max_issues_repo_head_hexsha": "7540392c475ef1436b0bb9117eec8282bb39b55a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Quickhull.cpp", "max_forks_repo_name": "raj808569/CSN-212-Assignment-4", "max_forks_repo_head_hexsha": "7540392c475ef1436b0bb9117eec8282bb39b55a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3785310734, "max_line_length": 81, "alphanum_fraction": 0.4432092798, "num_tokens": 1171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240090865198, "lm_q2_score": 0.8539127473751341, "lm_q1q2_score": 0.8010760499776455}}
{"text": "#include <armadillo>\n\nusing namespace arma;\n\nconst static double \u03c0 = 3.141592653589793238463;\nconst static float h = 0.74;\nconst static float l = 2.83;\nconst static float a = 0.95 + l;\nconst static float b = 0.50;\n\ndouble measure(double \u03b8){\n  double tmp = std::fmod(\u03b8,2*\u03c0);\n  return tmp - ((int) (tmp/\u03c0))*2*\u03c0;\n}\n\nmat inverse(mat q){\n  double d = q(0,0)*q(1,1)-q(0,1)*q(1,0);\n  return {{q(1,1)/d,-q(0,1)/d},{-q(1,0)/d,q(0,0)/d}};\n}\n\nmat jacobian_motion(float \u03b8, float v, float \u03b1, float dt){\n  return {{1, 0, -dt*(v*std::sin(\u03b8)+v/l*std::tan(\u03b1)*(a*std::cos(\u03b8)-b*std::sin(\u03b8)))},\n          {0, 1,  dt*(v*std::cos(\u03b8)-v/l*std::tan(\u03b1)*(a*std::sin(\u03b8)+b*std::cos(\u03b8)))},\n          {0, 0,  1}};\n}\n\nvec equation_motion(float \u03b8, float v1, float \u03b1, float dt){\n  float v = v1/(1-std::tan(\u03b1)*h/l);\n  return {dt*(v*std::cos(\u03b8)-v/l*std::tan(\u03b1)*(a*std::sin(\u03b8)+b*std::cos(\u03b8))),\n          dt*(v*std::sin(\u03b8)+v/l*std::tan(\u03b1)*(a*std::cos(\u03b8)-b*std::sin(\u03b8))),\n          dt*v/l*std::tan(\u03b1)};\n}\n\nmat jacobian_measurement(vec \u03bc, vec m){\n  //pb converting Col<uint> to uvec = Col<long long int>\n  vec \u03b4 = m-\u03bc(span(0,1));\n  vec \u03b41 = sum(square(\u03b4),0);\n  double q = \u03b41(0);\n\n  mat jcb = {{-\u03b4(0),-\u03b4(1),0,\u03b4(0),\u03b4(1)},\n             {\u03b4(1),-\u03b4(0),-q,-\u03b4(1),\u03b4(0)}};\n  jcb.row(0) *= (1/sqrt(q));\n  jcb.row(1) *= (1/q);\n\n  return jcb;\n}\n\nvec equation_measurement(vec \u03bc, vec m){\n\n  vec \u03b4 = m-\u03bc(span(0,1));\n  vec \u03b41 = sqrt(sum(square(\u03b4),0));\n  double q = \u03b41(0);\n  double \u03d5 = atan2(\u03b4(1),\u03b4(0)) - \u03bc(2) + \u03c0/2;\n  return {q,\u03d5};\n}\n\nmat inverse_measurement(vec \u03bc, mat z){\n  rowvec c = cos(z.row(1)+\u03bc(2));\n  rowvec s = sin(z.row(1)+\u03bc(2));\n\n  return mat(join_vert(z.row(0)%s,-z.row(0)%c)).each_col() + \u03bc(span(0,1));\n}\n", "meta": {"hexsha": "b64852da80c6723c483767d9c01f17ba5c431a07", "size": 1660, "ext": "cc", "lang": "C++", "max_stars_repo_path": "ch13_the_fastslam_algorithm/src/cpp/linear_model.cc", "max_stars_repo_name": "pankhurivanjani/probabilistic_robotics", "max_stars_repo_head_hexsha": "f5c009ae00fa1d5782baac04a858df541d41dc1c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch13_the_fastslam_algorithm/src/cpp/linear_model.cc", "max_issues_repo_name": "pankhurivanjani/probabilistic_robotics", "max_issues_repo_head_hexsha": "f5c009ae00fa1d5782baac04a858df541d41dc1c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch13_the_fastslam_algorithm/src/cpp/linear_model.cc", "max_forks_repo_name": "pankhurivanjani/probabilistic_robotics", "max_forks_repo_head_hexsha": "f5c009ae00fa1d5782baac04a858df541d41dc1c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-14T05:08:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-14T05:08:52.000Z", "avg_line_length": 26.3492063492, "max_line_length": 84, "alphanum_fraction": 0.5512048193, "num_tokens": 704, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133515091157, "lm_q2_score": 0.8519527963298947, "lm_q1q2_score": 0.8007618081259944}}
{"text": "// Boost.Geometry\n// QuickBook Example\n\n// Copyright (c) 2020, Aditya Mohan\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n//[dot_product\n//` Calculate the dot product of two points\n\n#include <iostream>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/arithmetic/dot_product.hpp>\n#include <boost/geometry/geometries/adapted/boost_array.hpp>\n\nnamespace bg = boost::geometry; /*< Convenient namespace alias >*/\n\nBOOST_GEOMETRY_REGISTER_BOOST_ARRAY_CS(cs::cartesian)\n\n\nint main()\n{            \n     double dp1,dp2,dp3,dp4;\n     bg::model::point<double, 3, bg::cs::cartesian> point1(1.0, 2.0, 3.0);\n     bg::model::point<double, 3, bg::cs::cartesian> point2(4.0, 5.0, 6.0);\n\n     //Example 1\n     dp1 = bg::dot_product(point1, point2);\n\n     std::cout << \"Dot Product 1: \"<< dp1 << std::endl; \n\n     bg::model::point<double, 2, bg::cs::cartesian> point3(3.0, 2.0);\n     bg::model::point<double, 2, bg::cs::cartesian> point4(4.0, 7.0);\n\n     //Example 2\t\n     dp2 = bg::dot_product(point3, point4);\n\n     std::cout << \"Dot Product 2: \"<< dp2 << std::endl; \n\n     boost::array<double, 2> a =  {1, 2};\n     boost::array<double, 2> b =  {2, 3};\n\n     //Example 3\n     dp3 = bg::dot_product(a, b);\n\n     std::cout << \"Dot Product 3: \"<< dp3 << std::endl; \n\n     return 0;\n\n}\n\n//]\n\n//[dot_product_output\n/*`\nOutput:\n[pre\nDot Product 1: 32\nDot Product 2: 26\nDot Product 3: 8\n]\n*/\n//]\n", "meta": {"hexsha": "9440b5dfd9a9d1d75beba5bfb3c36d8bbcd93604", "size": 1522, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/src/examples/arithmetic/dot_product.cpp", "max_stars_repo_name": "jkerkela/geometry", "max_stars_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 326.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T13:47:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T02:13:59.000Z", "max_issues_repo_path": "doc/src/examples/arithmetic/dot_product.cpp", "max_issues_repo_name": "jkerkela/geometry", "max_issues_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/geometry/doc/src/examples/arithmetic/dot_product.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T15:50:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T03:58:36.000Z", "avg_line_length": 22.7164179104, "max_line_length": 79, "alphanum_fraction": 0.6320630749, "num_tokens": 503, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133481428691, "lm_q2_score": 0.8519527963298946, "lm_q1q2_score": 0.8007618052581111}}
{"text": "#include <iostream>\n#include <cstdio>\n#include <armadillo>\n#include <ctime>\n#include <unistd.h>\n\n#include \"comp_eig.hh\"\n\nusing namespace std;\nusing namespace arma;\n\nconst double rmin = 0;\nconst double rmax = 6;\nconst double epsilon = 1e-10;\n\nstruct program_output {\n  size_t steps;\n  double step_time;\n  double arma_time;\n  double err;\n};\n\n// potential function\nstatic constexpr double V(double r) {\n  return r * r;\n}\n\n// calculate maximal off-diagonal element with respect to absolute value\n// return square of maximal off-diagonal element\nstatic double maxoff(const mat &A, size_t &i, size_t &j) {\n  i = 1; j = 0; // indices of maximal lement\n  double a = 0; // square of maximal element\n\n  SizeMat s = size(A);\n\n  for(size_t k = 0; k < s.n_rows; k++) {\n    for(size_t l = 0; l < s.n_cols; l++) {\n      if(k == l) continue;\n\n      const double x = A(k, l);\n      const double y = x * x;\n      if(y > a)\n        i = k, j = l, a = y;\n    }\n  }\n\n  return a;\n}\n\nstatic void apply_rot_col(size_t k, size_t l, double t, mat &M) {\n  if(k == l) return;\n\n  const double c = 1 / sqrt( 1 + t * t );\n  const double s = t * c;\n\n  colvec kvec = c * M.col(k) - s * M.col(l);\n  colvec lvec = s * M.col(k) + c * M.col(l);\n\n  M.col(k) = kvec;\n  M.col(l) = lvec;\n}\n\nstatic void apply_rot_row(size_t k, size_t l, double t, mat &M) {\n  if(k == l) return;\n\n  const double c = 1 / sqrt( 1 + t * t );\n  const double s = t * c;\n\n  rowvec kvec = c * M.row(k) - s * M.row(l);\n  rowvec lvec = s * M.row(k) + c * M.row(l);\n\n  M.row(k) = kvec;\n  M.row(l) = lvec;\n}\n\n// single step with Jacobi's method\nstatic bool jacobi_step(mat &B, mat &P) {\n  // calculate maximal off-diagonal element with respect to absolute value\n  size_t k, l;\n  const double a = maxoff(B, k, l); // square of maximal element\n\n  // if less than epsilon, stop\n  if(a < epsilon)\n    return false;\n\n  // calculate sin \u03b8 and cos \u03b8\n  const double tau = (B(l, l) - B(k, k)) / (2 * B(k, l));\n  const double t = (tau >= 0 ? - tau - sqrt( 1 + tau * tau ) : - tau + sqrt( 1 + tau * tau ));\n\n  // apply similarity transform\n  //   B = S.t() * B * S;\n  apply_rot_col(k, l, t, B);\n  apply_rot_row(k, l, t, B);\n\n  // apply S^T to P\n  //   P = P * S;\n  apply_rot_col(k, l, t, P);\n\n  return true;\n}\n\n// solve with Jacobi's method\n// A is input matrix, P is eigenvector matrix (with column vector eigenvectors), L is eigenvalue vector\nstatic void jacobi_solve(const mat &A, mat &P, vec &L, size_t &steps, double &step_time) {\n  // get N from A matrix\n  const size_t N = A.n_rows;\n  assert(A.n_cols == N);\n\n  std::cout << \"N=\" << N << std::endl;\n\n  // B is similar matrix to A through matrix transforms\n  mat B = A;\n\n  // set P matrix (that will contain eigenvectors) to the identity matrix\n  P.eye(size(A));\n\n  clock_t time_start, time_end;\n  double time_total = 0;\n  steps = 0;\n  while(true) {\n    // timing\n    time_start = clock();\n\n    if(!jacobi_step(B, P))\n      break;\n\n    // timing\n    time_end = clock();\n    time_total += (double)(time_end - time_start) / CLOCKS_PER_SEC;\n    steps++;\n  }\n\n  // export steps and time per step\n  step_time = time_total / steps;\n\n  std::cout << \"JACOBI DONE (N = \" << N << \", steps = \" << steps << \", time per step = \" << (1000 * step_time) << \"ms)\" << std::endl;\n\n  // find eigenvalues\n  L.set_size(N);\n  for(size_t i = 0; i < N; i++)\n    L(i) = B(i, i);\n}\n\nint run_program(size_t N, struct program_output &out) {\n  const double h = (rmax - rmin) / N;\n\n  // array of \u03c1 valuses\n  vec r(N);\n  for(size_t i = 0; i < N; i++)\n    r(i) = rmin + h * i;\n\n  // calculate e_i, which are all the same\n  double e = - 1 / (h * h);\n\n  // calculate d_i, which depend on V(\u03c1_i)\n  vec d(N);\n  for(size_t i = 0; i < N; i++)\n    d(i) = 2 / (h * h) + V(r[i]);\n\n  // calculate matrix A\n  mat A(N, N, arma::fill::zeros);\n  for(size_t i = 0; i < N; i++) {\n    A(i, i) = d(i);\n\n    if(i > 0)\n      A(i, i-1) = e;\n    if(i < N - 1)\n      A(i, i+1) = e;\n  }\n\n  // solve with Jacobi method\n  vec eigenvalues;\n  mat eigenvectors;\n  jacobi_solve(A, eigenvectors, eigenvalues, out.steps, out.step_time);\n\n  // solve with Armadillo's eig_sym\n  clock_t arma_start, arma_finish;\n  vec arma_eigenvalues;\n  mat arma_eigenvectors;\n  arma_start = clock();\n  eig_sym(arma_eigenvalues, arma_eigenvectors, A);\n  arma_finish = clock();\n  out.arma_time = (double)(arma_finish - arma_start)/CLOCKS_PER_SEC;\n\n  out.err = comp_eig(eigenvalues, eigenvectors, arma_eigenvalues, arma_eigenvectors);\n}\n\n#ifndef NO_MAIN\nint main(int argc, char **argv) {\n  const size_t Nvalues[] = { 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100 };\n  const size_t Nlen = sizeof(Nvalues) / sizeof(*Nvalues);\n\n  FILE *fp = fopen(\"b.dat\", \"w\");\n  fprintf(fp, \"N          epsilon    steps      step_time  arma_time  error\\n\");\n\n  for(size_t i = 0; i < Nlen; i++) {\n    size_t N = i[Nvalues]; // aww yeah abusing valid C++ syntax for no reason\n\n    struct program_output out;\n\n    std::cout << \"running with N = \" << N << std::endl;\n\n    run_program(N, out);\n\n    // write result row\n    fprintf(fp, \"%-10ld %-10.5g %-10ld %-10.5g %-10.5g %-10.5g\\n\", N, epsilon, out.steps, out.step_time, out.arma_time, out.err);\n    fflush(fp);\n  }\n\n  fclose(fp);\n}\n#endif\n", "meta": {"hexsha": "a13e3f33eac85dd7e7c88290c43dae86bce68aba", "size": 5190, "ext": "cc", "lang": "C++", "max_stars_repo_path": "project2/code-fredrik/b.cc", "max_stars_repo_name": "frxstrem/fys3150", "max_stars_repo_head_hexsha": "35c0310f48fca07444ec5924267bf646d121b147", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "project2/code-fredrik/b.cc", "max_issues_repo_name": "frxstrem/fys3150", "max_issues_repo_head_hexsha": "35c0310f48fca07444ec5924267bf646d121b147", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "project2/code-fredrik/b.cc", "max_forks_repo_name": "frxstrem/fys3150", "max_forks_repo_head_hexsha": "35c0310f48fca07444ec5924267bf646d121b147", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.3661971831, "max_line_length": 133, "alphanum_fraction": 0.5971098266, "num_tokens": 1727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422213778251, "lm_q2_score": 0.8418256551882382, "lm_q1q2_score": 0.8006959236885839}}
{"text": "/*****************************************************************************\n * reduce.cpp     Blitz++ array reduction example\n *\n * This example illustrates the array reduction functions provided by\n * Blitz++.  These functions reduce an N dimensional array (or array\n * expression) to an N-1 dimensional array expression by summing, taking\n * the mean, etc.  These array reductions are currently provided: sum,\n * mean, min, max, minIndex, maxIndex, product, count, any and all.\n *****************************************************************************/\n\n#include <blitz/array.h>\n\nBZ_USING_NAMESPACE(blitz)\n\nint main()\n{\n    Array<int, 2> A(4,4);\n\n    A = 3,  1,  2,  4,       \n        8, -1, -5,  3,       \n        0,  9, -1,  4,\n        1,  3,  1,  2;\n\n    cout << \"A = \" << A << endl;\n\n    /*\n     * Reduce the array A to a one-dimensional array, by summing/taking\n     * the mean/etc. of each row.\n     */\n\n    Array<int, 1> z(4);\n    Array<float, 1> z2(4);\n    secondIndex j;\n\n    z = sum(A, j);\n    cout << \"sum(A,j) = \" << endl << z << endl;\n\n    z2 = mean(A, j);\n    cout << \"mean(A,j) = \" << endl << z2 << endl;\n\n    z = min(A, j);\n    cout << \"min(A,j) = \" << endl << z << endl;\n\n    z = minIndex(A, j);\n    cout << \"minIndex(A, j) = \" << endl << z << endl;\n\n    z = max(A, j);\n    cout << \"max(A, j) = \" << endl << z << endl;\n\n    z = maxIndex(A, j);\n    cout << \"maxIndex(A, j) = \" << endl << z << endl;\n\n    z = first((A < 0), j);\n    cout << \"first((A < 0), j) = \" << endl << z << endl;\n\n    z = product(A, j);\n    cout << \"product(A, j) = \" << endl << z << endl;\n\n    z = count( (A > 0), j);\n    cout << \"count((A > 0), j) = \" << endl << z << endl;\n\n    z = any((abs(A) > 4), j);\n    cout << \"any((abs(A) > 4), j) = \" << endl << z << endl;\n\n    z = all(A > 0, j);\n    cout << \"all(A > 0, j) = \" << endl << z << endl;\n\n    return 0;\n}\n\n\n/*\n * Output\n */\n#if 0\nA = 4 x 4\n         3         1         2         4\n         8        -1        -5         3\n         0         9        -1         4\n         1         3         1         2\n\nsum(A,j) =\n[         10         5        12         7 ]\nmean(A,j) =\n[        2.5      1.25         3      1.75 ]\nmin(A,j) =\n[          1        -5        -1         1 ]\nminIndex(A, j) =\n[          1         2         2         0 ]\nmax(A, j) =\n[          4         8         9         3 ]\nmaxIndex(A, j) =\n[          3         0         1         1 ]\nproduct(A, j) =\n[         24       120         0         6 ]\ncount((A > 0), j) =\n[          4         2         2         4 ]\nany((abs(A) > 4), j) =\n[          0         1         1         0 ]\nall(A > 0, j) =\n[          1         0         0         1 ]\n\n#endif\n\n", "meta": {"hexsha": "8250f9fae6f475c6dedebae1898f21439ca0ced7", "size": 2672, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/examples/reduce.cpp", "max_stars_repo_name": "fraguela/depspawn", "max_stars_repo_head_hexsha": "b5760f4c0d38a1b245ee5274e2ccc5c5fe2d3d45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-04-12T11:05:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T11:10:27.000Z", "max_issues_repo_path": "ibtk/third_party/blitz-0.10/examples/reduce.cpp", "max_issues_repo_name": "MSV-Project/IBAMR", "max_issues_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ibtk/third_party/blitz-0.10/examples/reduce.cpp", "max_forks_repo_name": "MSV-Project/IBAMR", "max_forks_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.4476190476, "max_line_length": 79, "alphanum_fraction": 0.3660179641, "num_tokens": 882, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.925229959153748, "lm_q2_score": 0.8652240756264638, "lm_q1q2_score": 0.8005312361507124}}
