{"text": "#include <string>\n#include <vector>\n#include <Eigen/Dense>\n#include <cmath>\n#include <exception>\n\n#include <iostream>\n#include <fstream>\n\n#define PI 3.141592653589793238462643383279502884L\n#define REGULARIZATION_FACTOR 0.5\n\nconst std::string TRAINING_FILE_NAME = \"data/zip.train\"; // 7291 items\nconst std::string TEST_FILE_NAME = \"data/zip.test\"; // 2007 items\n\ntypedef struct {\n  unsigned label;\n  Eigen::VectorXd features;\n} ClassificationObject;\n\ntypedef struct {\n  unsigned label;\n  double prior;\n  Eigen::VectorXd mean;\n  Eigen::MatrixXd covariance;\n  double covarianceDeterminant;\n  Eigen::MatrixXd covarianceInverse;\n} ClassInfo;\n\n\nstd::vector<ClassificationObject>\nReadData(\n  const std::string& fileName,\n  const unsigned featureDim,\n  const unsigned numItems) {\n\n  std::ifstream fin;\n  fin.clear(); fin.open(fileName.c_str());\n\n  if (!fin.good()) {\n    throw std::exception();\n  }\n\n  std::vector<ClassificationObject> data; data.reserve(numItems);\n\n  for (unsigned i = 0; i < numItems; ++i) {\n    ClassificationObject classificationObject;\n    double dummy;\n    fin >> dummy;\n    classificationObject.label = (unsigned) dummy;\n\n    classificationObject.features.resize(featureDim);\n    for (unsigned j = 0; j < featureDim; ++j) {\n      fin >> classificationObject.features(j);\n    }\n    data.push_back(classificationObject);\n  }\n\n  return data;\n}\n\nClassInfo\nComputeClassInfo(\n  const std::vector<ClassificationObject>& data,\n  const unsigned classLabel,\n  const unsigned featureDim) {\n \n  ClassInfo classInfo;\n  classInfo.label = classLabel;\n  classInfo.mean.setZero(featureDim);\n  classInfo.covariance.setZero(featureDim, featureDim);\n\n  // compute mean and prior probability at once\n  std::vector<ClassificationObject> subset;\n  for (const ClassificationObject& classificationObject : data) {\n    if (classificationObject.label == classLabel) {\n      classInfo.mean += classificationObject.features;\n      subset.push_back(classificationObject);\n    }\n  }\n  classInfo.mean /= subset.size();\n  classInfo.prior = (double) subset.size() / (double) data.size();\n\n  // covariance matrix\n  // Note: I use a nifty trick that is simpler in code (not sure if\n  //       simpler computationally). Let $P_i = x_i - mu$, where $i$\n  //       corresponds to a particular observation vector. Then\n  //       $A$ is the concatenation of all the $P_i$ as column\n  //       vectors ($A = [P_1 ... P_m]$). Then\n  //       $\\frac{1}{m} * A * A^t$ results in the same computations\n  //       that create the covariance matrix as more traditional\n  //       formulae.\n  Eigen::MatrixXd A(featureDim, subset.size());\n  for (unsigned j = 0; j < subset.size(); ++j) {\n    A.col(j) = subset[j].features - classInfo.mean;\n  }\n  classInfo.covariance = A * A.transpose();\n  classInfo.covariance /= (double) subset.size();\n  if (classInfo.covariance.determinant() - 0.1 <= 0.0) {\n    Eigen::MatrixXd regularizationMatrix;\n    regularizationMatrix.setIdentity(featureDim, featureDim);\n    regularizationMatrix *= REGULARIZATION_FACTOR;\n    classInfo.covariance += regularizationMatrix;\n  }\n  classInfo.covarianceDeterminant = classInfo.covariance.determinant();\n  classInfo.covarianceInverse = classInfo.covariance.inverse();\n\n  return classInfo;\n}\n\ndouble\nGaussianPdf(\n  const Eigen::VectorXd& testFeatureVector,\n  const ClassInfo& classSummary) {\n\n  const Eigen::VectorXd& x = testFeatureVector;\n  const Eigen::VectorXd& mu = classSummary.mean;\n  const double& sigmaDet = classSummary.covarianceDeterminant;\n  const Eigen::MatrixXd& sigmaInv = classSummary.covarianceInverse; \n\n  double scalingFactor = 1.0 / sqrt(pow(2.0 * PI, mu.size()) * sigmaDet);\n  double exponent = -0.5 * (((x - mu).transpose() * sigmaInv).dot((x - mu)));\n\n  return scalingFactor * exp(exponent);\n}\n\nunsigned\nClassifyObject(const ClassificationObject& object, const std::vector<ClassInfo>& classSummaries) {\n  unsigned mostLikelyClass = 0;\n  double highestProbability = classSummaries.front().label;\n\n  for (const ClassInfo& classSummary : classSummaries) {\n    double probability = GaussianPdf(object.features, classSummary) * classSummary.prior;\n    if (probability > highestProbability) {\n      mostLikelyClass = classSummary.label;\n      highestProbability = probability;\n    }\n  }\n\n  return mostLikelyClass;\n}\n\nEigen::MatrixXi\nPerformClassifications(const std::vector<unsigned>& labelSet,\n  const std::vector<ClassInfo>& classSummaries,\n  const std::vector<ClassificationObject>& testObjects) {\n\n  Eigen::MatrixXi confusionMatrix(labelSet.size(), labelSet.size());\n  confusionMatrix.setZero(labelSet.size(), labelSet.size());\n\n  unsigned i = 1;\n  unsigned onePercent = testObjects.size() / 100;\n  for (const ClassificationObject& object : testObjects) {\n    if (i % onePercent == 0) {\n      std::cout << i << \"% processed.\" << std::endl;\n    }\n    i++;\n\n    unsigned classifiedAs = ClassifyObject(object, classSummaries);\n    confusionMatrix(object.label, classifiedAs)++;\n  }\n\n  return confusionMatrix;\n}\n\n\nint\nmain(const int argc, const char** argv) {\n  std::cout << \"Reading Data...\" << std::endl;\n  std::vector<ClassificationObject> trainingData = ReadData(\n    TRAINING_FILE_NAME,\n    256,\n    7291\n  );\n  std::vector<ClassificationObject> testData = ReadData(\n    TEST_FILE_NAME,\n    256,\n    2007\n  );\n\n  std::cout << \"Training Models...\" << std::endl;\n  std::vector<ClassInfo> classSummaries; classSummaries.reserve(10);\n  for (unsigned label = 0; label <= 9; ++label) {\n    classSummaries.push_back(ComputeClassInfo(trainingData, label, 256));\n  }\n\n  std::cout << \"Classifying Objects...\" << std::endl;\n  Eigen::MatrixXi confusionMatrix = PerformClassifications(\n    {0,1,2,3,4,5,6,7,8,9},\n    classSummaries,\n    testData\n  );\n\n  std::cout << \"Results:\" << std::endl;\n  std::cout << confusionMatrix << std::endl;\n\n\treturn 0;\n}\n", "meta": {"hexsha": "9eea5f2d19078820773bb77330a805aefd469053", "size": 5800, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "STAT775/HW02/hw02_bayesian_classification.cpp", "max_stars_repo_name": "T-R0D/Past-Courses", "max_stars_repo_head_hexsha": "0edc83a7bf09515f0d01d23a26df2ff90c0f458a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2017-03-13T17:32:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-27T16:51:22.000Z", "max_issues_repo_path": "STAT775/HW02/hw02_bayesian_classification.cpp", "max_issues_repo_name": "T-R0D/Past-Courses", "max_issues_repo_head_hexsha": "0edc83a7bf09515f0d01d23a26df2ff90c0f458a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-29T19:54:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-29T19:54:52.000Z", "max_forks_repo_path": "STAT775/HW02/hw02_bayesian_classification.cpp", "max_forks_repo_name": "T-R0D/Past-Courses", "max_forks_repo_head_hexsha": "0edc83a7bf09515f0d01d23a26df2ff90c0f458a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2016-10-18T03:31:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-29T13:23:10.000Z", "avg_line_length": 29.1457286432, "max_line_length": 98, "alphanum_fraction": 0.7018965517, "num_tokens": 1469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299570920386, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.7498793616575995}}
{"text": "/*\n *  Example code for fitting a polynomial to sample data (using Eigen 3)\n *\n *  Copyright (C) 2014  RIEGL Research ForschungsGmbH\n *  Copyright (C) 2014  Clifford Wolf <clifford@clifford.at>\n *  \n *  Permission to use, copy, modify, and/or distribute this software for any\n *  purpose with or without fee is hereby granted, provided that the above\n *  copyright notice and this permission notice appear in all copies.\n *  \n *  THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n */\n\n#include <Eigen/QR>\n#include <stdio.h>\n#include <vector>\n\nvoid polyfit(const std::vector<double> &xv, const std::vector<double> &yv, std::vector<double> &coeff, int order)\n{\n\tEigen::MatrixXd A(xv.size(), order+1);\n\tEigen::VectorXd yv_mapped = Eigen::VectorXd::Map(&yv.front(), yv.size());\n\tEigen::VectorXd result;\n\n\tassert(xv.size() == yv.size());\n\tassert(xv.size() >= order+1);\n\n\t// create matrix\n\tfor (size_t i = 0; i < xv.size(); i++)\n\tfor (size_t j = 0; j < order+1; j++)\n\t\tA(i, j) = pow(xv.at(i), j);\n\n\t// solve for linear least squares fit\n\tresult = A.householderQr().solve(yv_mapped);\n\n\tcoeff.resize(order+1);\n\tfor (size_t i = 0; i < order+1; i++)\n\t\tcoeff[i] = result[i];\n}\n\nint main()\n{\n\tstd::vector<double> x_values, y_values, coeff;\n\tdouble x, y;\n\n\twhile (scanf(\"%lf %lf\\n\", &x, &y) == 2) {\n\t\tx_values.push_back(x);\n\t\ty_values.push_back(y);\n\t}\n\n\tpolyfit(x_values, y_values, coeff, 3);\n\tprintf(\"%f + %f*x + %f*x^2 + %f*x^3\\n\", coeff[0], coeff[1], coeff[2], coeff[3]);\n\n\treturn 0;\n}\n\n", "meta": {"hexsha": "825bb177eb6f0632792e40395f242a8ed34e6e15", "size": 1940, "ext": "cc", "lang": "C++", "max_stars_repo_path": "include/polyfit.cc", "max_stars_repo_name": "CHEN-Lin/OpenMoor", "max_stars_repo_head_hexsha": "f463f586487b9023e7f3678c9d851000558b14d7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-02-10T07:03:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T16:09:38.000Z", "max_issues_repo_path": "include/polyfit.cc", "max_issues_repo_name": "CHEN-Lin/OpenMoor", "max_issues_repo_head_hexsha": "f463f586487b9023e7f3678c9d851000558b14d7", "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": "include/polyfit.cc", "max_forks_repo_name": "CHEN-Lin/OpenMoor", "max_forks_repo_head_hexsha": "f463f586487b9023e7f3678c9d851000558b14d7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-01-25T23:33:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T13:22:56.000Z", "avg_line_length": 30.7936507937, "max_line_length": 113, "alphanum_fraction": 0.6793814433, "num_tokens": 559, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425377849805, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7497224815849615}}
{"text": "#include <iostream>\n#include <ctime>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#define MATRIX_SIZE 4\n\nusing namespace std;\nusing namespace Eigen;\n\nint main( int argc, char** argv )\n{\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();\n  \n    Eigen::Matrix<double,MATRIX_SIZE,1> x = matrix_NN.inverse()*v_Nd;\n    cout <<\"time use in normal inverse is \" << 1000* (clock() - time_stt)/(double)CLOCKS_PER_SEC << \"ms\"<< endl;\n    \n    time_stt = clock();\n    x = matrix_NN.colPivHouseholderQr().solve(v_Nd);\n    cout <<\"time use in Qr decomposition is \" <<1000*  (clock() - time_stt)/(double)CLOCKS_PER_SEC <<\"ms\" << endl;\n    */\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    clock_t time_stt = clock();\n    Matrix<double, MATRIX_SIZE, 1> x = matrix_NN.inverse() * v_Nd;\n    cout<<\"time used\"<<clock()-time_stt<<endl;\n    cout<<x.transpose()<<endl;\n    time_stt = clock();\n    x = matrix_NN.colPivHouseholderQr().solve(v_Nd);\n    cout<<x.transpose()<<endl;\n    cout<<\"time used\"<<clock()-time_stt<<endl;\n\n    return 0;\n}", "meta": {"hexsha": "96171fd1e203eb172cc6752db73fec33e29cb3ce", "size": 1435, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2/my_solution/main.cpp", "max_stars_repo_name": "SFXiang/VSLAM_Homework", "max_stars_repo_head_hexsha": "023b3b21e7bfd986d181f76ba6778422e27cfc40", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-05-29T06:45:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-10T14:00:36.000Z", "max_issues_repo_path": "2/my_solution/main.cpp", "max_issues_repo_name": "SFXiang/VSLAM_Homework", "max_issues_repo_head_hexsha": "023b3b21e7bfd986d181f76ba6778422e27cfc40", "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": "2/my_solution/main.cpp", "max_forks_repo_name": "SFXiang/VSLAM_Homework", "max_forks_repo_head_hexsha": "023b3b21e7bfd986d181f76ba6778422e27cfc40", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-09-01T16:24:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-01T04:02:23.000Z", "avg_line_length": 33.3720930233, "max_line_length": 114, "alphanum_fraction": 0.6620209059, "num_tokens": 417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425333801889, "lm_q2_score": 0.8152324871074607, "lm_q1q2_score": 0.7497224697373372}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main() {\n  MatrixXf m(2, 2);\n  m << 1, -2,\n      -3, 4;\n\n  cout << \"1-norm(m)     = \" << m.cwiseAbs().colwise().sum().maxCoeff()\n       << \" == \" << m.colwise().lpNorm<1>().maxCoeff() << endl;\n\n  cout << \"infty-norm(m) = \" << m.cwiseAbs().rowwise().sum().maxCoeff()\n       << \" == \" << m.rowwise().lpNorm<1>().maxCoeff() << endl;\n}\n", "meta": {"hexsha": "13de689989815a06f3cd4762f11d253619d82ce7", "size": 425, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/Eigen-3.3/doc/examples/Tutorial_ReductionsVisitorsBroadcasting_reductions_operatornorm.cpp", "max_stars_repo_name": "chen0510566/CarND-Path-Planning-Project", "max_stars_repo_head_hexsha": "4652e5c459980252e4ab72a0fd687341f3245466", "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/Eigen-3.3/doc/examples/Tutorial_ReductionsVisitorsBroadcasting_reductions_operatornorm.cpp", "max_issues_repo_name": "chen0510566/CarND-Path-Planning-Project", "max_issues_repo_head_hexsha": "4652e5c459980252e4ab72a0fd687341f3245466", "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": "include/Eigen-3.3/doc/examples/Tutorial_ReductionsVisitorsBroadcasting_reductions_operatornorm.cpp", "max_forks_repo_name": "chen0510566/CarND-Path-Planning-Project", "max_forks_repo_head_hexsha": "4652e5c459980252e4ab72a0fd687341f3245466", "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.6111111111, "max_line_length": 71, "alphanum_fraction": 0.5247058824, "num_tokens": 144, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9019206686206199, "lm_q2_score": 0.8311430541321951, "lm_q1q2_score": 0.7496250991022936}}
{"text": "// The contents of this file are in the public domain.  See LICENSE_FOR_EXAMPLE_PROGRAMS.txt\n/*\n\n    This example demonstrates the usage of the numerical quadrature function\n    integrate_function_adapt_simp().  This function takes as input a single variable\n    function, the endpoints of a domain over which the function will be integrated, and a\n    tolerance parameter.  It outputs an approximation of the integral of this function over\n    the specified domain.  The algorithm is based on the adaptive Simpson method outlined in: \n\n        Numerical Integration method based on the adaptive Simpson method in\n        Gander, W. and W. Gautschi, \"Adaptive Quadrature \u2013 Revisited,\"\n        BIT, Vol. 40, 2000, pp. 84-101\n\n*/\n\n#include <iostream>\n#include <dlib/matrix.h>\n#include <dlib/numeric_constants.h>\n#include <dlib/numerical_integration.h>\n\nusing namespace std;\nusing namespace dlib;\n\n// Here we the set of functions that we wish to integrate and comment in the domain of\n// integration.\n\n// x in [0,1]\ndouble gg1(double x)\n{\n    return pow(e,x);\n}   \n\n// x in [0,1]\ndouble gg2(double x)\n{\n    return x*x;\n}\n\n// x in [0, pi]\ndouble gg3(double x)\n{\n    return 1/(x*x + cos(x)*cos(x));\n}\n\n// x in [-pi, pi]\ndouble gg4(double x)\n{\n    return sin(x);\n}\n\n// x in [0,2]\ndouble gg5(double x)\n{\n    return 1/(1 + x*x);\n}\n\n\n\n#if defined(BUILD_MONOLITHIC)\n#define main(cnt, arr)      dlib_integrate_function_adapt_simp_ex_main(cnt, arr)\n#endif\n\nint main(int argc, const char** argv)\n{\n    // We first define a tolerance parameter.  Roughly speaking, a lower tolerance will\n    // result in a more accurate approximation of the true integral.  However, there are \n    // instances where too small of a tolerance may yield a less accurate approximation\n    // than a larger tolerance.  We recommend taking the tolerance to be in the\n    // [1e-10, 1e-8] region.\n    \n    double tol = 1e-10;\n\n\n    // Here we compute the integrals of the five functions defined above using the same \n    // tolerance level for each.\n\n    double m1 = integrate_function_adapt_simp(&gg1, 0.0, 1.0, tol);\n    double m2 = integrate_function_adapt_simp(&gg2, 0.0, 1.0, tol);\n    double m3 = integrate_function_adapt_simp(&gg3, 0.0, pi, tol);\n    double m4 = integrate_function_adapt_simp(&gg4, -pi, pi, tol);\n    double m5 = integrate_function_adapt_simp(&gg5, 0.0, 2.0, tol);\n\n    // We finally print out the values of each of the approximated integrals to ten\n    // significant digits.\n\n    cout << \"\\nThe integral of exp(x) for x in [0,1] is \"          << std::setprecision(10) <<  m1  << endl; \n    cout << \"The integral of x^2 for in [0,1] is \"                 << std::setprecision(10) <<  m2  << endl; \n    cout << \"The integral of 1/(x^2 + cos(x)^2) for in [0,pi] is \" << std::setprecision(10) <<  m3  << endl;\n    cout << \"The integral of sin(x) for in [-pi,pi] is \"           << std::setprecision(10) <<  m4  << endl;\n    cout << \"The integral of 1/(1+x^2) for in [0,2] is \"           << std::setprecision(10) <<  m5  << endl;\n    cout << endl;\n\n    return 0;\n}\n\n", "meta": {"hexsha": "2430f2e97d5eed45809008a3c8187fcb8858dffd", "size": 3048, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/integrate_function_adapt_simp_ex.cpp", "max_stars_repo_name": "GerHobbelt/dlib", "max_stars_repo_head_hexsha": "d26e917abc626fb81f0b57ecf1f3be555bddf8de", "max_stars_repo_licenses": ["BSL-1.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": "examples/integrate_function_adapt_simp_ex.cpp", "max_issues_repo_name": "GerHobbelt/dlib", "max_issues_repo_head_hexsha": "d26e917abc626fb81f0b57ecf1f3be555bddf8de", "max_issues_repo_licenses": ["BSL-1.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": "examples/integrate_function_adapt_simp_ex.cpp", "max_forks_repo_name": "GerHobbelt/dlib", "max_forks_repo_head_hexsha": "d26e917abc626fb81f0b57ecf1f3be555bddf8de", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.75, "max_line_length": 109, "alphanum_fraction": 0.6601049869, "num_tokens": 873, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511616741041, "lm_q2_score": 0.8757869948899665, "lm_q1q2_score": 0.7495433169556505}}
{"text": "#include <iostream>\n#include <ctime>\nusing namespace std;\n\n// for Eigen\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#define MATRIX_SIZE 50\n\n/*\n* Demo of basic use for Eigen\n*/\nint main(int argc, char** argv)\n{\n\t// The basic unit in Eigen is matrix, which is a template class,\n\t// the first 3 parameters: data type, row, column\n\tEigen::Matrix<float, 2, 3> matrix_23;\n\n\t// with typedef, Eigen provides many embedded types, but behind\n\t// it's still Eigen::Matrix\n\t// e.g. Vector3d is Eigen::Matrix<double, 3, 1>\n\t// e.g. Matrix3d is Eigen::Matrix<double, 3, 3>\n\tEigen::Vector3d v_3d;\n\tEigen::Matrix3d matrix_33 = Eigen::Matrix3d::Zero(); // 0-initialization\n\n\t// If not sure about matrix size, it can be dynamically allocated\n\tEigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> matrix_dynamic;\n\t// or simplier\n\tEigen::MatrixXd matrix_x;\n\n\tmatrix_23 << 1, 2, 3, 4, 5, 6;\n\tcout << matrix_23 << endl;\n\n\t// use () to access matrix element\n\tfor (int i = 0; i < 1; ++i)\n\t\tfor (int j = 0; j < 2; ++j)\n\t\t\tcout << matrix_23(i, j) << endl;\n\n\tv_3d << 3, 2, 1;\n\n\t// multiply matrix and vector - type mixing is wrong\n    //Eigen::Matrix<double, 2, 1> result_wrong_type = matrix_23 * v_3d;\n\n\t// should cast\n\tEigen::Matrix<double, 2, 1> result = matrix_23.cast<double>() * v_3d;\n\tcout << result << endl;\n\n\t// size shouldn't be wrong\n    //Eigen::Matrix<double, 3, 1> result_wrong_dimension = matrix_23.cast<double>() * v_3d;\n\n\t// some typical matrix operation\n    matrix_33 = Eigen::Matrix3d::Random();\n\tcout << matrix_33 << endl << endl;\n\n\tcout << matrix_33.transpose() << endl;\n\tcout << matrix_33.sum() << endl;\n\tcout << matrix_33.trace() << endl;\n\tcout << 10*matrix_33 << endl;\n\tcout << matrix_33.inverse() << endl;\n\tcout << matrix_33.determinant() << endl;\n\n\t// Eigen\n\t// real symmetric matrix coudl be guaranteed being diagonalized\n    Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> eigen_solver(matrix_33.transpose()\n\t\t*matrix_33);\n\tcout << \"Eigen values: \" << eigen_solver.eigenvalues() << endl;\n\tcout << \"Eigen vectors: \" << eigen_solver.eigenvectors() << endl;\n\n\t// solve Ax = b\n\tEigen::Matrix<double, MATRIX_SIZE, MATRIX_SIZE> matrix_NN;\n\tmatrix_NN = Eigen::MatrixXd::Random(MATRIX_SIZE, MATRIX_SIZE);\n\tEigen::Matrix<double, MATRIX_SIZE, 1> v_Nd;\n\tv_Nd = Eigen::MatrixXd::Random(MATRIX_SIZE, 1);\n\n\tclock_t time_stt = clock();\n\t// solve directly, but inverse calculation is consuming\n\tEigen::Matrix<double, MATRIX_SIZE, 1> x = matrix_NN.inverse() * v_Nd;\n\tcout << \"time used in normal inverse is: \" << 1000*(clock() - time_stt)/\n\t(double)CLOCKS_PER_SEC << \"ms\" << endl;\n    cout << \"Result with normal inverse: \" << x.transpose() << endl;\n\n\t// matrix decomposition is faster\n\ttime_stt = clock();\n\tx = matrix_NN.colPivHouseholderQr().solve(v_Nd);\n\tcout << \"time used in QR decomposition is: \" << 1000*(clock() - time_stt)/\n\t(double)CLOCKS_PER_SEC << \"ms\" << endl;\n    cout << \"Result with Qr: \" << x.transpose() << endl;\n\n\treturn 0;\n}\n", "meta": {"hexsha": "8155e73f278fc4b76232c80c7eafc5e1d4fcfef3", "size": 2931, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch03/useEigen/eigenMatrix.cpp", "max_stars_repo_name": "sunoval2016/SLAM-14", "max_stars_repo_head_hexsha": "72d848c159ff766d87c9bc3c0a170f84745a3785", "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": "ch03/useEigen/eigenMatrix.cpp", "max_issues_repo_name": "sunoval2016/SLAM-14", "max_issues_repo_head_hexsha": "72d848c159ff766d87c9bc3c0a170f84745a3785", "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": "ch03/useEigen/eigenMatrix.cpp", "max_forks_repo_name": "sunoval2016/SLAM-14", "max_forks_repo_head_hexsha": "72d848c159ff766d87c9bc3c0a170f84745a3785", "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.8586956522, "max_line_length": 91, "alphanum_fraction": 0.6734902764, "num_tokens": 887, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894717137996, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.7494935299284644}}
{"text": "#pragma once\n\n#include \"math.h\"\n#include <Eigen/Dense>\n\nnamespace geodetic_trans {\n\n// Geodetic system parameters\nstatic double earthR = 6378137;\nstatic double earthFlattening = 1 / 298.257223563;\n\n/**\n * convert from radian to degrees\n * @param  radians angle in radian\n * @return         angle in degrees\n */\ninline double rad2deg(const double radians) {\n\treturn (radians / M_PI) * 180.0;\n}\n\n/**\n * convert from degree to radian\n * @param  degrees angle in degree\n * @return         angle in radian\n */\ninline double deg2rad(const double degrees) {\n\treturn (degrees / 180.0) * M_PI;\n}\n\n\n/**\n * convert from LLA position to ECEF position\n * @param lat latitude in [deg]\n * @param lon longitude in [deg]\n * @param alt altitude in [deg]\n * @param x   ECEF x position in [m]\n * @param y   ECEF y position in [m]\n * @param z   ECEF z position in [m]\n */\nvoid lla2ecef(const double lat, const double lon, const float alt,\n\t\t\t  float* x, float* y, float* z) {\n\n\tdouble lat_rad = deg2rad(lat);\n\tdouble lon_rad = deg2rad(lon);\n\n\tdouble e2 = (2 - earthFlattening) * earthFlattening;\n\tdouble r_N = earthR / sqrt(1 - e2 * sin(lat_rad) * sin(lat_rad));\n\t*x = (r_N + alt) * cos(lat_rad) * cos(lon_rad);\n\t*y = (r_N + alt) * cos(lat_rad) * sin(lon_rad);\n\t*z = (r_N * (1 - e2) + alt) * sin(lat_rad);\n}\n\n\n\nvoid ecef2ned(const double ref_lat, const double ref_lon, const float ref_alt,\n\t\t\t const float x, const float y, const float z,\n\t\t\t float* north, float* east, float* down) {\n\n\t// get the reference LLA position as an ECEF coordinate\n\tfloat ref_x, ref_y, ref_z;\n\tlla2ecef(ref_lat, ref_lon, ref_alt, &ref_x, &ref_y, &ref_z);\n\n\t// build the rotation matrix from ECEF to NED for the given reference\n\t// location\n\tconst double s_lat = sin(deg2rad(ref_lat));\n    const double s_lon = sin(deg2rad(ref_lon));\n    const double c_lat = cos(deg2rad(ref_lat));\n    const double c_lon = cos(deg2rad(ref_lon));\n\n    Eigen::Matrix3d rot_ecef2ned;\n    rot_ecef2ned(0, 0) = -s_lat * c_lon;\n    rot_ecef2ned(0, 1) = -s_lat * s_lon;\n    rot_ecef2ned(0, 2) = c_lat;\n    rot_ecef2ned(1, 0) = -s_lon;\n    rot_ecef2ned(1, 1) = c_lon;\n    rot_ecef2ned(1, 2) = 0.0;\n    rot_ecef2ned(2, 0) = c_lat * c_lon;\n    rot_ecef2ned(2, 1) = c_lat * s_lon;\n    rot_ecef2ned(2, 2) = s_lat;\n\n    // get the vector for the reference point to the current location and rotate\n    // it\n\tEigen::Vector3d ecef_vec, ned_vec;\n\tecef_vec << (x - ref_x), (y - ref_y), (z - ref_z);\n\tned_vec = rot_ecef2ned * ecef_vec;\n\t*north = ned_vec(0);\n\t*east = ned_vec(1);\n\t*down = -ned_vec(2);\n}\n\nvoid lla2enu(const double ref_lat, const double ref_lon, const float ref_alt,\n\t\t\t const double lat, const double lon, const float alt,\n\t\t\t float* east, float* north, float* up) {\n\n\t// Geodetic position to local ENU frame\n\tfloat x, y, z;\n\tlla2ecef(lat, lon, alt, &x, &y, &z);\n\n\tfloat aux_north, aux_east, aux_down;\n\tecef2ned(ref_lat, ref_lon, ref_alt, x, y, z, &aux_north, &aux_east, &aux_down);\n\n\t*east = aux_east;\n\t*north = aux_north;\n\t*up = -aux_down;\n}\n\n\n\n\n}; // namespace geodetic_trans\n", "meta": {"hexsha": "ad10e709d7d1f67e3a8f9386abb6bac73c1bbc7f", "size": 3017, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/geodetic_trans.hpp", "max_stars_repo_name": "adrnp/aa241x_mission", "max_stars_repo_head_hexsha": "bdd63ed27fe8380aed0e125fe5e15c1834dfb77d", "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/geodetic_trans.hpp", "max_issues_repo_name": "adrnp/aa241x_mission", "max_issues_repo_head_hexsha": "bdd63ed27fe8380aed0e125fe5e15c1834dfb77d", "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": "include/geodetic_trans.hpp", "max_forks_repo_name": "adrnp/aa241x_mission", "max_forks_repo_head_hexsha": "bdd63ed27fe8380aed0e125fe5e15c1834dfb77d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-04-30T22:12:53.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-04T19:51:50.000Z", "avg_line_length": 27.1801801802, "max_line_length": 80, "alphanum_fraction": 0.664235996, "num_tokens": 993, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947132556618, "lm_q2_score": 0.7931059438487662, "lm_q1q2_score": 0.7494809239887258}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n\nusing namespace std;\nusing namespace Eigen;\n\nint main()\n{\n   Matrix3f A;\n   Vector3f b;\n   A << 1,2,3,  4,5,6,  7,8,10;\n   b << 3, 3, 4;\n   cout << \"Here is the matrix A:\\n\" << A << endl;\n   cout << \"Here is the vector b:\\n\" << b << endl;\n   Vector3f x = A.colPivHouseholderQr().solve(b);\n   cout << \"The solution is:\\n\" << x << endl;\n}\n", "meta": {"hexsha": "3a99a94d75bc938abb4a82134875b928dbbfa32b", "size": 381, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Eigen-3.3/doc/examples/TutorialLinAlgExSolveColPivHouseholderQR.cpp", "max_stars_repo_name": "shareq2005/CarND-MPC-Project", "max_stars_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3457.0, "max_stars_repo_stars_event_min_datetime": "2018-06-09T15:36:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-01T22:09:25.000Z", "max_issues_repo_path": "src/Eigen-3.3/doc/examples/TutorialLinAlgExSolveColPivHouseholderQR.cpp", "max_issues_repo_name": "shareq2005/CarND-MPC-Project", "max_issues_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 851.0, "max_issues_repo_issues_event_min_datetime": "2017-11-27T15:09:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:26:38.000Z", "max_forks_repo_path": "src/Eigen-3.3/doc/examples/TutorialLinAlgExSolveColPivHouseholderQR.cpp", "max_forks_repo_name": "shareq2005/CarND-MPC-Project", "max_forks_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1380.0, "max_forks_repo_forks_event_min_datetime": "2017-06-12T23:58:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:52:48.000Z", "avg_line_length": 21.1666666667, "max_line_length": 50, "alphanum_fraction": 0.5721784777, "num_tokens": 140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9219218305645894, "lm_q2_score": 0.8128673155708976, "lm_q1q2_score": 0.7494001235772457}}
{"text": "#include <gtest/gtest.h>\n\n#include \"../Math/math.hh\"\n#include \"helpers.hh\"\n#include \"../geometry/LineSegment/LineSegment2/linesegment2.hh\"\n\n#include <Eigen/Core>\n\nusing namespace Eigen;\nusing namespace bold;\n\nTEST (MathTests, intersectRayWithPlane)\n{\n  // Intersect ray pointing straight downwards\n  EXPECT_EQ ( Maybe<Vector3d>(Vector3d(1,2,0)), Math::intersectRayWithPlane(Vector3d(1,2,3), Vector3d(0,0,-1), Vector4d(0,0,1,0)) );\n  // As above, but flip plane (intersect from other side)\n  EXPECT_EQ ( Maybe<Vector3d>(Vector3d(1,2,0)), Math::intersectRayWithPlane(Vector3d(1,2,3), Vector3d(0,0,-1), Vector4d(0,0,-1,0)) );\n\n  // Ray's position is on plane\n  EXPECT_EQ ( Maybe<Vector3d>(Vector3d(1,2,0)), Math::intersectRayWithPlane(Vector3d(1,2,0), Vector3d(0,0,1), Vector4d(0,0,1,0)) );\n\n  // Intersect x-axis with plane perpendicular to x-axis\n  EXPECT_EQ ( Maybe<Vector3d>(Vector3d(1,0,0)),\n              Math::intersectRayWithPlane(Vector3d(0,0,0), Vector3d(1,0,0), Vector4d(-1,0,0,1)) );\n\n  // Parallel ray doesn't intersect\n  EXPECT_EQ ( Maybe<Vector3d>::empty(),\n              Math::intersectRayWithPlane(Vector3d(0,0,1), Vector3d(1,0,0), Vector4d(0,0,1,0)) );\n\n  // Coplanar ray doesn't intersect\n  EXPECT_EQ ( Maybe<Vector3d>::empty(),\n              Math::intersectRayWithPlane(Vector3d(0,0,0), Vector3d(1,0,0), Vector4d(0,0,1,0)) );\n\n  // Ray that points away from plane doesn't intersect\n  EXPECT_EQ ( Maybe<Vector3d>::empty(),\n              Math::intersectRayWithPlane(Vector3d(0,0,1), Vector3d(0,0,1), Vector4d(0,0,1,0)) );\n}\n\nTEST (MathTests, intersectRayWithGroundPlane)\n{\n  // Intersect ray pointing straight downwards\n  EXPECT_EQ ( Maybe<Vector3d>(Vector3d(1,2,0)), Math::intersectRayWithGroundPlane(Vector3d(1,2,3), Vector3d(0,0,-1), 0) );\n\n  // Ray's position is on plane\n  EXPECT_EQ ( Maybe<Vector3d>(Vector3d(1,2,0)), Math::intersectRayWithGroundPlane(Vector3d(1,2,0), Vector3d(0,0,1), 0) );\n\n  // Parallel ray doesn't intersect\n  EXPECT_EQ ( Maybe<Vector3d>::empty(),\n              Math::intersectRayWithGroundPlane(Vector3d(0,0,1), Vector3d(1,0,0), 0) );\n\n  // Coplanar ray doesn't intersect\n  EXPECT_EQ ( Maybe<Vector3d>::empty(),\n              Math::intersectRayWithGroundPlane(Vector3d(0,0,0), Vector3d(1,0,0), 0) );\n\n  // Ray that points away from plane doesn't intersect\n  EXPECT_EQ ( Maybe<Vector3d>::empty(),\n              Math::intersectRayWithGroundPlane(Vector3d(0,0,1), Vector3d(0,0,1), 0) );\n\n  // Ground plane not at zero\n  EXPECT_EQ ( Maybe<Vector3d>(Vector3d(1,2,1)),\n              Math::intersectRayWithGroundPlane(Vector3d(1,2,3), Vector3d(0,0,-1), 1) );\n\n  // Diagonal ray\n  EXPECT_TRUE ( VectorsEqual(\n\t\t  Vector3d(1,1,0),\n\t\t  *(Math::intersectRayWithGroundPlane(Vector3d(0,0,1),\n\t\t\t\t\t\t      Vector3d(1,1,-1).normalized(),\n\t\t\t\t\t\t      0))\n\t\t  ) );\n  EXPECT_TRUE ( VectorsEqual(\n\t\t  Vector3d(2,2,0),\n\t\t  *(Math::intersectRayWithGroundPlane(Vector3d(0,0,2),\n\t\t\t\t\t\t      Vector3d(1,1,-1).normalized(),\n\t\t\t\t\t\t      0))\n\t\t  ) );\n}\n\nTEST (MathTests, findPerpendicularVector)\n{\n  EXPECT_TRUE( VectorsEqual (Vector2d( 0,-1), Math::findPerpendicularVector(Vector2d( 1, 0))) );\n  EXPECT_TRUE( VectorsEqual (Vector2d( 0, 1), Math::findPerpendicularVector(Vector2d(-1, 0))) );\n  EXPECT_TRUE( VectorsEqual (Vector2d( 1, 0), Math::findPerpendicularVector(Vector2d( 0, 1))) );\n  EXPECT_TRUE( VectorsEqual (Vector2d(-1, 0), Math::findPerpendicularVector(Vector2d( 0,-1))) );\n}\n\nTEST (MathTests, linePointClosestToPoint)\n{\n  LineSegment2d unitX(Vector2d(0,0), Vector2d::UnitX());\n\n  EXPECT_TRUE( VectorsEqual (Vector2d(  0, 0), Math::linePointClosestToPoint(unitX, Vector2d(  0, 0))) ) << \"At p1\";\n  EXPECT_TRUE( VectorsEqual (Vector2d(  1, 0), Math::linePointClosestToPoint(unitX, Vector2d(  1, 0))) ) << \"At p2\";\n  EXPECT_TRUE( VectorsEqual (Vector2d(  0, 0), Math::linePointClosestToPoint(unitX, Vector2d(  0, 1))) ) << \"Above p1\";\n  EXPECT_TRUE( VectorsEqual (Vector2d(  0, 0), Math::linePointClosestToPoint(unitX, Vector2d(  0,-1))) ) << \"Below p1\";\n  EXPECT_TRUE( VectorsEqual (Vector2d(0.5, 0), Math::linePointClosestToPoint(unitX, Vector2d(0.5, 1))) ) << \"Above midpoint\";\n  EXPECT_TRUE( VectorsEqual (Vector2d(0.5, 0), Math::linePointClosestToPoint(unitX, Vector2d(0.5,-1))) ) << \"Below midpoint\";\n  EXPECT_TRUE( VectorsEqual (Vector2d(  0, 0), Math::linePointClosestToPoint(unitX, Vector2d( -1, 0))) ) << \"Beyond p1\";\n  EXPECT_TRUE( VectorsEqual (Vector2d(  1, 0), Math::linePointClosestToPoint(unitX, Vector2d(  2, 0))) ) << \"Beyond p2\";\n}\n\nTEST (MathTests, createNormalRng)\n{\n  double mean = 1.5;\n  auto rng = Math::createNormalRng(mean, 1);\n  double sum = 0;\n  auto loopCount = unsigned{1000};\n  for (auto i = unsigned{0}; i < loopCount; i++)\n  {\n    sum += rng();\n  }\n  EXPECT_NEAR(mean, sum/loopCount, 0.2);\n}\n\nTEST (MathTests, degreesRadiansConversion)\n{\n  EXPECT_EQ( 0, Math::degToRad(0) );\n  EXPECT_EQ( 0, Math::radToDeg(0) );\n\n  EXPECT_EQ( M_PI, Math::degToRad(180) );\n  EXPECT_EQ( 180.0, Math::radToDeg(M_PI) );\n\n  EXPECT_EQ( M_PI/2, Math::degToRad(90) );\n  EXPECT_EQ( 90.0, Math::radToDeg(M_PI/2) );\n\n  EXPECT_EQ( M_PI/4, Math::degToRad(45) );\n  EXPECT_EQ( 45.0, Math::radToDeg(M_PI/4) );\n\n  EXPECT_EQ( -M_PI/4, Math::degToRad(-45) );\n  EXPECT_EQ( -45.0, Math::radToDeg(-M_PI/4) );\n}\n\nTEST (MathTests, smallestAngleBetween)\n{\n  EXPECT_NEAR( 0, Math::smallestAngleBetween(Vector2d(0,1), Vector2d(0,1)), 0.0000001 );\n  EXPECT_NEAR( 0, Math::smallestAngleBetween(Vector2d(1,1), Vector2d(1,1)), 0.0000001 );\n  EXPECT_NEAR( 0, Math::smallestAngleBetween(Vector2d(-1,-1), Vector2d(-1,-1)), 0.0000001 );\n\n  EXPECT_NEAR( M_PI, Math::smallestAngleBetween(Vector2d(0,1), Vector2d(0,-1)), 0.0000001 );\n  EXPECT_NEAR( M_PI, Math::smallestAngleBetween(Vector2d(1,1), Vector2d(-1,-1)), 0.0000001 );\n  EXPECT_NEAR( M_PI, Math::smallestAngleBetween(Vector2d(1,0), Vector2d(-1,0)), 0.0000001 );\n\n  EXPECT_NEAR( M_PI/2, Math::smallestAngleBetween(Vector2d(0,1), Vector2d(1,0)), 0.0000001 );\n  EXPECT_NEAR( M_PI/2, Math::smallestAngleBetween(Vector2d(0,1), Vector2d(-1,0)), 0.0000001 );\n\n  EXPECT_NEAR( M_PI/4, Math::smallestAngleBetween(Vector2d(0,1), Vector2d(1,1)), 0.0000001 );\n  EXPECT_NEAR( M_PI/4, Math::smallestAngleBetween(Vector2d(0,1), Vector2d(-1,1)), 0.0000001 );\n  EXPECT_NEAR( M_PI/4, Math::smallestAngleBetween(Vector2d(-1,-1), Vector2d(-1,0)), 0.0000001 );\n}\n\nTEST (MathTests, alignUp)\n{\n  auto transform = Affine3d::Identity();\n\n  EXPECT_TRUE( MatricesEqual( transform.matrix(), Math::alignUp(transform).matrix() ) );\n\n  auto rotated = AngleAxisd(.5 * M_PI, Vector3d(0, 0, 1)) * transform;\n  EXPECT_TRUE( MatricesEqual( rotated.matrix(), Math::alignUp(rotated).matrix() ) );\n  rotated = AngleAxisd(M_PI, Vector3d(0, 0, 1)) * transform;\n  EXPECT_TRUE( MatricesEqual( rotated.matrix(), Math::alignUp(rotated).matrix() ) );\n  rotated = AngleAxisd(1.5 * M_PI, Vector3d(0, 0, 1)) * transform;\n  EXPECT_TRUE( MatricesEqual( rotated.matrix(), Math::alignUp(rotated).matrix() ) );\n  rotated = AngleAxisd(2 * M_PI, Vector3d(0, 0, 1)) * transform;\n  EXPECT_TRUE( MatricesEqual( rotated.matrix(), Math::alignUp(rotated).matrix() ) );\n  rotated = AngleAxisd(0.64637 * M_PI, Vector3d(0, 0, 1)) * transform;\n  EXPECT_TRUE( MatricesEqual( rotated.matrix(), Math::alignUp(rotated).matrix() ) );\n\n  rotated = AngleAxisd(0.1 * M_PI, Vector3d(1, 0, 0)) * transform;\n  EXPECT_TRUE( MatricesEqual( transform.matrix(), Math::alignUp(rotated).matrix() ) );\n  rotated = AngleAxisd(0.25 * M_PI, Vector3d(1, 0, 0)) * transform;\n  EXPECT_TRUE( MatricesEqual( transform.matrix(), Math::alignUp(rotated).matrix() ) );\n  rotated = AngleAxisd(0.49 * M_PI, Vector3d(1, 0, 0)) * transform;\n  EXPECT_TRUE( MatricesEqual( transform.matrix(), Math::alignUp(rotated).matrix() ) );\n\n  rotated = AngleAxisd(-0.1 * M_PI, Vector3d(1, 0, 0)) * transform;\n  EXPECT_TRUE( MatricesEqual( transform.matrix(), Math::alignUp(rotated).matrix() ) );\n  rotated = AngleAxisd(-0.25 * M_PI, Vector3d(1, 0, 0)) * transform;\n  EXPECT_TRUE( MatricesEqual( transform.matrix(), Math::alignUp(rotated).matrix() ) );\n  rotated = AngleAxisd(-0.49 * M_PI, Vector3d(1, 0, 0)) * transform;\n  EXPECT_TRUE( MatricesEqual( transform.matrix(), Math::alignUp(rotated).matrix() ) );\n\n  rotated = AngleAxisd(0.1 * M_PI, Vector3d(0, 1, 0)) * transform;\n  EXPECT_TRUE( MatricesEqual( transform.matrix(), Math::alignUp(rotated).matrix() ) );\n  rotated = AngleAxisd(0.25 * M_PI, Vector3d(0, 1, 0)) * transform;\n  EXPECT_TRUE( MatricesEqual( transform.matrix(), Math::alignUp(rotated).matrix() ) );\n  rotated = AngleAxisd(0.49 * M_PI, Vector3d(0, 1, 0)) * transform;\n  EXPECT_TRUE( MatricesEqual( transform.matrix(), Math::alignUp(rotated).matrix() ) );\n\n  rotated = AngleAxisd(-0.1 * M_PI, Vector3d(0, 1, 0)) * transform;\n  EXPECT_TRUE( MatricesEqual( transform.matrix(), Math::alignUp(rotated).matrix() ) );\n  rotated = AngleAxisd(-0.25 * M_PI, Vector3d(0, 1, 0)) * transform;\n  EXPECT_TRUE( MatricesEqual( transform.matrix(), Math::alignUp(rotated).matrix() ) );\n  rotated = AngleAxisd(-0.49 * M_PI, Vector3d(0, 1, 0)) * transform;\n  EXPECT_TRUE( MatricesEqual( transform.matrix(), Math::alignUp(rotated).matrix() ) );\n\n  rotated = AngleAxisd(0.1 * M_PI, Vector3d(1, 1, 0).normalized()) * transform;\n  EXPECT_TRUE( MatricesEqual( transform.matrix(), Math::alignUp(rotated).matrix() ) );\n  rotated = AngleAxisd(0.25 * M_PI, Vector3d(1, 1, 0).normalized()) * transform;\n  EXPECT_TRUE( MatricesEqual( transform.matrix(), Math::alignUp(rotated).matrix() ) );\n  rotated = AngleAxisd(0.49 * M_PI, Vector3d(1, 1, 0).normalized()) * transform;\n  EXPECT_TRUE( MatricesEqual( transform.matrix(), Math::alignUp(rotated).matrix() ) );\n\n}\n\nTEST(MathTests, lerp)\n{\n  // Ratio based\n  EXPECT_NEAR( 0, Math::lerp(0, 0, 1), 0.00001 );\n  EXPECT_NEAR( 0, Math::lerp(0, 0, 0), 0.00001 );\n  EXPECT_NEAR( 0, Math::lerp(0, 0, 100), 0.00001 );\n  EXPECT_NEAR( 5, Math::lerp(0, 5, 100), 0.00001 );\n\n  EXPECT_NEAR( 5, Math::lerp(0.5, 0, 10), 0.00001 );\n  EXPECT_NEAR( 5, Math::lerp(0.5, 10, 0), 0.00001 );\n\n  EXPECT_NEAR( 5, Math::lerp(1, 4, 5), 0.00001 );\n  EXPECT_NEAR( 20, Math::lerp(2, 0, 10), 0.00001 );\n  EXPECT_NEAR( -10, Math::lerp(-1, 0, 10), 0.00001 );\n\n  // Map based\n  EXPECT_NEAR( 10, Math::lerp(0, 0, 1, 10, 20), 0.00001 );\n  EXPECT_NEAR( 15, Math::lerp(0.5, 0, 1, 10, 20), 0.00001 );\n  EXPECT_NEAR( 20, Math::lerp(1, 0, 1, 10, 20), 0.00001 );\n  // outside range\n  // TODO this is inconsistent with the other lerp function which extends beyond the given domain\n  EXPECT_NEAR( 20, Math::lerp(2, 0, 1, 10, 20), 0.00001 ); // other lerp gives 30\n  EXPECT_NEAR( 10, Math::lerp(0, 1, 2, 10, 20), 0.00001 ); // other lerp gives 0\n\n  EXPECT_TRUE ( VectorsEqual(Vector2d(0,0), Math::lerp(0.0, Vector2d(0,0), Vector2d(10,10))) );\n  EXPECT_TRUE ( VectorsEqual(Vector2d(5,5), Math::lerp(0.5, Vector2d(0,0), Vector2d(10,10))) );\n  EXPECT_TRUE ( VectorsEqual(Vector2d(9,9), Math::lerp(0.9, Vector2d(0,0), Vector2d(10,10))) );\n}\n\nQuaterniond create(double pitch, double roll, double yaw)\n{\n  AngleAxisd pitchAngle(pitch, Vector3d::UnitX());\n  AngleAxisd rollAngle(roll, Vector3d::UnitY());\n  AngleAxisd yawAngle(yaw, Vector3d::UnitZ());\n\n  Quaternion<double> q = rollAngle * pitchAngle * yawAngle;\n  return q;\n}\n\nTEST(MathTests, normaliseRads)\n{\n  // Ensures return value is in range [-PI,PI)\n  EXPECT_NEAR ( 0.0, Math::normaliseRads(0), 0.0001 );\n  EXPECT_NEAR ( -M_PI, Math::normaliseRads(M_PI), 0.0001 );\n  EXPECT_NEAR ( -M_PI, Math::normaliseRads(-M_PI), 0.0001 );\n  EXPECT_NEAR ( M_PI/2, Math::normaliseRads(M_PI/2), 0.0001 );\n  EXPECT_NEAR ( -M_PI/2, Math::normaliseRads(-M_PI/2), 0.0001 );\n  EXPECT_NEAR ( 0, Math::normaliseRads(6*M_PI), 0.0001 );\n}\n\nTEST(MathTests, angleDiffRads)\n{\n  EXPECT_NEAR ( 0.0, Math::angleDiffRads(M_PI, M_PI), 0.0001 );\n  EXPECT_NEAR ( 0.25 * M_PI, Math::angleDiffRads(0, 0.25 * M_PI), 0.0001 );\n  EXPECT_NEAR ( 0.25 * M_PI, Math::angleDiffRads(1.75 * M_PI, 0), 0.0001 );\n  EXPECT_NEAR ( M_PI, Math::angleDiffRads(.25 * M_PI, 1.25 * M_PI), 0.0001 );\n  EXPECT_NEAR ( M_PI, Math::angleDiffRads(1.25 * M_PI, 0.25 * M_PI), 0.0001 );\n  EXPECT_NEAR ( 1.5 * M_PI, Math::angleDiffRads(0, 1.5 * M_PI), 0.0001 );\n  EXPECT_NEAR ( 1.5 * M_PI, Math::angleDiffRads(0.5 * M_PI, 0), 0.0001 );\n}\n\nTEST(MathTests, shortestAngleDiffRads)\n{\n  // Assumes input angles are both in range [-PI,PI)\n  EXPECT_NEAR ( 0.0, Math::shortestAngleDiffRads(0, 0), 0.0001 );\n  EXPECT_NEAR ( 0.1, Math::shortestAngleDiffRads(0, 0.1), 0.0001 );\n  EXPECT_NEAR ( -0.1, Math::shortestAngleDiffRads(0.1, 0), 0.0001 );\n  EXPECT_NEAR ( 0.0, Math::shortestAngleDiffRads(0, 2*M_PI), 0.0001 );\n  EXPECT_NEAR ( 0.0, Math::shortestAngleDiffRads(-M_PI, M_PI), 0.0001 );\n  EXPECT_NEAR ( M_PI, Math::shortestAngleDiffRads(-M_PI/2, M_PI/2), 0.0001 );\n  EXPECT_NEAR ( -M_PI/2, Math::shortestAngleDiffRads(0, 3*M_PI/2), 0.0001 );\n  EXPECT_NEAR ( M_PI/2, Math::shortestAngleDiffRads(0, -3*M_PI/2), 0.0001 );\n  EXPECT_NEAR ( 2*M_PI/3, Math::shortestAngleDiffRads(-M_PI/3, M_PI/3), 0.0001 );\n  EXPECT_NEAR ( -2*M_PI/3, Math::shortestAngleDiffRads(-2*M_PI/3, 2*M_PI/3), 0.0001 );\n  EXPECT_NEAR ( 2*M_PI/3, Math::shortestAngleDiffRads(2*M_PI/3, -2*M_PI/3), 0.0001 );\n  EXPECT_NEAR ( -M_PI/3, Math::shortestAngleDiffRads(0, 11*M_PI/3), 0.0001 );\n  EXPECT_NEAR ( 2.00605, Math::shortestAngleDiffRads(-2.44379, -0.43774), 0.0001 );\n}\n\nTEST(MathTests, angleToPoint)\n{\n  EXPECT_EQ ( 0, Math::angleToPoint(Vector2d(0, 2)) );\n  EXPECT_EQ ( 0, Math::angleToPoint(Vector2d(0, 3)) );\n  EXPECT_NEAR (  M_PI/4, Math::angleToPoint(Vector2d(-1, 1)), 0.0001 );\n  EXPECT_NEAR ( -M_PI/4, Math::angleToPoint(Vector2d(1, 1)), 0.0001 );\n  EXPECT_NEAR (  M_PI/2, Math::angleToPoint(Vector2d(-1, 0)), 0.0001 );\n  EXPECT_NEAR ( -M_PI/2, Math::angleToPoint(Vector2d(1, 0)), 0.0001 );\n  EXPECT_NEAR ( -M_PI,   Math::angleToPoint(Vector2d(0, -1)), 0.0001 );\n}\n", "meta": {"hexsha": "ab5b67d8831fb11764537bb1a51b2fb715ad75f2", "size": 13754, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/MathTests.cc", "max_stars_repo_name": "drewnoakes/bold-humanoid", "max_stars_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "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": "test/MathTests.cc", "max_issues_repo_name": "drewnoakes/bold-humanoid", "max_issues_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "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": "test/MathTests.cc", "max_forks_repo_name": "drewnoakes/bold-humanoid", "max_forks_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "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": 47.102739726, "max_line_length": 133, "alphanum_fraction": 0.6757306965, "num_tokens": 5052, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.924141826246517, "lm_q2_score": 0.8104789155369047, "lm_q1q2_score": 0.7489974651385717}}
{"text": "#ifndef BRUTE_FORCE_HPP\n#define BRUTE_FORCE_HPP\n\n#include <boost/multiprecision/cpp_int.hpp>\n\n#include \"big_int_type.hpp\"\n#include \"euclidean.hpp\"\n#include \"mod_exponentiation.hpp\"\n\nbig_int sub_abs(const big_int &x, const big_int &y);\n\nbig_int naive_factorization(const big_int &n);\n\nbig_int pollard_algorithm(const big_int &n);\n\nbig_int brute_force_key(const big_int &e, const big_int &n, bool naive = false);\n\n#endif\n", "meta": {"hexsha": "86150b3ac208e465bb37f74b9895806c2da6d7ce", "size": 419, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/brute_force.hpp", "max_stars_repo_name": "paulora2405/cal-tf", "max_stars_repo_head_hexsha": "7fc1c5f5b070ff7dc2800ced5951f6e37abc1db5", "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/brute_force.hpp", "max_issues_repo_name": "paulora2405/cal-tf", "max_issues_repo_head_hexsha": "7fc1c5f5b070ff7dc2800ced5951f6e37abc1db5", "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": "include/brute_force.hpp", "max_forks_repo_name": "paulora2405/cal-tf", "max_forks_repo_head_hexsha": "7fc1c5f5b070ff7dc2800ced5951f6e37abc1db5", "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.0526315789, "max_line_length": 80, "alphanum_fraction": 0.7875894988, "num_tokens": 105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9161096204605945, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.7489878390120028}}
{"text": "#ifndef MATH_FUNCTIONS\n#define MATH_FUNCTIONS\n\n#include <Eigen/Dense>\n#include <Eigen/Core>\n#include <math.h>\n#include <iostream>\n\n\nnamespace Math {\nclass MathFunc {\n  typedef Eigen::Matrix<double, 3, 3> RotationMatrix;\n  typedef Eigen::Matrix<double, 3, 1> EulerVector;\n  typedef Eigen::Matrix<double, 3, 1> Axis;\n  typedef Eigen::Matrix<double, 4, 1> Quaternion;\n\n\n public:\n  template<typename T>\n  static inline int getSign(T val) {\n    return (T(0) < val) - (val < T(0));\n  }\n\n  static inline RotationMatrix skewM(Eigen::Vector3d &vec) {\n    RotationMatrix mat;\n    mat << 0.0, -vec(2), vec(1),\n        vec(2), 0.0, -vec(0),\n        -vec(1), vec(0), 0.0;\n    return mat;\n  }\n\n  static inline RotationMatrix expM(EulerVector &vec) {\n    RotationMatrix rot;\n    double angle = vec.norm();\n    if (angle < 1e-10) return RotationMatrix::Identity();\n    Axis axis = vec / angle;\n    Eigen::Matrix3d vecSkew = skewM(axis);\n    rot = RotationMatrix::Identity() + sin(angle) * vecSkew + (1.0 - cos(angle)) * vecSkew * vecSkew;\n    return rot;\n  }\n\n  static inline RotationMatrix expM(double angle, Axis &axis) {\n    RotationMatrix rot;\n    Eigen::Matrix3d vecSkew = skewM(axis);\n    rot = RotationMatrix::Identity() + sin(angle) * vecSkew + (1.0 - cos(angle)) * vecSkew * vecSkew;\n    return rot;\n  }\n\n  template<typename Derived, typename Dtype>\n  static inline void limitAbsoluteValue(Eigen::MatrixBase<Derived> &matrix, Dtype threshold) {\n    int numberOfElements = matrix.rows() * matrix.cols();\n    for (int rowID = 0; rowID < matrix.rows(); rowID++)\n      for (int colID = 0; colID < matrix.cols(); colID++)\n        if (abs(matrix(rowID, colID)) > threshold)\n          matrix(rowID, colID) = getSign(Dtype(1.0)) * threshold;\n  }\n  static inline Quaternion EulertoQuat(double roll, double pitch,  double yaw)\n  {\n    Quaternion q;\n    double t0 = std::cos(yaw * 0.5);\n    double t1 = std::sin(yaw * 0.5);\n    double t2 = std::cos(roll * 0.5);\n    double t3 = std::sin(roll * 0.5);\n    double t4 = std::cos(pitch * 0.5);\n    double t5 = std::sin(pitch * 0.5);\n\n    q[0] = t0 * t2 * t4 + t1 * t3 * t5;\n    q[1] = t0 * t3 * t4 - t1 * t2 * t5;\n    q[2] = t0 * t2 * t5 + t1 * t3 * t4;\n    q[3] = t1 * t2 * t4 - t0 * t3 * t5;\n    return q;\n  }\n\n  static inline void QuattoEuler(const Quaternion& q, double& roll, double& pitch, double& yaw)\n  {\n    double ysqr = q[2] * q[2];\n\n    // roll (x-axis rotation)\n    double t0 = +2.0 * (q[0] * q[1] + q[2] * q[3]);\n    double t1 = +1.0 - 2.0 * (q[1] * q[1] + ysqr);\n    roll = std::atan2(t0, t1);\n\n    // pitch (y-axis rotation)\n    double t2 = +2.0 * (q[0] * q[2] - q[3] * q[1]);\n    t2 = t2 > 1.0 ? 1.0 : t2;\n    t2 = t2 < -1.0 ? -1.0 : t2;\n    pitch = std::asin(t2);\n\n    // yaw (z-axis rotation)\n    double t3 = +2.0 * (q[0] * q[3] + q[1] * q[2]);\n    double t4 = +1.0 - 2.0 * (ysqr + q[3] * q[3]);\n    yaw = std::atan2(t3, t4);\n  }\n\n  static inline RotationMatrix quatToRotMat(Quaternion &q) {\n    RotationMatrix R;\n    R << q(0) * q(0) + q(1) * q(1) - q(2) * q(2) - q(3) * q(3),\n        2 * q(1) * q(2) - 2 * q(0) * q(3),\n        2 * q(0) * q(2) + 2 * q(1) * q(3),\n\n        2 * q(0) * q(3) + 2 * q(1) * q(2),\n        q(0) * q(0) - q(1) * q(1) + q(2) * q(2) - q(3) * q(3),\n        2 * q(2) * q(3) - 2 * q(0) * q(1),\n\n        2 * q(1) * q(3) - 2 * q(0) * q(2),\n        2 * q(0) * q(1) + 2 * q(2) * q(3),\n        q(0) * q(0) - q(1) * q(1) - q(2) * q(2) + q(3) * q(3);\n    return R;\n  }\n\n  static inline Quaternion rotMatToQuat(RotationMatrix &R) {\n    Quaternion quat;\n    double tr = R.trace();\n    if (tr > 0.0) {\n      double S = sqrt(tr + 1.0) * 2.0; // S=4*qw\n      quat(0) = 0.25 * S;\n      quat(1) = (R(2, 1) - R(1, 2)) / S;\n      quat(2) = (R(0, 2) - R(2, 0)) / S;\n      quat(3) = (R(1, 0) - R(0, 1)) / S;\n    } else if ((R(0, 0) > R(1, 1)) & (R(0, 0) > R(2, 2))) {\n      double S = sqrt(1.0 + R(0, 0) - R(1, 1) - R(2, 2)) * 2.0; // S=4*qx\n      quat(0) = (R(2, 1) - R(1, 2)) / S;\n      quat(1) = 0.25 * S;\n      quat(2) = (R(0, 1) + R(1, 0)) / S;\n      quat(3) = (R(0, 2) + R(2, 0)) / S;\n    } else if (R(1, 1) > R(2, 2)) {\n      double S = sqrt(1.0 + R(1, 1) - R(0, 0) - R(2, 2)) * 2.0; // S=4*qy\n      quat(0) = (R(0, 2) - R(2, 0)) / S;\n      quat(1) = (R(0, 1) + R(1, 0)) / S;\n      quat(2) = 0.25 * S;\n      quat(3) = (R(1, 2) + R(2, 1)) / S;\n    } else {\n      double S = sqrt(1.0 + R(2, 2) - R(0, 0) - R(1, 1)) * 2.0; // S=4*qz\n      quat(0) = (R(1, 0) - R(0, 1)) / S;\n      quat(1) = (R(0, 2) + R(2, 0)) / S;\n      quat(2) = (R(1, 2) + R(2, 1)) / S;\n      quat(3) = 0.25 * S;\n    }\n    return quat;\n  }\n\n\n  static inline Quaternion quatMultiplication(Quaternion &q, Quaternion &p) {\n    Quaternion quat;\n    quat << p(0) * q(0) - p(1) * q(1) - p(2) * q(2) - p(3) * q(3),\n        p(0) * q(1) + p(1) * q(0) - p(2) * q(3) + p(3) * q(2),\n        p(0) * q(2) + p(1) * q(3) + p(2) * q(0) - p(3) * q(1),\n        p(0) * q(3) - p(1) * q(2) + p(2) * q(1) + p(3) * q(0);\n    return quat;\n  }\n\n  static inline Quaternion boxplusB_Frame(Quaternion &quat, EulerVector &rotation) {\n    Quaternion quat2;\n    double norm = rotation.norm();\n    double halfNorm = 0.5 * norm;\n    double sinHalfNorm = sin(halfNorm);\n    quat2 << cos(halfNorm), sinHalfNorm * rotation(0) / norm, sinHalfNorm * rotation(1) / norm, sinHalfNorm\n        * rotation(2) / norm;\n    return quatMultiplication(quat, quat2);\n  }\n\n  static inline Quaternion boxplusI_Frame(Quaternion &quat, EulerVector &rotation) {\n    RotationMatrix rotmat = expM(rotation);\n    Quaternion quat2 = rotMatToQuat(rotmat);\n    return quatMultiplication(quat2, quat);\n  }\n\n  static inline void normalizeQuat(Quaternion &q) {\n    double norm = sqrt(q[0] * q[0] + q[1] * q[1] + q[2] * q[2] + q[3] * q[3]);\n    q[0] = q[0] / norm;\n    q[1] = q[1] / norm;\n    q[2] = q[2] / norm;\n    q[3] = q[3] / norm;\n  }\n\n  static inline Quaternion angleAxisToQuat(double angle, Axis &axis) {\n    Quaternion quat;\n    quat << cos(angle / 2.0), axis * sin(angle / 2.0);\n    return quat;\n  }\n\n  static inline Quaternion rotateQuatByAngleAxis(Quaternion &q, double angle, Axis &axis) {\n\n//  Quaternion quat;\n//  quat = quatMultiplication(angleAxisToQuat(angle, axis), q);\n//  return quat;\n\n    EulerVector vector = angle * axis;\n    return boxplusI_Frame(q, vector);\n  }\n\n  template<typename Dtype>\n  static inline Dtype standardDev(Eigen::Matrix<Dtype, 1, -1> &samples) {\n    Eigen::Matrix<Dtype, 1, -1> centered = samples.array() - samples.mean();\n    return std::sqrt(centered.array().square().sum() / (samples.cols() - 1));\n  }\n\n  template<typename Dtype>\n  static inline void normalize(Eigen::Matrix<Dtype, -1, 1> &samples) {\n    Eigen::Matrix<Dtype, -1, 1> centered = samples.array() - samples.mean();\n    Dtype std = std::sqrt(centered.array().square().sum() / (samples.cols() - 1));\n    samples = centered / std;\n  }\n\n  template<typename Dtype>\n  static inline void normalize(Eigen::Matrix<Dtype, 1, -1> &samples) {\n    Eigen::Matrix<Dtype, 1, -1> centered = samples.array() - samples.mean();\n    Dtype std = std::sqrt(centered.array().square().sum() / (samples.cols() - 1));\n    samples = centered / std;\n  }\n\n  template<typename Dtype>\n  static inline void normalize(std::vector<Dtype> &samples) {\n    Eigen::Matrix<Dtype, 1, -1> sampleEigen(1, samples.size());\n    memcpy(sampleEigen.data(), &samples[0], sizeof(Dtype) * samples.size());\n    normalize(sampleEigen);\n    memcpy(&samples[0], sampleEigen.data(), sizeof(Dtype) * samples.size());\n  }\n\n  /// gives you the smaller angle difference\n  static inline double angleDiff(double a, double b) {\n    return M_PI - std::fabs(std::fmod(std::fabs(a - b), 2.0 * M_PI) - M_PI);\n  }\n\n  /// gives you the smaller angle difference, positive if a is more clockwise\n  static inline double angleDiffSigned(double a, double b) {\n    double diff = std::fmod(a - b, 2.0 * M_PI);\n    if (diff > 0) {\n      return (diff > M_PI) ? diff - 2.0 * M_PI : diff;\n    } else {\n      return (-diff > M_PI) ? diff + 2.0 * M_PI : diff;\n    }\n  }\n\n  /// keeping track of the indices. if you do not care about index, use std::sort\n  /// assending order\n  template<typename Dtype, typename IndType>\n  static inline void sort ( std::vector<Dtype>& value, std::vector<IndType>& indx){\n    unsigned i, j,  flag = 1;    // set flag to 1 to start first pass\n    Dtype temp; // holding variable\n    IndType temp2;\n    unsigned numLength = value.size( );\n    for(i = 1; (i <= numLength) && flag; i++)\n    {\n      flag = 0;\n      for (j=0; j < (numLength -1); j++)\n      {\n        if (value[j+1] < value[j])      // descending order simply changes to >\n        {\n          temp = value[j];             // swap elements\n          temp2 = indx[j];\n          value[j] = value[j+1];\n          indx[j] = indx[j+1];\n          value[j+1] = temp;\n          indx[j+1] = temp2;\n          flag = 1;               // indicates that a swap occurred.\n        }\n      }\n    }\n  }\n\n  /// keeping track of the indices. if you do not care about index, use std::sort\n  /// assending order\n  template<typename Dtype, typename IndType>\n  static inline void sort ( Eigen::Matrix<Dtype, 1, -1>& value, Eigen::Matrix<IndType, 1, -1>& indx){\n    unsigned i, j,  flag = 1;    // set flag to 1 to start first pass\n    Dtype temp; // holding variable\n    IndType temp2;\n    unsigned numLength = value.size( );\n    for(i = 1; (i <= numLength) && flag; i++)\n    {\n      flag = 0;\n      for (j=0; j < (numLength -1); j++)\n      {\n        if (value[j+1] < value[j])      // descending order simply changes to >\n        {\n          temp = value[j];             // swap elements\n          temp2 = indx[j];\n          value[j] = value[j+1];\n          indx[j] = indx[j+1];\n          value[j+1] = temp;\n          indx[j+1] = temp2;\n          flag = 1;               // indicates that a swap occurred.\n        }\n      }\n    }\n  }\n\n};\n\n}\n\n#endif //math functions\n", "meta": {"hexsha": "1d2fef783f668147c385439a7df96836345496d7", "size": 9821, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/common/math.hpp", "max_stars_repo_name": "xdaNvidia/learning_quadrupedal_locomotion_over_challenging_terrain_supplementary", "max_stars_repo_head_hexsha": "2f94b13455ff16e26d1acd6a984f1f88f7824e31", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 94.0, "max_stars_repo_stars_event_min_datetime": "2020-10-22T08:47:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T15:33:49.000Z", "max_issues_repo_path": "include/common/math.hpp", "max_issues_repo_name": "lixuechuan123/learning_quadrupedal_locomotion_over_challenging_terrain_supplementary", "max_issues_repo_head_hexsha": "277d19b007fd3109956d1ea0cc9e0cd50d3ecb5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-10-25T09:41:06.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-04T06:58:11.000Z", "max_forks_repo_path": "include/common/math.hpp", "max_forks_repo_name": "lixuechuan123/learning_quadrupedal_locomotion_over_challenging_terrain_supplementary", "max_forks_repo_head_hexsha": "277d19b007fd3109956d1ea0cc9e0cd50d3ecb5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 30.0, "max_forks_repo_forks_event_min_datetime": "2020-10-22T13:36:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T01:17:14.000Z", "avg_line_length": 33.4047619048, "max_line_length": 107, "alphanum_fraction": 0.5421036554, "num_tokens": 3544, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810436809827, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.7489334336873823}}
{"text": "#include \"goto_solver.h\"\n#include <Eigen/Dense>\n#include <iostream>\n\nstatic Eigen::MatrixXd A_goto(6,6);\n\nstatic double t_goto = 0.5;\n\ninline Eigen::MatrixXd A_from_t(double t)\n{\n    Eigen::MatrixXd A(6,6);\n    A << 1.0,0.0,0.0,0.0,0.0,0.0,\n    0.0,1.0,0.0,0.0,0.0,0.0,\n    0.0,0.0,2.0,0.0,0.0,0.0,\n    1,t,pow(t,2),pow(t,3),pow(t,4),pow(t,5),\n    0,1,2*t,3*pow(t,2),4*pow(t,3),5*pow(t,4),\n    0.0,0.0,2.0,6.0*t,12.0*pow(t,2),20.0*pow(t,3);\n    return A;\n}\n\nstatic TrajectoryInfo cal_goto_with_A(double x_init, double y_init, double z_init, \n                                    double x_dest, double y_dest, double z_dest, \n                                    Eigen::MatrixXd &A, double t)\n{\n    TrajectoryInfo cur_traj;\n    Eigen::VectorXd bx(6),by(6), bz(6), solx(6), soly(6), solz(6);\n    bx<< x_init,0.0,0.0,x_dest,0.0,0.0;\n    solx = A.colPivHouseholderQr().solve(bx);\n    by<< y_init,0.0,0.0,y_dest,0.0,0.0;\n    soly = A.colPivHouseholderQr().solve(by);\n    bz<< z_init,0.0,0.0,z_dest,0.0,0.0;\n    solz = A.colPivHouseholderQr().solve(bz);\n    cur_traj.duration = t;\n    cur_traj.xcoef[0] = 0;\n    cur_traj.xcoef[1] = 0;\n    cur_traj.ycoef[0] = 0;\n    cur_traj.ycoef[1] = 0;\n    cur_traj.zcoef[0] = 0;\n    cur_traj.zcoef[1] = 0;\n    for(int i = 0; i < 6; i++){\n      cur_traj.xcoef[7-i] = solx(i);\n      cur_traj.ycoef[7-i] = soly(i);\n      cur_traj.zcoef[7-i] = solz(i);\n    }\n    return cur_traj;\n}\n\nTrajectoryInfo cal_goto(double x_init, double y_init, double z_init, double x_dest, double y_dest, double z_dest) \n{\n    return cal_goto_with_A(x_init, y_init, z_init, x_dest, y_dest, z_dest, A_goto, t_goto);\n}\n\nTrajectoryInfo cal_goto_with_t(double x_init, double y_init, double z_init, \n                               double x_dest, double y_dest, double z_dest,\n                               double t) \n{\n    Eigen::MatrixXd A = A_from_t(t);\n    return cal_goto_with_A(x_init, y_init, z_init, x_dest, y_dest, z_dest, A, t);\n}\n\nvoid set_t_goto(double _t_goto)\n{\n    t_goto = _t_goto;\n    A_goto = A_from_t(t_goto);\n}\n\n", "meta": {"hexsha": "d87c91858b9cc79d0a6226185f4a69852d68a55e", "size": 2029, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Src/ros_simulator/src/quad_controller/src/goto_solver.cpp", "max_stars_repo_name": "Drona-Org/Drona-DMR", "max_stars_repo_head_hexsha": "ecc756ec137aee90ab5ac9ea97f09b6e030066f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-05-14T14:49:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T06:53:28.000Z", "max_issues_repo_path": "Src/ros_simulator/src/quad_controller/src/goto_solver.cpp", "max_issues_repo_name": "Dronacharya-Org/Dronacharya", "max_issues_repo_head_hexsha": "ecc756ec137aee90ab5ac9ea97f09b6e030066f0", "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/ros_simulator/src/quad_controller/src/goto_solver.cpp", "max_forks_repo_name": "Dronacharya-Org/Dronacharya", "max_forks_repo_head_hexsha": "ecc756ec137aee90ab5ac9ea97f09b6e030066f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-12-15T20:18:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-31T19:26:57.000Z", "avg_line_length": 30.2835820896, "max_line_length": 114, "alphanum_fraction": 0.5973385904, "num_tokens": 750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533088603709, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.7489220618063959}}
{"text": "#include <math.h>\r\n#include <iostream>\r\n#include <Eigen/Dense>\r\n#include <Eigen/Geometry>\r\n#include <Eigen/Geometry>\r\n#include <eigen3/unsupported/Eigen/NumericalDiff>\r\n\r\n\r\ntypedef Eigen::VectorXd vector_t;\r\ntypedef Eigen::MatrixXd matrix_t;\r\ntypedef Eigen::Transform<double,2,Eigen::Affine> trafo2d_t;\r\n\r\ntrafo2d_t forward_kinematics(vector_t const & q ) ;\r\n\r\ntemplate<typename T>\r\nT pseudoInverse(const T &a, double epsilon = std::numeric_limits<double>::epsilon());\r\n\r\n\r\ntemplate<typename _Scalar, int NX = Eigen::Dynamic, int NY = Eigen::Dynamic>\r\n\r\nstruct Functor\r\n{\r\n    // Information that tells the caller the numeric type (eg. double) and size (input / output dim)\r\n    typedef _Scalar Scalar;\r\n    enum {\r\n        InputsAtCompileTime = NX,\r\n        ValuesAtCompileTime = NY\r\n};\r\n\r\ntypedef Eigen::Matrix<Scalar,InputsAtCompileTime,1> InputType;\r\ntypedef Eigen::Matrix<Scalar,ValuesAtCompileTime,1> ValueType;\r\ntypedef Eigen::Matrix<Scalar,ValuesAtCompileTime,InputsAtCompileTime> JacobianType;\r\n\r\n\r\nint m_inputs, m_values;\r\n\r\nFunctor() : m_inputs(InputsAtCompileTime), m_values(ValuesAtCompileTime) {}\r\nFunctor(int inputs, int values) : m_inputs(inputs), m_values(values) {}\r\n\r\n// Get methods for users to determine function input and output dimensions\r\nint inputs() const { return m_inputs; }\r\nint values() const { return m_values; }\r\n\r\n};\r\n\r\nstruct numericalDifferentiationFKFunctor : Functor<double>\r\n{\r\n    // Simple constructor\r\n    numericalDifferentiationFKFunctor(): Functor<double>(3,3) {}\r\n\r\n    // Implementation of the objective function\r\n    int operator()(const Eigen::VectorXd &q, Eigen::VectorXd &fvec) const\r\n    {\r\n        trafo2d_t t= forward_kinematics(q);\r\n        double theta=atan2( t.rotation()(1,0),t.rotation()(0,0));\r\n        double x = t.translation()(0);\r\n        double y = t.translation()(1);\r\n\r\n        fvec(0) = x;\r\n        fvec(1) = y;\r\n        fvec(2) = theta;\r\n\r\n        return 0;\r\n    }\r\n};\r\n\r\nEigen::MatrixXd numericalDifferentiationFK(const Eigen::VectorXd &q);\r\n\r\nEigen::VectorXd transformationMatrixToPose(trafo2d_t const &m);\r\n\r\nEigen::VectorXd distanceError(trafo2d_t const &golesStart, trafo2d_t const &poseStart);\r\n\r\ntemplate <typename T> inline constexpr\r\nint signum(T x, std::false_type is_signed);\r\n\r\ntemplate <typename T> inline constexpr\r\nint signum(T x, std::true_type is_signed);\r\n\r\ntemplate <typename  T>\r\nvoid normaliseAngle(T &q);\r\n\r\ntemplate <typename  T>\r\nvoid normaliseAngle2(T &q);\r\n\r\nvoid normaliseAngle(Eigen::VectorXd &q);\r\n\r\nvoid normaliseAngle2(Eigen::VectorXd &q);\r\n\r\nvector_t inverse_kinematics(vector_t const & q_start, trafo2d_t const & goal );\r\n\r\nvector_t inverse_kinematics(trafo2d_t const & goal );\r\n\r\n", "meta": {"hexsha": "927009e5e7727509fea3a908220038c9716cb0d6", "size": 2682, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/task.hpp", "max_stars_repo_name": "behnamasadi/planar_3_link_robot", "max_stars_repo_head_hexsha": "b10b5b0f9b1b5af89b9a9278dab32b18380d66c6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-08-11T02:34:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-11T05:15:08.000Z", "max_issues_repo_path": "src/task.hpp", "max_issues_repo_name": "behnamasadi/planar_3_link_robot", "max_issues_repo_head_hexsha": "b10b5b0f9b1b5af89b9a9278dab32b18380d66c6", "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/task.hpp", "max_forks_repo_name": "behnamasadi/planar_3_link_robot", "max_forks_repo_head_hexsha": "b10b5b0f9b1b5af89b9a9278dab32b18380d66c6", "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": 28.8387096774, "max_line_length": 101, "alphanum_fraction": 0.7058165548, "num_tokens": 658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971871, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.7487756132268123}}
{"text": "/*\n For more information, please see: http://software.sci.utah.edu\n The MIT License\n Copyright (c) 2015 Scientific Computing and Imaging Institute,\n University of Utah.\n \n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n */\n\n\n//ComputePCA Algorithm: Computes Principal Component Analysis.\n\n#include <Core/Algorithms/Base/AlgorithmPreconditions.h>\n#include <Core/Algorithms/Math/ComputePCA.h>\n#include <Core/Datatypes/DenseMatrix.h>\n#include <Core/Datatypes/DenseColumnMatrix.h>\n#include <Core/Datatypes/MatrixTypeConversions.h>\n#include <Eigen/SVD>\n#include <Core/Algorithms/Base/AlgorithmVariableNames.h>\n\nusing namespace SCIRun;\nusing namespace SCIRun::Core::Algorithms;\nusing namespace SCIRun::Core::Datatypes;\nusing namespace SCIRun::Core::Algorithms::Math;\n\n//Let's do some math.\n//Algorithm:\nvoid ComputePCAAlgo::run(MatrixHandle input, DenseMatrixHandle& LeftPrinMat, DenseMatrixHandle& PrinVals, DenseMatrixHandle& RightPrinMat) const{\n    \n    //Throws an error if one or both of the input matrix dimensions is zero.\n    if (input->nrows() == 0 || input->ncols() == 0){\n    \n        THROW_ALGORITHM_INPUT_ERROR(\"Input has a zero dimension.\");\n    }\n    \n    //Input matrix: nxm\n    if (matrixIs::dense(input))\n    {\n        //First, we have to center the data.\n        auto denseInputCentered = centerData(input);\n        \n        //After the data is centered, then we compute SVD on the centered matrix.\n        //Centered Matrix = U*S*Vt, Vt = V transpose\n        Eigen::JacobiSVD<DenseMatrix::EigenBase> svd_mat(denseInputCentered, Eigen::ComputeFullU | Eigen::ComputeFullV);\n        \n        //U: Left principal matrix, nxn, orthogonal\n        LeftPrinMat = boost::make_shared<DenseMatrix>(svd_mat.matrixU());\n        \n        //S: Principal values nxm, diagonal\n        PrinVals = boost::make_shared<DenseMatrix>(svd_mat.singularValues());\n        \n        //V: Right singular mxm, orthognol\n        RightPrinMat = boost::make_shared<DenseMatrix>(svd_mat.matrixV());\n    }\n    else\n    {\n        //Throw an error if the matrix is not dense.\n        //Sparse matrices not supported at this time.\n        THROW_ALGORITHM_INPUT_ERROR(\"ComputePCA works for dense matrix input only.\");\n    }\n}\n\n//Centers input matrix.\nDenseMatrix ComputePCAAlgo::centerData(MatrixHandle input_matrix)\n{\n    //Casts the matrix as dense.\n    auto denseInput = castMatrix::toDense(input_matrix);\n    \n    //Counts the number of rows in the input matrix.\n    auto rows = denseInput->rows();\n    \n    //Calulates the centering matrix (C).\n    // C = Identity(nxn) - 1/n * matrix of ones(nxn)\n    auto centerMatrix = Eigen::MatrixXd::Identity(rows,rows) - (1.0/rows)*Eigen::MatrixXd::Constant(rows,rows,1);\n    \n    //Multiplying the input matrix by the centering matrix.\n    auto denseInputCentered = centerMatrix * *denseInput;\n    \n    return denseInputCentered;\n}\n\n//Run the algorithm.\nAlgorithmOutput ComputePCAAlgo::run(const AlgorithmInput& input) const\n{\n    auto input_matrix = input.get<Matrix>(Variables::InputMatrix);\n    \n    DenseMatrixHandle LeftPrinMat;\n    DenseMatrixHandle PrinVals;\n    DenseMatrixHandle RightPrinMat;\n    \n    run(input_matrix, LeftPrinMat, PrinVals, RightPrinMat);\n    \n    AlgorithmOutput output;\n    \n    output[LeftPrincipalMatrix] = LeftPrinMat;\n    output[PrincipalValues] = PrinVals;\n    output[RightPrincipalMatrix] = RightPrinMat;\n    \n    return output;\n}\n\n//Outputs:\nAlgorithmOutputName ComputePCAAlgo::LeftPrincipalMatrix(\"LeftPrincipalMatrix\");\nAlgorithmOutputName ComputePCAAlgo::PrincipalValues(\"PrincipalValues\");\nAlgorithmOutputName ComputePCAAlgo::RightPrincipalMatrix(\"RightPrincipalMatrix\");\n", "meta": {"hexsha": "52048ecc902888eba9499520c967b6f0970cac73", "size": 4623, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/Core/Algorithms/Math/ComputePCA.cc", "max_stars_repo_name": "Nahusa/SCIRun", "max_stars_repo_head_hexsha": "c54e714d4c7e956d053597cf194e07616e28a498", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-30T06:00:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-30T06:00:15.000Z", "max_issues_repo_path": "src/Core/Algorithms/Math/ComputePCA.cc", "max_issues_repo_name": "manual123/SCIRun", "max_issues_repo_head_hexsha": "3816b1dc4ebd0c5bd4539b7e50e08592acdac903", "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/Core/Algorithms/Math/ComputePCA.cc", "max_forks_repo_name": "manual123/SCIRun", "max_forks_repo_head_hexsha": "3816b1dc4ebd0c5bd4539b7e50e08592acdac903", "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.525, "max_line_length": 145, "alphanum_fraction": 0.7326411421, "num_tokens": 1089, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750373915658, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.748615066809695}}
{"text": "/*\n * p61, exercise 07 for chap 03\n * rbt01, rbt02 poses are known in unnormalized Quaternion form\n * of transformation from world frame to camera frame\n * the goal is find a point position expressed in rbt02 frame with\n * known coordinate in rbt01 frame\n*/\n#include <iostream>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\nint main(int argc, char** argv)\n{\n    Eigen::Vector4d q1(0.35, 0.2, 0.3, 0.1);\n    q1.normalize();\n    // quaternion from 4d vector with order (w, x, y, z)\n    Eigen::Quaterniond Q1 = Eigen::Quaterniond(q1);\n    // Tij represents the transformation from frame j to frame i\n    // 0 usually represents the world frame\n    Eigen::Isometry3d T10 = Eigen::Isometry3d::Identity();\n    T10.rotate(Q1);\n    T10.pretranslate(Eigen::Vector3d(0.3, 0.1, 0.1));\n\n    Eigen::Vector4d q2(-0.5, 0.4, -0.1, 0.2);\n    q2.normalize();\n    // quaternion from 4d vector with order (w, x, y, z)\n    Eigen::Quaterniond Q2 = Eigen::Quaterniond(q2);\n\n    Eigen::Isometry3d T20 = Eigen::Isometry3d::Identity();\n    T20.rotate(Q2);\n    T20.pretranslate(Eigen::Vector3d(-0.1, 0.5, 0.3));\n\n    Eigen::Vector3d p_in1(0.5, 0, 0.2);\n    Eigen::Vector3d p_in2 = T20*T10.inverse()*p_in1;\n\n    std::cout << \"the point observed in robo 2 frame is: \" << p_in2.transpose() << std::endl;\n    return 0;\n}\n", "meta": {"hexsha": "954ef5fb4cac93f2d6d187761d3cd8022d066ca1", "size": 1294, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch03/exercise/rbtPosition.cpp", "max_stars_repo_name": "sunoval2016/SLAM-14", "max_stars_repo_head_hexsha": "72d848c159ff766d87c9bc3c0a170f84745a3785", "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": "ch03/exercise/rbtPosition.cpp", "max_issues_repo_name": "sunoval2016/SLAM-14", "max_issues_repo_head_hexsha": "72d848c159ff766d87c9bc3c0a170f84745a3785", "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": "ch03/exercise/rbtPosition.cpp", "max_forks_repo_name": "sunoval2016/SLAM-14", "max_forks_repo_head_hexsha": "72d848c159ff766d87c9bc3c0a170f84745a3785", "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.35, "max_line_length": 93, "alphanum_fraction": 0.6599690881, "num_tokens": 430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897542390751, "lm_q2_score": 0.7956581024858786, "lm_q1q2_score": 0.7485469906960186}}
{"text": "// Eigen\n#include <Eigen/Dense>\n\n// OpenCV\n#include <opencv2/calib3d.hpp>\n#include <opencv2/core/eigen.hpp>\n\n// Local\n#include \"estimators/homography_pose_estimator.h\"\n\n\nnamespace estimators\n{\n\nHomographyPoseEstimator::HomographyPoseEstimator(const Eigen::Matrix3d& K)\n    : K_{K}\n{ }\n\n\nPoseEstimate HomographyPoseEstimator::estimate(const std::vector<cv::Point2f>& image_points,\n                                               const std::vector<cv::Point3f>& world_points,\n                                               const std::vector<float>& matched_distances)\n{\n  // Set a minimum required number of points,\n  // here 3 times the theoretic minimum.\n  constexpr size_t min_number_points = 12;\n\n  // Check that we have enough points.\n  if (image_points.size() < min_number_points)\n  {\n    return {};\n  }\n\n  // Compute the homography and extract the inliers.\n  std::vector<char> inliers;\n  cv::Mat H_cv = cv::findHomography(world_points, image_points, cv::RANSAC, 3, inliers);\n\n  std::vector<cv::Point2f> inlier_image_points;\n  std::vector<cv::Point3f> inlier_world_points;\n  for (size_t i=0; i<inliers.size(); ++i)\n  {\n    if (inliers[i] > 0)\n    {\n      inlier_image_points.push_back(image_points[i]);\n      inlier_world_points.push_back(world_points[i]);\n    }\n  }\n\n  // Check that we have enough inliers.\n  if (inlier_image_points.size() < min_number_points)\n  {\n    return {};\n  }\n\n  // Convert homography to Eigen matrix.\n  Eigen::Matrix3d H;\n  cv::cv2eigen(H_cv, H);\n\n  // Compute the matrix M\n  Eigen::Matrix3d M;\n  M = K_.lu().solve(H); \n\n  // Extract M_bar (the two first columns of M).\n  Eigen::MatrixXd M_bar = M.leftCols<2>();\n\n  // Perform SVD on M_bar.\n  auto svd = M_bar.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV);\n\n  // TODO 3: Compute R_bar.\n  // Compute R_bar (the two first columns of R)\n  // from the result of the SVD.\n  Eigen::Matrix<double, 3, 2> R_bar;\n  R_bar = svd.matrixU() * svd.matrixV().transpose(); \n\n  // Construct R by inserting R_bar and\n  // computing the third column of R from the two first.\n  Eigen::Matrix3d R = Eigen::Matrix3d::Identity();\n  R.col(0) = R_bar.col(0); \n  R.col(1) = R_bar.col(1);\n  R.col(2) = R_bar.col(0).cross(R_bar.col(1)); \n\n  if (R.determinant() < 0.0)\n    R.col(2) *= -1; \n\n  // Compute the scale factor lambda.\n  double lambda = \n    (R_bar.transpose() * M).trace() / \n    (M.transpose() * M).trace(); \n\n  // Extract the translation t.\n  // Check that this is the correct solution\n  // by testing the last element of t.\n  Eigen::Vector3d t = lambda * M.col(2);\n  if (t.z() < 0)\n  {\n    t *= -1; \n    R.col(0) *= -1; \n    R.col(1) *= -1; \n  }\n\n  // Return camera pose in the world.\n  Sophus::SE3d pose_C_W(R, t);\n  return {pose_C_W.inverse(), Eigen::MatrixXd::Zero(6, 6), inlier_image_points, inlier_world_points, std::make_pair(0, 0)};\n}\n\n} // namespace estimators\n", "meta": {"hexsha": "ddd63483d700b4321c217e5c44555a2dd0183fe8", "size": 2840, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/estimators/homography_pose_estimator.cpp", "max_stars_repo_name": "martiege/lab_06", "max_stars_repo_head_hexsha": "2c20adf354327c162a43473ee4c0653f698ac30f", "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/estimators/homography_pose_estimator.cpp", "max_issues_repo_name": "martiege/lab_06", "max_issues_repo_head_hexsha": "2c20adf354327c162a43473ee4c0653f698ac30f", "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/estimators/homography_pose_estimator.cpp", "max_forks_repo_name": "martiege/lab_06", "max_forks_repo_head_hexsha": "2c20adf354327c162a43473ee4c0653f698ac30f", "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": 26.5420560748, "max_line_length": 123, "alphanum_fraction": 0.6411971831, "num_tokens": 842, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896824119662, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.7484798436089894}}
{"text": "// The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt\n/*\n\n    This is an example illustrating the use the general purpose non-linear \n    optimization routines from the dlib C++ Library.\n\n    The library provides implementations of the conjugate gradient,  BFGS,\n    L-BFGS, and BOBYQA optimization algorithms.  These algorithms allow you to\n    find the minimum of a function of many input variables.  This example walks\n    though a few of the ways you might put these routines to use.\n\n*/\n\n\n#include <dlib/optimization.h>\n#include <iostream>\n\n\nusing namespace std;\nusing namespace dlib;\n\n// ----------------------------------------------------------------------------------------\n\n// In dlib, the general purpose solvers optimize functions that take a column\n// vector as input and return a double.  So here we make a typedef for a\n// variable length column vector of doubles.  This is the type we will use to\n// represent the input to our objective functions which we will be minimizing.\ntypedef matrix<double,0,1> column_vector;\n\n// ----------------------------------------------------------------------------------------\n// Below we create a few functions.  When you get down into main() you will see that\n// we can use the optimization algorithms to find the minimums of these functions.\n// ----------------------------------------------------------------------------------------\n\ndouble rosen (const column_vector& m)\n/*\n    This function computes what is known as Rosenbrock's function.  It is \n    a function of two input variables and has a global minimum at (1,1).\n    So when we use this function to test out the optimization algorithms\n    we will see that the minimum found is indeed at the point (1,1). \n*/\n{\n    const double x = m(0); \n    const double y = m(1);\n\n    // compute Rosenbrock's function and return the result\n    return 100.0*pow(y - x*x,2) + pow(1 - x,2);\n}\n\n// This is a helper function used while optimizing the rosen() function.  \nconst column_vector rosen_derivative (const column_vector& m)\n/*!\n    ensures\n        - returns the gradient vector for the rosen function\n!*/\n{\n    const double x = m(0);\n    const double y = m(1);\n\n    // make us a column vector of length 2\n    column_vector res(2);\n\n    // now compute the gradient vector\n    res(0) = -400*x*(y-x*x) - 2*(1-x); // derivative of rosen() with respect to x\n    res(1) = 200*(y-x*x);              // derivative of rosen() with respect to y\n    return res;\n}\n\n// This function computes the Hessian matrix for the rosen() fuction.  This is\n// the matrix of second derivatives.\nmatrix<double> rosen_hessian (const column_vector& m)\n{\n    const double x = m(0);\n    const double y = m(1);\n\n    matrix<double> res(2,2);\n\n    // now compute the second derivatives \n    res(0,0) = 1200*x*x - 400*y + 2; // second derivative with respect to x\n    res(1,0) = res(0,1) = -400*x;   // derivative with respect to x and y\n    res(1,1) = 200;                 // second derivative with respect to y\n    return res;\n}\n\n// ----------------------------------------------------------------------------------------\n\nclass test_function\n{\n    /*\n        This object is an example of what is known as a \"function object\" in C++.\n        It is simply an object with an overloaded operator().  This means it can \n        be used in a way that is similar to a normal C function.  The interesting\n        thing about this sort of function is that it can have state.  \n        \n        In this example, our test_function object contains a column_vector \n        as its state and it computes the mean squared error between this \n        stored column_vector and the arguments to its operator() function.\n\n        This is a very simple function, however, in general you could compute\n        any function you wanted here.  An example of a typical use would be \n        to find the parameters of some regression function that minimized \n        the mean squared error on a set of data.  In this case the arguments\n        to the operator() function would be the parameters of your regression\n        function.  You would loop over all your data samples and compute the output \n        of the regression function for each data sample given the parameters and \n        return a measure of the total error.   The dlib optimization functions \n        could then be used to find the parameters that minimized the error.\n    */\npublic:\n\n    test_function (\n        const column_vector& input\n    )\n    {\n        target = input;\n    }\n\n    double operator() ( const column_vector& arg) const\n    {\n        // return the mean squared error between the target vector and the input vector\n        return mean(squared(target-arg));\n    }\n\nprivate:\n    column_vector target;\n};\n\n// ----------------------------------------------------------------------------------------\n\nclass rosen_model \n{\n    /*!\n        This object is a \"function model\" which can be used with the\n        find_min_trust_region() routine.  \n    !*/\n\npublic:\n    typedef ::column_vector column_vector;\n    typedef matrix<double> general_matrix;\n\n    double operator() (\n        const column_vector& x\n    ) const { return rosen(x); }\n\n    void get_derivative_and_hessian (\n        const column_vector& x,\n        column_vector& der,\n        general_matrix& hess\n    ) const\n    {\n        der = rosen_derivative(x);\n        hess = rosen_hessian(x);\n    }\n};\n\n// ----------------------------------------------------------------------------------------\n\nint main()\n{\n    try\n    {\n        // make a column vector of length 2\n        column_vector starting_point(2);\n\n\n        // Set the starting point to (4,8).  This is the point the optimization algorithm\n        // will start out from and it will move it closer and closer to the function's \n        // minimum point.   So generally you want to try and compute a good guess that is\n        // somewhat near the actual optimum value.\n        starting_point = 4, 8;\n\n        // The first example below finds the minimum of the rosen() function and uses the\n        // analytical derivative computed by rosen_derivative().  Since it is very easy to\n        // make a mistake while coding a function like rosen_derivative() it is a good idea\n        // to compare your derivative function against a numerical approximation and see if\n        // the results are similar.  If they are very different then you probably made a \n        // mistake.  So the first thing we do is compare the results at a test point: \n        cout << \"Difference between analytic derivative and numerical approximation of derivative: \" \n              << length(derivative(rosen)(starting_point) - rosen_derivative(starting_point)) << endl;\n\n\n        cout << \"Find the minimum of the rosen function()\" << endl;\n        // Now we use the find_min() function to find the minimum point.  The first argument\n        // to this routine is the search strategy we want to use.  The second argument is the \n        // stopping strategy.  Below I'm using the objective_delta_stop_strategy which just \n        // says that the search should stop when the change in the function being optimized \n        // is small enough.\n\n        // The other arguments to find_min() are the function to be minimized, its derivative, \n        // then the starting point, and the last is an acceptable minimum value of the rosen() \n        // function.  That is, if the algorithm finds any inputs to rosen() that gives an output \n        // value <= -1 then it will stop immediately.  Usually you supply a number smaller than \n        // the actual global minimum.  So since the smallest output of the rosen function is 0 \n        // we just put -1 here which effectively causes this last argument to be disregarded.\n\n        find_min(bfgs_search_strategy(),  // Use BFGS search algorithm\n                 objective_delta_stop_strategy(1e-7), // Stop when the change in rosen() is less than 1e-7\n                 rosen, rosen_derivative, starting_point, -1);\n        // Once the function ends the starting_point vector will contain the optimum point \n        // of (1,1).\n        cout << \"rosen solution:\\n\" << starting_point << endl;\n\n\n        // Now let's try doing it again with a different starting point and the version\n        // of find_min() that doesn't require you to supply a derivative function.  \n        // This version will compute a numerical approximation of the derivative since \n        // we didn't supply one to it.\n        starting_point = -94, 5.2;\n        find_min_using_approximate_derivatives(bfgs_search_strategy(),\n                                               objective_delta_stop_strategy(1e-7),\n                                               rosen, starting_point, -1);\n        // Again the correct minimum point is found and stored in starting_point\n        cout << \"rosen solution:\\n\" << starting_point << endl;\n\n\n        // Here we repeat the same thing as above but this time using the L-BFGS \n        // algorithm.  L-BFGS is very similar to the BFGS algorithm, however, BFGS \n        // uses O(N^2) memory where N is the size of the starting_point vector.  \n        // The L-BFGS algorithm however uses only O(N) memory.  So if you have a \n        // function of a huge number of variables the L-BFGS algorithm is probably \n        // a better choice.\n        starting_point = 0.8, 1.3;\n        find_min(lbfgs_search_strategy(10),  // The 10 here is basically a measure of how much memory L-BFGS will use.\n                 objective_delta_stop_strategy(1e-7).be_verbose(),  // Adding be_verbose() causes a message to be \n                                                                    // printed for each iteration of optimization.\n                 rosen, rosen_derivative, starting_point, -1);\n\n        cout << endl << \"rosen solution: \\n\" << starting_point << endl;\n\n        starting_point = -94, 5.2;\n        find_min_using_approximate_derivatives(lbfgs_search_strategy(10),\n                                               objective_delta_stop_strategy(1e-7),\n                                               rosen, starting_point, -1);\n        cout << \"rosen solution: \\n\"<< starting_point << endl;\n\n\n\n\n        // dlib also supports solving functions subject to bounds constraints on\n        // the variables.  So for example, if you wanted to find the minimizer\n        // of the rosen function where both input variables were in the range\n        // 0.1 to 0.8 you would do it like this:\n        starting_point = 0.1, 0.1; // Start with a valid point inside the constraint box.\n        find_min_box_constrained(lbfgs_search_strategy(10),  \n                                 objective_delta_stop_strategy(1e-9),  \n                                 rosen, rosen_derivative, starting_point, 0.1, 0.8);\n        // Here we put the same [0.1 0.8] range constraint on each variable, however, you\n        // can put different bounds on each variable by passing in column vectors of\n        // constraints for the last two arguments rather than scalars.  \n\n        cout << endl << \"constrained rosen solution: \\n\" << starting_point << endl;\n\n        // You can also use an approximate derivative like so:\n        starting_point = 0.1, 0.1; \n        find_min_box_constrained(bfgs_search_strategy(),  \n                                 objective_delta_stop_strategy(1e-9),  \n                                 rosen, derivative(rosen), starting_point, 0.1, 0.8);\n        cout << endl << \"constrained rosen solution: \\n\" << starting_point << endl;\n\n\n\n\n        // In many cases, it is useful if we also provide second derivative information\n        // to the optimizers.  Two examples of how we can do that are shown below.  \n        starting_point = 0.8, 1.3;\n        find_min(newton_search_strategy(rosen_hessian),\n                 objective_delta_stop_strategy(1e-7),\n                 rosen,\n                 rosen_derivative,\n                 starting_point,\n                 -1);\n        cout << \"rosen solution: \\n\"<< starting_point << endl;\n\n        // We can also use find_min_trust_region(), which is also a method which uses\n        // second derivatives.  For some kinds of non-convex function it may be more\n        // reliable than using a newton_search_strategy with find_min().\n        starting_point = 0.8, 1.3;\n        find_min_trust_region(objective_delta_stop_strategy(1e-7),\n            rosen_model(), \n            starting_point, \n            10 // initial trust region radius\n        );\n        cout << \"rosen solution: \\n\"<< starting_point << endl;\n\n\n\n\n        // Now let's look at using the test_function object with the optimization \n        // functions.  \n        cout << \"\\nFind the minimum of the test_function\" << endl;\n\n        column_vector target(4);\n        starting_point.set_size(4);\n\n        // This variable will be used as the target of the test_function.   So,\n        // our simple test_function object will have a global minimum at the\n        // point given by the target.  We will then use the optimization \n        // routines to find this minimum value.\n        target = 3, 5, 1, 7;\n\n        // set the starting point far from the global minimum\n        starting_point = 1,2,3,4;\n        find_min_using_approximate_derivatives(bfgs_search_strategy(),\n                                               objective_delta_stop_strategy(1e-7),\n                                               test_function(target), starting_point, -1);\n        // At this point the correct value of (3,5,1,7) should be found and stored in starting_point\n        cout << \"test_function solution:\\n\" << starting_point << endl;\n\n        // Now let's try it again with the conjugate gradient algorithm.\n        starting_point = -4,5,99,3;\n        find_min_using_approximate_derivatives(cg_search_strategy(),\n                                               objective_delta_stop_strategy(1e-7),\n                                               test_function(target), starting_point, -1);\n        cout << \"test_function solution:\\n\" << starting_point << endl;\n\n\n\n        // Finally, let's try the BOBYQA algorithm.  This is a technique specially\n        // designed to minimize a function in the absence of derivative information.  \n        // Generally speaking, it is the method of choice if derivatives are not available.\n        starting_point = -4,5,99,3;\n        find_min_bobyqa(test_function(target), \n                        starting_point, \n                        9,    // number of interpolation points\n                        uniform_matrix<double>(4,1, -1e100),  // lower bound constraint\n                        uniform_matrix<double>(4,1, 1e100),   // upper bound constraint\n                        10,    // initial trust region radius\n                        1e-6,  // stopping trust region radius\n                        100    // max number of objective function evaluations\n        );\n        cout << \"test_function solution:\\n\" << starting_point << endl;\n\n    }\n    catch (std::exception& e)\n    {\n        cout << e.what() << endl;\n    }\n}\n\n", "meta": {"hexsha": "8b2f9bff2d2195a3469588253e71b51907a5cf53", "size": 15060, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dlib/examples/optimization_ex.cpp", "max_stars_repo_name": "maxmert/nlp-mitie", "max_stars_repo_head_hexsha": "ec3153ef2fe7a80e7cf3d80d14b388b8cd679343", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2695.0, "max_stars_repo_stars_event_min_datetime": "2015-01-01T21:13:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T04:45:32.000Z", "max_issues_repo_path": "dlib/examples/optimization_ex.cpp", "max_issues_repo_name": "maxmert/nlp-mitie", "max_issues_repo_head_hexsha": "ec3153ef2fe7a80e7cf3d80d14b388b8cd679343", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 208.0, "max_issues_repo_issues_event_min_datetime": "2015-01-23T19:29:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-08T02:55:17.000Z", "max_forks_repo_path": "dlib/examples/optimization_ex.cpp", "max_forks_repo_name": "maxmert/nlp-mitie", "max_forks_repo_head_hexsha": "ec3153ef2fe7a80e7cf3d80d14b388b8cd679343", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 567.0, "max_forks_repo_forks_event_min_datetime": "2015-01-06T19:22:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T17:01:04.000Z", "avg_line_length": 44.2941176471, "max_line_length": 118, "alphanum_fraction": 0.61062417, "num_tokens": 3274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972784807408, "lm_q2_score": 0.8596637541053281, "lm_q1q2_score": 0.7484209247326354}}
{"text": "#include <Eigen/KroneckerProduct>\n#include <Eigen/Sparse>\n#include <vector>\n#include <iostream>\n#include <functional>\n#include <math.h>\n#include <fstream>\n#include \"colormap.h\"\n#include <Eigen/IterativeLinearSolvers>\n\n#define COL(a, b, c) colors.push_back(Color(a, b, c));\n\ntypedef Eigen::SparseMatrix<double> mat;\ntypedef Eigen::MatrixXd mat2;\ntypedef std::vector<std::function<double(double)>> function_array;\n\n\ndouble source(double x, double y){\n    return 20*sin(M_PI * y)*sin(1.5*M_PI*x+M_PI);\n}\n\n\nmat source_flattened(int Nx, int Ny, double h, std::function<double(double, double)> f){\n    auto index = [](int nx, int ny, int Nx){return nx+(Nx-1)*ny;};\n    int size = (Nx-1)*(Ny-1);\n    mat vec(size, 1);\n    std::vector<Eigen::Triplet<double>> vals((Nx-1)*(Nx-1));\n    int count = 0;\n    for(int j = 1; j < Ny; j++){\n        for(int i = 1; i < Nx; i++){\n            vals[count] = Eigen::Triplet<double>(count, 0, f(i*h, j*h));\n            count++;\n        }\n    }\n    vals.shrink_to_fit();\n    vec.setFromTriplets(vals.begin(), vals.end());\n    return vec;\n}\n\nmat make_eigen(int N, int index,double h){\n    mat vec(N, 1);\n    vec.insert(index, 0) = 1/h/h;\n    return vec;\n}\n\nmat fill_from_function(int N, double h, std::function<double(double)> f){\n    mat vec(N,1);\n    for(int i = 1; i <= N; i++){\n        vec.insert(i-1,0) = f(i*h);\n    }\n    return vec;\n}\n\nmat make_boundary_vec(int Nx, int Ny, double h, function_array boundaries){\n    mat Bx_lower(Nx-1, 1);\n    mat Bx_upper(Nx-1, 1);\n    mat By_left(Ny-1, 1);\n    mat By_right(Ny-1, 1);\n\n    Bx_lower = fill_from_function(Nx-1, h, boundaries[0]);\n    By_right = fill_from_function(Ny-1, h, boundaries[1]);\n    Bx_upper = fill_from_function(Nx-1, h, boundaries[2]);\n    By_left = fill_from_function(Ny-1, h, boundaries[3]);\n\n    return Eigen::kroneckerProduct(make_eigen(Ny-1, 0, h), Bx_lower).eval()+\\\n           Eigen::kroneckerProduct(make_eigen(Ny-1, Ny-2, h), Bx_upper).eval()+\\\n           Eigen::kroneckerProduct(By_left, make_eigen(Nx-1, 0, h)).eval()+\\\n           Eigen::kroneckerProduct(By_right, make_eigen(Nx-1, Nx-2, h)).eval();\n}\n\n\nstd::vector<Eigen::Triplet<double>> make_1D_Laplacian(int N, double h){\n    std::vector<Eigen::Triplet<double>> vals(N*3);\n    int counter = 0;\n\n    for(int i = 0; i < N; i++){\n        vals[counter] = Eigen::Triplet<double>(i, i, 2.f/h/h);\n        counter++;\n        if(i != 0){\n            vals[counter] = Eigen::Triplet<double>(i-1, i, -1.f/h/h);\n            counter++;\n            vals[counter] = Eigen::Triplet<double>(i, i-1, -1.f/h/h);\n            counter++;\n        }\n    }\n    vals.shrink_to_fit();\n    return vals;\n}\n\nmat build_Matrix(int Nx, int Ny, double h){\n    mat Dx(Nx-1, Nx-1);\n    mat Dy(Ny-1, Ny-1);\n\n    auto Dx_vals = make_1D_Laplacian(Nx-1, h);\n    Dx.setFromTriplets(Dx_vals.begin(), Dx_vals.end());\n\n    auto Dy_vals = make_1D_Laplacian(Ny-1, h);\n    Dy.setFromTriplets(Dy_vals.begin(), Dy_vals.end());\n\n    mat Iy(Ny-1,Ny-1);\n    Iy.setIdentity();\n\n    mat Ix(Nx-1,Nx-1);\n    Ix.setIdentity();\n\n    auto L1 = Eigen::kroneckerProduct(Iy, Dx).eval();\n    auto L2 = Eigen::kroneckerProduct(Dy, Ix).eval();\n\n    int size = (Nx-1)*(Ny-1);\n    return(L1+L2);\n}\n\ndouble normalize(double val, double max, double min){\n    double x = ((val-min)/(max-min));\n    return x;\n}\n\nint main(int argc, char* argv[]){\n    double xmax = 2;\n    double ymax = 1;\n    double h = atof(argv[1]);\n    int Nx = (int)(xmax/h);\n    int Ny = (int)(ymax/h);\n    std::cout << Nx << \", \" << Ny << std::endl;\n    std::cout << \"Assembling Matrix\" << std::endl;\n    auto L = build_Matrix(Nx, Ny, h);\n    auto source_vec = source_flattened(Nx, Ny, h, std::bind<double>(source, std::placeholders::_1, std::placeholders::_2));\n    \n    function_array fns(4);\n    fns[0] = std::bind<double>([](double x){return sin(0.5*M_PI*x);}, std::placeholders::_1);\n    fns[1] = std::bind<double>([](double x){return sin(2*M_PI*x);}, std::placeholders::_1);\n    fns[2] = std::bind<double>([](double x){return 0;}, std::placeholders::_1);\n    fns[3] = std::bind<double>([](double x){return sin(2*M_PI*x);}, std::placeholders::_1);\n\n    auto boundary_conds = make_boundary_vec(Nx, Ny, h, fns);\n\n    Eigen::ConjugateGradient<mat, Eigen::Upper|Eigen::Lower> solver;\n    std::cout << \"Matrix assembled \\n Compression Start\" << std::endl;\n    L.makeCompressed();\n    std::cout << \"Matrix compressed \\nStart Solving Start\" << std::endl;\n    solver.analyzePattern(L);\n    solver.factorize(L);\n    std::cout << source_vec.innerSize() << std::endl;\n    std::cout << boundary_conds.innerSize() << std::endl;\n    std::cout << L.outerSize() << std::endl;\n    Eigen::VectorXd un = solver.solve(source_vec+boundary_conds);\n    std::cout << \"Solve\\nMaking Solution\" << std::endl;\n    \n    double max_val = un.maxCoeff();\n    double min_val = un.minCoeff();\n    std::cout << \"System solved \\n writing to file\" << std::endl;\n\n    auto norm = std::bind<double>(normalize, std::placeholders::_1, max_val, min_val);\n\n    std::vector<Color> colors;\n    COL(47, 0, 135);\n    COL(98, 0, 164);\n    COL(146, 0, 166);\n    COL(186, 47, 138);\n    COL(216, 91, 105);\n    COL(238, 137, 73);\n    COL(246, 189, 39);\n    COL(28, 250, 21);\n\n    Colormap cmap(colors);\n\n    std::fstream fs;\n    fs.open(\"default.ppm\", std::fstream::out | std::fstream::trunc | std::fstream::in);\n    std::cout << fs.is_open() << std::endl;\n    //print header to file\n    fs << \"P3\\n\"<<(Nx-1)<<\" \"<<(Ny-1)<<\"\\n255\\n\";\n    for(int j = (Ny-2); j >= 0; j--){\n        for(int i = 0; i < (Nx-1); i++){\n            auto val = norm(un.coeff(i+j*(Nx-1),0));\n            Color c = cmap.get_val(val);\n            fs << c.R << \" \" << c.G << \" \" << c.B << \" \";\n        }\n        fs << \"\\n\";\n\n    }\n    fs.close();\n    std::cout << \"File written, Exiting\" << std::endl;\n}\n", "meta": {"hexsha": "507c94f89fe6bb63df6312d41f3caccf75c896cf", "size": 5786, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Side_Projects/eigentest/Projects/App/eigentest.cpp", "max_stars_repo_name": "MalteWegener99/University", "max_stars_repo_head_hexsha": "b29f6e247336cb3faac9500136f5425605748c61", "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": "Side_Projects/eigentest/Projects/App/eigentest.cpp", "max_issues_repo_name": "MalteWegener99/University", "max_issues_repo_head_hexsha": "b29f6e247336cb3faac9500136f5425605748c61", "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": "Side_Projects/eigentest/Projects/App/eigentest.cpp", "max_forks_repo_name": "MalteWegener99/University", "max_forks_repo_head_hexsha": "b29f6e247336cb3faac9500136f5425605748c61", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-06T19:55:26.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-06T19:55:26.000Z", "avg_line_length": 31.4456521739, "max_line_length": 123, "alphanum_fraction": 0.5876253025, "num_tokens": 1833, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966671870766, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.7483133649630517}}
{"text": "#include \"writer.hpp\"\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <iostream>\n#include <tuple>\n#include <utility>\n\n//----------------stepBegin----------------\n//! Does one Forward-Euler timestep of the heat equation\n//!\n//! @param[out] u at the end, u will contain the values at time t^{n+1}\n//! @param[in] uPrevous should contain the values at time t^n\n//! @param[in] dr the cell length in r direction\n//! @param[in] dt the timestep size\nvoid stepHeatEquation(Eigen::VectorXd &      u,\n                      const Eigen::VectorXd &uPrevious,\n                      const double           dr,\n                      const double           dt) {\n\t// (write your solution here)\n\t#pragma omp parallel for if(u.size() > 10000)\n\tfor (int i = 1; i < u.size() - 1; ++i) {\n\t\tu(i) = uPrevious(i) + dt / (dr * dr) * ((i + 0.5) * dr * uPrevious(i + 1) - 2 * i * dr * uPrevious(i) + (i - 0.5) * dr * uPrevious(i - 1)) / (i * dr);\n\t}\n\tu(0)            = u(1);\n\tu(u.size() - 1) = 0;\n}\n//----------------stepEnd----------------\n\n//----------------solveBegin----------------\n//! Gives an approximation to the heat equation with the given initial data\n//!\n//! @param initialData represents the function \\tilde{u}_0.\n//!\n//! @param shouldStop is a function taking as first\n//!        parameter the current value of u, and\n//!        as second value the current time t.\n//!        The simulation should run until shouldStop(u,t) == true. That is\n//!\n//!        \\code{.cpp}\n//!        while(!shouldStop(u,t)) { /* Do one more timestep */ }\n//!        \\endcode\n//!\n//! @param N the number of inner points\n//! @param cfl the constant C with which we choose the timestep size. We set\n//!        \\code{.cpp}\n//!        dt = cfl*dr*dr\n//!        \\endcode\nEigen::VectorXd solveHeatEquation(const std::function<double(double)> &initialData,\n                                  const std::function<bool(const Eigen::VectorXd &, double)> &shouldStop,\n                                  const int N,\n                                  double    cfl = 0.5) {\n\tEigen::VectorXd u1(N + 2), u2(N + 2);\n\tu1.setZero();\n\n\tEigen::VectorXd &u         = u1;\n\tEigen::VectorXd &uPrevious = u2;\n\n\t// Set the initial value\n\t// (write your solution here)\n\n\tdouble t = 0;\n\n\tdouble dr = 1.0 / (N + 1);\n\tdouble dt = cfl * dr * dr;\n\n\tfor (int i = 0; i < u.size() - 1; ++i) {\n\t\tu(i) = initialData(i * dr);\n\t}\n\n\twhile (!shouldStop(u, t)) {\n\t\t// make one step forward.\n\t\t// Make sure you swap u and uPrevious\n\t\t// accordingly!\n\t\t// And update the current time\n\t\t// (write your solution here)\n\t\tstd::swap(u, uPrevious);\n\t\tt += dt;\n\t\tstepHeatEquation(u, uPrevious, dr, dt);\n\t}\n\t// Return the final solution\n\treturn u;\n}\n//----------------solveEnd----------------\n\nbool stopAtTimeOne(const Eigen::VectorXd &u, double t) {\n\tstd::ignore = u;\n\treturn t > 1;\n}\n\n//----------------convergenceBegin----------------\nvoid convergenceStudy() {\n\tconst size_t NReference = (1 << 10) - 2;\n\tauto initialData        = [](double r) {\n\t\treturn 1 - r * r * cos(r);\n\t};\n\n\tauto stopAtTime0025 = [](const Eigen::VectorXd &, double t) {\n\t\treturn t > 0.025;\n\t};\n\n\tstd::cout << \"Computing reference solution\" << std::endl;\n\tauto uReference = solveHeatEquation(initialData, stopAtTime0025, NReference, 0.5);\n\tstd::cout << \"Done computing reference solution\" << std::endl;\n\tstd::vector<size_t> resolutions;\n\tstd::vector<double> errors;\n\n\t//// NPDE_TEMPLATE_START\n\tfor (int k = 3; k < 10; ++k) {\n\t\tconst size_t N = (1 << k) - 2;\n\t\tauto         u = solveHeatEquation(initialData, stopAtTime0025, N, 0.5);\n\n\t\tdouble maxError = 0;\n\n\t\tsize_t ratioReference = (NReference + 2) / (N + 2);\n\t\tfor (int i = 0; i < u.rows(); ++i) {\n\t\t\tmaxError = std::max(maxError, std::abs(u[i] - uReference[i * ratioReference]));\n\t\t}\n\n\t\tresolutions.push_back(N);\n\t\terrors.push_back(maxError);\n\t}\n\t//// NPDE_TEMPLATE_END\n\twriteToFile(\"resolutions.txt\", resolutions);\n\twriteToFile(\"errors.txt\", errors);\n}\n//----------------convergenceEnd----------------\n\nint main(int, char **) {\n\tauto initialData = [](double) {\n\t\treturn 20;\n\t};\n\n\tauto u05 = solveHeatEquation(initialData, stopAtTimeOne, 20, 0.5);\n\twriteToFile(\"u_05.txt\", u05);\n\n\tauto u051 = solveHeatEquation(initialData, stopAtTimeOne, 20, 0.51);\n\twriteToFile(\"u_051.txt\", u051);\n\n\t//----------------maxstopBegin----------------\n\t// (write your solution here)\n\tauto stopMax4 = [](const Eigen::VectorXd &u, double t) -> bool {\n\t\tif (u.maxCoeff() <= 4.0) {\n\t\t\tstd::cout << \"Max 4 reached after time t = \" << t << std::endl;\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t};\n\n\tsolveHeatEquation(initialData, stopMax4, 500, 0.5);\n\t//----------------maxstopEnd----------------\n\n\tconvergenceStudy();\n\treturn 0;\n}\n", "meta": {"hexsha": "0ca6a5f5e229909d3b55259acc9f543ab460b254", "size": 4646, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "series3/heateq_polar/heateq_polar.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": "series3/heateq_polar/heateq_polar.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": "series3/heateq_polar/heateq_polar.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": 29.7820512821, "max_line_length": 152, "alphanum_fraction": 0.5701678864, "num_tokens": 1310, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.8577681013541611, "lm_q1q2_score": 0.7482717569923819}}
{"text": "/**\n * @file stabrk3.cc\n * @brief NPDE homework StabRK3 code\n * @author Unknown, Oliver Rietmann, Philippe Peter\n * @date 13.04.2021\n * @copyright Developed at ETH Zurich\n */\n\n#include \"stabrk3.h\"\n\n#include <Eigen/Core>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\nnamespace StabRK3 {\n\n/* SAM_LISTING_BEGIN_0 */\nEigen::Vector2d PredPrey(Eigen::Vector2d y0, double T, unsigned int M) {\n  double h = T / M;\n  Eigen::Vector2d y = y0;\n\n#if SOLUTION\n  // Define right-hand-saide function for Lotka-Volterra ODE\n  auto f = [](Eigen::Vector2d y) -> Eigen::Vector2d {\n    return {(1 - y(1)) * y(0), (y(0) - 1) * y(1)};\n  };\n  // Main timstepping loop: uniform stepsize\n  for (int j = 0; j < M; ++j) {\n    // Compute increments and updates according to \\lref{def:rk} for the method\n    // described by the Butcher scheme \\prbeqref{eq:rkesv}\n    Eigen::Vector2d k1 = f(y);\n    Eigen::Vector2d k2 = f(y + h * k1);\n    Eigen::Vector2d k3 = f(y + (h / 4.) * k1 + (h / 4.) * k2);\n    y = y + (h / 6.) * k1 + (h / 6.) * k2 + (2. * h / 3.) * k3;\n  }\n#else\n  //====================\n  // Your code goes here\n  //====================\n#endif\n\n  return y;\n}\n/* SAM_LISTING_END_0 */\n\n/* SAM_LISTING_BEGIN_1 */\nvoid SimulatePredPrey() {\n#if SOLUTION\n  // Parameters\n  double T = 1.0;\n  Eigen::Vector2d y0(100.0, 1.0);\n\n  // (Approximate) reference solution\n  Eigen::Vector2d y_ref = PredPrey(y0, T, std::pow(2, 14));\n\n  Eigen::ArrayXd error(12);\n  Eigen::ArrayXd M(12);\n  // Studying the error for geometrically increasing numbers of equidistant\n  // timesteps is the most appropriate approach to empirically exploring\n  // algebraic convergence.\n  M << 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192;\n\n  // Compute errors\n  for (int i = 0; i < M.size(); ++i) {\n    Eigen::Vector2d y = PredPrey(y0, T, M(i));\n    error(i) = (y - y_ref).norm();\n  }\n  // Print error table\n  PrintErrorTable(M, error);\n#else\n  //====================\n  // Your code goes here\n  //====================\n#endif\n}\n\nvoid PrintErrorTable(const Eigen::ArrayXd& M, const Eigen::ArrayXd& error) {\n  std::cout << std::setw(15) << \"N\" << std::setw(15) << \"error\" << std::setw(15)\n            << \"rate\" << std::endl;\n  // Formatted output in C++\n  for (unsigned int i = 0; i < M.size(); ++i) {\n    std::cout << std::setw(15) << M(i) << std::setw(15) << error(i);\n    if (i > 0) {\n      std::cout << std::setw(15) << std::log2(error(i - 1) / error(i));\n    }\n    std::cout << std::endl;\n  }\n}\n/* SAM_LISTING_END_1 */\n\n}  // namespace StabRK3\n", "meta": {"hexsha": "df2df6fa1b8461e2346812fec719a43e30e4c25d", "size": 2525, "ext": "cc", "lang": "C++", "max_stars_repo_path": "developers/StabRK3/mastersolution/stabrk3.cc", "max_stars_repo_name": "yiluchen1066/NPDECODES", "max_stars_repo_head_hexsha": "f7b1d96555bace59aba2b65f3ef1e95fa7a9017c", "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/StabRK3/mastersolution/stabrk3.cc", "max_issues_repo_name": "yiluchen1066/NPDECODES", "max_issues_repo_head_hexsha": "f7b1d96555bace59aba2b65f3ef1e95fa7a9017c", "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/StabRK3/mastersolution/stabrk3.cc", "max_forks_repo_name": "yiluchen1066/NPDECODES", "max_forks_repo_head_hexsha": "f7b1d96555bace59aba2b65f3ef1e95fa7a9017c", "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": 26.8617021277, "max_line_length": 80, "alphanum_fraction": 0.5805940594, "num_tokens": 867, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681013541613, "lm_q2_score": 0.8723473630627235, "lm_q1q2_score": 0.7482717413356216}}
{"text": "#include <empiricalcpp/src/quadrature.hpp>\n#include <cassert>\n#include <boost/multi_array.hpp>\n#include <Eigen/Dense>\n\nusing empirical::Scalar;\nusing empirical::epsScalar;\nusing empirical::PI;\nusing namespace empirical::quadrature;\n\nnamespace {\n\n    Quadrature::points_weights_type trapezoid_gen(const Quadrature::size_type N1, const Scalar min, const Scalar max) {\n        Quadrature::vector_type points(N1), weights(N1);\n        const Quadrature::size_type N = N1 - 1;\n        const Scalar step = (max - min) / N;\n        const Scalar weight = (max - min) / N;\n        for (Quadrature::size_type i = 0; i < N1; i++) {\n            points[i] = min + i * step;\n            weights[i] = weight;\n        }\n        weights[0] = weight / 2.0;\n        weights[N - 1] = weight / 2.0;\n        return Quadrature::points_weights_type({ points, weights });\n    }\n\n    Quadrature::points_weights_type periodic_trapezoid_gen(const Quadrature::size_type N1, const Scalar min, const Scalar max) {\n        Quadrature::vector_type points(N1), weights(N1);\n        const Scalar step = (max - min) / N1;\n        const Scalar weight = (max - min) / N1;\n        for (Quadrature::size_type i = 0; i < N1; i++) {\n            points[i] = (2 * min + step * (2 * i + 1)) / 2;\n            weights[i] = weight;\n        }\n        return Quadrature::points_weights_type({ points, weights });\n    }\n\n    Quadrature::points_weights_type lgl_gen(const Quadrature::size_type N1, const Scalar min, const Scalar max) {\n        using namespace Eigen;\n        typedef Array<Scalar, Dynamic, 1> Vector;\n        const int64_t N = N1 - 1;\n\n        Vector x = Vector::LinSpaced(N1, 0, PI).cos();\n        Vector xold = Vector::Constant(N1, 1, Scalar(2));\n        Array<Scalar, Dynamic, Dynamic> P = Array<Scalar, Dynamic, Dynamic>::Zero(N1, N1);\n\n        while ((x - xold).abs().maxCoeff() > epsScalar) {\n            xold = x;\n            P.col(0).setOnes();\n            P.col(1) = x;\n\n            for (Quadrature::size_type k = 2; k < N1; k++) {\n                P.col(k) = (Scalar(2 * k - 1) * x * P.col(k - 1) - Scalar(k - 1) * P.col(k - 2)) / Scalar(k);\n            }\n            x = xold - (x * P.col(N) - P.col(N - 1)) / (Scalar(N1) * P.col(N));\n        }\n\n        // Populate x2 with the weights.\n        xold = Scalar(max - min) / (Scalar(N) * Scalar(N1) * P.col(N).square());\n\n        // Reverse the arrays and store them.\n        Quadrature::vector_type points(N1);\n        Quadrature::vector_type weights(N1);\n\n        const Scalar scale = (max - min) / 2.0;\n        const Scalar mid = min + scale;\n        for (Quadrature::size_type i = 0; i < N1; i++) {\n            points[i] = mid + (x(N - i, 0) * scale);\n            weights[i] = xold(N - i, 0);\n        }\n        return Quadrature::points_weights_type({ points, weights });\n    }\n\n}\n\nnamespace empirical {\n    namespace quadrature {\n\n        Quadrature trapezoid(const Quadrature::size_type N, const Scalar min, const Scalar max) {\n            return Quadrature(trapezoid_gen, N, min, max);\n        }\n\n        Quadrature periodicTrapezoid(const Quadrature::size_type N, const Scalar min, const Scalar max) {\n            return Quadrature(periodic_trapezoid_gen, N, min, max);\n        }\n\n        Quadrature legendreGaussLobatto(const Quadrature::size_type N, const Scalar min, const Scalar max) {\n            return Quadrature(lgl_gen, N, min, max);\n        }\n    }\n}\n", "meta": {"hexsha": "cc81162541629ab1c6c803c2f097c0b31eb49e36", "size": 3389, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "empirical/src/quadrature.cpp", "max_stars_repo_name": "dhild/empiricalcpp", "max_stars_repo_head_hexsha": "d369be51ee022a6797a03f415c2dec78762a0822", "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": "empirical/src/quadrature.cpp", "max_issues_repo_name": "dhild/empiricalcpp", "max_issues_repo_head_hexsha": "d369be51ee022a6797a03f415c2dec78762a0822", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2015-01-08T07:15:49.000Z", "max_issues_repo_issues_event_max_datetime": "2015-01-20T04:03:40.000Z", "max_forks_repo_path": "empirical/src/quadrature.cpp", "max_forks_repo_name": "dhild/empiricalcpp", "max_forks_repo_head_hexsha": "d369be51ee022a6797a03f415c2dec78762a0822", "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.8369565217, "max_line_length": 128, "alphanum_fraction": 0.5795219829, "num_tokens": 936, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.893309411735131, "lm_q2_score": 0.8376199592797929, "lm_q1q2_score": 0.7482537930818363}}
{"text": "// -*- coding: utf-16 -*-\n#pragma once\n\n/** @file include/fractions.hpp\n *  This is a C++ Library header.\n */\n\n// #include <boost/operators.hpp>\n// #include <cmath>\n#include <numeric>\n#include <type_traits>\n#include <utility>\n\n#include \"common_concepts.h\"\n\nnamespace fun {\n\n    /**\n     * @brief absolute\n     *\n     * @tparam T\n     * @param[in] a\n     * @return T\n     */\n    template <typename T> inline constexpr auto abs(const T& a) -> T {\n        if constexpr (std::is_unsigned_v<T>) {\n            return a;\n        } else {\n            return (a < T(0)) ? -a : a;\n        }\n    }\n\n    /**\n     * @brief Greatest common divider\n     *\n     * @tparam _Mn\n     * @param[in] __m\n     * @param[in] __n\n     * @return _Mn\n     */\n    template <Integral _Mn> inline constexpr auto gcd_recur(const _Mn& __m, const _Mn& __n) -> _Mn {\n        if (__n == 0) {\n            return abs(__m);\n        }\n        return gcd_recur(__n, __m % __n);\n    }\n\n    /**\n     * @brief Greatest common divider\n     *\n     * @tparam _Mn\n     * @param[in] __m\n     * @param[in] __n\n     * @return _Mn\n     */\n    template <Integral _Mn> inline constexpr auto gcd(const _Mn& __m, const _Mn& __n) -> _Mn {\n        if (__m == 0) {\n            return abs(__n);\n        }\n        return gcd_recur(__m, __n);\n    }\n\n    /**\n     * @brief Least common multiple\n     *\n     * @tparam _Mn\n     * @param[in] __m\n     * @param[in] __n\n     * @return _Mn\n     */\n    template <Integral _Mn> inline constexpr auto lcm(const _Mn& __m, const _Mn& __n) -> _Mn {\n        if (__m == 0 || __n == 0) {\n            return 0;\n        }\n        return (abs(__m) / gcd(__m, __n)) * abs(__n);\n    }\n\n    /**\n     * @brief Fraction\n     *\n     * @tparam Z\n     */\n    template <Integral Z> struct Fraction {\n        Z _num;\n        Z _den;\n\n        /**\n         * @brief Construct a new Fraction object\n         *\n         * @param[in] num\n         * @param[in] den\n         */\n        constexpr Fraction(Z num, Z den) : _num{std::move(num)}, _den{std::move(den)} {\n            this->normalize();\n        }\n\n        /**\n         * @brief normalize to a canonical form\n         *\n         * denominator is always non-negative and co-prime with numerator\n         */\n        constexpr auto normalize() -> Z {\n            this->normalize1();\n            return this->normalize2();\n        }\n\n        /**\n         * @brief normalize to a canonical form\n         *\n         * denominator is always non-negative\n         */\n        constexpr void normalize1() {\n            if (this->_den < Z(0)) {\n                this->_num = -this->_num;\n                this->_den = -this->_den;\n            }\n        }\n\n        /**\n         * @brief normalize to a canonical form\n         *\n         * denominator is always co-prime with numerator\n         */\n        constexpr auto normalize2() -> Z {\n            Z common = gcd(this->_num, this->_den);\n            if (common == Z(1) || common == Z(0)) {\n                return common;\n            }\n            this->_num /= common;\n            this->_den /= common;\n            return common;\n        }\n\n        /**\n         * @brief Construct a new Fraction object\n         *\n         * @param[in] num\n         */\n        constexpr explicit Fraction(Z&& num) : _num{std::move(num)}, _den(Z(1)) {}\n\n        /**\n         * @brief Construct a new Fraction object\n         *\n         * @param[in] num\n         */\n        constexpr explicit Fraction(const Z& num) : _num{num}, _den(1) {}\n\n        /**\n         * @brief Construct a new Fraction object\n         *\n         * @param[in] num\n         */\n        constexpr Fraction() : _num(0), _den(1) {}\n\n        /**\n         * @brief\n         *\n         * @return const Z&\n         */\n        [[nodiscard]] constexpr auto num() const noexcept -> const Z& { return _num; }\n\n        /**\n         * @brief\n         *\n         * @return const Z&\n         */\n        [[nodiscard]] constexpr auto den() const noexcept -> const Z& { return _den; }\n\n        /**\n         * @brief cross product\n         *\n         * @param rhs\n         * @return Z\n         */\n        constexpr auto cross(const Fraction& rhs) const -> Z {\n            return this->_num * rhs._den - this->_den * rhs._num;\n        }\n\n        /** @name Comparison operators\n         *  ==, !=, <, >, <=, >= etc.\n         */\n        ///@{\n\n        /**\n         * @brief Equal to\n         *\n         * @param[in] lhs\n         * @param[in] rhs\n         * @return true\n         * @return false\n         */\n        friend constexpr auto operator==(Fraction lhs, Z rhs) -> bool {\n            if (lhs._den == Z(1) || rhs == Z(0)) {\n                return lhs._num == rhs;\n            }\n            std::swap(lhs._den, rhs);\n            lhs.normalize2();\n            return lhs._num == lhs._den * rhs;\n        }\n\n        /**\n         * @brief Less than\n         *\n         * @param[in] lhs\n         * @param[in] rhs\n         * @return true\n         * @return false\n         */\n        friend constexpr auto operator<(Fraction lhs, Z rhs) -> bool {\n            if (lhs._den == Z(1) || rhs == Z(0)) {\n                return lhs._num == rhs;\n            }\n            std::swap(lhs._den, rhs._num);\n            lhs.normalize2();\n            return lhs._num < lhs._den * rhs;\n        }\n\n        /**\n         * @brief Less than\n         *\n         * @param[in] lhs\n         * @param[in] rhs\n         * @return true\n         * @return false\n         */\n        friend constexpr auto operator<(Z lhs, Fraction rhs) -> bool {\n            if (rhs._den == Z(1) || lhs == Z(0)) {\n                return lhs < rhs._num;\n            }\n            std::swap(rhs._den, lhs);\n            rhs.normalize2();\n            return rhs._den * lhs < rhs._num;\n        }\n\n        /**\n         * @brief Equal to\n         *\n         * @param[in] lhs\n         * @param[in] rhs\n         * @return true\n         * @return false\n         */\n        friend constexpr auto operator==(const Z& lhs, const Fraction& rhs) -> bool {\n            return rhs == lhs;\n        }\n\n        /**\n         * @brief Equal to\n         *\n         * @param[in] rhs\n         * @return true\n         * @return false\n         */\n\n        /**\n         * @brief Equal to\n         *\n         * @param lhs\n         * @param rhs\n         * @return true\n         * @return false\n         */\n        constexpr friend auto operator==(Fraction lhs, Fraction rhs) -> bool {\n            if (lhs._den == rhs._den) {\n                return lhs._num == rhs._num;\n            }\n            std::swap(lhs._den, rhs._num);\n            lhs.normalize2();\n            rhs.normalize2();\n            return lhs._num * rhs._den == lhs._den * rhs._num;\n        }\n\n        /**\n         * @brief Less than\n         *\n         * @param lhs\n         * @param rhs\n         * @return true\n         * @return false\n         */\n        constexpr friend auto operator<(Fraction lhs, Fraction rhs) -> bool {\n            if (lhs._den == rhs._den) {\n                return lhs._num < rhs._num;\n            }\n            std::swap(lhs._den, rhs._num);\n            lhs.normalize2();\n            rhs.normalize2();\n            return lhs._num * rhs._den < lhs._den * rhs._num;\n        }\n\n        /**\n         * @brief\n         *\n         * @param[in] rhs\n         * @return true\n         * @return false\n         */\n        constexpr auto operator!=(const Fraction& rhs) const -> bool { return !(*this == rhs); }\n\n        /**\n         * @brief Greater than\n         *\n         * @param[in] rhs\n         * @return true\n         * @return false\n         */\n        constexpr auto operator>(const Fraction& rhs) const -> bool { return rhs < *this; }\n\n        /**\n         * @brief Greater than or euqal to\n         *\n         * @param[in] rhs\n         * @return true\n         * @return false\n         */\n        constexpr auto operator>=(const Fraction& rhs) const -> bool { return !(*this < rhs); }\n\n        /**\n         * @brief Less than or equal to\n         *\n         * @param[in] rhs\n         * @return true\n         * @return false\n         */\n        constexpr auto operator<=(const Fraction& rhs) const -> bool { return !(rhs < *this); }\n\n        /**\n         * @brief Greater than\n         *\n         * @param[in] rhs\n         * @return true\n         * @return false\n         */\n        constexpr auto operator>(const Z& rhs) const -> bool { return rhs < *this; }\n\n        /**\n         * @brief Less than or equal to\n         *\n         * @param[in] rhs\n         * @return true\n         * @return false\n         */\n        constexpr auto operator<=(const Z& rhs) const -> bool { return !(rhs < *this); }\n\n        /**\n         * @brief Greater than or equal to\n         *\n         * @param[in] rhs\n         * @return true\n         * @return false\n         */\n        constexpr auto operator>=(const Z& rhs) const -> bool { return !(*this < rhs); }\n\n        /**\n         * @brief Greater than\n         *\n         * @param[in] lhs\n         * @param[in] rhs\n         * @return true\n         * @return false\n         */\n        friend constexpr auto operator>(const Z& lhs, const Fraction& rhs) -> bool {\n            return rhs < lhs;\n        }\n\n        /**\n         * @brief Less than or equal to\n         *\n         * @param[in] lhs\n         * @param[in] rhs\n         * @return true\n         * @return false\n         */\n        friend constexpr auto operator<=(const Z& lhs, const Fraction& rhs) -> bool {\n            return !(rhs < lhs);\n        }\n\n        /**\n         * @brief Greater than or euqal to\n         *\n         * @param[in] lhs\n         * @param[in] rhs\n         * @return true\n         * @return false\n         */\n        friend constexpr auto operator>=(const Z& lhs, const Fraction& rhs) -> bool {\n            return !(lhs < rhs);\n        }\n\n        ///@}\n\n        /**\n         * @brief reciprocal\n         *\n         */\n        constexpr void reciprocal() noexcept(std::is_nothrow_swappable_v<Z>) {\n            std::swap(this->_num, this->_den);\n            this->normalize1();\n        }\n\n        /**\n         * @brief multiply and assign\n         *\n         * @param rhs\n         * @return Fraction&\n         */\n        constexpr auto operator*=(Fraction rhs) -> Fraction& {\n            std::swap(this->_num, rhs._num);\n            this->normalize2();\n            rhs.normalize2();\n            this->_num *= rhs._num;\n            this->_den *= rhs._den;\n            return *this;\n        }\n\n        /**\n         * @brief multiply\n         *\n         * @param lhs\n         * @param rhs\n         * @return Fraction\n         */\n        friend constexpr auto operator*(Fraction lhs, const Fraction& rhs) -> Fraction {\n            return lhs *= rhs;\n        }\n\n        /**\n         * @brief multiply and assign\n         *\n         * @param rhs\n         * @return Fraction&\n         */\n        constexpr auto operator*=(Z rhs) -> Fraction& {\n            std::swap(this->_num, rhs);\n            this->normalize2();\n            this->_num *= rhs;\n            return *this;\n        }\n\n        /**\n         * @brief multiply\n         *\n         * @param lhs\n         * @param rhs\n         * @return Fraction\n         */\n        friend constexpr auto operator*(Fraction lhs, const Z& rhs) -> Fraction {\n            return lhs *= rhs;\n        }\n\n        /**\n         * @brief multiply\n         *\n         * @param lhs\n         * @param rhs\n         * @return Fraction\n         */\n        friend constexpr auto operator*(const Z& lhs, Fraction rhs) -> Fraction {\n            return rhs *= lhs;\n        }\n\n        /**\n         * @brief divide and assign\n         *\n         * @param rhs\n         * @return Fraction&\n         */\n        constexpr auto operator/=(Fraction rhs) -> Fraction& {\n            std::swap(this->_den, rhs._num);\n            this->normalize();\n            rhs.normalize2();\n            this->_num *= rhs._den;\n            this->_den *= rhs._num;\n            return *this;\n        }\n\n        /**\n         * @brief divide\n         *\n         * @param lhs\n         * @param rhs\n         * @return Fraction\n         */\n        friend constexpr auto operator/(Fraction lhs, const Fraction& rhs) -> Fraction {\n            return lhs /= rhs;\n        }\n\n        /**\n         * @brief divide and assign\n         *\n         * @param rhs\n         * @return Fraction&\n         */\n        constexpr auto operator/=(const Z& rhs) -> Fraction& {\n            std::swap(this->_den, rhs);\n            this->normalize();\n            this->_den *= rhs;\n            return *this;\n        }\n\n        /**\n         * @brief divide\n         *\n         * @param lhs\n         * @param rhs\n         * @return Fraction\n         */\n        friend constexpr auto operator/(Fraction lhs, const Z& rhs) -> Fraction {\n            return lhs /= rhs;\n        }\n\n        /**\n         * @brief divide\n         *\n         * @param lhs\n         * @param rhs\n         * @return Fraction\n         */\n        friend constexpr auto operator/(const Z& lhs, Fraction rhs) -> Fraction {\n            rhs.reciprocal();\n            return rhs *= lhs;\n        }\n\n        /**\n         * @brief Negate\n         *\n         * @return Fraction\n         */\n        constexpr auto operator-() const -> Fraction {\n            auto res = Fraction(*this);\n            res._num = -res._num;\n            return res;\n        }\n\n        /**\n         * @brief Add\n         *\n         * @param rhs\n         * @return Fraction\n         */\n        constexpr auto operator+(const Fraction& rhs) const -> Fraction {\n            if (this->_den == rhs._den) {\n                return Fraction(this->_num + rhs._num, this->_den);\n            }\n            const auto common = gcd(this->_den, rhs._den);\n            if (common == Z(0)) {\n                return Fraction(rhs._den * this->_num + this->_den * rhs._num, Z(0));\n            }\n            const auto l = this->_den / common;\n            const auto r = rhs._den / common;\n            auto d = this->_den * r;\n            auto n = r * this->_num + l * rhs._num;\n            return Fraction(std::move(n), std::move(d));\n        }\n\n        /**\n         * @brief Subtract\n         *\n         * @param[in] frac\n         * @return Fraction\n         */\n        constexpr auto operator-(const Fraction& frac) const -> Fraction { return *this + (-frac); }\n\n        /**\n         * @brief Add\n         *\n         * @param[in] frac\n         * @param[in] i\n         * @return Fraction\n         */\n        friend constexpr auto operator+(Fraction frac, const Z& i) -> Fraction { return frac += i; }\n\n        /**\n         * @brief Add\n         *\n         * @param[in] i\n         * @param[in] frac\n         * @return Fraction\n         */\n        friend constexpr auto operator+(const Z& i, Fraction frac) -> Fraction { return frac += i; }\n\n        /**\n         * @brief\n         *\n         * @param[in] i\n         * @return Fraction\n         */\n        constexpr auto operator-(const Z& i) const -> Fraction { return *this + (-i); }\n\n        /**\n         * @brief\n         *\n         * @param[in] rhs\n         * @return Fraction\n         */\n        constexpr auto operator+=(const Fraction& rhs) -> Fraction& { return *this -= (-rhs); }\n\n        /**\n         * @brief\n         *\n         * @param[in] rhs\n         * @return Fraction\n         */\n        constexpr auto operator-=(const Fraction& rhs) -> Fraction& {\n            if (this->_den == rhs._den) {\n                this->_num -= rhs._num;\n                this->normalize2();\n                return *this;\n            }\n\n            auto other{rhs};\n            std::swap(this->_den, other._num);\n            auto common_n = this->normalize2();\n            auto common_d = other.normalize2();\n            std::swap(this->_den, other._num);\n            this->_num = this->cross(other);\n            this->_den *= other._den;\n            std::swap(this->_den, common_d);\n            this->normalize2();\n            this->_num *= common_n;\n            this->_den *= common_d;\n            this->normalize2();\n            return *this;\n        }\n\n        /**\n         * @brief\n         *\n         * @param[in] i\n         * @return Fraction\n         */\n        constexpr auto operator+=(const Z& i) -> Fraction& { return *this -= (-i); }\n\n        /**\n         * @brief\n         *\n         * @param[in] rhs\n         * @return Fraction\n         */\n        constexpr auto operator-=(const Z& rhs) -> Fraction& {\n            if (this->_den == Z(1)) {\n                this->_num -= rhs;\n                return *this;\n            }\n\n            auto other{rhs};\n            std::swap(this->_den, other);\n            auto common_n = this->normalize2();\n            std::swap(this->_den, other);\n            this->_num -= other * this->_den;\n            this->_num *= common_n;\n            this->normalize2();\n            return *this;\n        }\n\n        /**\n         * @brief\n         *\n         * @param[in] c\n         * @param[in] frac\n         * @return Fraction\n         */\n        friend constexpr auto operator-(const Z& c, const Fraction& frac) -> Fraction {\n            return c + (-frac);\n        }\n\n        /**\n         * @brief\n         *\n         * @param[in] c\n         * @param[in] frac\n         * @return Fraction\n         */\n        friend constexpr auto operator+(int&& c, const Fraction& frac) -> Fraction {\n            return frac + Z(c);\n        }\n\n        /**\n         * @brief\n         *\n         * @param[in] c\n         * @param[in] frac\n         * @return Fraction\n         */\n        friend constexpr auto operator-(int&& c, const Fraction& frac) -> Fraction {\n            return (-frac) + Z(c);\n        }\n\n        /**\n         * @brief\n         *\n         * @param[in] c\n         * @param[in] frac\n         * @return Fraction<Z>\n         */\n        friend constexpr auto operator*(int&& c, const Fraction& frac) -> Fraction {\n            return frac * Z(c);\n        }\n\n        /**\n         * @brief\n         *\n         * @tparam _Stream\n         * @tparam Z\n         * @param[in] os\n         * @param[in] frac\n         * @return _Stream&\n         */\n        template <typename _Stream> friend auto operator<<(_Stream& os, const Fraction& frac)\n            -> _Stream& {\n            os << \"(\" << frac.num() << \"/\" << frac.den() << \")\";\n            return os;\n        }\n    };\n\n    // For template deduction\n    // Integral{Z} Fraction(const Z &, const Z &) noexcept -> Fraction<Z>;\n\n}  // namespace fun\n", "meta": {"hexsha": "1ecbf9b2136972dc4309f718b361e47d9a2c65b4", "size": 18358, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/projgeom/fractions.hpp", "max_stars_repo_name": "luk036/projgeom-cpp", "max_stars_repo_head_hexsha": "665f852e17804a251639808c509df0a675f21e1d", "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": "include/projgeom/fractions.hpp", "max_issues_repo_name": "luk036/projgeom-cpp", "max_issues_repo_head_hexsha": "665f852e17804a251639808c509df0a675f21e1d", "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": "include/projgeom/fractions.hpp", "max_forks_repo_name": "luk036/projgeom-cpp", "max_forks_repo_head_hexsha": "665f852e17804a251639808c509df0a675f21e1d", "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": 25.4972222222, "max_line_length": 100, "alphanum_fraction": 0.4327813487, "num_tokens": 4347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391579526934, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.748103765172056}}
{"text": "// $ g++ -std=c++14 -I/usr/include/eigen3 coordinateTransform.cpp \n//\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <iomanip>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\nusing namespace std;\nusing namespace Eigen;\n\nint main(int argc, char** argv) {\n  Quaterniond q1(0.35, 0.2, 0.3, 0.1), q2(-0.5, 0.4, -0.1, 0.2);\n  q1.normalize();\n  q2.normalize();\n  Vector3d t1(0.3, 0.1, 0.1), t2(-0.1, 0.5, 0.3);\n  Vector3d p1(0.5, 0, 0.2);\n\n  Isometry3d T1w(q1), T2w(q2);\n  T1w.pretranslate(t1);\n  T2w.pretranslate(t2);\n\n  Vector3d p2 = T2w * T1w.inverse() * p1;\n  cout << endl << p2.transpose() << endl;\n\n  // ---\n  auto w1 = T1w.inverse() * p1;\n  cout << \"word1 cor=\" << w1 << endl;\n\n  auto w2 = T2w.inverse() * p2;\n  cout << \"word2 cor=\" << w2 << endl;\n  // https://stackoverflow.com/questions/15051367/how-to-compare-vectors-approximately-in-eigen\n  // There is also isApprox function which was not working for me. I am just using ( expect - res).norm() < some small number.\n  cout << w1.x() << \",\"<< w2.x() << \" and they are equal?\"<< (w1.x() == w2.x()) <<endl;\n  auto diff = (w2 - w1).norm();\n  cout << std::setprecision(10) << std::fixed<< diff << endl;\n  cout << \"std::setprecision(10): \" << std::setprecision(10) << std::fixed<< diff << '\\n'\n       << \"max precision:        \" << std::setprecision(std::numeric_limits<long double>::digits10 + 1) << diff << endl;\n  return 0;\n}\n", "meta": {"hexsha": "9c2146c31700139197c4acfae68a9b52524bbddc", "size": 1402, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch3/examples/coordinateTransform.cpp", "max_stars_repo_name": "zhishan/slambook2", "max_stars_repo_head_hexsha": "6cfce988fe327e35f307284fff92f75b873c952b", "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/examples/coordinateTransform.cpp", "max_issues_repo_name": "zhishan/slambook2", "max_issues_repo_head_hexsha": "6cfce988fe327e35f307284fff92f75b873c952b", "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/examples/coordinateTransform.cpp", "max_forks_repo_name": "zhishan/slambook2", "max_forks_repo_head_hexsha": "6cfce988fe327e35f307284fff92f75b873c952b", "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.6046511628, "max_line_length": 126, "alphanum_fraction": 0.6055634807, "num_tokens": 494, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333483, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7480715614472457}}
{"text": "// tests/unit/stanmath/StanPerceptronTest_unittest.cc\n#include <Eigen/Dense>\n#include <cmath>\n#include <gtest/gtest.h>\n#include <iostream>\n#include <random>\n#include <stan/math.hpp>\nusing namespace std;\nusing namespace Eigen;\nusing namespace stan::math;\n\n/*\nThis test will implement a perceptron using stan math\nThe perceptron will have one input, the column vector [1 1 1]^T\nThen, it will have 2x3 Matrix of weights that it will learn\nThen, the output is a 2x1 column vector\nIn this example, we want to learn the weights W such that the square\nError loss from the output of the perceptron to [1 1]^T is minimized.\nSince we can find weights from [1 1 1]^T to [1 1]^T in a perceptron,\nthis error should be very close to zero after 100 epochs.\n*/\nTEST(StanPerceptronTest, sample_perceptron)\n{\n\t// Initialize the Input Vector\n\tMatrix<var, 3, 1> inp;\n\tinp(0, 0) = 1;\n\tinp(1, 0) = 1;\n\tinp(2, 0) = 1;\n\n\t// Randomly Initialize the weights on the perceptron\n\tstd::random_device rd{};\n\tstd::mt19937 gen{rd()};\n\tnormal_distribution<> d{0, 1};\n\tMatrix<var, 2, 3> W1;\n\tfor (int i = 0; i < 2; ++i)\n\t{\n\t\tfor (int j = 0; j < 3; ++j)\n\t\t{\n\t\t\tW1(i, j) = 0.01 * d(gen);\n\t\t}\n\t}\n\n\t// Define the outputs of the neural network\n\tMatrix<var, 2, 1> outputs;\n\n\tdouble learning_rate = 0.1;\n\tdouble last_error = 0;\n\tfor (int epoch = 0; epoch < 100; ++epoch)\n\t{\n\t\tvar error = 0;\n\t\toutputs = W1 * inp;\n\t\tfor (int i = 0; i < 2; ++i)\n\t\t{\n\t\t\terror += (outputs(i, 0) - 1) * (outputs(i, 0) - 1);\n\t\t}\n\t\terror.grad();\n\n\t\t// Now use gradient descent to change the weights\n\t\tfor (int i = 0; i < 2; ++i)\n\t\t{\n\t\t\tfor (int j = 0; j < 3; ++j)\n\t\t\t{\n\t\t\t\tW1(i, j) = W1(i, j) - learning_rate * W1(i, j).adj();\n\t\t\t}\n\t\t}\n\n\t\t// Store the value of current error in last_error\n\t\tlast_error = value_of(error);\n\t}\n\n\t// Error should be very close to 0.0\n\tEXPECT_NEAR(last_error, 0.0, 1e-6);\n}\n", "meta": {"hexsha": "8a0315dab3be99d3de1fafad45bf3ffcd448e92a", "size": 1836, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tests/unit/StanMath/StanPerceptronTest_unittest.cc", "max_stars_repo_name": "cloner1984/shogun", "max_stars_repo_head_hexsha": "901c04b2c6550918acf0594ef8afeb5dcd840a7d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-08-12T18:11:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-17T10:56:49.000Z", "max_issues_repo_path": "tests/unit/StanMath/StanPerceptronTest_unittest.cc", "max_issues_repo_name": "cloner1984/shogun", "max_issues_repo_head_hexsha": "901c04b2c6550918acf0594ef8afeb5dcd840a7d", "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": "tests/unit/StanMath/StanPerceptronTest_unittest.cc", "max_forks_repo_name": "cloner1984/shogun", "max_forks_repo_head_hexsha": "901c04b2c6550918acf0594ef8afeb5dcd840a7d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-06-02T09:15:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-02T09:15:40.000Z", "avg_line_length": 24.8108108108, "max_line_length": 69, "alphanum_fraction": 0.6486928105, "num_tokens": 638, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107896491796, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.7480692557536199}}
{"text": "//\n//  interp.hpp\n//  test_proj\n//\n//  Created by Erlend Basso on 08/03/2021.\n//\n\n#ifndef interp_h\n#define interp_h\n\n#include <Eigen/Dense>\n\n// M: M \\times M matrix of data to interpolate from\ntemplate <unsigned int M>\n\nclass BilinearInterpolator\n{\npublic:\n    using VectorMd = Eigen::Matrix<double, M, 1>;\n    using MatrixMd = Eigen::Matrix<double, M, M>;\n    using Vector2d = Eigen::Vector2d;\n\n    BilinearInterpolator() {}\n\n    BilinearInterpolator(const MatrixMd &F, const VectorMd &breakpoints_x, const VectorMd &breakpoints_y)\n        : F_{F},\n          breakpoints_x_{breakpoints_x},\n          breakpoints_y_{breakpoints_y}\n    {\n    }\n\n    void init(const MatrixMd &F, const VectorMd &breakpoints_x, const VectorMd &breakpoints_y)\n    {\n        F_ = F;\n        breakpoints_x_ = breakpoints_x;\n        breakpoints_y_ = breakpoints_y;\n    }\n\n    double interp(double x, double y)\n    {\n        int ind_x = 0;\n        int ind_y = 0;\n\n        for (int i = 0; i < M - 1; i++)\n        {\n            if (x >= breakpoints_x_(i) && x <= breakpoints_x_(i + 1))\n            {\n                x1_ = breakpoints_x_(i);\n                x2_ = breakpoints_x_(i + 1);\n                ind_x = i;\n                break;\n            }\n        }\n        for (int j = 0; j < M - 1; j++)\n        {\n            if (y >= breakpoints_y_(j) && y <= breakpoints_y_(j + 1))\n            {\n                y1_ = breakpoints_y_(j);\n                y2_ = breakpoints_y_(j + 1);\n                ind_y = j;\n                break;\n            }\n        }\n\n        Vector2d delta_x{x2_ - x, x - x1_};\n        Vector2d delta_y{y2_ - y, y - y1_};\n\n        return 1.0 / ((x2_ - x1_) * (y2_ - y1_)) * delta_x.transpose() * F_.block(ind_x, ind_y, 2, 2) * delta_y;\n    }\n\nprivate:\n    MatrixMd F_;\n    VectorMd breakpoints_x_;\n    VectorMd breakpoints_y_;\n    double x1_, x2_, y1_, y2_;\n};\n\n#endif /* interp_h */\n", "meta": {"hexsha": "6c1d725fb52b5977098841b310990dbe7e374090", "size": 1878, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ROS/C++/ros_cse_actuator_driver/include/cse_actuator_driver/interp.hpp", "max_stars_repo_name": "NTNU-MCS/CS_EnterpriseI_archive", "max_stars_repo_head_hexsha": "a5676d8037a5125c28f221074ad4b44fa78ef79f", "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": "ROS/C++/ros_cse_actuator_driver/include/cse_actuator_driver/interp.hpp", "max_issues_repo_name": "NTNU-MCS/CS_EnterpriseI_archive", "max_issues_repo_head_hexsha": "a5676d8037a5125c28f221074ad4b44fa78ef79f", "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": "ROS/C++/ros_cse_actuator_driver/include/cse_actuator_driver/interp.hpp", "max_forks_repo_name": "NTNU-MCS/CS_EnterpriseI_archive", "max_forks_repo_head_hexsha": "a5676d8037a5125c28f221074ad4b44fa78ef79f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-01-23T10:01:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-02T09:44:41.000Z", "avg_line_length": 23.7721518987, "max_line_length": 112, "alphanum_fraction": 0.5319488818, "num_tokens": 535, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009480320036, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7479996653896598}}
{"text": "//  (C) Copyright Nick Thompson 2021.\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#ifndef BOOST_MATH_TOOLS_CUBIC_ROOTS_HPP\n#define BOOST_MATH_TOOLS_CUBIC_ROOTS_HPP\n#include <array>\n#include <algorithm>\n#include <boost/math/special_functions/sign.hpp>\n#include <boost/math/tools/roots.hpp>\n\nnamespace boost::math::tools {\n\n// Solves ax^3 + bx^2 + cx + d = 0.\n// Only returns the real roots, as types get weird for real coefficients and complex roots.\n// Follows Numerical Recipes, Chapter 5, section 6.\n// NB: A better algorithm apparently exists:\n// Algorithm 954: An Accurate and Efficient Cubic and Quartic Equation Solver for Physical Applications\n// However, I don't have access to that paper!\ntemplate<typename Real>\nstd::array<Real, 3> cubic_roots(Real a, Real b, Real c, Real d) {\n    using std::sqrt;\n    using std::acos;\n    using std::cos;\n    using std::cbrt;\n    using std::abs;\n    using std::fma;\n    std::array<Real, 3> roots = {std::numeric_limits<Real>::quiet_NaN(),\n                                 std::numeric_limits<Real>::quiet_NaN(),\n                                 std::numeric_limits<Real>::quiet_NaN()};\n    if (a == 0) {\n        // bx^2 + cx + d = 0:\n        if (b == 0) {\n            // cx + d = 0:\n            if (c == 0) {\n                if (d != 0) {\n                    // No solutions:\n                    return roots;\n                }\n                roots[0] = 0;\n                roots[1] = 0;\n                roots[2] = 0;\n                return roots;\n            }\n            roots[0] = -d/c;\n            return roots;\n        }\n        auto [x0, x1] = quadratic_roots(b, c, d);\n        roots[0] = x0;\n        roots[1] = x1;\n        return roots;\n    }\n    if (d == 0) {\n        auto [x0, x1] = quadratic_roots(a, b, c);\n        roots[0] = x0;\n        roots[1] = x1;\n        roots[2] = 0;\n        std::sort(roots.begin(), roots.end());\n        return roots;\n    }\n    Real p = b/a;\n    Real q = c/a;\n    Real r = d/a;\n    Real Q = (p*p - 3*q)/9;\n    Real R = (2*p*p*p - 9*p*q + 27*r)/54;\n    if (R*R < Q*Q*Q) {\n        Real rtQ = sqrt(Q);\n        Real theta = acos(R/(Q*rtQ))/3;\n        Real st = sin(theta);\n        Real ct = cos(theta);\n        roots[0] = -2*rtQ*ct - p/3;\n        roots[1] = -rtQ*(-ct + sqrt(Real(3))*st) - p/3;\n        roots[2] = rtQ*(ct + sqrt(Real(3))*st) - p/3;\n    } else {\n        // In Numerical Recipes, Chapter 5, Section 6, it is claimed that we only have one real root\n        // if R^2 >= Q^3. But this isn't true; we can even see this from equation 5.6.18.\n        // The condition for having three real roots is that A = B.\n        // It *is* the case that if we're in this branch, and we have 3 real roots, two are a double root.\n        // Take (x+1)^2(x-2) = x^3 - 3x -2 as an example. This clearly has a double root at x = -1,\n        // and it gets sent into this branch.\n        Real arg = R*R - Q*Q*Q;\n        Real A = -boost::math::sign(R)*cbrt(abs(R) + sqrt(arg));\n        Real B = 0;\n        if (A != 0) {\n            B = Q/A;\n        }\n        roots[0] = A + B - p/3;\n        // Yes, we're comparing floats for equality:\n        // Any perturbation pushes the roots into the complex plane; out of the bailiwick of this routine.\n        if (A == B || arg == 0) {\n            roots[1] = -A - p/3;\n            roots[2] = -A - p/3;\n        }\n    }\n    // Root polishing:\n    for (auto & r : roots) {\n        // Horner's method.\n        // Here I'll take John Gustaffson's opinion that the fma is a *distinct* operation from a*x +b:\n        // Make sure to compile these fmas into a single instruction and not a function call!\n        // (I'm looking at you Windows.)\n        Real f = fma(a, r, b);\n        f = fma(f,r,c);\n        f = fma(f,r,d);\n        Real df = fma(3*a, r, 2*b);\n        df = fma(df, r, c);\n        if (df != 0) {\n            // No standard library feature for fused-divide add!\n            r -= f/df;\n        }\n    }\n    std::sort(roots.begin(), roots.end());\n    return roots;\n}\n\n// Computes the empirical residual p(r) (first element) and expected residual eps*|rp'(r)| (second element) for a root.\n// Recall that for a numerically computed root r satisfying r = r_0(1+eps) of a function p, |p(r)| <= eps|rp'(r)|.\ntemplate<typename Real>\nstd::array<Real, 2> cubic_root_residual(Real a, Real b, Real c, Real d, Real root) {\n    using std::fma;\n    using std::abs;\n    std::array<Real, 2> out;\n    Real residual = fma(a, root, b);\n    residual = fma(residual,root,c);\n    residual = fma(residual,root,d);\n\n    out[0] = residual;\n\n    Real expected_residual = fma(3*a, root, 2*b);\n    expected_residual = fma(expected_residual, root, c);\n    expected_residual = abs(root*expected_residual)*std::numeric_limits<Real>::epsilon();\n    out[1] = expected_residual;\n    return out;\n}\n\n}\n#endif\n", "meta": {"hexsha": "cec282eac485d65cbce0e87d97e8eeacb2d5d8bf", "size": 4937, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/boost_1.78.0/boost/math/tools/cubic_roots.hpp", "max_stars_repo_name": "LaudateCorpus1/math", "max_stars_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_stars_repo_licenses": ["BSD-3-Clause"], "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": "lib/boost_1.78.0/boost/math/tools/cubic_roots.hpp", "max_issues_repo_name": "LaudateCorpus1/math", "max_issues_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_issues_repo_licenses": ["BSD-3-Clause"], "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": "lib/boost_1.78.0/boost/math/tools/cubic_roots.hpp", "max_forks_repo_name": "LaudateCorpus1/math", "max_forks_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_forks_repo_licenses": ["BSD-3-Clause"], "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": 36.0364963504, "max_line_length": 119, "alphanum_fraction": 0.5474984809, "num_tokens": 1452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554475, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.7479560142609468}}
{"text": "#include <blitzml/smooth_loss/huber_loss.h>\n#include <blitzml/base/math_util.h>\n#include <math.h>\n\nnamespace BlitzML {\n\nvalue_t HuberLoss::compute_loss(value_t a_dot_omega, value_t label) const {\n  value_t residual = a_dot_omega - label;\n  if (residual < -1.) {\n    return -residual - 0.5;\n  } else if (residual > 1.) {\n    return residual - 0.5;\n  } else {\n    return 0.5 * sq(residual);\n  }\n}\n\n\nvalue_t HuberLoss::compute_conjugate(value_t dual_variable,\n                                     value_t label) const {\n  return dual_variable * label + sq(dual_variable) / 2;\n}\n\n\nvalue_t HuberLoss::compute_deriative(value_t a_dot_omega,\n                                     value_t label) const {\n  value_t residual = a_dot_omega - label;\n  if (residual < -1.) {\n    return -1.;\n  } else if (residual > 1.) {\n    return 1.;\n  } else {\n    return residual;\n  }\n}\n\n\nvalue_t HuberLoss::compute_2nd_derivative(value_t a_dot_omega,\n                                             value_t label) const {\n  value_t residual = a_dot_omega - label;\n  if (residual < -1.) {\n    return MIN_SMOOTH_LOSS_2ND_DERIVATIVE;\n  } else if (residual > 1.) {\n    return MIN_SMOOTH_LOSS_2ND_DERIVATIVE;\n  } else {\n    return 1.;\n  }\n}\n\n\nvalue_t HuberLoss::lipschitz_constant() const {\n  return 1;\n}\n\n} // namespace BlitzML\n\n\n", "meta": {"hexsha": "2d89da80503750ba133c0dfcb2f21cd5dec2bca8", "size": 1297, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/smooth_loss/huber_loss.cpp", "max_stars_repo_name": "vlad17/BlitzML", "max_stars_repo_head_hexsha": "f13e089acf7435416bec17e87e5b3130426fc2cd", "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/smooth_loss/huber_loss.cpp", "max_issues_repo_name": "vlad17/BlitzML", "max_issues_repo_head_hexsha": "f13e089acf7435416bec17e87e5b3130426fc2cd", "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/smooth_loss/huber_loss.cpp", "max_forks_repo_name": "vlad17/BlitzML", "max_forks_repo_head_hexsha": "f13e089acf7435416bec17e87e5b3130426fc2cd", "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.3620689655, "max_line_length": 75, "alphanum_fraction": 0.6229760987, "num_tokens": 368, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595163, "lm_q2_score": 0.8267117898012104, "lm_q1q2_score": 0.7478852587674453}}
{"text": "#include <catch2/catch.hpp>\n#include <Euclid/Geometry/Spectral.h>\n\n#include <string>\n#include <vector>\n#include <iostream>\n\n#include <CGAL/Simple_cartesian.h>\n#include <CGAL/Surface_mesh.h>\n#include <Eigen/Core>\n#include <Euclid/Math/Numeric.h>\n#include <Euclid/MeshUtil/CGALMesh.h>\n#include <Euclid/IO/OffIO.h>\n\n#include <config.h>\n\nusing Kernel = CGAL::Simple_cartesian<double>;\nusing Point_3 = typename Kernel::Point_3;\nusing Vector_3 = typename Kernel::Vector_3;\nusing Mesh = CGAL::Surface_mesh<Point_3>;\n\nTEST_CASE(\"Geometry, Spectral\", \"[geometry][spectral]\")\n{\n    std::string fin(DATA_DIR);\n    fin.append(\"bumpy.off\");\n    std::vector<double> positions;\n    std::vector<int> indices;\n    Euclid::read_off<3>(fin, positions, nullptr, &indices, nullptr);\n    Mesh mesh;\n    Euclid::make_mesh<3>(mesh, positions, indices);\n\n    int nv = positions.size() / 3;\n    unsigned k = 20;\n    Eigen::VectorXd lambdas1, lambdas2;\n    Eigen::MatrixXd phis1, phis2;\n\n    auto n1 = Euclid::spectrum(\n        mesh, k, lambdas1, phis1, Euclid::SpecOp::mesh_laplacian);\n    auto n2 = Euclid::spectrum(\n        mesh, k, lambdas2, phis2, Euclid::SpecOp::graph_laplacian);\n\n    // test size of outputs\n    REQUIRE(n1 == k);\n    REQUIRE(n2 == k);\n    REQUIRE(lambdas1.size() == k);\n    REQUIRE(lambdas2.size() == k);\n    REQUIRE(phis1.rows() == nv);\n    REQUIRE(phis1.cols() == k);\n    REQUIRE(phis2.rows() == nv);\n    REQUIRE(phis2.cols() == k);\n\n    // the first eigenvalue shoule be 0\n    REQUIRE(Euclid::eq_abs_err(lambdas1(0), 0.0, 1e-14));\n    REQUIRE(Euclid::eq_abs_err(lambdas2(0), 0.0, 1e-14));\n\n    // the first eigenvector should be ones, but need to be scaled though,\n    // so we only test if the entries are equal\n    REQUIRE(Euclid::eq_abs_err(\n        phis1.col(0).maxCoeff(), phis1.col(0).minCoeff(), 1e-14));\n    REQUIRE(Euclid::eq_abs_err(\n        phis2.col(0).maxCoeff(), phis2.col(0).minCoeff(), 1e-14));\n\n    // eigenvectors of the mesh laplacian are orthogonal wrt mass weighted\n    // inner product\n    auto D = Euclid::mass_matrix(mesh);\n    auto dot = (phis1.col(1).transpose() * D * phis1.col(10))(0);\n    REQUIRE(Euclid::eq_abs_err(dot, 0.0, 1e-14));\n\n    // eigenvectors of the graph laplacian are orthonormal\n    REQUIRE(Euclid::eq_abs_err(phis2.col(1).dot(phis2.col(10)), 0.0, 1e-14));\n    REQUIRE(\n        Euclid::eq_abs_err(phis2.col(1).norm(), phis2.col(10).norm(), 1e-14));\n}\n", "meta": {"hexsha": "f10cda8da20c680d8d9366be25046bc62b094468", "size": 2397, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/Geometry/test_Spectral.cpp", "max_stars_repo_name": "unclejimbo/euclid", "max_stars_repo_head_hexsha": "e118abdcdf51b6bc05cf5aa056bf228e052cf501", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2017-05-02T07:04:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T10:00:01.000Z", "max_issues_repo_path": "test/Geometry/test_Spectral.cpp", "max_issues_repo_name": "unclejimbo/euclid", "max_issues_repo_head_hexsha": "e118abdcdf51b6bc05cf5aa056bf228e052cf501", "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/Geometry/test_Spectral.cpp", "max_forks_repo_name": "unclejimbo/euclid", "max_forks_repo_head_hexsha": "e118abdcdf51b6bc05cf5aa056bf228e052cf501", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-07-02T17:59:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-18T07:01:17.000Z", "avg_line_length": 32.3918918919, "max_line_length": 78, "alphanum_fraction": 0.6608260325, "num_tokens": 760, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133498259924, "lm_q2_score": 0.7956581097540519, "lm_q1q2_score": 0.7478496792551481}}
{"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::VecotrXd::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) = ( -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                // TODO: reconstruct finite-difference slope\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        size_t i_star=0:\n        double tmp,t1,t2,y1,y2,c1,c2;\n        // TODO: evaluate interpolant at x\n        for (int j=0; j<x.size();j++){\n\t\t\tt1=t(i_star-1);\n\t\t\tt2=t(i_star);\n\t\t\t\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\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    //auto f = [] (double x) {return 1./((1+t)*(1+t));}\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    // TODO: error and rates and print\n\n\n\n}\n", "meta": {"hexsha": "366b39cc259d1a95df75b6361cb5d7438c4b44e3", "size": 3228, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/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/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/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": 33.2783505155, "max_line_length": 107, "alphanum_fraction": 0.5408921933, "num_tokens": 935, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563335, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.7478463498456702}}
{"text": "// wsn: program to illustrate use of Eigen library to fit a plane to a collection of points\n\n#include<ros/ros.h>\n\n#include <fstream>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\n#include <Eigen/Eigen>\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <Eigen/Eigenvalues>\n\nusing namespace Eigen;\nusing namespace std;\n//using namespace Eigen; //if you get tired of typing Eigen:: everywhere, uncomment this.\n                         // but I'll leave this as required, for now, to highlight when Eigen classes are being used\n    double g_noise_gain = 0.1; //0.1; //0.1; //0.1; //decide how much noise to add to points; start with 0.0, and should get precise results\n\nint main(int argc, char** argv) {\n    ros::init(argc, argv, \"example_eigen_plane_fit\"); //node name\n    ros::NodeHandle nh; // create a node handle; need to pass this to the class constructor\n\n    ros::Rate sleep_timer(1.0); //a timer for desired rate, e.g. 1Hz\n\n    //xxxxxxxxxxxxxxxxxx  THIS PART IS JUST TO GENERATE DATA xxxxxxxxxxxxxxxxxxxx\n    //xxxxxxxxxxxxxxxxxx  NORMALLY, THIS DATA WOULD COME FROM TOPICS OR FROM GOALS xxxxxxxxx\n    // define a plane and generate some points on that plane\n    // the plane can be defined in terms of a normal vector and a distance from the origin\n    Eigen::Vector3d normal_vec(1,2,3); // here is an arbitrary normal vector, initialized to (1,2,3) upon instantiation\n    ROS_INFO(\"creating example noisy, planar data...\");\n    cout<<\"normal: \"<<normal_vec.transpose()<<endl; //.transpose() is so I can display the components on the same line, instead of as a column\n    normal_vec/=normal_vec.norm(); // make this vector unit length\n    cout<<\"unit length normal: \"<<normal_vec.transpose()<<endl;\n    double dist = 1.23;  // define the plane to have this distance from the origin.  Note that if we care about positive/negative sides of a plane,\n                         // then this \"distance\" could be negative, as measured from the origin to the plane along the positive plane normal\n    cout<<\"plane distance from origin: \"<<dist<<endl;\n    \n    // to generate points on the plane, construct a pair of axes perpendicular to the plane normal\n    Eigen::Vector3d v1,v2; //need to fill in values for these\n    // we'll use an Eigen \"Matrix\" type to help out.  Define a 3x3 \"double precision\" matrix, Matrix3d\n    //define a rotation about the z axis of 90 deg; elements of this matrix are:\n    // [0,-1,0; \n    //  1, 0, 0; \n    //  0;0;1]\n    Eigen::Matrix3d Rot_z;\n    Rot_z.row(0)<<0,-1,0;  // populate the first row--shorthand method\n    Rot_z.row(1)<<1, 0,0;  //second row\n    Rot_z.row(2)<<0, 0,1;  // yada, yada\n    cout<<\"Rot_z: \"<<endl;  \n\n    cout<<Rot_z<<endl;  // Eigen matrices and vectors are nicely formatted; better: use ROS_INFO_STREAM() instead of cout\n\n    ROS_INFO_STREAM(endl<<Rot_z);\n    // we need another vector to generate two desired vectors in our plane.\n    // start by generating a new vector that is a rotation of our normal vector, rotated about the z-axis\n    // this hack will NOT work if our normal_vec = [0,0,1], \n    v1 = Rot_z*normal_vec; //here is how to multiply a matrix times a vector\n        //although Rot_z and normal_vec are both objects (with associated data and member methods), multiplication is defined,\n        // resulting in the data members being altered or generated as expected for matrix-vector multiplies\n    ROS_INFO_STREAM(\"v1: \"<<v1.transpose()<<endl);\n\n\n    // let's look at the dot product between v1 and normal_vec, using two approaches\n    double dotprod = v1.dot(normal_vec); //using the \"dot()\" member function\n    double dotprod2 = v1.transpose()*normal_vec;// alt: turn v1 into a row vector, then multiply times normal_vec\n\n    cout<<\"v1 dot normal: \"<<dotprod<<\"; v1.transpose()*normal_vec: \"<<dotprod2<<endl; //yields the same answer\n    cout<<\"(should be identical)\"<<endl;\n    \n    // let's look at the cross product, v1 X normal_vec; use the member fnc cross()\n    v2 = v1.cross(normal_vec);\n    v2/=v2.norm(); // normalize the output, i.e. make v2 unit length\n    cout<<\"v2: \"<<v2.transpose()<<endl;\n    \n    //because v2 was generated from the cross product of v1 and normal_vec, it should be perpendicular to both\n    // i.e., the dot product with v1 or normal_vec should be = 0\n    dotprod = v2.dot(normal_vec);\n    cout<<\"v2 dot normal_vec = \"<<dotprod<<\"  (should be zero)\"<<endl;\n\n    v1 = v2.cross(normal_vec);  // re-use v1; make it the cross product of v2 into normal_vec\n      // thus, v1 should now also be perpendicular to normal_vec (and thus it is parallel to our plane)\n      // and also perpendicular to v2 (so both v1 and v2 lie in the plane and are perpendicular to each other)\n    cout<<\"v1= \"<<v1.transpose()<<endl;\n    cout<<\" v1 dot v2 = \"<<v1.dot(v2)<<\"; v1 dot normal_vec = \"<<v1.dot(normal_vec)<<endl;\n    cout<<\"(these should also be zero)\"<<endl;\n    // we now have two orthogonal vectors, both perpendicular to our defined plane's normal\n    // we'll use these to generate some points that lie in our defined plane:\n        \n    int npts= 10; // create this many planar points\n    Eigen::MatrixXd points_mat(3,npts);  // create a matrix, double-precision values, 3 rows and npts columns\n            // we will populate this with 3-D points, column by column\n    Eigen::Vector3d point; //a 3x1 vector\n    Eigen::Vector2d rand_vec; //a 2x1 vector\n    //generate random points that all lie on plane defined by distance and normal_vec\n    for (int ipt = 0;ipt<npts;ipt++) {\n    \t// MatrixXd::Random returns uniform random numbers in the range (-1, 1).\n    \trand_vec.setRandom(2,1);  // populate 2x1 vector with random values\n    \t//cout<<\"rand_vec: \"<<rand_vec.transpose()<<endl; //optionally, look at these random values\n    \t//construct a random point ON the plane normal to normal_vec at distance \"dist\" from origin:\n        // a point on the plane is a*x_vec + b*y_vec + c*z_vec, where we may choose\n        // x_vec = v1, y_vec = v2 (both of which are parallel to our plane) and z_vec is the plane normal\n        // choose coefficients a and b to be random numbers, but \"c\" must be the plane's distance from the origin, \"dist\"\n    \tpoint =  rand_vec(0)*v1 + rand_vec(1)*v2 + dist*normal_vec;\n\t//save this point as the i'th column in the matrix \"points_mat\"\n\tpoints_mat.col(ipt) = point;\n    }\n\n    //all of the above points are identically on the plane defined by normal_vec and dist\n\n    cout<<\"random points on plane (in columns): \"<<endl; // display these points; only practical for relatively small number of points\n    cout<<points_mat<<endl;\n    \n    \n    // add random noise to these points in range [-0.1,0.1]\n    Eigen::MatrixXd Noise = Eigen::MatrixXd::Random(3,npts);\n\n    cout<<\"noise_gain = \"<<g_noise_gain<<\"; edit this as desired\"<<endl;\n    // add two matrices, term by term.  Also, scale all points in a matrix by a scalar: Noise*g_noise_gain\n    points_mat = points_mat + Noise*g_noise_gain;  \n    cout<<\"random points on plane (in columns) w/ noise: \"<<endl;\n    cout<<points_mat<<endl;\n    //xxxxxxxxxxxxxxxxxx  DONE CREATING PLANAR DATA xxxxxxxxxxxxxxxxxx\n    // xxxxxxxxxxxxxxx   NOW, INTERPRET THE DATA TO DISCOVER THE UNDERLYING PLANE xxxxxxxx\n\n    //now let's see if we can discover the plane from the data:\n    cout<<endl<<endl;\n    ROS_INFO(\"starting identification of plane from data: \");\n    // first compute the centroid of the data:\n    // here's a handy way to initialize data to all zeros; more variants exist\n    // see http://eigen.tuxfamily.org/dox/AsciiQuickReference.txt\n    Eigen::Vector3d centroid = Eigen::MatrixXd::Zero(3,1);\n    \n    //add all the points together:\n    npts = points_mat.cols(); // number of points = number of columns in matrix; check the size\n    cout<<\"matrix has ncols = \"<<npts<<endl;\n    for (int ipt =0;ipt<npts;ipt++) {\n\tcentroid+= points_mat.col(ipt); //add all the column vectors together\n    }\n    centroid/=npts; //divide by the number of points to get the centroid\n    cout<<\"centroid: \"<<centroid.transpose()<<endl;\n    \n    \n    // subtract this centroid from all points in points_mat:\n    Eigen::MatrixXd points_offset_mat = points_mat;\n    for (int ipt =0;ipt<npts;ipt++) {\n        points_offset_mat.col(ipt)  = points_offset_mat.col(ipt)-centroid;\n    }\n    //compute the covariance matrix w/rt x,y,z:\n    Eigen::Matrix3d CoVar;\n    CoVar = points_offset_mat*(points_offset_mat.transpose());  //3xN matrix times Nx3 matrix is 3x3\n    cout<<\"covariance: \"<<endl;\n    cout<<CoVar<<endl;\n    \n    // here is a more complex object: a solver for eigenvalues/eigenvectors;\n    // we will initialize it with our covariance matrix, which will induce computing eval/evec pairs\n    Eigen::EigenSolver<Eigen::Matrix3d> es3d(CoVar);\n    \n    Eigen::VectorXd evals; //we'll extract the eigenvalues to here\n    //cout<<\"size of evals: \"<<es3d.eigenvalues().size()<<endl;\n    //cout<<\"rows,cols = \"<<es3d.eigenvalues().rows()<<\", \"<<es3d.eigenvalues().cols()<<endl;\n    cout << \"The eigenvalues of CoVar are:\" << endl << es3d.eigenvalues().transpose() << endl;\n    cout<<\"(these should be real numbers, and one of them should be zero)\"<<endl;\n    cout << \"The matrix of eigenvectors, V, is:\" << endl;\n    cout<< es3d.eigenvectors() << endl << endl;\n    cout<< \"(these should be real-valued vectors)\"<<endl;\n    // in general, the eigenvalues/eigenvectors can be complex numbers\n    //however, since our matrix is self-adjoint (symmetric, positive semi-definite), we expect\n    // real-valued evals/evecs;  we'll need to strip off the real parts of the solution\n\n    evals= es3d.eigenvalues().real(); // grab just the real parts\n    cout<<\"real parts of evals: \"<<evals.transpose()<<endl;\n\n    // our solution should correspond to an e-val of zero, which will be the minimum eval\n    //  (all other evals for the covariance matrix will be >0)\n    // however, the solution does not order the evals, so we'll have to find the one of interest ourselves\n    \n    double min_lambda = evals[0]; //initialize the hunt for min eval\n    Eigen::Vector3cd complex_vec; // here is a 3x1 vector of double-precision, complex numbers\n    Eigen::Vector3d est_plane_normal;\n    complex_vec=es3d.eigenvectors().col(0); // here's the first e-vec, corresponding to first e-val\n    //cout<<\"complex_vec: \"<<endl;\n    //cout<<complex_vec<<endl;\n    est_plane_normal = complex_vec.real();  //strip off the real part\n    //cout<<\"real part: \"<<est_plane_normal.transpose()<<endl;\n    //est_plane_normal = es3d.eigenvectors().col(0).real(); // evecs in columns\n\n    double lambda_test;\n    int i_normal=0;\n    //loop through \"all\" (\"both\", in this 3-D case) the rest of the solns, seeking min e-val\n    for (int ivec=1;ivec<3;ivec++) {\n        lambda_test = evals[ivec];\n    \tif (lambda_test<min_lambda) {\n\t\tmin_lambda =lambda_test;\n                i_normal= ivec; //this index is closer to index of min eval\n\t\test_plane_normal = es3d.eigenvectors().col(ivec).real();\n        }\n    }\n    // at this point, we have the minimum eval in \"min_lambda\", and the plane normal\n    // (corresponding evec) in \"est_plane_normal\"/\n    // these correspond to the ith entry of i_normal\n    cout<<\"min eval is \"<<min_lambda<<\", corresponding to component \"<<i_normal<<endl;\n    cout<<\"corresponding evec (est plane normal): \"<<est_plane_normal.transpose()<<endl;\n    cout<<\"correct answer is: \"<<normal_vec.transpose()<<endl;\n    double est_dist = est_plane_normal.dot(centroid);\n    cout<<\"est plane distance from origin = \"<<est_dist<<endl;\n    cout<<\"correct answer is: \"<<dist<<endl;\n    cout<<endl<<endl;\n           \n    \n    //xxxx  one_vec*dist = point.dot(nx,ny,nz)\n    // so, one_vec = points_mat.transpose()*x_vec, where x_vec = [nx;ny;nz]/dist (does not work if dist=0)\n    // this is of the form: b = A*x, an overdetermined system of eqns\n    // solve this using one of many Eigen methods\n    // see: http://eigen.tuxfamily.org/dox/group__TutorialLinearAlgebra.html\n    \n    ROS_INFO(\"2ND APPROACH b = A*x SOLN\");\n    Eigen::VectorXd  ones_vec= Eigen::MatrixXd::Ones(npts,1); // this is our \"b\" vector in b = A*x\n    Eigen::MatrixXd A = points_mat.transpose(); // make this a Nx3 matrix, where points are along the rows\n    // we'll pick the \"full pivot LU\" solution approach; see: http://eigen.tuxfamily.org/dox/group__TutorialLinearAlgebra.html\n    // a matrix in \"Eigen\" has member functions that include solution methods to this common problem, b = A*x\n    // use: x = A.solution_method(b)\n    Eigen::Vector3d x_soln = A.fullPivLu().solve(ones_vec);\n    cout<<\"x_soln: \"<<x_soln.transpose()<<endl;\n    double dist_est2 = 1.0/x_soln.norm();\n    x_soln*=dist_est2;\n    cout<<\"normal vec, 2nd approach: \"<<x_soln.transpose()<<endl;\n    cout<<\"plane distance = \"<<dist_est2<<endl;\n    \n    \n\n    return 0;\n\n   // while (ros::ok()) {\n   //     sleep_timer.sleep();\n   // }\n}\n\n", "meta": {"hexsha": "b8ffa5f8ddf46227b8f60e228b05c9cca666ca27", "size": 12859, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Part_2/example_eigen/src/example_eigen_plane_fit.cpp", "max_stars_repo_name": "zhaolongkzz/ROS", "max_stars_repo_head_hexsha": "52c70d9d22fe1714c438312fde61214920a4dc3c", "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_2/example_eigen/src/example_eigen_plane_fit.cpp", "max_issues_repo_name": "zhaolongkzz/ROS", "max_issues_repo_head_hexsha": "52c70d9d22fe1714c438312fde61214920a4dc3c", "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_2/example_eigen/src/example_eigen_plane_fit.cpp", "max_forks_repo_name": "zhaolongkzz/ROS", "max_forks_repo_head_hexsha": "52c70d9d22fe1714c438312fde61214920a4dc3c", "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": 53.356846473, "max_line_length": 147, "alphanum_fraction": 0.6798351349, "num_tokens": 3442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392848011834, "lm_q2_score": 0.8459424295406088, "lm_q1q2_score": 0.7478463403940553}}
{"text": "#ifndef PCP_COMMON_NORMALS_NORMAL_ESTIMATION_HPP\n#define PCP_COMMON_NORMALS_NORMAL_ESTIMATION_HPP\n\n/**\n * @file\n * @ingroup common\n */\n\n#include \"pcp/common/normals/normal.hpp\"\n#include \"pcp/traits/point_map.hpp\"\n#include \"pcp/traits/point_traits.hpp\"\n\n#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\n#include <cstdint>\n#include <iterator>\n\nnamespace pcp {\n\n/**\n * @ingroup common\n * @brief\n * Estimates the normal from a group of points using PCA.\n * @tparam ForwardIter Type of iterator to the points\n * @tparam PointViewMap Type satisfying PointViewMap concept\n * @tparam Normal Type of the normal to return\n * @param it Begin iterator to the points\n * @param end End iterator to the points\n * @param point_map The point view map property map\n * @return\n */\ntemplate <class ForwardIter, class PointViewMap, class Normal = pcp::normal_t>\nNormal estimate_normal(ForwardIter it, ForwardIter end, PointViewMap const& point_map)\n{\n    using normal_type = Normal;\n\n    static_assert(\n        traits::is_point_view_map_v<PointViewMap, decltype(*it)>,\n        \"Type of point_map must satisfy PointViewMap concept\");\n\n    auto const n = std::distance(it, end);\n    Eigen::Matrix3Xf V;\n    V.resize(3, n);\n    for (auto i = 0; i < n; ++i, ++it)\n    {\n        auto p              = point_map(*it);\n        V.block(0, i, 3, 1) = Eigen::Vector3f(p.x(), p.y(), p.z());\n    }\n\n    Eigen::Vector3f const Mu      = V.rowwise().mean();\n    Eigen::Matrix3Xf const Vprime = V.colwise() - Mu;\n    Eigen::Matrix3f const Cov     = Vprime * Vprime.transpose();\n    Eigen::SelfAdjointEigenSolver<decltype(Cov)> A(Cov);\n    auto const l  = A.eigenvalues();\n    auto const& X = A.eigenvectors();\n\n    normal_type normal;\n    // instead of sorting, just use 3 if statements\n    // First eigenvalue is smallest\n    if (l(0) <= l(1) && l(0) <= l(2))\n    {\n        normal = {X(0, 0), X(1, 0), X(2, 0)};\n    }\n    // Second eigenvalue is smallest\n    if (l(1) <= l(0) && l(1) <= l(2))\n    {\n        normal = {X(0, 1), X(1, 1), X(2, 1)};\n    }\n    // Third eigenvalue is smallest\n    if (l(2) <= l(0) && l(2) <= l(1))\n    {\n        normal = {X(0, 2), X(1, 2), X(2, 2)};\n    }\n\n    // normal is already normalized, since Eigen returns\n    // normalized eigenvectors\n    return normal;\n}\n\n} // namespace pcp\n\n#endif // PCP_COMMON_NORMALS_NORMAL_ESTIMATION_HPP\n", "meta": {"hexsha": "33921a60092635936814e0c75bc0a3962a8054f7", "size": 2331, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/pcp/common/normals/normal_estimation.hpp", "max_stars_repo_name": "Q-Minh/octree", "max_stars_repo_head_hexsha": "0c3fd5a791d660b37461daf968a68ffb1c80b965", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-03-10T09:57:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-13T21:19:57.000Z", "max_issues_repo_path": "include/pcp/common/normals/normal_estimation.hpp", "max_issues_repo_name": "Q-Minh/octree", "max_issues_repo_head_hexsha": "0c3fd5a791d660b37461daf968a68ffb1c80b965", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2020-12-07T20:09:39.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-12T20:42:59.000Z", "max_forks_repo_path": "include/pcp/common/normals/normal_estimation.hpp", "max_forks_repo_name": "Q-Minh/octree", "max_forks_repo_head_hexsha": "0c3fd5a791d660b37461daf968a68ffb1c80b965", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0843373494, "max_line_length": 86, "alphanum_fraction": 0.6362076362, "num_tokens": 685, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026641072386, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.747814940526131}}
{"text": "#include \"utils.hpp\"\n\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/multiprecision/integer.hpp>\n#include <boost/multiprecision/miller_rabin.hpp>\n#include <cmath>\n#include <cassert>\n\nusing namespace std;\nusing Bint = boost::multiprecision::cpp_int;\n\n\nBint ilog(Bint n){\n    Bint result = ZERO;\n    while(n>0){\n        n = n/2;\n        result++;\n    }\n    return result;\n}\n\nBint ilog(Bint n, Bint const& a){\n    Bint result = ZERO;\n    while(n>0){\n        n = n/a;\n        result++;\n    }\n    return result;\n}\n\nBint _jacobi_symbol(Bint const& a, Bint const& p){\n    if(a==1){ // (11) p43 [Wada 2001]\n        return ONE;\n    }\n    else if(a==-1){ // (14) p43 [Wada 2001]\n        if(a%4==1){\n            return ONE;\n        }\n        else{\n            return MINUS_ONE;\n        }\n    }\n    else if(a==2){ // (15) p43 [Wada 2001]// (15) p43 [Wada 2001]\n        int tmp = (int)(a%8);\n        if(tmp == 1 or tmp == 7){\n            return ONE;\n        }\n        else{\n            return MINUS_ONE;\n        }\n    }\n\n    if(a%2==0){ // (13) p43 [Wada 2001]\n        return _jacobi_symbol(2, p) * _jacobi_symbol(a/2, p);\n    }\n    else{ // (16) p43 [Wada 2001]\n        if(a%4==1 or p%4==1){\n            return _jacobi_symbol(p%a, a);\n        }\n        else{\n            return MINUS_ONE * _jacobi_symbol(p%a, a);\n        }\n    }\n}\n\n\nBint jacobi_symbol(Bint const& a, Bint const& p){\n    //returns (a/p)\n    //https://en.wikipedia.org/wiki/Jacobi_symbol\n    assert(p%2==1);\n    if(a == 0){\n        return ZERO;\n    }\n    assert(gcd(a,p)==1);\n    return _jacobi_symbol(a%p, p);\n}\n\n\nBint quadratic_residue(Bint const& a, Bint const& p){\n    // returns x s.t. x^2 \u2261 a (mod p)\n    \n}\n\n//return first(smallest) prime p s.t. p>=n\nBint next_prime(Bint const& n){\n    if(n<=2){\n        return TWO;\n    }\n    Bint retval = n;\n    if(retval%2==1){\n        retval++;\n    }\n    while(true){\n        if(boost::multiprecision::miller_rabin_test(retval, 25)){\n            return retval;\n        }\n        retval+=2;\n    }\n}", "meta": {"hexsha": "03690b2f8418f5eabbc67f28ce092d87829b1342", "size": 2009, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/utils.cpp", "max_stars_repo_name": "FullteaR/factorizer", "max_stars_repo_head_hexsha": "f4beb7a14d6cda38d69b9ff6dbe673575b554288", "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/utils.cpp", "max_issues_repo_name": "FullteaR/factorizer", "max_issues_repo_head_hexsha": "f4beb7a14d6cda38d69b9ff6dbe673575b554288", "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/utils.cpp", "max_forks_repo_name": "FullteaR/factorizer", "max_forks_repo_head_hexsha": "f4beb7a14d6cda38d69b9ff6dbe673575b554288", "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": 20.2929292929, "max_line_length": 65, "alphanum_fraction": 0.5161772026, "num_tokens": 627, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026482819236, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.7478149235069765}}
{"text": "#include <vector>\n#include <cmath>\n\n#include <math.h>\n#include <boost/tuple/tuple.hpp>\n\n#include \"gnuplot-iostream.h\"\n\nusing namespace std;\nconst int SAMPLES = 1000;\ndouble pi = 3.1415926535897;\n\nstruct datas {\npublic:\n\tdouble a;\n\tdouble b;\n\tdatas(double x, double y) {\n\t\ta = x;\n\t\tb = y;\n\t}\n};\n\ndatas getVal(double in, int n, int k, int N) {\n\tdouble bn = (2 * pi*k*n / N);\n\treturn datas(in*(cos(-bn)),in*sin(-bn));\n}\n\nvector<double> dft(vector<double> &in) {\n\tvector<double> ret;\n\tint N = in.size();\n\tfor (int i = 1; i < N / 2; i++) {\n\t\tdouble suma = 0;\n\t\tdouble sumb = 0;\n\t\tfor (int n = 0; n < N; n++) {\n\t\t\tdatas d = getVal(in.at(n), n, i, N);\n\t\t\tsuma += d.a;\n\t\t\tsumb += d.b;\n\t\t}\n\t\tdouble sum = sqrt(pow(suma, 2) + pow(sumb, 2));\n\t\tret.push_back(sum / (N/2));\n\t}\n\treturn ret;\n}\nconst int range = 20;\nint main() {\n\t\n\tGnuplot gp;\n\n\t// Gnuplot vectors (i.e. arrows) require four columns: (x,y,dx,dy)+ sin(3*x) + sin(5*x)\n\tgp << \"set samples \" << SAMPLES << \"\\n\";\n\tgp << \"set xrange[0:\" << range << \"]\\n\";\n\tgp << \"plot '-' with lines title 'de'\\n\";\n\tstd::vector<double> xs;\n\tstd::vector<double> samples;\n\tfor (int i = 0; i < SAMPLES; i++) {\n\t\tdouble x = 0 + ((double)range / SAMPLES)*i;\n\t\txs.push_back(x);\n\t\tsamples.push_back(sin(x) + sin(3 * x) + sin(5 * x));\n\t}\n\tgp.send1d(boost::make_tuple(xs,\n\t\tsamples));\n\tfor (int i = 0; i < SAMPLES / 2; i++) {\n\t\txs.at(i)=i;\n\t}\n\tvector<double> dat =dft(samples);\n\n\tstd::vector<double>::iterator it;\n\tit = dat.begin();\n\tdat.insert(it, 0.0);\n\txs.resize(SAMPLES / 2 );\n\n\tgp << \"set terminal qt 1\\n\";\n\tgp << \"set xrange[0:100]\\n\";\n\tgp << \"plot '-' with lines title 'ptf'\\n\";\n\tgp.send1d(boost::make_tuple(xs,\n\t\tdat));\n\tstd::cout << \"Press enter to exit\" << std::endl;\n\tstd::cin.get();\n}\n\n", "meta": {"hexsha": "54bfe173a13b5e25634efcbcd9fb3e2526a5b248", "size": 1720, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Fourier transforms/Source.cpp", "max_stars_repo_name": "ooosssososos/Fourier-transforms", "max_stars_repo_head_hexsha": "eeb8ad6b475fc8d8127f850673c0760f6b37b4a6", "max_stars_repo_licenses": ["BSL-1.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": "Fourier transforms/Source.cpp", "max_issues_repo_name": "ooosssososos/Fourier-transforms", "max_issues_repo_head_hexsha": "eeb8ad6b475fc8d8127f850673c0760f6b37b4a6", "max_issues_repo_licenses": ["BSL-1.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": "Fourier transforms/Source.cpp", "max_forks_repo_name": "ooosssososos/Fourier-transforms", "max_forks_repo_head_hexsha": "eeb8ad6b475fc8d8127f850673c0760f6b37b4a6", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.2345679012, "max_line_length": 88, "alphanum_fraction": 0.5784883721, "num_tokens": 610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299612154571, "lm_q2_score": 0.8080672066194946, "lm_q1q2_score": 0.7476479902400377}}
{"text": "\r\n// Use, modification and distribution are subject to the\r\n// Boost Software License, Version 1.0.\r\n// (See accompanying file LICENSE_1_0.txt\r\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n// Copyright Paul A. Bristow 2015.\r\n// Copyright Christopher Kormanyos 2015.\r\n\r\n// This file is written to be included from a Quickbook .qbk document.\r\n// It can be compiled by the C++ compiler, and run. Any output can\r\n// also be added here as comment or included or pasted in elsewhere.\r\n// Caution: this file contains Quickbook markup as well as code\r\n// and comments: don't change any of the special comment markups!\r\n\r\n// This file also includes Doxygen-style documentation about the function of the code.\r\n// See http://www.doxygen.org for details.\r\n\r\n//! \\file\r\n\r\n//! \\brief Example program showing a polynomial approximation of tgamma(negatable).\r\n\r\n// Below are snippets of code that are included into Quickbook file fixed_point.qbk.\r\n\r\n#include <iomanip>\r\n#include <iostream>\r\n\r\n#include <boost/array.hpp>\r\n#include <boost/fixed_point/fixed_point.hpp>\r\n#include <boost/math/tools/rational.hpp>\r\n\r\nnamespace local\r\n{\r\n  template<typename NumericType>\r\n  NumericType tgamma(const NumericType& x)\r\n  {\r\n    // This subroutine uses a polynomial approximation to\r\n    // computes tgamma(x - 2) to approximately order 7\r\n    // in the range 2 < x < 3.\r\n\r\n    // The coefficients originate from J. F. Hart et al.,\r\n    // Computer Approximations (John Wiley and Sons, Inc., 1968).\r\n    // See Chap. 7, Tables of Coefficients, Table 5206 on page 244.\r\n    BOOST_CONSTEXPR boost::array<NumericType, 8U> coefs =\r\n    {\r\n      NumericType(0.9999999757437L),\r\n      NumericType(0.4227874604607L),\r\n      NumericType(0.4117741970939L),\r\n      NumericType(0.0821117276973L),\r\n      NumericType(0.0721101941645L),\r\n      NumericType(0.00445108786245L),\r\n      NumericType(0.005159029832L),\r\n      NumericType(0.0016063028892L),\r\n    };\r\n\r\n    return boost::math::tools::evaluate_polynomial(coefs, x - 2);\r\n  }\r\n}\r\n\r\nint main()\r\n{\r\n  // This example performs computations of the tgamma(x)\r\n  // function for x = 1/2 for a fixed-point negatable\r\n  // type and built-in float.\r\n\r\n  // A 32-bit fixed-point type is used, as might be\r\n  // well-suited for a high-performance 32-bit embedded\r\n  // system that does not have or does not use an FPU.\r\n\r\n  typedef boost::fixed_point::negatable<7, -24> fixed_point_type;\r\n  typedef fixed_point_type::float_type float_point_type;\r\n\r\n  // Here we compute tgamma(5/2) and subsequently perform\r\n  // two iterations of downward recursion via division with\r\n  // [(3/2) * (1/2)] = (3/4). The result is tgamma(1/2),\r\n  // which has a known closed-form value = sqrt(pi).\r\n\r\n  const fixed_point_type x = fixed_point_type(5U) / 2U;\r\n  const fixed_point_type g = (local::tgamma(x) * 4U) / 3U;\r\n\r\n  std::cout << std::setprecision(6)\r\n            << std::fixed\r\n            << g\r\n            << std::endl;\r\n\r\n  using std::sqrt;\r\n\r\n  // Compare with the control value, sqrt(pi),\r\n  // computed with a built-in floating-point type.\r\n  std::cout << std::setprecision(6)\r\n            << std::fixed\r\n            << sqrt(boost::math::constants::pi<float_point_type>())\r\n            << std::endl;\r\n}\r\n", "meta": {"hexsha": "d1f332ba9c5b2c8af0a6254ae3edb89234625d09", "size": 3215, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/fixed_point_polynomial_approx_tgamma.cpp", "max_stars_repo_name": "BoostGSoC15/fixed-point", "max_stars_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_stars_repo_licenses": ["BSL-1.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": "example/fixed_point_polynomial_approx_tgamma.cpp", "max_issues_repo_name": "BoostGSoC15/fixed-point", "max_issues_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_issues_repo_licenses": ["BSL-1.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": "example/fixed_point_polynomial_approx_tgamma.cpp", "max_forks_repo_name": "BoostGSoC15/fixed-point", "max_forks_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8421052632, "max_line_length": 87, "alphanum_fraction": 0.6709175739, "num_tokens": 845, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.8289388146603364, "lm_q1q2_score": 0.7476370521493717}}
{"text": "#include <gmp_lib/math/math.h>\n\n#include <Eigen/Eigenvalues>\n#include <Eigen/Geometry>\n\nnamespace as64_\n{\n\nnamespace gmp_\n{\n\n// =======================================================\n// =======================================================\n\nEigen::Vector4d rotm2quat(Eigen::Matrix3d rotm, bool is_rotm_orthonormal)\n{\n    if (!is_rotm_orthonormal) return mat2quat(rotm);\n\n    Eigen::Quaternion<double> temp_quat(rotm);\n    Eigen::Vector4d quat;\n    quat << temp_quat.w(), temp_quat.x(), temp_quat.y(), temp_quat.z();\n\n    quat = quat * (2*(quat(0)>=0)-1); // to avoid discontinuities\n\n    return quat;\n}\n\narma::vec rotm2quat(const arma::mat &rotm, bool is_rotm_orthonormal)\n{\n  arma::vec quat(4);\n\n  Eigen::Map<const Eigen::Matrix3d> rotm_wrapper(rotm.memptr());\n  Eigen::Map<Eigen::Vector4d> quat_wrapper(quat.memptr());\n  quat_wrapper = rotm2quat(rotm_wrapper, is_rotm_orthonormal);\n\n  return quat;\n}\n\nEigen::Vector4d mat2quat(Eigen::Matrix3d R)\n{\n  Eigen::Matrix4d K;\n  // Calculate all elements of symmetric K matrix\n  K(0,0) = R(0,0) - R(1,1) - R(2,2);\n  K(0,1) = K(1,0) = R(0,1) + R(1,0);\n  K(0,2) = K(2,0) = R(0,2) + R(2,0);\n  K(0,3) = K(3,0) = R(2,1) - R(1,2);\n\n  K(1,1) = R(1,1) - R(0,0) - R(2,2);\n  K(1,2) = K(2,1) = R(1,2) + R(2,1);\n  K(1,3) = K(3,1) = R(0,2) - R(2,0);\n\n  K(2,2) = R(2,2) - R(0,0) - R(1,1);\n  K(2,3) = K(3,2) = R(1,0) - R(0,1);\n\n  K(3,3) = R(0,0) + R(1,1) + R(2,2);\n\n  K = K/3;\n\n  // For each input rotation matrix, calculate the corresponding eigenvalues\n  // and eigenvectors. The eigenvector corresponding to the largest eigenvalue\n  // is the unit quaternion representing the same rotation.\n\n  Eigen::EigenSolver<Eigen::Matrix4d> es(K);\n\n  Eigen::Vector4cd eigVal = es.eigenvalues();\n  Eigen::Matrix4d eigVec = es.eigenvectors().real(); // keep only real part\n  int maxIdx;\n  eigVal.real().maxCoeff(&maxIdx);\n\n  Eigen::Vector4d quat;\n  quat << eigVec(3,maxIdx), eigVec(0,maxIdx), eigVec(1,maxIdx), eigVec(2,maxIdx);\n\n  // By convention, always keep scalar quaternion element positive.\n  // Note that this does not change the rotation that is represented\n  // by the unit quaternion, since q and -q denote the same rotation.\n  if (quat(0) < 0) quat = -quat;\n\n  return quat;\n}\n\n// =======================================================\n// =======================================================\n\nEigen::Matrix3d quat2rotm(Eigen::Vector4d quat)\n{\n  double qw=quat(0), qx=quat(1), qy=quat(2), qz=quat(3);\n\n  Eigen::Matrix3d rotm;\n  rotm << 1 - 2*qy*qy - 2*qz*qz, \t2*qx*qy - 2*qz*qw, \t2*qx*qz + 2*qy*qw,\n\t    2*qx*qy + 2*qz*qw, \t      1 - 2*qx*qx - 2*qz*qz, \t2*qy*qz - 2*qx*qw,\n\t    2*qx*qz - 2*qy*qw, \t        2*qy*qz + 2*qx*qw, \t1 - 2*qx*qx - 2*qy*qy;\n\n  return rotm;\n}\n\narma::mat quat2rotm(const arma::vec &quat)\n{\n  double qw=quat(0), qx=quat(1), qy=quat(2), qz=quat(3);\n\n  arma::mat rotm;\n  rotm = {{1 - 2*qy*qy - 2*qz*qz,      2*qx*qy - 2*qz*qw,      2*qx*qz + 2*qy*qw},\n\t        {    2*qx*qy + 2*qz*qw,  1 - 2*qx*qx - 2*qz*qz,      2*qy*qz - 2*qx*qw},\n\t        {    2*qx*qz - 2*qy*qw,      2*qy*qz + 2*qx*qw,  1 - 2*qx*qx - 2*qy*qy}};\n  // rotm << 1 - 2*qy*qy - 2*qz*qz << \t2*qx*qy - 2*qz*qw     <<  \t2*qx*qz + 2*qy*qw << arma::endr\n\t//      << 2*qx*qy + 2*qz*qw     <<  1 - 2*qx*qx - 2*qz*qz <<  \t2*qy*qz - 2*qx*qw << arma::endr\n\t//      << 2*qx*qz - 2*qy*qw     <<    2*qy*qz + 2*qx*qw   << \t1 - 2*qx*qx - 2*qy*qy;\n\n  return rotm;\n}\n\n// =======================================================\n// =======================================================\n\nEigen::Vector4d rotm2axang(Eigen::Matrix3d rotm)\n{\n  Eigen::AngleAxis<double> angleAxis(rotm);\n\n  Eigen::Vector4d axang;\n  axang(3) = angleAxis.angle();\n  axang.segment(0,3) = angleAxis.axis();\n\n  return axang;\n}\n\narma::vec rotm2axang(const arma::mat &rotm)\n{\n  arma::vec axang(4);\n\n  Eigen::Map<const Eigen::Matrix3d> rotm_wrapper(rotm.memptr());\n  Eigen::Map<Eigen::Vector4d> axang_wrapper(axang.memptr());\n  axang_wrapper = rotm2axang(rotm_wrapper);\n\n  return axang;\n}\n\n// =======================================================\n// =======================================================\n\nEigen::Matrix3d axang2rotm(Eigen::Vector4d axang)\n{\n  Eigen::Matrix3d rotm;\n  Eigen::Vector3d axis = axang.segment(0,3);\n  axis /= axis.norm();\n  double angle = axang(3);\n\n  double x=axis(0), y=axis(1), z=axis(2), c=std::cos(angle), s=std::sin(angle), t=1-c;\n  rotm <<   t*x*x + c,\t    t*x*y - z*s,     t*x*z + y*s,\n  \t        t*x*y + z*s,    t*y*y + c,\t     t*y*z - x*s,\n            t*x*z - y*s,    t*y*z + x*s,     t*z*z + c;\n\n  return rotm;\n}\n\narma::mat axang2rotm(const arma::vec &axang)\n{\n  arma::vec axis = axang.subvec(0,2);\n  axis /= arma::norm(axis);\n  double angle = axang(3);\n  double x=axis(0), y=axis(1), z=axis(2), c=std::cos(angle), s=std::sin(angle), t=1-c;\n\n  return { { t*x*x + c,\t    t*x*y - z*s,   t*x*z + y*s },\n  \t       { t*x*y + z*s,   t*y*y + c,\t   t*y*z - x*s },\n           { t*x*z - y*s,   t*y*z + x*s,   t*z*z + c   } };\n}\n\n// =======================================================\n// =======================================================\n\nEigen::Vector4d axang2quat(Eigen::Vector4d axang)\n{\n  Eigen::Vector4d quat;\n  double theta = axang(3);\n\n  quat(0) = std::cos(theta/2);\n  quat.segment(1,3) = std::sin(theta/2) * axang.segment(0,3);\n\n  return quat;\n}\n\narma::vec axang2quat(const arma::vec &axang)\n{\n  arma::vec quat(4);\n\n  Eigen::Map<const Eigen::Vector4d> axang_wrapper(axang.memptr());\n  Eigen::Map<Eigen::Vector4d> quat_wrapper(quat.memptr());\n  quat_wrapper = axang2quat(axang_wrapper);\n\n  return quat;\n}\n\n// =======================================================\n// =======================================================\n\nEigen::Vector4d quat2axang(Eigen::Vector4d quat)\n{\n  Eigen::Vector4d axang;\n  Eigen::Vector3d r = quat.segment(1,3);\n\n  if (r.norm()){\n    axang(3) = 2 * std::acos(quat(0));\n    axang.segment(0,3) = r/r.norm();\n  }else axang << 0, 0, 1, 0;\n\n  return axang;\n}\n\narma::vec quat2axang(const arma::vec &quat)\n{\n  arma::vec axang(4);\n\n  Eigen::Map<const Eigen::Vector4d> quat_wrapper(quat.memptr());\n  Eigen::Map<Eigen::Vector4d> axang_wrapper(axang.memptr());\n  axang_wrapper = quat2axang(quat_wrapper);\n\n  return axang;\n}\n\n// =======================================================\n// =======================================================\n\n} // namespace gmp_\n\n} // namespace as64_\n", "meta": {"hexsha": "31ccf84d92ad1e8cf66645d0cf9f2cb9cf604392", "size": 6328, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "experiments/ros packages/gmp_lib/src/math/math.cpp", "max_stars_repo_name": "Slifer64/novel-DMP-constraints", "max_stars_repo_head_hexsha": "cad6727a12642130dc64fd93827099e4cb763ec8", "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": "experiments/ros packages/gmp_lib/src/math/math.cpp", "max_issues_repo_name": "Slifer64/novel-DMP-constraints", "max_issues_repo_head_hexsha": "cad6727a12642130dc64fd93827099e4cb763ec8", "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": "experiments/ros packages/gmp_lib/src/math/math.cpp", "max_forks_repo_name": "Slifer64/novel-DMP-constraints", "max_forks_repo_head_hexsha": "cad6727a12642130dc64fd93827099e4cb763ec8", "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.25, "max_line_length": 97, "alphanum_fraction": 0.5183312263, "num_tokens": 2276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969136, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.747581867590878}}
{"text": "/*\n * Copyright 2020 \u00a9 Centre Interdisciplinaire de d\u00e9veloppement en Cartographie des Oc\u00e9ans (CIDCO), Tous droits r\u00e9serv\u00e9s\n */\n\n/* \n * File:   PlaneFitAndResidualsTest.hpp\n * Author: Jordan McManus\n */\n\n#ifndef PLANEFITANDRESIDUALSTEST_HPP\n#define PLANEFITANDRESIDUALSTEST_HPP\n\n#include \"catch.hpp\"\n#include <cmath>\n#include <Eigen/Dense>\n#include \"../src/math/PlaneFitter.hpp\"\n\nTEST_CASE(\"plane fit and residual test\") {\n\n    //create plane params\n    //Z = Ax + By + C\n    double A = 10;\n    double B = 20;\n    double C = 30;\n    Eigen::Vector3d planeParamsZform(A, B, C);\n    \n    // general form: ax + by + cz + d = 0 with (a*a + b*b + c*c = 1)\n    Eigen::Vector4d planeParamsGeneralForm;\n    PlaneFitter::convertPlaneZform2GeneralForm(planeParamsZform, planeParamsGeneralForm);\n    \n    Eigen::Vector3d testZform;\n    PlaneFitter::convertPlaneGeneralForm2Zform(planeParamsGeneralForm, testZform);\n    \n    double eps = 1e-9;\n    REQUIRE(std::abs(testZform(0)-A) < eps);\n    REQUIRE(std::abs(testZform(1)-B) < eps);\n    REQUIRE(std::abs(testZform(2)-C) < eps);\n    \n    //create points on plane\n    \n    double minX = 5.0;\n    double maxX = 10.0;\n    double minY = 5.0;\n    double maxY = 10.0;\n    int n = 100;\n    \n    Eigen::VectorXd x = (0.5*(maxX-minX)*Eigen::VectorXd::Random(n)) + (0.5*(minX+maxX)*Eigen::VectorXd::Ones(n));\n    Eigen::VectorXd y = (0.5*(maxY-minY)*Eigen::VectorXd::Random(n)) + (0.5*(minY+maxY)*Eigen::VectorXd::Ones(n));\n    Eigen::VectorXd z = A*x + B*y + C*Eigen::VectorXd::Ones(n);\n    \n    //add noise\n    double variance = 0.01;\n    Eigen::VectorXd xnoise = variance*Eigen::VectorXd::Random(n);\n    Eigen::VectorXd ynoise = variance*Eigen::VectorXd::Random(n);\n    Eigen::VectorXd znoise = variance*Eigen::VectorXd::Random(n);\n    \n    Eigen::VectorXd xn = x + xnoise;\n    Eigen::VectorXd yn = y + ynoise;\n    Eigen::VectorXd zn = z + znoise;\n    \n    //fit plane\n    Eigen::MatrixXd xyz(n, 3);\n    xyz.col(0) = xn;\n    xyz.col(1) = yn;\n    xyz.col(2) = zn;\n    \n    Eigen::Vector4d planeParamsGeneralFormEstimation;\n    PlaneFitter::fitPlane(xyz, planeParamsGeneralFormEstimation);\n    \n    //verify that original plane parameters are obtained\n    REQUIRE((planeParamsGeneralFormEstimation-planeParamsGeneralForm).norm() < 0.01);\n    \n    \n    // calculate residual of a point to the plane\n    double a = planeParamsGeneralForm(0);\n    double b = planeParamsGeneralForm(1);\n    double c = planeParamsGeneralForm(2);\n    double d = planeParamsGeneralForm(3);\n    Eigen::Vector3d unitNormal;\n    unitNormal << a,b,c;\n    \n    double p1x = 1.0;\n    double p1y = 1.0;\n    double p1z = (a*p1x + b*p1y + d)*(-1.0/c);\n    Eigen::Vector3d pointOnPlane;\n    pointOnPlane << p1x, p1y, p1z;\n    \n    Eigen::Vector3d pointOutsidePlane = pointOnPlane + unitNormal;\n    \n    Eigen::MatrixXd points(1,3);\n    points.row(0) = pointOutsidePlane;\n    \n    \n    Eigen::VectorXd residuals;\n    PlaneFitter::calculatePlaneResidualsFromMatrix(residuals, points, planeParamsGeneralForm);\n    REQUIRE(std::abs(residuals(0) - 1) < eps);\n}\n\n\n#endif /* PLANEFITANDRESIDUALSTEST_HPP */\n\n", "meta": {"hexsha": "80f09730cabe47ca6544d9b753221b79c902d3cd", "size": 3094, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/PlaneFitAndResidualsTest.hpp", "max_stars_repo_name": "JordanMcManus/MBES-lib", "max_stars_repo_head_hexsha": "618d64f4e042bf5660015819f89537cdd70e696d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2019-10-29T14:16:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T06:44:37.000Z", "max_issues_repo_path": "test/PlaneFitAndResidualsTest.hpp", "max_issues_repo_name": "JordanMcManus/MBES-lib", "max_issues_repo_head_hexsha": "618d64f4e042bf5660015819f89537cdd70e696d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 62.0, "max_issues_repo_issues_event_min_datetime": "2019-04-16T13:53:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T19:44:23.000Z", "max_forks_repo_path": "test/PlaneFitAndResidualsTest.hpp", "max_forks_repo_name": "JordanMcManus/MBES-lib", "max_forks_repo_head_hexsha": "618d64f4e042bf5660015819f89537cdd70e696d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2019-04-10T19:51:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T21:42:22.000Z", "avg_line_length": 30.3333333333, "max_line_length": 119, "alphanum_fraction": 0.6551389787, "num_tokens": 938, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425223682085, "lm_q2_score": 0.8128673178375735, "lm_q1q2_score": 0.7475473505268263}}
{"text": "#pragma once\n/*\nConvex Hull Trick\n- y = ax + b \u304c\u9806\u6b21\u8ffd\u52a0\u3055\u308c\u3064\u3064\uff0c\u6700\u5927\u5024/\u6700\u5c0f\u5024\u30af\u30a8\u30ea\u306b\u7b54\u3048\u308b\n- y = c(x - a)^2 + b \u578b\u306e\u95a2\u6570\u3092\u8868\u3059(a, b)\u305f\u3061\u304c\u9806\u6b21\u8ffd\u52a0\u3055\u308c\u3064\u3064\uff0c\u6700\u5c0f\u5024\u30af\u30a8\u30ea\u306b\u7b54\u3048\u308b\nVerify:\nCF 1179D https://codeforces.com/contest/1179/submission/59448330\nCF 1137E https://codeforces.com/contest/1137/submission/59448399\n*/\n#include <limits>\n#include <set>\n#include <utility>\n#include <vector>\n// CUT begin\n// Convex Hull Trick\n// Implementation Idea:\n// https://github.com/satanic0258/Cpp_snippet/blob/master/src/technique/ConvexHullTrick.cpp\n// #include <boost/multiprecision/cpp_int.hpp>\n// using mpint = boost::multiprecision::cpp_int;\nnamespace CHT {\nusing T_CHT = long long;\nstatic const T_CHT T_MIN = std::numeric_limits<T_CHT>::lowest() + 1;\nstruct Line {\n    T_CHT a, b; // y = ax + b\n    mutable std::pair<T_CHT, T_CHT>\n        rp; // (numerator, denominator) `x` coordinate of the crossing point with next line\n    Line(T_CHT a, T_CHT b) : a(a), b(b), rp(T_MIN, T_MIN) {}\n    static std::pair<T_CHT, T_CHT> cross(const Line &ll, const Line &lr) {\n        return std::make_pair(ll.b - lr.b, lr.a - ll.a); // `ll.a < lr.a` is assumed implicitly\n    }\n    bool operator<(const Line &r) const {\n        if (b == T_MIN) {\n            return r.rp.first == T_MIN ? true : a * r.rp.second < r.rp.first;\n        } else if (r.b == T_MIN) {\n            return rp.first == T_MIN ? false : !(r.a * rp.second < rp.first);\n        } else {\n            return a < r.a;\n        }\n    }\n};\ntemplate <typename T_MP> struct Lines : std::multiset<Line> {\n    bool flg_min; // true iff for minimization\n    inline bool isNeedless(iterator itr) {\n        if (size() == 1) return false;\n        auto nxt = std::next(itr);\n        if (itr == begin())\n            return itr->a == nxt->a and itr->b <= nxt->b;\n        else {\n            auto prv = std::prev(itr);\n            if (nxt == end())\n                return itr->a == prv->a and itr->b <= prv->b;\n            else\n                return T_MP(prv->b - itr->b) * (nxt->a - itr->a) >=\n                       T_MP(itr->b - nxt->b) * (itr->a - prv->a);\n        }\n    }\n    void add_line(T_CHT a, T_CHT b) {\n        if (flg_min) a = -a, b = -b;\n        auto itr = insert({a, b});\n        if (isNeedless(itr))\n            erase(itr);\n        else {\n            while (std::next(itr) != end() and isNeedless(std::next(itr))) {\n                erase(std::next(itr));\n            }\n            while (itr != begin() and isNeedless(std::prev(itr))) { erase(std::prev(itr)); }\n            if (std::next(itr) != end()) { itr->rp = CHT::Line::cross(*itr, *std::next(itr)); }\n            if (itr != begin()) { std::prev(itr)->rp = CHT::Line::cross(*std::prev(itr), *itr); }\n        }\n    }\n    Lines(bool is_minimizer) : flg_min(is_minimizer) {}\n    std::pair<T_CHT, T_CHT> get(T_CHT x) {\n        auto itr = lower_bound({x, CHT::T_MIN});\n        T_CHT retval = CHT::T_MIN, reta = CHT::T_MIN;\n        if (itr != end()) { retval = itr->a * x + itr->b, reta = itr->a; }\n        if (itr != begin()) {\n            T_CHT tmp = std::prev(itr)->a * x + std::prev(itr)->b;\n            if (tmp >= retval) { retval = tmp, reta = std::max(reta, std::prev(itr)->a); }\n        }\n        return std::make_pair(flg_min ? -retval : retval, flg_min ? -reta : reta);\n    }\n};\n} // namespace CHT\n\ntemplate <typename T_MP> struct ConvexHullTrick {\n    using T_CHT = CHT::T_CHT;\n    CHT::Lines<T_MP> lines;\n    ConvexHullTrick(bool is_minimizer) : lines(is_minimizer) {}\n    void add_line(T_CHT a, T_CHT b) { lines.add_line(a, b); } // Add y = ax + b\n    std::pair<T_CHT, T_CHT> get(T_CHT x) { return lines.get(x); }\n    void add_convex_parabola(T_CHT c, T_CHT a, T_CHT b) {\n        add_line(c * a * (-2), c * a * a + b);\n    } // Add y = c(x - a)^2 + b\n    T_CHT parabola_lower_bound(T_CHT c, T_CHT x) { return lines.get(x).first + c * x * x; }\n};\n", "meta": {"hexsha": "ebdb272dd3c629c2de78a4f309784a8620ac1572", "size": 3802, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "convex_hull_trick/convex_hull_trick.hpp", "max_stars_repo_name": "rsm9/cplib-cpp", "max_stars_repo_head_hexsha": "269064381eb259a049236335abb31f8f73ded7f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-05-13T05:06:22.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-18T17:03:36.000Z", "max_issues_repo_path": "convex_hull_trick/convex_hull_trick.hpp", "max_issues_repo_name": "rsm9/cplib-cpp", "max_issues_repo_head_hexsha": "269064381eb259a049236335abb31f8f73ded7f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-12-11T13:53:17.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-11T13:53:17.000Z", "max_forks_repo_path": "convex_hull_trick/convex_hull_trick.hpp", "max_forks_repo_name": "rsm9/cplib-cpp", "max_forks_repo_head_hexsha": "269064381eb259a049236335abb31f8f73ded7f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-12-11T06:45:45.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-07T13:45:32.000Z", "avg_line_length": 39.6041666667, "max_line_length": 97, "alphanum_fraction": 0.5549710679, "num_tokens": 1242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067195846919, "lm_q2_score": 0.7931059438487663, "lm_q1q2_score": 0.7475076814200216}}
{"text": "#include <vector>\n\n#include <NTL/ZZ.h>\n\n#include \"../src/elements/element.hpp\"\n#include \"../src/algorithms/utils.hpp\"\n\n/* Example: using the remainder tree algorithm to compute central trinomial\n * coefficients modulo squared primes.\n *\n * The n'th central trinomial coefficient, denoted a_n is the coefficient\n * of x^n in (1+x+x^2)^n. It is also the number of permutations of n symbols\n * taken from {-1, 0, 1} which sum to 0. The a_n satisfy the following identity:\n * a_p = 1 (mod p) for all primes p, and are given by the following recurrence:\n * a_n = [(2*n - 1)*a_{n-1} + 3*(n - 1)*a_{n-2}]/n, with a_0 = a_1 = 1.\n *\n * Suppose we wish to find primes p for which a_p = 1 (mod p^2) using remainder tree.\n * Let R_1 be the 2x2 matrix with ones in the top row and zeros in the bottom. For n>1, define\n *\n *       [2*n - 1,  n]\n * R_n = [3*(n-1),  0]\n *\n * Now, let M_1 = R_1. For n > 1, define\n *\n *       [a_n, a_{n-1}]\n * M_n = [0,         0]  \n *\n * Now observe n! * M_n = (R_n)! Our goal is to find\n * a_2 (mod 4), a_3 (mod 9), a_5 (mod 25)... Using remainder tree,\n * we can find n! * M_n (mod n) for a range of values of n, then divide each by n!\n * However, a similar problem to the Wolstenholme case arises: we cannot divide by n modulo n\n * We will employ a similar solution (see wolstenholme.hpp for more explanation)\n *\n * For primes p, we will use remainder tree to compute (R_p)! (mod p^3), take the\n * upper left entry only, divide it by p, and then reduce modulo p^2.\n * With another remainder tree, separately compute the rest of the denominator, (n-1)! modulo p^2,\n * find its modular inverse, and multiply to get the final result: a_p (mod p^2)\n *\n * For the first remainder tree, let A_0 = Id, and A_n = R_n.\n * The moduli m_n will be n^3 when n is prime, and 1 otherwise.\n * For the second remainder tree, let A_0 = A_1 = 1, and then A_n = n-1. The moduli\n * are now just n^2 when n is prime, and 1 otherwise.\n * Divide each of the upper left entries in the output by their index, then reduce modulo p^2,\n * and multiply by the modular inverse of the corresponding output in the second remainder tree.\n */\n\n\n/* Like the Kurepa example, we will need to use a matrix of integers for this problem.\n * Thankfully, we still do not have to deal with using polynomials.\n */\nusing NTL::ZZ;\nusing NTL::Mat;\n//TODO: specialize methods for Elt<Mat<ZZ> >, including modding by ZZ\n\nvector<Elt<Mat<ZZ> > > gen_trinomial_numerator(long lower, long upper) {\n    vector<Elt<Mat<ZZ> > > output(upper-lower);\n\n    for(long i = lower; i < upper; i++) {\n        Mat<ZZ> M;\n        M.SetDims(2,2);\n\n        if (i == 0) {\n            M[0][0] = ZZ(1);\n            M[0][1] = ZZ(0);\n            M[1][0] = ZZ(0);\n            M[1][1] = ZZ(1);\n            output[i] = Elt<Mat<ZZ> >(M);\n        }\n\n        else if (i == 1) {\n            M[0][0] = ZZ(1);\n            M[0][1] = ZZ(1);\n            M[1][0] = ZZ(0);\n            M[1][1] = ZZ(0);\n            output[i] = Elt<Mat<ZZ> >(M);\n        }\n\n        else {\n            M[0][0] = ZZ(2*i - 1);\n            M[0][1] = ZZ(i);\n            M[1][0] = ZZ(3*(i - 1));\n            M[1][1] = ZZ(0);\n            output[i-lower] = Elt<Mat<ZZ> >(M);\n        }\n    }\n    return output;\n}\n\nvector<Elt<ZZ>> gen_trinomial_denominator(long lower, long upper){\n    vector<Elt<ZZ>> output(upper-lower);\n\n    for(long i = lower; i < upper; ++i) {\n        if(i <= 1){\n            output[i] = Elt<ZZ>(1);\n        }\n        else {\n            output[i-lower] = Elt<ZZ> (i - 1);\n        }\n    }\n    return output;\n}\n\n\nvector<Elt<ZZ>> gen_second_prime_power(long lower, long upper) {\n    vector<Elt<ZZ>> output(upper-lower);\n    \n    for(long i = lower; i < upper; i++){\n        NTL::ZZ n(i);\n        if(ProbPrime(n)) { //Technically a sieve is faster & more correct, but shouldn't make a big difference.\n                            //This is just an example anyway.\n            power(n, n, 2);\n            output[i-lower] = Elt<ZZ>(n);\n        }\n        else{\n            output[i-lower] = Elt<ZZ>(1);\n        }\n    }\n    return output;\n}\n\nvector<Elt<ZZ>> gen_third_prime_power(long lower, long upper) {\n    vector<Elt<ZZ>> output(upper-lower);\n    \n    for(long i = lower; i < upper; i++){\n        ZZ n(i);\n        if(ProbPrime(n)) { //Technically a sieve is faster & more correct, but shouldn't make a big difference.\n                            //This is just an example anyway.\n            power(n, n, 3);\n            output[i-lower] = Elt<ZZ>(n);\n        }\n        else{\n            output[i-lower] = Elt<ZZ>(1);\n        }\n    }\n    return output;\n}\n\n\n//TODO: combine the above and actually write a search function that zips the outputs and finds XGCD etc.\n//TODO: explain how to modify calculate_factorial and compute V", "meta": {"hexsha": "35a513c5c1f2db8694bf08aac52bb4e6634ec05b", "size": 4744, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "examples/trinomial.hpp", "max_stars_repo_name": "adienes/remainder-tree", "max_stars_repo_head_hexsha": "0aa76214ab6f2a4389ec45a239ea660749989a90", "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": "examples/trinomial.hpp", "max_issues_repo_name": "adienes/remainder-tree", "max_issues_repo_head_hexsha": "0aa76214ab6f2a4389ec45a239ea660749989a90", "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": "examples/trinomial.hpp", "max_forks_repo_name": "adienes/remainder-tree", "max_forks_repo_head_hexsha": "0aa76214ab6f2a4389ec45a239ea660749989a90", "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.8857142857, "max_line_length": 111, "alphanum_fraction": 0.5735666105, "num_tokens": 1445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308091776495, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.7473905811988082}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n#include <functional> // for std::function\n#include <Eigen/SparseCore>\n#include <Eigen/SparseLU>\n\n// New version 1.1: using sparse matrices, dropping general nonlinear solver, using error instead of residual\n\n//! \\brief Implements a single step of the fixed point iteration $x^{(k+1)} = A(x^{(k)})^{-1} * b$\n//! \\tparam func type of the lambda function implementing A(x)\n//! \\tparam Vector type for the vector b, x, x_new $\\in \\mathbf{R}^2$\n//! \\param[in] A lambda function implementing A(x)\n//! \\param[in] b rhs vector $b \\in \\mathbf{R}^n$\n//! \\param[in] x previous step $x^{(k)}$\n//! \\param[out] x_new next step $x^{(k+1)}$\ntemplate <class func, class Vector>\nvoid fixed_point_step(func&& A, const Vector & b, const Vector & x, Vector & x_new) {\n    // Next step\n    auto T = A(x);\n    Eigen::SparseLU<Eigen::SparseMatrix<double>> Ax_lu;\n    Ax_lu.analyzePattern(T); \n    Ax_lu.factorize(T);\n    x_new = Ax_lu.solve(b);\n}\n\n//! \\brief Implements a single step of the Netwon iteration for $x^{(k+1)}$\n//! Exploits Sherman-Morrison-Woodbury formula for fast inversion of rank-one modification of a matrix.\n//! \\tparam func type of the lambda function implementing A(x)\n//! \\tparam Vector type for the vector b, x, x_new $\\in \\mathbf{R}^2$\n//! \\param[in] A lambda function implementing A(x)\n//! \\param[in] b rhs vector $b \\in \\mathbf{R}^n$\n//! \\param[in] x previous step $x^{(k)}$\n//! \\param[out] x_new next step in Newton iteration $x^{(k+1)}$\ntemplate <class func, class Vector>\nvoid newton_step(func&& A, const Vector & b, const Vector & x, Vector & x_new) {\n    // Reuse LU decomposition with SMW\n    auto T = A(x);\n    Eigen::SparseLU<Eigen::SparseMatrix<double>> Ax_lu;\n    Ax_lu.analyzePattern(T); \n    Ax_lu.factorize(T);\n    // Solve a bunch of systems\n    auto Axinv_b = Ax_lu.solve(b);\n    auto Axinv_x = Ax_lu.solve(x);\n    // Next step\n    x_new = Axinv_b + Ax_lu.solve(x*x.transpose()*(x-Axinv_b)) / (x.norm() + x.dot(Axinv_x) );\n}\n\nint main(void) {\n    double eps = 10e-14;\n    int max_itr = 100;\n    \n    // Define a test vector and test rhs and x0 = b\n    int n = 8;\n    Eigen::SparseMatrix<double> T(n,n);\n    T.reserve(3);\n    for(int i = 0; i < n; ++i) {\n        if(i > 0) T.insert(i,i-1) = 1;\n        T.insert(i,i) = 0;\n        if(i < n-1) T.insert(i,i+1) = 1;\n    }\n    \n    Eigen::VectorXd b = Eigen::VectorXd::Random(n);\n    \n    // Define a lambda function implementing A(x)\n    // auto = std::function<Eigen::SparseMatrix<double>(const Eigen::VectorXd &)>\n    auto A = [&T, n] (const Eigen::VectorXd & x) -> Eigen::SparseMatrix<double> & { double nrm = x.norm();\n        for(int i = 0; i < n; ++i) { T.coeffRef(i,i) = 3 + nrm; } return T; };\n    \n    // Perform convergence study with fixed point iteration\n    std::cout << std::endl << \"*** Fixed point method ***\" << std::endl << std::endl;\n    // auto = std::function<Eigen::VectorXd(const Eigen::VectorXd &, Eigen::VectorXd &)>\n    auto fix_step = [&A, &b] (const Eigen::VectorXd & x, Eigen::VectorXd & x_new) { fixed_point_step(A, b, x, x_new); };\n    \n    auto x = b;\n    auto x_new = x;\n    \n    for( int itr = 0;; ) { // Forever until break\n        \n        // Advance to next step, override x with x_{k+1}\n        fix_step(x, x_new);\n        \n        // Compute residual\n        double r = (x - x_new).norm();\n        \n        std::cout << \"[Step \" << itr << \"] Error: \" << r << std::endl;\n        \n        // Termination conditions\n        // If tol reached\n        if (r < eps) {\n            std::cout << \"[CONVERGED] in \" << itr << \" it. due to err. err = \" << r << \" < \" << eps << \".\" << std::endl;\n            break;\n        }\n        // If max it reached\n        if (++itr >= max_itr) {\n            std::cout << \"[NOT CONVERGED] due to MAX it. = \" << max_itr << \" reached, err = \" << r << \".\" << std::endl;\n            break;\n        }\n        x = x_new;\n    }\n    \n    std::cout << std::endl << \"x^*_fix = \" << std::endl << x_new << std::endl;\n    \n    // Perform convergence study with Newton iteration\n    std::cout << std::endl << \"*** Newton method ***\" << std::endl << std::endl;\n    \n    // auto = std::function<Eigen::VectorXd(const Eigen::VectorXd &, Eigen::VectorXd &)>\n    auto newt_step = [&A, &b] (const Eigen::VectorXd & x, Eigen::VectorXd & x_new) { newton_step(A, b, x, x_new); };\n    \n    x = b;\n    \n    for( int itr = 0;; ) { // Forever until break\n        \n        \n        // Advance to next step, override x with x_{k+1}\n        newt_step(x, x_new);\n        \n        // Compute residual\n        double r = (x - x_new).norm();\n        \n        std::cout << \"[Step \" << itr << \"] Error: \" << r << std::endl;\n        \n        // Termination conditions\n        // If tol reached\n        if (r < eps) {\n            std::cout << \"[CONVERGED] in \" << itr << \" it. due to err. err = \" << r << \" < \" << eps << \".\" << std::endl;\n            break;\n        }\n        // If max it reached\n        if (++itr >= max_itr) {\n            std::cout << \"[NOT CONVERGED] due to MAX it. = \" << max_itr << \" reached, err = \" << r << \".\" << std::endl;\n            break;\n        }\n        x = x_new;\n    }\n    \n    std::cout << std::endl << \"x^*_newt = \" << std::endl << x_new << std::endl;\n}\n", "meta": {"hexsha": "5d530cf94f4e447665e7166adffb5b215e428345", "size": 5224, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/PS5/solutions_ps5/quasilin.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/PS5/solutions_ps5/quasilin.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/PS5/solutions_ps5/quasilin.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": 37.8550724638, "max_line_length": 120, "alphanum_fraction": 0.5491960184, "num_tokens": 1534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.8311430415844385, "lm_q1q2_score": 0.7472984762577303}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include <cmath>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <stdexcept>\n#include \"atoms.h\"\n\n\nusing namespace std;\nusing namespace Eigen;\n\nvector<string> split(const string &s, char delim) {\n    stringstream ss(s);\n    string item;\n    vector<string> elems;\n    while (getline(ss, item, delim)) {\n        if (!item.empty()){\n            elems.push_back(item);\n        }\n    }\n    return elems;\n}\n\n\nclass Molecule{\n\n    public:\n        vector<int> atomic_numbers;\n        MatrixXd coords;\n        int n_atoms = 0;\n\n        explicit Molecule(string xyz_filename){                         // Constructor\n                extract_from_xyz_file(xyz_filename);\n        }\n\n    void extract_from_xyz_file(string &xyz_filename){\n        /************************************************\n         *  Set coordinates and atomic numbers from a .xyz file\n         ***********************************************/\n\n        string line, item;\n        ifstream xyz_file (xyz_filename);\n\n        bool assigned_n_atoms = false;\n\n        vector<float> coord_list;\n\n        // Iterate through the xyz file\n        while (getline(xyz_file, line, '\\n')){\n\n            // Ignore any blank lines etc.\n            if (line.empty()){\n                continue;\n            }\n\n            // Assign the number of atoms\n            if (!assigned_n_atoms){\n                n_atoms = stoi(line);\n                assigned_n_atoms = true;\n                continue;\n            }\n\n            vector<string> xyz_items = split(line, ' ');\n\n            atomic_numbers.push_back(stoi(xyz_items[0]));\n            for (int i=1; i < 4; i++){\n                coord_list.push_back(stod(xyz_items[i]));\n            }\n\n        }\n        xyz_file.close();\n\n        if (atomic_numbers.size() != n_atoms) {\n            cout << atomic_numbers.size() << \" \" << n_atoms << endl;\n            throw runtime_error(\"Number of atoms not equal to the number declared\");\n        }\n\n        // Now we can assign the coordinate as a Nx3 matrix, after defining it's shape\n        coords.resize(n_atoms, 3);\n\n        for (int i=0; i < coord_list.size(); i++){\n            coords(i/3, i%3) = coord_list[i];\n        }\n    }\n\n    double distance_ij(int i, int j){\n        /******************************************************\n         *  Calculate the distance between to atoms i and j as\n         *  \u221a((x_i - x_j)^2 + (y_i - y_j)^2 + (z_i - z_j)^2)\n         *****************************************************/\n\n        return sqrt(pow((coords(i, 0) - coords(j, 0)), 2)\n                    + pow((coords(i, 1) - coords(j, 1)), 2)\n                    + pow((coords(i, 2) - coords(j, 2)), 2));\n        }\n\n    double angle_ijk(int i, int j, int k){\n        /******************************************************\n        *  Calculate the angle in radians between three atoms\n        *  raises a runtime error if any indices are the same\n        *\n        *         i    k\n        *          \\  /            j is the mid atom\n        *           j\n        *\n        *                    ( v_ij . v_jk  )\n        *          \u03b8 = arccos(--------------)\n          *                  ( |v_ij||v_jk| )\n        *\n        * where v_ij and v_jk are unit vectors\n        *****************************************************/\n        if (i==j | i==k | j==k){\n            throw runtime_error(\"Angle must be calcd. with three different \"\n                                \"indices\");\n            }\n\n        // Calculate the dot product over the three components of the vector\n        double dot_product = 0;\n\n        for (int c=0; c < 3; c++){\n            dot_product += (coords(i, c) - coords(j, c)) * (coords(k, c) - coords(j, c));\n        }\n\n        return acos(dot_product / (distance_ij(i, j) * distance_ij(j, k)));\n\n        }\n\n    MatrixXd distance_matrix(){\n        /************************************************\n         *  Calculate the distance matrix (N x N)\n         ***********************************************/\n        double dist;\n\n        // N x N matrix of zeros\n        MatrixXd dist_mat = MatrixXd::Zero(n_atoms, n_atoms);\n\n        for (int i=0; i < n_atoms; i++){\n            for (int j=i+1; j < n_atoms; j++){\n\n                dist = distance_ij(i, j);\n\n                // And set the values of the symmetric matrix\n                dist_mat(i, j) = dist;\n                dist_mat(j, i) = dist;\n            }\n        }\n        return dist_mat;\n    }\n\n    void shift_to_com(){\n        /************************************************\n        *  Shift the molecule so that the center of mass_i\n        *  (COM) is centered at the origin\n        ***********************************************/\n        // Center of mass as a column vector\n        Vector3d com = Vector3d::Zero();\n\n        double mass_i;\n        double total_mass = 0;\n\n        // COM = \u03a3_i m_i v_i /  \u03a3_i m_i\n        for (int i=0; i<n_atoms; i++){\n\n            mass_i = atomic_weight(atomic_numbers[i]);\n            total_mass += mass_i;\n\n            com += mass_i * coords.row(i);\n        }\n\n        // Subtract the COM from each row of the coordinates\n        // COM needs transposing into a row vector_\n        coords.rowwise() -= com.transpose() / total_mass;\n    }\n\n    Vector3d moments_of_inertia(){\n        /************************************************\n        *  Calculate the moments of inertia as the\n        *  eigenvalues of the moment of inertia tensor\n        ***********************************************/\n        shift_to_com();\n\n        VectorXd atomic_weights(n_atoms);\n\n        for (int i=0; i<n_atoms; i++) atomic_weights(i) = atomic_weight(atomic_numbers[i]);\n\n        auto x = coords.col(0);\n        auto y = coords.col(1);\n        auto z = coords.col(2);\n\n        VectorXd x_sq = x.array().pow(2);\n        VectorXd y_sq = y.array().pow(2);\n        VectorXd z_sq = z.array().pow(2);\n\n        Matrix3d I_mat = Matrix3d::Zero();\n        // Calculate the diagonal elements\n        I_mat(0, 0) = atomic_weights.adjoint() * (y_sq + z_sq);\n        I_mat(1, 1) = atomic_weights.adjoint() * (x_sq + z_sq);\n        I_mat(2, 2) = atomic_weights.adjoint() * (x_sq + y_sq);\n\n        // Calculate the off diagonals\n        I_mat(0, 1 ) = -atomic_weights.adjoint() * (x.cwiseProduct(y));\n        I_mat(0, 2 ) = -atomic_weights.adjoint() * (x.cwiseProduct(z));\n        I_mat(1, 2 ) = -atomic_weights.adjoint() * (y.cwiseProduct(z));\n\n        // Assign the rest of the bottom left of the symmetric matrix\n        I_mat(1, 0) = I_mat(0, 1);\n        I_mat(2, 0) = I_mat(0, 2);\n        I_mat(2, 1) = I_mat(1, 2);\n\n        EigenSolver<MatrixXd> solver(I_mat);\n        return solver.eigenvalues().real();\n    }\n\n};\n\n\nint main(){\n\n    Molecule mol = Molecule(\"../project1.xyz\");\n    cout << mol.moments_of_inertia().transpose() << endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "800aa36b940feafa35918754dd50c090a960bd96", "size": 6837, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "project1/project1.cpp", "max_stars_repo_name": "t-young31/cpp_tutorials", "max_stars_repo_head_hexsha": "321135177a8fb3a058e479b4974ec35dd65e7dc5", "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": "project1/project1.cpp", "max_issues_repo_name": "t-young31/cpp_tutorials", "max_issues_repo_head_hexsha": "321135177a8fb3a058e479b4974ec35dd65e7dc5", "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": "project1/project1.cpp", "max_forks_repo_name": "t-young31/cpp_tutorials", "max_forks_repo_head_hexsha": "321135177a8fb3a058e479b4974ec35dd65e7dc5", "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.2522123894, "max_line_length": 91, "alphanum_fraction": 0.4676027497, "num_tokens": 1594, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218412907381, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.7471982078086516}}
{"text": "/* Copyright (c) 2018, Skolkovo Institute of Science and Technology (Skoltech)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\n * arun.cpp\n *\n *  Created on: Jan 31, 2018\n *      Author: Gonzalo Ferrer\n *              g.ferrer@skoltech.ru\n *              Mobile Robotics Lab, Skoltech \n */\n\n#include <Eigen/LU>\n#include <Eigen/SVD>\n\n#include <memory>\n#include <iostream>\n#include \"mrob/pc_registration.hpp\"\n\nusing namespace mrob;\nusing namespace Eigen;\n\nint PCRegistration::arun(const Ref<const MatX> X, const Ref<const MatX> Y, SE3 &T)\n{\n    assert(X.cols() == 3  && \"PCRegistration::Arun: Incorrect sizing, we expect Nx3\");\n    assert(X.rows() >= 3  && \"PCRegistration::Arun: Incorrect sizing, we expect at least 3 correspondences (not aligned)\");\n    assert(Y.rows() == X.rows()  && \"PCRegistration::Arun: Same number of correspondences\");\n    uint_t N = X.rows();\n    /** Algorithm:\n     *  1) calculate centroids cx = sum x_i. cy = sum y_i\n     *  2) calculate dispersion from centroids qx = x_i - cx\n     *  3) calculate matrix H = sum qx_i * qy_i^T\n     *  4) svd decomposition: H = U*D*V'\n     *      4.5) look for co-linear solutions, that is 2 of the 3 singular values are equal\n     *  5) Calculate the rotation solution R = V*U'\n     *      5.5) check for correct solution (det = +1) or reflection (det = -1)\n     *      step 5.5 is actually unnecessary IF applying Umeyama technique\n     *  6) calculate translation as: t = cy - R * cx\n     */\n    // We have already asserted in base_T that they are 3xN matrices. (and the same length).\n\n    //std::cout << \"X: \\n\" << X << \"\\nY:\\n\" << Y << std::endl;\n    // 1) calculate centroids cx = E{x_i}. cy = E{y_i}\n    //More efficient than creating a matrix of ones when on Release mode (not is Debug mode)\n    Mat13 cxm = X.colwise().sum();\n    cxm /= (double)N;\n    Mat13 cym = Y.colwise().sum();\n    cym /= (double)N;\n\n    // 2)  calculate dispersion from centroids qx = x_i - cx\n    MatX qx = X.rowwise() - cxm;\n    MatX qy = Y.rowwise() - cym;\n\n\n    // 3) calculate matrix H = sum qx_i * qy_i^T (noting that we are obtaingin row vectors)\n    Mat3 H = qx.transpose() * qy;\n\n    // 4) svd decomposition: H = U*D*V'\n    JacobiSVD<Matrix3d> SVD(H, ComputeFullU | ComputeFullV);//Full matrices indicate Square matrices\n\n    //test: prints results so far\n    /*std::cout << \"Checking matrix SVD: \\n\" << SVD.singularValues() <<\n                 \",\\n U = \" << SVD.matrixU() <<\n                 \",\\n V = \" << SVD.matrixV() << std::endl;*/\n\n\n    // 4.5) look for co-linear solutions, that is 2 of the 3 singular values are equal\n    double l_prev = SVD.singularValues()(0), l;\n    for(int i =1; i < 3; ++i)\n    {\n        l = SVD.singularValues()(i);\n        if (fabs(l - l_prev) < 1e-6)\n\n            return 0; //they are co-linear, there exist infinite transformations\n        else\n            l_prev = l;//this works because we assume that they singular values are ordered.\n    }\n\n\n    // 5) Calculate the rotation solution R = V*U'\n    Mat3 R = SVD.matrixV() * SVD.matrixU().transpose();\n\n    // 5.5) check for correct solution (det = +1) or reflection (det = -1)\n    // that is, solve the problem for co-planar set of points and centroid, when is l1 > l2 > l3 = 0\n    // Since H = D1*u1*v1' + D2*u2*v2' + D3*u3*v3',    and D3 = 0, we can swap signs in V\n    // such as Vp = [v1,v2,-v3] and the solution is still minimal, but we want a valid rotation R \\in SO(3)\n    if (R.determinant() < 0.0 )\n    {\n        Mat3 Vn;\n        Vn << SVD.matrixV().topLeftCorner<3,2>(), -SVD.matrixV().topRightCorner<3,1>();\n        R << Vn * SVD.matrixU().transpose();\n        //std::cout << \"R value = \" << R << std::endl;\n    }\n\n    // 6) calculate translation as: t = cy - R * cx\n    Mat31 t = cym.transpose() - R*cxm.transpose();\n    //std::cout << \"t = \" << t << std::endl;\n\n    // 7) return result\n    T.ref2T() << R, t,\n                 0,0,0,1;\n\n    return 1;\n}\n", "meta": {"hexsha": "89af244e7a52a42161e61fa1ed9068876a2b9028", "size": 4420, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/PCRegistration/arun.cpp", "max_stars_repo_name": "nosmokingsurfer/mrob", "max_stars_repo_head_hexsha": "7e92c1747373d5acf32895e688b568ae8244072e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2020-09-22T15:33:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T17:27:39.000Z", "max_issues_repo_path": "src/PCRegistration/arun.cpp", "max_issues_repo_name": "nosmokingsurfer/mrob", "max_issues_repo_head_hexsha": "7e92c1747373d5acf32895e688b568ae8244072e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 46.0, "max_issues_repo_issues_event_min_datetime": "2020-09-22T15:47:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-22T10:56:44.000Z", "max_forks_repo_path": "src/PCRegistration/arun.cpp", "max_forks_repo_name": "nosmokingsurfer/mrob", "max_forks_repo_head_hexsha": "7e92c1747373d5acf32895e688b568ae8244072e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2020-09-22T15:59:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-20T20:15:16.000Z", "avg_line_length": 38.1034482759, "max_line_length": 123, "alphanum_fraction": 0.6095022624, "num_tokens": 1328, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.957912273285902, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.7471647771282274}}
{"text": "\n#ifndef _PFASST_QUADRATURE_HPP_\n#define _PFASST_QUADRATURE_HPP_\n\n#include <algorithm>\n#include <cmath>\n#include <complex>\n#include <limits>\n#include <vector>\n\n#include <Eigen/Dense>\n\ntemplate<typename coeff>\nusing Matrix = Eigen::Matrix<coeff, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\n\n#include <boost/math/constants/constants.hpp>\nusing namespace boost::math::constants;\n\nusing std::complex;\nusing std::string;\nusing std::vector;\n\n#include \"interfaces.hpp\"\n\nnamespace pfasst\n{\n  template<typename CoeffT>\n  class Polynomial\n  {\n      vector<CoeffT> c;\n\n    public:\n      Polynomial(size_t n)\n        : c(n)\n      {\n        fill(c.begin(), c.end(), 0.0);\n      }\n\n      size_t order() const\n      {\n        return c.size() - 1;\n      }\n\n      CoeffT& operator[](const size_t i)\n      {\n        return c.at(i);\n      }\n\n      Polynomial<CoeffT> differentiate() const\n      {\n        Polynomial<CoeffT> p(c.size() - 1);\n        for (size_t j = 1; j < c.size(); j++) {\n          p[j - 1] = j * c[j];\n        }\n        return p;\n      }\n\n      Polynomial<CoeffT> integrate() const\n      {\n        Polynomial<CoeffT> p(c.size() + 1);\n        for (size_t j = 0; j < c.size(); j++) {\n          p[j + 1] = c[j] / (j + 1);\n        }\n        return p;\n      }\n\n      template<typename xtype>\n      xtype evaluate(const xtype x) const\n      {\n        int n = c.size() - 1;\n        xtype v = c[n];\n        for (int j = n - 1; j >= 0; j--) {\n          v = x * v + c[j];\n        }\n        return v;\n      }\n\n      Polynomial<CoeffT> normalize() const\n      {\n        Polynomial<CoeffT> p(c.size());\n        for (size_t j = 0; j < c.size(); j++) {\n          p[j] = c[j] / c.back();\n        }\n        return p;\n      }\n\n      vector<CoeffT> roots() const\n      {\n        assert(c.size() >= 1);\n        size_t n = c.size() - 1;\n\n        // initial guess\n        Polynomial<complex<CoeffT>> z0(n), z1(n);\n        for (size_t j = 0; j < n; j++) {\n          z0[j] = pow(complex<double>(0.4, 0.9), j);\n          z1[j] = z0[j];\n        }\n\n        // durand-kerner-weierstrass iterations\n        Polynomial<CoeffT> p = normalize();\n        for (size_t k = 0; k < 100; k++) {\n          complex<CoeffT> num, den;\n          for (size_t i = 0; i < n; i++) {\n            num = p.evaluate(z0[i]);\n            den = 1.0;\n            for (size_t j = 0; j < n; j++) {\n              if (j == i) { continue; }\n              den = den * (z0[i] - z0[j]);\n            }\n            z0[i] = z0[i] - num / den;\n          }\n\n          // converged?\n          CoeffT acc = 0.0;\n          for (size_t j = 0; j < n; j++) { acc += abs(z0[j] - z1[j]); }\n          if (acc < 2 * std::numeric_limits<CoeffT>::epsilon()) { break; }\n\n          z1 = z0;\n        }\n\n        vector<CoeffT> roots(n);\n        for (size_t j = 0; j < n; j++) {\n          roots[j] = (abs(z0[j]) < 4 * std::numeric_limits<CoeffT>::epsilon()) ? 0.0 : real(z0[j]);\n        }\n\n        sort(roots.begin(), roots.end());\n        return roots;\n      }\n\n      static Polynomial<CoeffT> legendre(const size_t order)\n      {\n        if (order == 0) {\n          Polynomial<CoeffT> p(1);\n          p[0] = 1.0;\n          return p;\n        }\n\n        if (order == 1) {\n          Polynomial<CoeffT> p(2);\n          p[0] = 0.0;\n          p[1] = 1.0;\n          return p;\n        }\n\n        Polynomial<CoeffT> p0(order + 1), p1(order + 1), p2(order + 1);\n        p0[0] = 1.0; p1[1] = 1.0;\n\n        // (n + 1) P_{n+1} = (2n + 1) x P_{n} - n P_{n-1}\n        for (size_t m = 1; m < order; m++) {\n          for (size_t j = 1; j < order + 1; j++) {\n            p2[j] = ((2 * m + 1) * p1[j - 1] - m * p0[j]) / (m + 1);\n          }\n          p2[0] = - int(m) * p0[0] / (m + 1);\n\n          for (size_t j = 0; j < order + 1; j++) {\n            p0[j] = p1[j];\n            p1[j] = p2[j];\n          }\n        }\n\n        return p2;\n      }\n  };\n\n\n  enum class QuadratureType {\n      GaussLegendre\n    , GaussLobatto\n    , GaussRadau\n    , ClenshawCurtis\n    , Uniform\n  };\n\n\n  template<typename node = time_precision>\n  vector<node> compute_nodes(size_t nnodes, QuadratureType qtype)\n  {\n    vector<node> nodes(nnodes);\n\n    if (qtype == QuadratureType::GaussLegendre) {\n      auto roots = Polynomial<node>::legendre(nnodes).roots();\n      for (size_t j = 0; j < nnodes; j++) {\n        nodes[j] = 0.5 * (1.0 + roots[j]);\n      }\n\n    } else if (qtype == QuadratureType::GaussLobatto) {\n      auto roots = Polynomial<node>::legendre(nnodes - 1).differentiate().roots();\n      assert(nnodes >= 2);\n      for (size_t j = 0; j < nnodes - 2; j++) {\n        nodes[j + 1] = 0.5 * (1.0 + roots[j]);\n      }\n      nodes.front() = 0.0;\n      nodes.back() = 1.0;\n\n    } else if (qtype == QuadratureType::GaussRadau) {\n      auto l   = Polynomial<node>::legendre(nnodes);\n      auto lm1 = Polynomial<node>::legendre(nnodes - 1);\n      for (size_t i = 0; i < nnodes; i++) {\n        l[i] += lm1[i];\n      }\n      auto roots = l.roots();\n      for (size_t j = 1; j < nnodes; j++) {\n        nodes[j - 1] = 0.5 * (1.0 - roots[nnodes - j]);\n      }\n      nodes.back() = 1.0;\n\n    } else if (qtype == QuadratureType::ClenshawCurtis) {\n      for (size_t j = 0; j < nnodes; j++) {\n        nodes[j] = 0.5 * (1.0 - cos(j * pi<node>() / (nnodes - 1)));\n      }\n\n    } else if (qtype == QuadratureType::Uniform) {\n      for (size_t j = 0; j < nnodes; j++) {\n        nodes[j] = node(j) / (nnodes - 1);\n      }\n\n    } else {\n      throw ValueError(\"invalid node type passed to compute_nodes.\");\n    }\n\n    return nodes;\n  }\n\n  template<typename node>\n  auto augment_nodes(vector<node> const orig) -> pair<vector<node>, vector<bool>> {\n    vector<node> nodes = orig;\n\n    bool left = nodes.front() == node(0.0);\n    bool right = nodes.back() == node(1.0);\n\n    if (!left)  { nodes.insert(nodes.begin(), node(0.0)); }\n    if (!right) { nodes.insert(nodes.end(),   node(1.0)); }\n\n    vector<bool> is_proper(nodes.size(), true);\n    is_proper.front() = left;\n    is_proper.back() = right;\n\n    return pair<vector<node>, vector<bool>>(nodes, is_proper);\n  }\n\n//  enum class QuadratureMatrix { S, Q, QQ }; // returning QQ might be cool for 2nd-order stuff\n  enum class QuadratureMatrix { S, Q };\n\n  template<typename node = time_precision>\n  Matrix<node> compute_quadrature(vector<node> dst, vector<node> src, vector<bool> is_proper,\n                                  QuadratureMatrix type)\n  {\n    const size_t ndst = dst.size();\n    const size_t nsrc = src.size();\n\n    assert(ndst >= 1);\n    Matrix<node> mat(ndst - 1, nsrc);\n    mat.fill(0.0);\n\n    Polynomial<node> p(nsrc + 1), p1(nsrc + 1);\n\n    for (size_t i = 0; i < nsrc; i++) {\n      if (!is_proper[i]) { continue; }\n\n      // construct interpolating polynomial coefficients\n      p[0] = 1.0;\n      for (size_t j = 1; j < nsrc + 1; j++) { p[j] = 0.0; }\n      for (size_t m = 0; m < nsrc; m++) {\n        if ((!is_proper[m]) || (m == i)) { continue; }\n\n        // p_{m+1}(x) = (x - x_j) * p_m(x)\n        p1[0] = 0.0;\n        for (size_t j = 0; j < nsrc;   j++) { p1[j + 1]  = p[j]; }\n        for (size_t j = 0; j < nsrc + 1; j++) { p1[j]   -= p[j] * src[m]; }\n        for (size_t j = 0; j < nsrc + 1; j++) { p[j] = p1[j]; }\n      }\n\n      // evaluate integrals\n      auto den = p.evaluate(src[i]);\n      auto P = p.integrate();\n      for (size_t j = 1; j < ndst; j++) {\n        node q = 0.0;\n        if (type == QuadratureMatrix::S) {\n          q = P.evaluate(dst[j]) - P.evaluate(dst[j - 1]);\n        } else if (type == QuadratureMatrix::Q) {\n          q = P.evaluate(dst[j]) - P.evaluate(0.0);\n        } else {\n          throw ValueError(\"Further matrix types are not implemented yet\");\n        }\n\n        mat(j - 1, i) = q / den;\n      }\n    }\n\n    return mat;\n  }\n\n  template<typename node = time_precision>\n  Matrix<node> compute_interp(vector<node> dst, vector<node> src)\n  {\n    const size_t ndst = dst.size();\n    const size_t nsrc = src.size();\n\n    Matrix<node> mat(ndst, nsrc);\n\n    for (size_t i = 0; i < ndst; i++) {\n      for (size_t j = 0; j < nsrc; j++) {\n        node den = 1.0;\n        node num = 1.0;\n\n        for (size_t k = 0; k < nsrc; k++) {\n          if (k == j) { continue; }\n          den *= src[j] - src[k];\n          num *= dst[i] - src[k];\n        }\n\n        if (abs(num) > 1e-32) {\n          mat(i, j) = num / den;\n        } else {\n          mat(i, j) = 0.0;\n        }\n      }\n    }\n\n    return mat;\n  }\n\n}  // ::pfasst\n\n#endif\n", "meta": {"hexsha": "65636fe4e1e9fb26e194ad82c8905906bbc4cc3f", "size": 8389, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/pfasst/quadrature.hpp", "max_stars_repo_name": "danielru/PFASST", "max_stars_repo_head_hexsha": "d74a822f98fc84ae98232a61fed6f47f60341b08", "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": "include/pfasst/quadrature.hpp", "max_issues_repo_name": "danielru/PFASST", "max_issues_repo_head_hexsha": "d74a822f98fc84ae98232a61fed6f47f60341b08", "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": "include/pfasst/quadrature.hpp", "max_forks_repo_name": "danielru/PFASST", "max_forks_repo_head_hexsha": "d74a822f98fc84ae98232a61fed6f47f60341b08", "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": 25.7331288344, "max_line_length": 99, "alphanum_fraction": 0.4807485994, "num_tokens": 2696, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.8198933403143929, "lm_q1q2_score": 0.7470701740907593}}
{"text": "#include <Eigen/Dense>\n/*\n  Helper functions that support operations like\n  data wrangling and transformations.\n*/\n\n\nEigen::MatrixXd insert_bias(Eigen::MatrixXd X) {\n  /*\n    Inserts the bias into a dataset X by\n    preprending a column of all ones.\n  */\n  Eigen::MatrixXd biased;\n  int n_rows, n_cols;\n\n  n_rows = X.rows();\n  n_cols = X.cols() + 1;  // With extra bias column\n\n  biased = Eigen::MatrixXd::Constant(n_rows, n_cols, 1.0);\n  for (int col = 1; col < n_cols; col++) {\n    biased.col(col) = X.col(col - 1);\n  }\n\n  return biased;\n}", "meta": {"hexsha": "897dfa686f83c1c867fa9b5246a273632e076c28", "size": 541, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/utilities.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/utilities.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/utilities.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": 21.64, "max_line_length": 58, "alphanum_fraction": 0.6524953789, "num_tokens": 154, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379296, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7469987351799408}}
{"text": "#include <iostream>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\nusing namespace std;\nusing namespace Eigen;\n\nint main(int argc, char ** argv){\n    Matrix<double, 2, 3> matrix_23;\n    matrix_23 << 1,2,3,4,5,6;\n    cout << matrix_23 << endl;\n\n    Matrix<int, 2, 3> matrix_232;\n    matrix_232 << 1,2,3,4,5,6;\n\n    Matrix<double, Dynamic, Dynamic> matrix_dd;\n    matrix_dd = matrix_23 * matrix_232.cast<double>().transpose();\n    // cout << matrix_23*matrix_232.cast<double>().transpose() << endl;\n    cout << matrix_dd << endl;\n    cout << matrix_dd.sum() << endl;\n    cout << matrix_dd.trace() << endl;\n    cout << matrix_dd.inverse() << endl;\n    cout << matrix_dd.determinant() << endl;\n\n    Matrix<double, 5, 5> matrix_nn = MatrixXd::Random(5,5);\n    matrix_nn = matrix_nn * matrix_nn.transpose();\n    Matrix<double, 5, 1> vector_n = MatrixXd::Random(5,1);\n    Matrix<double, Dynamic, Dynamic> x = matrix_nn.inverse()*vector_n;\n    cout << x << endl;\n    x = matrix_nn.colPivHouseholderQr().solve(vector_n);\n    cout << x << endl;\n    x = matrix_nn.ldlt().solve(vector_n);\n    cout << x << endl;\n}", "meta": {"hexsha": "4bab05e8bb95119b8ffb11f216fa074d3bdf49e1", "size": 1100, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch3/useEigen/testEigen/main.cpp", "max_stars_repo_name": "LeoDuhz/learn_slambook", "max_stars_repo_head_hexsha": "39be3fc667b0481ff6297b6add0c456c8f6e98c8", "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/testEigen/main.cpp", "max_issues_repo_name": "LeoDuhz/learn_slambook", "max_issues_repo_head_hexsha": "39be3fc667b0481ff6297b6add0c456c8f6e98c8", "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/testEigen/main.cpp", "max_forks_repo_name": "LeoDuhz/learn_slambook", "max_forks_repo_head_hexsha": "39be3fc667b0481ff6297b6add0c456c8f6e98c8", "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.3529411765, "max_line_length": 71, "alphanum_fraction": 0.6336363636, "num_tokens": 324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517050371972, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.7469476219635186}}
{"text": "\n#ifndef VECTOR_3D_HPP\n#define VECTOR_3D_HPP\n\n#include <manu343726/portable_cpp/specifiers.hpp>\n#include <boost/operators.hpp>\n#include <boost/lexical_cast.hpp>\n#include <iostream>\n#include <string>\n#include <tuple>\n#include <cmath>\n\nnamespace math\n{\n\ttemplate<typename T>\n\tstruct vector3 \n\t     : boost::addable< vector3<T>             // vector + vector\n    \t , boost::subtractable< vector3<T>        // vector - vector\n    \t , boost::dividable2< vector3<T>, T       // vector / T\n    \t , boost::multipliable2< vector3<T>, T    // vector * T, T * vector\n    \t , boost::equality_comparable< vector3<T> // vector != vector\n      > > > > >\n\t{\n\t\tT x, y, z;\n\n\t\tvector3() : vector3{0, 0, 0}\n\t\t{}\n\n\t\tvector3(T xx, T yy, T zz) :\n\t\t\tx{xx},\n\t\t\ty{yy},\n\t\t\tz{zz}\n\t\t{}\n\n\t\ttemplate<typename U>\n\t\texplicit vector3(const vector3<U>& v) : vector3{v.x, v.y, v.z}\n\t\t{}\n\n\t\tvector3(const vector3& begin, const vector3& end) :\n\t\t\tx{end.x - begin.x},\n\t\t\ty{end.y - begin.y},\n\t\t\tz{end.z - begin.z}\n\t\t{}\n\n\t\tT squared_length() const NOEXCEPT\n\t\t{\n\t\t\treturn x*x + y*y + z*z;\n\t\t}\n\n\t\tT length() const NOEXCEPT\n\t\t{\n\t\t\treturn std::sqrt(squared_length());\n\t\t}\n\n\t\tvector3& operator+=(const vector3& v)\n\t\t{\n\t\t\tx += v.x;\n\t\t\ty += v.y;\n\t\t\tz += v.z;\n\n\t\t\treturn *this;\n\t\t}\n\n\t\tvector3& operator-=(const vector3& v)\n\t\t{\n\t\t\tx -= v.x;\n\t\t\ty -= v.y;\n\t\t\tz -= v.z;\n\n\t\t\treturn *this;\n\t\t}\n\n\t\tvector3& operator*=(T v)\n\t\t{\n\t\t\tx *= v;\n\t\t\ty *= v;\n\t\t\tz *= v;\n\n\t\t\treturn *this;\n\t\t}\n\n\t\tvector3& operator/=(T v)\n\t\t{\n\t\t\tx /= v;\n\t\t\ty /= v;\n\t\t\tz /= v;\n\n\t\t\treturn *this;\n\t\t}\n\n\t\tfriend T operator*(const vector3& lhs, const vector3& rhs)\n\t\t{\n\t\t\treturn lhs.x * rhs.x + lhs.y * rhs.y + lhs.z * rhs.z;\n\t\t}\n\n\t\tfriend std::ostream& operator<<(std::ostream& os, const vector3& v)\n\t\t{\n\t\t\treturn os << \"(\" << v.x << \",\" << v.y << \",\" << v.z << \")\";\n\t\t}\n\n\t\tfriend std::istream& operator>>(std::istream& is, vector3& v)\n\t\t{\n\t\t\tchar placeholder;\n\n\t\t\treturn is >> placeholder >> v.x >> placeholder >> v.y >> placeholder >> v.z >> placeholder;\n\t\t}\n\n\t\tstd::string to_string() const\n\t\t{\n\t\t\treturn boost::lexical_cast<std::string>(*this);\n\t\t}\n\n\t\tfriend bool operator==(const vector3& lhs, const vector3& rhs)\n\t\t{\n\t\t\treturn std::tie(lhs.x, lhs.y, lhs.z) == std::tie(rhs.x, rhs.y, rhs.z);\n\t\t}\n\t};\n}\n\n#endif /* VECTOR_2D_HPP */", "meta": {"hexsha": "c1d6d41f8ec0b0042ababcc10083e2dafb4fc159", "size": 2245, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "blocktemplates/manu343726/math/vector3.hpp", "max_stars_repo_name": "Manu343726/boost", "max_stars_repo_head_hexsha": "397a6193817923db4b713b01709c8b73a9a243ac", "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": "blocktemplates/manu343726/math/vector3.hpp", "max_issues_repo_name": "Manu343726/boost", "max_issues_repo_head_hexsha": "397a6193817923db4b713b01709c8b73a9a243ac", "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": "blocktemplates/manu343726/math/vector3.hpp", "max_forks_repo_name": "Manu343726/boost", "max_forks_repo_head_hexsha": "397a6193817923db4b713b01709c8b73a9a243ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-03-04T15:15:13.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-03T05:41:03.000Z", "avg_line_length": 18.7083333333, "max_line_length": 94, "alphanum_fraction": 0.5599109131, "num_tokens": 741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513648201267, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7468683021766511}}
{"text": "#include <iostream>\n#include <Eigen/SVD>\nusing namespace Eigen;\nusing namespace std;\n\nfloat inv_cond(const Ref<const MatrixXf>& a)\n{\n  const VectorXf sing_vals = a.jacobiSvd().singularValues();\n  return sing_vals(sing_vals.size()-1) / sing_vals(0);\n}\n\nint main()\n{\n  Matrix4f m = Matrix4f::Random();\n  cout << \"matrix m:\" << endl << m << endl << endl;\n  cout << \"inv_cond(m):          \" << inv_cond(m)                      << endl;\n  cout << \"inv_cond(m(1:3,1:3)): \" << inv_cond(m.topLeftCorner(3,3))   << endl;\n  cout << \"inv_cond(m+I):        \" << inv_cond(m+Matrix4f::Identity()) << endl;\n}\n", "meta": {"hexsha": "162a202e4dc258e07b04438c37416c9fa6db32da", "size": 594, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Eigen-3.3/doc/examples/function_taking_ref.cpp", "max_stars_repo_name": "shareq2005/CarND-MPC-Project", "max_stars_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3457.0, "max_stars_repo_stars_event_min_datetime": "2018-06-09T15:36:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-01T22:09:25.000Z", "max_issues_repo_path": "src/Eigen-3.3/doc/examples/function_taking_ref.cpp", "max_issues_repo_name": "shareq2005/CarND-MPC-Project", "max_issues_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 851.0, "max_issues_repo_issues_event_min_datetime": "2017-11-27T15:09:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:26:38.000Z", "max_forks_repo_path": "src/Eigen-3.3/doc/examples/function_taking_ref.cpp", "max_forks_repo_name": "shareq2005/CarND-MPC-Project", "max_forks_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1380.0, "max_forks_repo_forks_event_min_datetime": "2017-06-12T23:58:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:52:48.000Z", "avg_line_length": 29.7, "max_line_length": 79, "alphanum_fraction": 0.595959596, "num_tokens": 178, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787564, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.7467687096693619}}
{"text": "// FEM_2D_Plane_Stress.cpp (Main)\r\n\r\n#include \"pch.h\"\r\n#include \"FEM_Input.h\"\r\n#include \"FEM_GNUPlot.h\"\r\n#include <Eigen/Dense>\r\n#include <Eigen/Sparse>\r\n#include <string>\r\n#include <vector>\r\n#include <iostream>\r\n#include <fstream>\r\n\r\n//Element data type\r\nstruct Element\r\n{\r\n\tvoid CalculateStiffnessMatrix(const Eigen::Matrix3f& D, std::vector<Eigen::Triplet<float> >& triplets);\r\n\r\n\tEigen::Matrix<float, 3, 6> B;\r\n\tint nodesIds[3];\r\n};\r\n\r\n//Boundary constraint data type\r\nstruct Constraint\r\n{\r\n\tenum Type\r\n\t{\r\n\t\tUX = 1 << 0,\r\n\t\tUY = 1 << 1,\r\n\t\tUXY = UX | UY\r\n\t};\r\n\tint node;\r\n\tType type;\r\n};\r\n\r\n//Globals\r\nint\t\t\t\tnodesCount;\r\nEigen::VectorXf\t\t\tnodesX;\r\nEigen::VectorXf\t\t\tnodesY;\r\nEigen::VectorXf\t\t\tloads;\r\nstd::vector< Element >\t\telements;\r\nstd::vector< Constraint >\tconstraints;\r\n\r\n//Function for calculating the element stiffness matrix.\r\nvoid Element::CalculateStiffnessMatrix(const Eigen::Matrix3f& D, std::vector<Eigen::Triplet<float> >& triplets)\r\n{\r\n\tEigen::Vector3f x, y;\r\n\tx << nodesX[nodesIds[0]], nodesX[nodesIds[1]], nodesX[nodesIds[2]];\r\n\ty << nodesY[nodesIds[0]], nodesY[nodesIds[1]], nodesY[nodesIds[2]];\r\n\r\n\tEigen::Matrix3f C;\r\n\tC << Eigen::Vector3f(1.0f, 1.0f, 1.0f), x, y;\r\n\r\n\t//Calculating coefficients for shape functions (a1, a2, a3). \r\n\t//These are relevant for interpolation.\r\n\tEigen::Matrix3f IC = C.inverse();\r\n\r\n\t//Assemble B matrix\r\n\tfor (int i = 0; i < 3; i++)\r\n\t{\r\n\t\tB(0, 2 * i + 0) = IC(1, i);\r\n\t\tB(0, 2 * i + 1) = 0.0f;\r\n\t\tB(1, 2 * i + 0) = 0.0f;\r\n\t\tB(1, 2 * i + 1) = IC(2, i);\r\n\t\tB(2, 2 * i + 0) = IC(2, i);\r\n\t\tB(2, 2 * i + 1) = IC(1, i);\r\n\t}\r\n\r\n\t//Calculate element stiffness (det(C)/2 = area of triangle).\r\n\tEigen::Matrix<float, 6, 6> K = B.transpose() * D * B * C.determinant() / 2.0f;\r\n\r\n\t//Store values of element stiffness matrix with corresponding indices in global stiffness matrix in triplets.\r\n\tfor (int i = 0; i < 3; i++)\r\n\t{\r\n\t\tfor (int j = 0; j < 3; j++)\r\n\t\t{\r\n\t\t\tEigen::Triplet<float> trplt11(2 * nodesIds[i] + 0, 2 * nodesIds[j] + 0, K(2 * i + 0, 2 * j + 0));\r\n\t\t\tEigen::Triplet<float> trplt12(2 * nodesIds[i] + 0, 2 * nodesIds[j] + 1, K(2 * i + 0, 2 * j + 1));\r\n\t\t\tEigen::Triplet<float> trplt21(2 * nodesIds[i] + 1, 2 * nodesIds[j] + 0, K(2 * i + 1, 2 * j + 0));\r\n\t\t\tEigen::Triplet<float> trplt22(2 * nodesIds[i] + 1, 2 * nodesIds[j] + 1, K(2 * i + 1, 2 * j + 1));\r\n\r\n\t\t\ttriplets.push_back(trplt11);\r\n\t\t\ttriplets.push_back(trplt12);\r\n\t\t\ttriplets.push_back(trplt21);\r\n\t\t\ttriplets.push_back(trplt22);\r\n\t\t}\r\n\t}\r\n}\r\n\r\n//Function for setting constraints. \r\nvoid SetConstraints(Eigen::SparseMatrix<float>::InnerIterator& it, int index)\r\n{\r\n\tif (it.row() == index || it.col() == index)\r\n\t{\r\n\t\tit.valueRef() = it.row() == it.col() ? 1.0f : 0.0f;\r\n\t}\r\n}\r\n\r\n//Function for applying constraints in stiffness matrix.\r\nvoid ApplyConstraints(Eigen::SparseMatrix<float>& K, const std::vector<Constraint>& constraints)\r\n{\r\n\tstd::vector<int> indicesToConstraint;\r\n\r\n\tfor (std::vector<Constraint>::const_iterator it = constraints.begin(); it != constraints.end(); ++it)\r\n\t{\r\n\t\tif (it->type & Constraint::UX)\r\n\t\t{\r\n\t\t\tindicesToConstraint.push_back(2 * it->node + 0);\r\n\t\t}\r\n\t\tif (it->type & Constraint::UY)\r\n\t\t{\r\n\t\t\tindicesToConstraint.push_back(2 * it->node + 1);\r\n\t\t}\r\n\t}\r\n\r\n\tfor (int k = 0; k < K.outerSize(); ++k)\r\n\t{\r\n\t\tfor (Eigen::SparseMatrix<float>::InnerIterator it(K, k); it; ++it)\r\n\t\t{\r\n\t\t\tfor (std::vector<int>::iterator idit = indicesToConstraint.begin(); idit != indicesToConstraint.end(); ++idit)\r\n\t\t\t{\r\n\t\t\t\tSetConstraints(it, *idit);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nint main(void)\r\n{\r\n\tstd::cout << \"---------------------- 2D FEM SOLVER ---------------------\" << std::endl;\r\n\tstd::cout << \"FEM software for solving elastic 2D plain stress problems.\" << std::endl;\r\n\tstd::cout << \"Created by Joshua Simon. Date: 25.02.2019.\" << std::endl;\r\n\tstd::cout << std::endl;\r\n\r\n\r\n\t//1. Paths and filenames\r\n\tstring mesh_data_file;\t\t\t\t\t\t\t\t//This filename is read from user input.\r\n\tstring solver_input_file = \"Solver_Input.txt\";\r\n\tstring displacement_plot_data = \"GNUPlot_Input_displacement.txt\";\r\n\tstring stress_plot_data = \"GNUPlot_Input_contour.txt\";\r\n\t\r\n\t//User input of mesh data file\r\n\tstd::cout << \"Enter the filename of the GiD mesh data file. If the data file is \" << std::endl;\r\n\tstd::cout << \"not in same folder as this application, than enter the whole path \" << std::endl;\r\n\tstd::cout << \"of the mesh data file with filename. Use \\\\\\\\ for \\\\ in address. \" << std::endl;\r\n\tstd::cout << std::endl << \"Filename >> \";\r\n\tstd::cin >> mesh_data_file;\r\n\tstd::cout << std::endl << std::endl;\r\n\r\n\t//2. Pre Processing:\r\n\t//Read GiD mesh Data and write solver input.\r\n\tstd::cout << \"Pre Processor: Define boundary conditions and loads.\" << std::endl << std::endl;\r\n\tgenerateSolverInput(mesh_data_file, solver_input_file);\r\n\tstd::cout << \"Pre Processor: Solver input generated!\" << std::endl << std::endl;\r\n\r\n\tstd::ifstream infile(solver_input_file);\r\n\tstd::ofstream outfile(\"Solution_Data.txt\");\t\t\t\t\t//This file contains solution data.\r\n\tstd::ofstream outfile_gnuplot(displacement_plot_data);\t\t\t\t//This file contains plot data.\r\n\tstd::ofstream outfile_gnuplot_contur(stress_plot_data);\t\t\t\t//This file contains plot data.\r\n\r\n\t//3. Solution:\r\n\tstd::cout << \"Solver: Creating mathematical model...\" << std::endl;\r\n\r\n\t//Read material specifications\r\n\tfloat poissonRatio, youngModulus;\r\n\tinfile >> poissonRatio >> youngModulus;\r\n\r\n\t//Assemble elasticity matrix D\r\n\tEigen::Matrix3f D;\r\n\tD <<\r\n\t\t1.0f, poissonRatio, 0.0f,\r\n\t\tpoissonRatio, 1.0, 0.0f,\r\n\t\t0.0f, 0.0f, (1.0f - poissonRatio) / 2.0f;\r\n\r\n\tD *= youngModulus / (1.0f - pow(poissonRatio, 2.0f));\r\n\r\n\t//Read number of nodes and their coordinates\r\n\tinfile >> nodesCount;\r\n\tnodesX.resize(nodesCount);\r\n\tnodesY.resize(nodesCount);\r\n\r\n\tfor (int i = 0; i < nodesCount; ++i)\r\n\t{\r\n\t\tinfile >> nodesX[i] >> nodesY[i];\r\n\t}\r\n\r\n\t//Read number of elements and their nodes\r\n\tint elementCount;\r\n\tinfile >> elementCount;\r\n\r\n\tfor (int i = 0; i < elementCount; ++i)\r\n\t{\r\n\t\tElement element;\r\n\t\tinfile >> element.nodesIds[0] >> element.nodesIds[1] >> element.nodesIds[2];\r\n\t\telements.push_back(element);\r\n\t}\r\n\r\n\t//Read number of constraints and their node settings\r\n\tint constraintCount;\r\n\tinfile >> constraintCount;\r\n\r\n\tfor (int i = 0; i < constraintCount; ++i)\r\n\t{\r\n\t\tConstraint constraint;\r\n\t\tint type;\r\n\t\tinfile >> constraint.node >> type;\r\n\t\tconstraint.type = static_cast<Constraint::Type>(type);\r\n\t\tconstraints.push_back(constraint);\r\n\t}\r\n\r\n\tloads.resize(2 * nodesCount);\r\n\tloads.setZero();\r\n\r\n\t//Read number of nodal loads and nodal forces\r\n\tint loadsCount;\r\n\tinfile >> loadsCount;\r\n\r\n\tfor (int i = 0; i < loadsCount; ++i)\r\n\t{\r\n\t\tint node;\r\n\t\tfloat x, y;\r\n\t\tinfile >> node >> x >> y;\r\n\t\tloads[2 * node + 0] = x;\r\n\t\tloads[2 * node + 1] = y;\r\n\t}\r\n\r\n\t//Calculate stiffness matrix for each element\r\n\tstd::vector<Eigen::Triplet<float> > triplets;\r\n\tfor (std::vector<Element>::iterator it = elements.begin(); it != elements.end(); ++it)\r\n\t{\r\n\t\tit->CalculateStiffnessMatrix(D, triplets);\r\n\t}\r\n\r\n\t//Assemble global stiffness matirx\r\n\tEigen::SparseMatrix<float> globalK(2 * nodesCount, 2 * nodesCount);\r\n\tglobalK.setFromTriplets(triplets.begin(), triplets.end());\r\n\r\n\t//Apply Constraints\r\n\tApplyConstraints(globalK, constraints);\r\n\r\n\tstd::cout << \"Solver: Mathematical model created!\" << std::endl;\r\n\r\n\t//Solving\r\n\tstd::cout << \"Solver: Solving in progress...\" << std::endl;\r\n\tEigen::SimplicialLDLT<Eigen::SparseMatrix<float> > solver(globalK);\r\n\tEigen::VectorXf displacements = solver.solve(loads);\r\n\tstd::cout << \"Solver: Solving done!\" << std::endl << std::endl;\r\n\r\n\t//Writing output and display on console\r\n\t//std::cout << \"Loads vector:\" << std::endl << loads << std::endl << std::endl;\t\t\t//Loads\r\n\t//std::cout << \"Displacements vector:\" << std::endl << displacements << std::endl;\t\t//Displaysments\r\n\r\n\toutfile << displacements << std::endl;\r\n\r\n\t//std::cout << \"Stresses:\" << std::endl;\t\t\t\t\t\t\t//Von Mises Stress\r\n\r\n\tint m = 0;\r\n\tfloat sigma_max = 0.0;\r\n\tfloat *sigma_mises = new float[elementCount];\r\n\r\n\tfor (std::vector<Element>::iterator it = elements.begin(); it != elements.end(); ++it)\r\n\t{\r\n\t\tEigen::Matrix<float, 6, 1> delta;\r\n\t\tdelta << displacements.segment<2>(2 * it->nodesIds[0]),\r\n\t\t\tdisplacements.segment<2>(2 * it->nodesIds[1]),\r\n\t\t\tdisplacements.segment<2>(2 * it->nodesIds[2]);\r\n\r\n\t\tEigen::Vector3f sigma = D * it->B * delta;\r\n\t\tsigma_mises[m] = sqrt(sigma[0] * sigma[0] - sigma[0] * sigma[1] + sigma[1] * sigma[1] + 3.0f * sigma[2] * sigma[2]);\r\n\r\n\t\t//Search for maximum stress\r\n\t\tif (sigma_mises[m] > sigma_max) {\r\n\t\t\tsigma_max = sigma_mises[m];\r\n\t\t}\r\n\r\n\t\t//std::cout << sigma_mises[m] << std::endl;\t\t\t\t\t\t//Von Mises Stress\r\n\t\toutfile << sigma_mises[m] << std::endl;\r\n\r\n\t\tm++;\r\n\t}\r\n\r\n\t//4. Post Processing:\r\n\t//4.1 Writing GNUPlot output file for ploting mesh and mesh + displacements\r\n\tfor (std::vector<Element>::iterator it = elements.begin(); it != elements.end(); ++it)\r\n\t{\r\n\t\t//Prints x,y,dis-x,dis-y for every node of element in one line\r\n\t\tfor (int i = 0; i < 3; i++) {\r\n\t\t\toutfile_gnuplot << nodesX(it->nodesIds[i]) << \" \" << nodesY(it->nodesIds[i]) \\\r\n\t\t\t\t<< \" \" << displacements(it->nodesIds[i] * 2) << \" \" << displacements(it->nodesIds[i] * 2 + 1) << std::endl;\r\n\t\t}\r\n\t\t//First node of element has to appear twice for plotting purpose\r\n\t\toutfile_gnuplot << nodesX(it->nodesIds[0]) << \" \" << nodesY(it->nodesIds[0]) \\\r\n\t\t\t<< \" \" << displacements(it->nodesIds[0] * 2) << \" \" << displacements(it->nodesIds[0] * 2 + 1) << std::endl;\r\n\r\n\t\t//Empty line to sperate between elements\r\n\t\toutfile_gnuplot << std::endl;\r\n\t}\r\n\r\n\t//4.2 Writing GNUPlot output file for stress contour plot\r\n\toutfile_gnuplot_contur << \"unset xtics\" << std::endl;\r\n\toutfile_gnuplot_contur << \"unset ytics\" << std::endl;\r\n\toutfile_gnuplot_contur << \"set cbrange [0:1]\" << std::endl << std::endl;\r\n\toutfile_gnuplot_contur << \"plot[-15:15][-15:15] \\\\\" << std::endl;\r\n\r\n\t//Write color information for every element\r\n\tint mm = 0;\r\n\tfor (std::vector<Element>::iterator it = elements.begin(); it != (elements.end()-1); ++it) {\r\n\t\toutfile_gnuplot_contur << \"\\\"-\\\" title \\\"\\\" with filledcurve lt palette cb \" \\\r\n\t\t\t                   << sigma_mises[mm] / sigma_max << \" \\\\\" << std::endl;\r\n\t\toutfile_gnuplot_contur << \"fillstyle transparent solid 1.000000 ,\\\\\" << std::endl;\r\n\t\tmm++;\r\n\t}\r\n\r\n\t//Write color information for last element\r\n\toutfile_gnuplot_contur << \"\\\"-\\\" title \\\"\\\" with filledcurve lt palette cb \" \\\r\n\t\t\t\t\t\t   << sigma_mises[elementCount-1] / sigma_max << \" \\\\\" << std::endl;\r\n\toutfile_gnuplot_contur << \"fillstyle transparent solid 1.000000 ;\" << std::endl;\r\n\r\n\r\n\tfor (std::vector<Element>::iterator it = elements.begin(); it != elements.end(); ++it)\r\n\t{\r\n\t\t//Elements and their nodes:\r\n\t\t//Prints x,y for every node of element in one line\r\n\t\tfor (int i = 0; i < 3; i++) {\r\n\t\t\toutfile_gnuplot_contur << nodesX(it->nodesIds[i]) << \" \" << nodesY(it->nodesIds[i]) << std::endl;\r\n\t\t}\r\n\t\t//First node of element has to appear twice for plotting purpose\r\n\t\toutfile_gnuplot_contur << nodesX(it->nodesIds[0]) << \" \" << nodesY(it->nodesIds[0]) << std::endl;\r\n\r\n\t\t//'e' to sperate between elements\r\n\t\toutfile_gnuplot_contur << \"e\" << std::endl;\r\n\t}\r\n\r\n\tstd::cout << \"Post Processor: Plotting solution...\" << std::endl << std::endl;\r\n\r\n\t//4.3 Plot results\r\n\tplot(displacement_plot_data);\r\n\r\n\tdelete[] sigma_mises;\r\n\r\n\treturn 0;\r\n}\r\n", "meta": {"hexsha": "4323ae1e55c975972ce0e40f3dd94e4413e2ae15", "size": 11278, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "FEM_2D_Plane_Stress.cpp", "max_stars_repo_name": "JoshuaSimon/2D-FEM-Solver", "max_stars_repo_head_hexsha": "9f3c19b760350338a33445e9817e1c077f4718d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-03-27T12:45:51.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-25T09:41:56.000Z", "max_issues_repo_path": "FEM_2D_Plane_Stress.cpp", "max_issues_repo_name": "JoshuaSimon/2D-FEM-Solver", "max_issues_repo_head_hexsha": "9f3c19b760350338a33445e9817e1c077f4718d5", "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": "FEM_2D_Plane_Stress.cpp", "max_forks_repo_name": "JoshuaSimon/2D-FEM-Solver", "max_forks_repo_head_hexsha": "9f3c19b760350338a33445e9817e1c077f4718d5", "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.9766081871, "max_line_length": 119, "alphanum_fraction": 0.6288348998, "num_tokens": 3490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802395624259, "lm_q2_score": 0.8128673269042767, "lm_q1q2_score": 0.7466025771475088}}
{"text": "#include \"problemes.h\"\n#include \"arithmetique.h\"\n#include \"premiers.h\"\n\n#include <fstream>\n\n#include <boost/numeric/ublas/matrix.hpp>\n\ntypedef unsigned long long nombre;\ntypedef std::vector<nombre> vecteur;\n\nENREGISTRER_PROBLEME(214, \"Totient Chains\") {\n    // Let \u03c6 be Euler's totient function, i.e. for a natural number n, \u03c6(n) is the number of k, 1 \u2264 k \u2264 n, for which\n    // gcd(k,n) = 1.\n    // \n    // By iterating \u03c6, each positive integer generates a decreasing chain of numbers ending in 1.\n    // E.g. if we start with 5 the sequence 5,4,2,1 is generated.\n    // Here is a listing of all chains with length 4:\n    // \n    //                                      5,4,2,1\n    //                                      7,6,2,1\n    //                                      8,4,2,1\n    //                                      9,6,2,1\n    //                                      10,4,2,1\n    //                                      12,4,2,1\n    //                                      14,6,2,1\n    //                                      18,6,2,1\n    //\n    // Only two of these chains start with a prime, their sum is 12.\n    //\n    // What is the sum of all primes less than 40000000 which generate a chain of length 25?\n    nombre limite = 40000000;\n    nombre chaine = 25;\n    vecteur premiers;\n    premiers::crible235<nombre>(limite, std::back_inserter(premiers));\n\n    nombre resultat = 0;\n    for (nombre p: premiers) {\n        if (p >= limite)\n            break;\n\n        nombre longueur = 1;\n        nombre m = p;\n        while (m != 1 && longueur < chaine) {\n            m = arithmetique::phi(m, premiers);\n            ++longueur;\n        }\n\n        if (m == 1 && longueur == chaine)\n            resultat += p;\n    }\n\n    return std::to_string(resultat);\n}\n", "meta": {"hexsha": "8938169fbd0c56b82071d3dc3775377b9a77a749", "size": 1766, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problemes/probleme2xx/probleme214.cpp", "max_stars_repo_name": "ZongoForSpeed/ProjectEuler", "max_stars_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-10-13T17:07:21.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-08T11:50:22.000Z", "max_issues_repo_path": "problemes/probleme2xx/probleme214.cpp", "max_issues_repo_name": "ZongoForSpeed/ProjectEuler", "max_issues_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "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": "problemes/probleme2xx/probleme214.cpp", "max_forks_repo_name": "ZongoForSpeed/ProjectEuler", "max_forks_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "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.1090909091, "max_line_length": 116, "alphanum_fraction": 0.4847112118, "num_tokens": 477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465152482723, "lm_q2_score": 0.7981867873410141, "lm_q1q2_score": 0.7465812300566314}}
{"text": "#include \"rkintegrator.hpp\"\n#include <vector>\n#include <cassert>\n\n#include <iostream>\n#include <iomanip>\n\n#include <Eigen/Dense>\n\ntemplate <class Function>\nvoid errors(const Function &f, const double &T, const Eigen::VectorXd &y0, \n\tconst Eigen::MatrixXd &A, const Eigen::VectorXd &b){\n\t\tstd::vector<unsigned int> N = {1,2,4,8,16,32,64,128, 256, 512, 1024, 2048, 4096, 8192,16384,32768};\n\t\tunsigned int N_f=32768;\n\t\tdouble sum=0;\n\t\tdouble count =0;\n\t\tstd::vector<double> err_vect;\n\t\terr_vect.push_back(1.);\n\t\tRKIntegrator<Eigen::VectorXd> RK(A,b);\n\t\tauto y_f=RK.solve(f,T,y0,N_f);\n\t\tfor(unsigned int i = 0; i < N.size(); ++i){\n\t\t\tauto temp = RK.solve(f,T,y0,N[i]);\n\t\t\tdouble err= (temp.back()-y_f.back()).norm();\n\t\t\tdouble order = log2(err_vect.back()/err);\n\t\t\torder= std::abs(order);\n\t\t\tstd::cout << \"n = \" << N[i] << std::setw(15)  << \"error = \" << err << std::setw(15)<< \"order is : \" << order<< std::endl;\n\t\t\terr_vect.push_back(err);\n\t\t\tif(i>1 && err>1e-16){\n\t\t\t\tsum+=order; count+=1;\n\t\t\t}\n\t\t}\n\nstd::cout << \" average order : \" <<sum/count  << std::endl;\n\n};\n", "meta": {"hexsha": "a6792e1f4e8572481fa78595d622921f98786bd0", "size": 1063, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/PS12/order.hpp", "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/PS12/order.hpp", "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/PS12/order.hpp", "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.5277777778, "max_line_length": 124, "alphanum_fraction": 0.6208842897, "num_tokens": 354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.74648408143389}}
{"text": "#include <iostream>\n#include <functional>\n#include <armadillo>\n#include <string>\n\n// include code from b.cc (except main function)\n#define NO_MAIN\n#include \"b.cc\"\n#undef NO_MAIN\n\nusing namespace std;\nusing namespace arma;\n\nconst std::string CHECK_MARK = \"\u2713\";\nconst std::string BALLOT_X = \"\u2717\";\n\nstruct test { std::function<bool()> func; std::string name; };\n\nconst double TOLERANCE = 1e-13;\n\n/**\n * Test maxoff() on a symmetric matrix\n**/\nbool test_maxoff_sym() {\n  // create known symmetric matrix\n  mat M(5, 5, arma::fill::zeros);\n\n  M(0,0) = 3;\n  M(1,1) = 9;\n  M(2,2) = 17;\n  M(3,3) = 0;\n  M(4,4) = -9;\n  M(2,0) = M(0,2) = 9;\n  M(2,1) = M(1,2) = -5;\n  M(3,0) = M(0,3) = -11;\n  M(3,1) = M(1,3) = 10;\n  M(3,2) = M(2,3) = -7;\n  M(4,0) = M(0,4) = 5;\n\n  // expected values\n  size_t exp_k = 3, exp_l = 0; // maximal element position\n  double exp_a = 121;          // square of maximal element\n\n  // find maximal element\n  size_t k, l;\n  double a = maxoff(M, k, l);\n\n  // compare (up to order of k and l, since M is symmetric)\n  return (abs(a - exp_a) < TOLERANCE && ((k == exp_k && l == exp_l) || (k == exp_l && l == exp_k)));\n}\n\n/**\n * Check that jacobi_step() conserves orthonormality of S.\n**/\nbool test_ortho() {\n  // if a matrix preserves scalar product (or orthonormality) then it must be an orthogonal matrix,\n  // so S * S^T = I\n\n  // set of random, pre-calculated tau, k and l values (where k != l)\n  const double tau_values[] = { 0.5 };\n  const double kl_values[][2] = { { 1, 2 } };\n  const size_t count = 1;\n\n  // initial P matrix (identity) and constant identity matrix I\n  mat P(5, 5, arma::fill::eye);\n  const mat I(5, 5, arma::fill::eye);\n\n  // for each step, P' = P * S where S is calculated from a random tau value (see above list)\n  for(size_t i = 0; i < count; i++) {\n    apply_rot_col(kl_values[i][0], kl_values[i][1], tau_values[i], P);\n\n    // check that P * P^T = I, within tolerance\n    if(arma::abs(P * P.t() - I).max() >= TOLERANCE)\n      return false;\n  }\n\n  // for each step, P' = S^T * P where S is calculated from a random tau value (see above list)\n  for(size_t i = 0; i < count; i++) {\n    apply_rot_row(kl_values[i][0], kl_values[i][1], tau_values[i], P);\n\n    // check that P * P^T = I, within tolerance\n    if(arma::abs(P * P.t() - I).max() >= TOLERANCE)\n      return false;\n  }\n\n  return true;\n}\n\nint main() {\n  // define tests\n  const struct test tests[] = {\n    { test_maxoff_sym, \"Maximal diagonal test on symmetric matrix\" },\n    { test_ortho, \"Orthonormality test\" },\n  };\n  const size_t test_count = 2;\n\n  // run tests\n  std::cout << \"Running tests:\" << std::endl;\n  for(size_t i = 0; i < test_count; i++) {\n    auto test = tests[i];\n\n    std::cout << \"  \" << test.name << std::endl;\n\n    if(test.func()) {\n      std::cout << \"    \" << CHECK_MARK << \" test passed\" << std::endl;\n    } else {\n      std::cout << \"    \" << BALLOT_X << \" test failed\" << std::endl;\n    }\n  }\n}\n", "meta": {"hexsha": "90a75352b9dae0c80fa059c4aae596420f8eb9b8", "size": 2912, "ext": "cc", "lang": "C++", "max_stars_repo_path": "project2/code-fredrik/b.test.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.test.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.test.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": 26.2342342342, "max_line_length": 100, "alphanum_fraction": 0.5841346154, "num_tokens": 987, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772253241802, "lm_q2_score": 0.8539127566694178, "lm_q1q2_score": 0.7463856930185265}}
{"text": "#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <iostream>\n\nEigen::Matrix3d OthMatrix(const Eigen::Matrix3d& input) {\n    Eigen::Quaterniond q(input);\n    q.normalize();\n    return q.toRotationMatrix();\n}\n\n// \u89e3\u51b3\u5982\u4e0b\u95ee\u9898\n// 1. \u4e07\u5411\u9501\u65f6\uff0c\u5206\u89e3\u6b27\u62c9\u89d2\u662f\u5426\u4ecd\u7136\u6709\u6548\n// 2. \u4e07\u5411\u9501\u53cd\u5e94\u4e86\u4e00\u4e2a\u4ec0\u4e48\u6837\u7684\u95ee\u9898\uff1f\nint main(int argv, char** argc) {\n    double theta_z = M_PI * 60 / 180;\n    double theta_y = M_PI * 30 / 180;\n    double theta_x = M_PI * 40 / 180;\n    Eigen::Matrix3d rz =\n        Eigen::AngleAxisd(theta_z, Eigen::Vector3d::UnitZ()).toRotationMatrix();\n    Eigen::Matrix3d ry =\n        Eigen::AngleAxisd(theta_y, Eigen::Vector3d::UnitY()).toRotationMatrix();\n    Eigen::Matrix3d rx =\n        Eigen::AngleAxisd(theta_x, Eigen::Vector3d::UnitX()).toRotationMatrix();\n\n    // 1 \u6ca1\u6709\u4e07\u5411\u9501\n    Eigen::Matrix3d composition = rz * ry * rx;\n    composition = OthMatrix(composition);\n    Eigen::Vector3d euler_angles = composition.eulerAngles(2, 1, 0);\n    std::cout << \"\u6b63\u5e38\u60c5\u51b5:\\n\";\n    std::cout << euler_angles.transpose() * 180 / M_PI << std::endl;\n\n    // 2 \u5c06y\u6539\u4e3a90\u5ea6\uff0c\u89c2\u5bdf\u4e07\u5411\u9501\u65f6\u7684\u5206\u89e3\u7ed3\u679c\n    theta_y = M_PI * 90 / 180;\n    ry =\n        Eigen::AngleAxisd(theta_y, Eigen::Vector3d::UnitY()).toRotationMatrix();\n    composition = rz * ry * rx;\n    composition = OthMatrix(composition);\n    std::cout << \"\u4e07\u5411\u9501\u5bf9\u5e94\u7684\u5206\u89e3:\\n\";\n    std::cout << composition << std::endl;\n    euler_angles = composition.eulerAngles(2, 1, 0);\n    std::cout << \"eular angles :\\n\";\n    std::cout << euler_angles.transpose() * 180 / M_PI << std::endl;\n\n    // 3 x\u7528\u5408\u6210\u89d2\u5ea6\n    theta_x = (40 - 60) * M_PI / 180;\n    rx =\n        Eigen::AngleAxisd(theta_x, Eigen::Vector3d::UnitX()).toRotationMatrix();\n    Eigen::Matrix3d composition_yx = ry * rx;\n    composition_yx = OthMatrix(composition_yx);\n\n    std::cout << \"\\n\u8003\u8651\u4e07\u5411\u9501\u4e22\u5931\u4e86\u8f74\uff0c\u4ec5\u7528\u4e24\u4e2a\u8f74\u5f97\u5230\u65cb\u8f6c\u77e9\u9635\uff0c\u5e76\u8fdb\u884c\u5206\u89e3\\n\";\n    std::cout << composition_yx << std::endl;\n    euler_angles = composition_yx.eulerAngles(2, 1, 0);\n    std::cout << \"eular angles :\\n\";\n    std::cout << euler_angles.transpose() * 180 / M_PI << std::endl;\n\n    // 4 \u4f7f\u7528\n    double diff = (composition_yx - composition).norm();\n    std::cout << \"difference between zyx and yx: \" << diff << std::endl;\n}", "meta": {"hexsha": "dc176adfeb743b3467322184931a4f1dc0017ce2", "size": 2134, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/space_transform/euler_composition.cpp", "max_stars_repo_name": "sliding-window/algorithm-practice", "max_stars_repo_head_hexsha": "c70fd954423372cebbfd9dee368058a85e43a292", "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/space_transform/euler_composition.cpp", "max_issues_repo_name": "sliding-window/algorithm-practice", "max_issues_repo_head_hexsha": "c70fd954423372cebbfd9dee368058a85e43a292", "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/space_transform/euler_composition.cpp", "max_forks_repo_name": "sliding-window/algorithm-practice", "max_forks_repo_head_hexsha": "c70fd954423372cebbfd9dee368058a85e43a292", "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.9836065574, "max_line_length": 80, "alphanum_fraction": 0.6354264292, "num_tokens": 728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896693699844, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.7462806000232137}}
{"text": "#include \"writer.hpp\"\n#include <Eigen/Sparse>\n#include <Eigen/SparseCholesky>\n#include <cmath>\n#include <iostream>\n#include <stdexcept>\n\n//! Sparse Matrix type. Makes using this type easier.\ntypedef Eigen::SparseMatrix<double> SparseMatrix;\n\n//! Used for filling the sparse matrix.\ntypedef Eigen::Triplet<double> Triplet;\n\n//! Vector type\ntypedef Eigen::VectorXd Vector;\n\ntypedef double (*FunctionPointer)(double);\n\n//----------------poissonBegin----------------\n//! Create the 1D Poisson matrix\n//! @param[out] A will contain the Poisson matrix\n//! @param[in] N the number of points\nvoid createPoissonMatrix(SparseMatrix &A, int N) {\n\tA.resize(N, N);\n\tstd::vector<Triplet> triplets;\n\ttriplets.reserve(N + 2 * N - 2);\n\tfor (int i = 0; i < N; ++i) {\n\t\t// This is the diagonal\n\t\ttriplets.push_back(Triplet(i, i, 2));\n\n\t\t// (write your solution here)\n\t\tif (i > 0) {\n\t\t\ttriplets.push_back(Triplet(i - 1, i, -1));\n\t\t}\n\t\tif (i < N - 1) {\n\t\t\ttriplets.push_back(Triplet(i + 1, i, -1));\n\t\t}\n\t}\n\n\tA.setFromTriplets(triplets.begin(), triplets.end());\n}\n//----------------poissonEnd----------------\n\n//----------------RHSBegin----------------\n//! Create the right hand side for the poisson problem.\n//! @note This scales the right hand side (ie. $dx^2 * f(x)$)\n//!\n//! @param[out] rhs will contain the right hand side\n//! @param[in] f function pointer to f\n//! @param[in] N the number of points to use\n//! @param[in] dx the cell length\nvoid createRHS(Vector &rhs, FunctionPointer f, int N, double dx) {\n\trhs.resize(N);\n\t// Set RHS\n\t// (write your solution here)\n\tfor (int i = 0; i < N; i++) {\n\t\trhs[i] = dx * dx * f(i * dx);\n\t}\n}\n//----------------RHSEnd----------------\n\n//! Solves the Poisson equation\n//!\n//!   $-u''(x) = f(x) $\n//!\n//! on [0,1] with boundary values $u(0)=u(1) = 0$.\n//!\n//! @param[out] u should contain the solution u at the end\n//! @param[in] f should be a function pointer to f\n//! @param[in] N as in the exercise\nvoid poissonSolve(Vector &u, FunctionPointer f, int N) {\n\tdouble dx = 1.0 / (N + 1);\n\n\tSparseMatrix A;\n\t// create the matrix\n\t// (write your solution here)\n\tcreatePoissonMatrix(A, N);\n\tVector rhs;\n\n\t// create RHS\n\t// (write your solution here)\n\tcreateRHS(rhs, f, N, dx);\n\n\tEigen::SparseLU<SparseMatrix> solver;\n\n\tsolver.compute(A);\n\n\tif (solver.info() != Eigen::Success) {\n\t\tthrow std::runtime_error(\"Could not decompose the matrix\");\n\t}\n\n\t// Find u: ....\n\t// (write your solution here)\n\tu.resize(N);\n\tu.setZero();\n\tu = solver.solve(rhs);\n}\n\ndouble F(double x) {\n\treturn sin(2 * M_PI * x);\n}\n\ndouble exact(double x) {\n\treturn 1.0 / (4 * M_PI * M_PI) * F(x);\n}\n\n//! Test if the Poisson matrix is correctly set up for one case\n//! This does NOT guarantee that the code is correct, it is only a small\n//! indiciation\nvoid testPoissonMatrix() {\n\tSparseMatrix A;\n\tconst int    N = 13;\n\tcreatePoissonMatrix(A, N);\n\tfor (int i = 0; i < N; ++i) {\n\t\tfor (int j = 0; j < N; j++) {\n\t\t\tif (i == j) {\n\t\t\t\tif (A.coeff(i, j) != 2) {\n\t\t\t\t\tthrow std::runtime_error(\"Poisson matrix: Wrong Poisson matrix!\");\n\t\t\t\t}\n\t\t\t} else if (i == j - 1 || i == j + 1) {\n\t\t\t\tif (A.coeff(i, j) != -1) {\n\t\t\t\t\tthrow std::runtime_error(\"Poisson matrix: Wrong upper or lower diagonal\");\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (A.coeff(i, j) != 0) {\n\t\t\t\t\tthrow std::runtime_error(\"Poisson matrix: Matrix is not band diagonal!\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n//----------------convergenceBegin----------------\n//! Computes error for a range of cell lengths and stores them to errors\n//! @param[out] errors the errors computed\n//! @param[out] resolutions the resolutions used\nvoid poissonConvergence(std::vector<double> &errors,\n                        std::vector<int> &   resolutions) {\n\tconst int startK = 2;\n\tconst int endK   = 13;\n\terrors.resize(endK - startK);\n\tresolutions.resize(errors.size());\n\tfor (int k = startK; k < endK; ++k) {\n\t\tconst int N = 1 << (k - 1);\n\t\t// compute the solution and the error\n\t\t// (write your solution here)\n\t\tresolutions[k - startK] = N;\n\t\tVector u;\n\t\tpoissonSolve(u, F, N);\n\t\tdouble error = 0;\n\t\tfor (int i = 0; i < N; i++) {\n\t\t\tdouble e = abs(u[i] - exact(i / double(N)));\n\t\t\tif (e > error) {\n\t\t\t\terror = e;\n\t\t\t}\n\t\t}\n\t\terrors[k - startK] = error;\n\t}\n}\n//----------------convergenceEnd----------------\n\nint main(int, char **) {\n\ttestPoissonMatrix();\n\tVector u;\n\tpoissonSolve(u, F, 50);\n\twriteToFile(\"u_fd.txt\", u);\n\n\tstd::vector<double> errors;\n\tstd::vector<int>    resolutions;\n\tpoissonConvergence(errors, resolutions);\n\twriteToFile(\"errors_fd.txt\", errors);\n\twriteToFile(\"resolutions_fd.txt\", resolutions);\n}\n", "meta": {"hexsha": "b523f8d24527562aaf1599c35f0a023a4ed25ad7", "size": 4511, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "series1/1d-FD/finite_difference.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": "series1/1d-FD/finite_difference.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": "series1/1d-FD/finite_difference.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": 25.9252873563, "max_line_length": 79, "alphanum_fraction": 0.6054090002, "num_tokens": 1341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.926303728259492, "lm_q2_score": 0.8056321959813275, "lm_q1q2_score": 0.7462601067433854}}
{"text": "#include <utils/math_utils.hh>\n\n#include <utils/debug_utils.hh>\n\n#include <Eigen/Eigenvalues>\n\nnamespace math \n{\n\nbool is_equal(const Eigen::MatrixXd &mat1, const Eigen::MatrixXd &mat2, const double tol)\n{\n    IS_EQUAL(mat1.rows(), mat2.rows());\n    IS_EQUAL(mat1.cols(), mat2.cols());\n    return ((mat1 - mat2).array().abs() < tol).all();\n}\n\nbool is_symmetric(const Eigen::MatrixXd &mat, const double tol)\n{\n    IS_EQUAL(mat.rows(), mat.cols());\n    return math::is_equal(mat, mat.transpose(), tol);\n}\n\nEigen::VectorXd gradient(\n        const std::function<double(const Eigen::VectorXd&)> &func, \n        const Eigen::VectorXd &pt, const double delta)\n{\n    IS_GREATER(delta, 0);\n\n    const int dim = pt.size();\n    IS_GREATER(dim, 0);\n\n    Eigen::VectorXd gradient(dim);\n\n    for (int i = 0; i < dim; ++i)\n    {\n        Eigen::VectorXd pt_positive = pt;\n        pt_positive[i] += delta;\n\n        Eigen::VectorXd pt_negative = pt;\n        pt_negative[i] -= delta;\n\n        gradient(i) = (func(pt_positive) - func(pt_negative)) / (2.0 * delta);\n    }\n\n    return gradient;\n}\n\nEigen::MatrixXd jacobian(\n        const std::function<Eigen::VectorXd(const Eigen::VectorXd&)> &func, \n        const Eigen::VectorXd &pt, const double delta)\n{\n    IS_TRUE(func);\n    IS_GREATER(delta, 0);\n\n    const int in_dim = pt.size();\n    IS_GREATER(in_dim, 0);\n\n    const int out_dim = func(pt).size();\n    IS_GREATER(out_dim, 0);\n\n    Eigen::MatrixXd jacobian(out_dim, in_dim);\n\n    for (int i = 0; i < in_dim; ++i)\n    {\n        Eigen::VectorXd pt_positive = pt;\n        pt_positive[i] += delta;\n\n        Eigen::VectorXd pt_negative = pt;\n        pt_negative[i] -= delta;\n\n        jacobian.col(i) = (func(pt_positive) - func(pt_negative)) / (2.0 * delta);\n    }\n\n    return jacobian;\n}\n\nEigen::MatrixXd hessian(\n        const std::function<double(const Eigen::VectorXd&)> &func, \n        const Eigen::VectorXd &pt, const double delta)\n{\n    IS_GREATER(delta, 0);\n    const int dim = pt.size();\n    IS_GREATER(dim, 0);\n\n    // Precompute constants.\n    const double two_delta = 2.0*delta;\n    const double delta_sq = delta*delta;\n    const double ij_eq_div = 12.*delta_sq;\n    const double ij_neq_div = 4.*delta_sq;\n    \n    Eigen::MatrixXd hessian(dim, dim);\n    // Central difference approximation based on \n    // https://v8doc.sas.com/sashtml/ormp/chap5/sect28.htm\n    for (int i = 0; i < dim; ++i)\n    {\n        for (int j = i; j < dim; ++j)\n        {\n            Eigen::VectorXd p1 = pt;\n            Eigen::VectorXd p2 = pt;\n            Eigen::VectorXd p3 = pt;\n            Eigen::VectorXd p4 = pt;\n            double value = 0;\n            if (i == j)\n            {\n                p1[i] += two_delta; \n                p2[i] += delta;\n                p3[i] -= delta;\n                p4[i] -= two_delta;\n                value = (-func(p1) + 16.*(func(p2) + func(p3)) - 30.*func(pt) - func(p4)) \n                    / (ij_eq_div);\n            } \n            else\n            {\n                p1[i] += delta;\n                p1[j] += delta;\n\n                p2[i] += delta;\n                p2[j] -= delta;\n\n                p3[i] -= delta;\n                p3[j] += delta;\n\n                p4[i] -= delta;\n                p4[j] -= delta;\n\n                value = (func(p1) - func(p2) - func(p3) + func(p4)) / (ij_neq_div);\n            }\n\n            hessian(i,j) = value;\n            hessian(j,i) = value;\n        }\n    }\n\n    return hessian;\n}\n\nEigen::MatrixXd project_to_psd(const Eigen::MatrixXd &symmetric_mat, const double min_eigval)\n{\n    // Cheap check to confirm matrix is square.\n    IS_EQUAL(symmetric_mat.rows(), symmetric_mat.cols());\n\n    // O(n^2) check to make sure that the matrix is symmetric.\n    IS_TRUE(math::is_symmetric(symmetric_mat));\n\n    const Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(symmetric_mat);\n    Eigen::MatrixXd evals = es.eigenvalues().asDiagonal();\n    const Eigen::MatrixXd evecs = es.eigenvectors();\n\n    // Indices of eigen values that are less than the minimum eigenvalue threshold.\n    int num_failed_evals = 0;\n    const int num_evals = evals.rows();\n    for (int i = 0; i < num_evals; ++i)\n    {\n        if (evals(i,i) < min_eigval)\n        {\n            ++num_failed_evals;\n            evals(i,i) = min_eigval;\n        }\n    }\n    // If we didn't have eigenvalues less than the minimum threshold, then return the original\n    // matrix.\n    if (num_failed_evals == 0)\n    {\n        return symmetric_mat;\n    }\n\n    // We can reconstruct with P D P\\inv = P D P^T if P is orthonormal.\n    const Eigen::MatrixXd projection = evecs * evals * evecs.transpose() ;\n    return projection;\n}\n\nvoid check_psd(const Eigen::MatrixXd &mat, const double min_eigval)\n{\n    // Cheap check to confirm matrix is square.\n    IS_EQUAL(mat.rows(), mat.cols());\n\n    // O(n^2) check to make sure that the matrix is symmetric.\n    IS_TRUE(math::is_symmetric(mat));\n\n    const Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(mat, Eigen::EigenvaluesOnly);\n    const auto evals = es.eigenvalues();\n\n    for (int i = 0; i < evals.size(); ++i)\n    {\n        // Throw an exception if this is not true.\n        IS_GREATER_EQUAL(evals(i), min_eigval);\n    }\n}\n\n} // namespace math \n", "meta": {"hexsha": "874c2a26be4e0387b3ad8ab955a188d926e72871", "size": 5194, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/utils/math_utils.cc", "max_stars_repo_name": "LAIRLAB/qr_trees", "max_stars_repo_head_hexsha": "66eb7310daa1d9978158198a508d02bf2128a377", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-16T08:42:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-16T08:42:33.000Z", "max_issues_repo_path": "src/utils/math_utils.cc", "max_issues_repo_name": "LAIRLAB/qr_trees", "max_issues_repo_head_hexsha": "66eb7310daa1d9978158198a508d02bf2128a377", "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/utils/math_utils.cc", "max_forks_repo_name": "LAIRLAB/qr_trees", "max_forks_repo_head_hexsha": "66eb7310daa1d9978158198a508d02bf2128a377", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-07-10T03:25:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-22T15:58:44.000Z", "avg_line_length": 27.1937172775, "max_line_length": 94, "alphanum_fraction": 0.5714285714, "num_tokens": 1386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037221561136, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.7462600931807166}}
{"text": "/** \n * Write a function 'filter()' that implements a multi-\n *   dimensional Kalman Filter for the example given\n */\n\n#include <iostream>\n#include <vector>\n#include <Eigen/Dense>\n#include <cmath>\n\nusing std::cout;\nusing std::endl;\nusing std::vector;\nusing Eigen::VectorXd;\nusing Eigen::MatrixXd;\n\n// Kalman Filter variables\nVectorXd x;\t// object state\nMatrixXd P;\t// object covariance matrix\nVectorXd u;\t// external motion\nMatrixXd F; // state transition matrix\nMatrixXd H;\t// measurement matrix\nMatrixXd R;\t// measurement covariance matrix\nMatrixXd S;    //used in creation of Kalman Gain??  Why named S?\nMatrixXd K;   //Kalman Gain Matrix\nMatrixXd Y;  //measurment matrix\nMatrixXd C;  //C matrix\nMatrixXd I; // Identity matrix\nMatrixXd Q;\t// process covariance matrix\nMatrixXd B; //B matrix \n\nvoid update_prediction(VectorXd &x);\nvoid initial_process_cov_matrix();\nvoid update_predicted_process_cov_matrix();\nvoid calculate_Kalman_gain();\nvoid import_new_observation(int speed, int velocity);\nvoid update_current_state();\nvoid update_process_cov_matrix();\n\nint main() {\n  /**\n   * Code used as example to work with Eigen matrices\n  */\n\n  float dt = 1.;\n\n  // design the KF with 1D motion\n  x = VectorXd(2);\n  x << 4000, 280;\n  P = MatrixXd(2, 2);\n\n  u = VectorXd(1);\n  u << 2;\n\n  F = MatrixXd(2, 2);\n  F << 1, dt, 0, 1;\n\n//  H = MatrixXd(1, 2);\n//  H << 1, 0;\n  H = MatrixXd::Identity(2,2);\n\n  R = MatrixXd(2, 2);\n  R << 625, 0, 0, 36;\n\n  S = MatrixXd(2,2);\n  S << 0, 0, 0, 0;\n\n  K = MatrixXd(2,2);\n\n  C = MatrixXd::Identity(2, 2);\n\n  B = MatrixXd(2,1);\n  B << .5*pow(dt,2), dt;\n\n  Y = MatrixXd(2,1);\n\n  I = MatrixXd::Identity(2, 2);\n\n  Q = MatrixXd(2, 2);\n  Q << 0, 0, 0, 0;\n  \n  // create a list of measurements\n  VectorXd pos_measurements(4);\n  pos_measurements << 4260, 4550, 4860, 5110;\n\n  VectorXd vel_measurements(4);\n  vel_measurements << 282, 285, 286, 290;\n    \n  initial_process_cov_matrix();\n  // call Kalman filter algorithm for each measurement (1Hz)\n\n  for (unsigned int n = 0; n < 4; ++n) {\n    cout << \"********** N: \" << n << endl;\n    update_prediction(x);\n    update_predicted_process_cov_matrix();\n    calculate_Kalman_gain();\n    import_new_observation(pos_measurements[n], vel_measurements[n]);\n    update_current_state();\n    update_process_cov_matrix();\n  }\n\n  return 0;\n}\n\nvoid initial_process_cov_matrix() {\n  cout << \"Initial_process_cov_matrix\" << endl;\n  P << 400, 0, 0, 25;\n  cout << P << endl;\n}\n\nvoid update_prediction(VectorXd &x) {\n  cout << \"update_prediction\" << endl;\n  x = (F * x) + (B * u);\n  cout << x << endl;\n}\n\nvoid update_predicted_process_cov_matrix() {\n  cout << \"update_predicted_process_cov_matrix\" << endl;\n  P = (F * P) * F.transpose() + Q;\n  P(0,1) = 0;\n  P(1,0) = 0;\n\n  cout << \"P after update: \" << P << endl;\n\n}\n\nvoid calculate_Kalman_gain() {\n    cout << \"calculate_Kalman_gain\" << endl;\n    S = R + (H * (P * H.transpose()));\n    K = (P * H.transpose()) * S.inverse();\n    cout << \"Kalman gain matrix: \" << K << endl;\n}\n\nvoid import_new_observation(int speed, int velocity) {\n    MatrixXd measurement = MatrixXd(2, 1);\n    measurement << speed, velocity;\n    cout << \"measurement: \"<<  measurement  << endl;\n    Y  = C * measurement;\n    cout << \"Y: \" << Y << endl;\n}\n\nvoid update_current_state() {\n  cout << \"x: \" << x << endl;\n  cout << \"H: \" << H << endl;\n  cout << \"Y: \" << Y << endl;\n\n  MatrixXd delta = Y - (H * x);\n  cout << \"delta: \" << delta << endl;\n\n  x = x + (K * delta);\n  cout << \"adjusted x: \" << x << endl;\n}\n\n\nvoid update_process_cov_matrix() {\n\n    MatrixXd I = MatrixXd::Identity(2, 2);\n  \n    P = P * (I - (K * H)) * (I - (K * H)).transpose() + (K * R) * K.transpose();\n\n   cout << \"Updated Process Covariance Matrix: \" << P << endl;\n\n}\n", "meta": {"hexsha": "373c3ec8dcc3266e65d346c313e104ef48ee117c", "size": 3717, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Kalman-Tutorial.cpp", "max_stars_repo_name": "alejandroterrazas/Kalman-Tutorial", "max_stars_repo_head_hexsha": "025e3ce303d2745dca7568bb378c3278a6f35d46", "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": "Kalman-Tutorial.cpp", "max_issues_repo_name": "alejandroterrazas/Kalman-Tutorial", "max_issues_repo_head_hexsha": "025e3ce303d2745dca7568bb378c3278a6f35d46", "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": "Kalman-Tutorial.cpp", "max_forks_repo_name": "alejandroterrazas/Kalman-Tutorial", "max_forks_repo_head_hexsha": "025e3ce303d2745dca7568bb378c3278a6f35d46", "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.6646341463, "max_line_length": 80, "alphanum_fraction": 0.6182405165, "num_tokens": 1154, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342024724487, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.7461678811763439}}
{"text": "/**\n * @file Utils.cpp\n *\n * Fichier d'impl\u00e9mentation pour la calculation math\u00e9matique\n */\n\n#include <iostream>\n#include <armadillo>\n#include \"Solution1DHO.h\"\n#include \"Utils.h\"\n\n\n/** Calcul de la factorielle de n\n*\n* Cette fonction a pour but de calculer la factorielle de n par r\u00e9currence.\n*\n* @param n entier\n*\n* @return le r\u00e9sultat de la factorielle de n\n*/\nint Utils::fac(int n)\n{\n    int f;\n\n    if (n==0 || n==1)\n        f=1;\n    else\n        f=fac(n-1)*n;\n\n    return f;\n}\n\n/**\n * Calcul de d\u00e9riv\u00e9e\n *\n * Cette fonction a pour but d'approximer la d\u00e9riv\u00e9e du premier ordre\n *\n * @param F1 vecteur contenant les n valeurs d'une fonction\n * @param F2 vecteur contenant les n valeurs d'une fonction d\u00e9cal\u00e9e d'une valeur\n * @param Z1 vecteur contenant les n points o\u00f9 sont \u00e9valu\u00e9e la fonction\n * @param Z2 vecteur contenant les n points o\u00f9 sont \u00e9valu\u00e9e la fonction d\u00e9cal\u00e9e d'une valeur\n *\n * @return res vecteur contenant les valeurs de la fonction d\u00e9riv\u00e9e\n */\narma::mat Utils::derivative(arma::mat F1, arma::mat F2, arma::mat Z1, arma::mat Z2)\n{\n    arma::mat res = (F2-F1)/(Z2-Z1);\n    return res;\n}\n\n", "meta": {"hexsha": "17031862aa4fd598cf018e8094ffe1eabcc3a0fe", "size": 1106, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Utils.cpp", "max_stars_repo_name": "DinghaoLI/SchrodingerEquation", "max_stars_repo_head_hexsha": "1dc139b5ca33506e28de7e4a9c966e86f3c2078b", "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/Utils.cpp", "max_issues_repo_name": "DinghaoLI/SchrodingerEquation", "max_issues_repo_head_hexsha": "1dc139b5ca33506e28de7e4a9c966e86f3c2078b", "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/Utils.cpp", "max_forks_repo_name": "DinghaoLI/SchrodingerEquation", "max_forks_repo_head_hexsha": "1dc139b5ca33506e28de7e4a9c966e86f3c2078b", "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.6862745098, "max_line_length": 92, "alphanum_fraction": 0.6772151899, "num_tokens": 336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070084811307, "lm_q2_score": 0.8198933271118222, "lm_q1q2_score": 0.7460266845459592}}
{"text": "#include <iostream>\n#include <cmath>\nusing namespace std;\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include \"sophus/so3.h\"\n#include \"sophus/se3.h\"\n\nint main(int argc, char** argv) {\n    //rotate 90 along the Z axis\n    Eigen::Matrix3d R=Eigen::AngleAxisd(M_PI/2, Eigen::Vector3d(0,0,1)).toRotationMatrix();\n    Sophus::SO3 SO3_R(R);  //from the matrix\n    Sophus::SO3 SO3_v(0,0,M_PI/2);  //from the vector\n    Sophus::Quaterniond q(R);  //from the quaternion\n\n    cout<<\"SO(3) from matrix: \"<<SO3_R<<endl;\n    cout<<\"SO(3) from vector: \"<<SO3_R<<endl;\n    cout<<\"SO(3) from quaternion: \"<<SO3_R<<endl;\n\n    Eigen::Vector3d so3 = SO3_R.log();\n    cout<<\"so3 = \"<<so3.transpose()<<endl;\n    cout<<\"so3 hat\"<<Sophus::SO3::hat(so3)<<endl; //hat:vector->matrix\n    cout<<\"so3 hat vee\"<<Sophus::SO3::vee(Sophus::SO3::hat(so3)).transpose()<<endl; //vee:matrix->vector\n\n    //BCH\n    Eigen::Vector3d update_so3(1e-4,0,0);\n    Sophus::SO3 SO3_updated = Sophus::SO3::exp(update_so3)*SO3_R;\n    cout<<\"Sophus updated = \"<<SO3_updated<<endl;\n\n    Eigen::Vector3d t(1,0,0);\n    Sophus::SE3 SE3_Rt(R,t);\n    Sophus::SE3 SE3_qt(q,t);\n    cout<<\"SE3 from R,t = \"<<SE3_Rt<<endl;\n    cout<<\"SE3 from q,t = \"<<SE3_qt<<endl;\n\n    typedef Eigen::Matrix<double,6,1> Vector6d;\n    Vector6d se3=SE3_Rt.log();\n    cout<<\"se3 = \"<<se3.transpose();//transfer is the former, rotation is the latter\n    cout<<\"se3 hat = \"<<Sophus::SE3::hat(se3)<<endl;\n    cout<<\"se3 vee = \"<<Sophus::SE3::vee(Sophus::SE3::hat(se3)).transpose()<<endl;\n\n    //update\n    Vector6d update_se3;\n    update_se3.setZero();\n    update_se3(0,0) = 1e-4d;\n    Sophus::SE3 SE3_updated = Sophus::SE3::exp(update_se3)*SE3_Rt;\n    cout<<\"SE3 updated = \"<<SE3_updated.matrix()<<endl;\n\n    return 0;\n}", "meta": {"hexsha": "24e46d13ef750b7c4014a4dacb567fecb9ea8cea", "size": 1748, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch4_Sophus/useSopgus.cpp", "max_stars_repo_name": "ClovisChen/slam14", "max_stars_repo_head_hexsha": "35fad23a491f2dd7666edab55ae849ac937d44c2", "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": "ch4_Sophus/useSopgus.cpp", "max_issues_repo_name": "ClovisChen/slam14", "max_issues_repo_head_hexsha": "35fad23a491f2dd7666edab55ae849ac937d44c2", "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_Sophus/useSopgus.cpp", "max_forks_repo_name": "ClovisChen/slam14", "max_forks_repo_head_hexsha": "35fad23a491f2dd7666edab55ae849ac937d44c2", "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.6153846154, "max_line_length": 104, "alphanum_fraction": 0.6327231121, "num_tokens": 617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436167620237, "lm_q2_score": 0.8175744806385543, "lm_q1q2_score": 0.7459845258579482}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n\n#include <unsupported/Eigen/NonLinearOptimization>\n#include <unsupported/Eigen/NumericalDiff>\n\n// Generic functor\ntemplate<typename _Scalar, int NX = Eigen::Dynamic, int NY = Eigen::Dynamic>\nstruct Functor\n{\n    typedef _Scalar Scalar;\n    enum {\n        InputsAtCompileTime = NX,\n        ValuesAtCompileTime = NY\n    };\n    typedef Eigen::Matrix<Scalar,InputsAtCompileTime,1> InputType;\n    typedef Eigen::Matrix<Scalar,ValuesAtCompileTime,1> ValueType;\n    typedef Eigen::Matrix<Scalar,ValuesAtCompileTime,InputsAtCompileTime> JacobianType;\n\n    int m_inputs, m_values;\n\n    Functor() : m_inputs(InputsAtCompileTime), m_values(ValuesAtCompileTime) {}\n    Functor(int inputs, int values) : m_inputs(inputs), m_values(values) {}\n\n    int inputs() const { return m_inputs; }\n    int values() const { return m_values; }\n\n};\n\nstruct my_functor : Functor<double>\n{\n    my_functor(void): Functor<double>(2,2) {}\n    int operator()(const Eigen::VectorXd &x, Eigen::VectorXd &fvec) const\n    {\n        // Implement y = 10*(x0+3)^2 + (x1-5)^2\n        fvec(0) = 10.0*pow(x(0)+3.0,2) +  pow(x(1)-5.0,2);\n        fvec(1) = 0;\n\n        return 0;\n    }\n};\n\nint main(int argc, char *argv[]) {\n    Eigen::VectorXd x(2);\n    x(0) = 2.0;\n    x(1) = 3.0;\n    std::cout << \"x: \" << x << std::endl;\n\n    my_functor functor;\n    Eigen::NumericalDiff<my_functor> numDiff(functor);\n    Eigen::LevenbergMarquardt<Eigen::NumericalDiff<my_functor>,double> lm(numDiff);\n    lm.parameters.maxfev = 2000;\n    lm.parameters.xtol = 1.0e-10;\n    std::cout << lm.parameters.maxfev << std::endl;\n\n    int ret = lm.minimize(x);\n    std::cout << lm.iter << std::endl;\n    std::cout << ret << std::endl;\n\n    std::cout << \"x that minimizes the function: \" << x << std::endl;\n\n    std::cout << \"press [ENTER] to continue \" << std::endl;\n    std::cin.get();\n    return 0;\n}", "meta": {"hexsha": "f93c854936c5254b75fe66454fb8269625900ded", "size": 1878, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "zhongjingjogy/use-eigen-with-cmake", "max_stars_repo_head_hexsha": "2db6ad45f8a08a07a18af8cf816bab41656db2ab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2019-04-19T23:49:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T02:55:17.000Z", "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "zhongjingjogy/use-eigen-with-cmake", "max_issues_repo_head_hexsha": "2db6ad45f8a08a07a18af8cf816bab41656db2ab", "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": "zhongjingjogy/use-eigen-with-cmake", "max_forks_repo_head_hexsha": "2db6ad45f8a08a07a18af8cf816bab41656db2ab", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-03T04:02:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-03T04:02:20.000Z", "avg_line_length": 28.8923076923, "max_line_length": 87, "alphanum_fraction": 0.6405750799, "num_tokens": 558, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361628580401, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7459845158809516}}
{"text": "\n#include <eigen3/Eigen/Core>\n#include <gtest/gtest.h>\n\n#include <math.h>\n#include <Eigen/Dense>\n\n\n#include \"mpi_cpp_tools/basic_tools.hpp\"\n#include \"mpi_cpp_tools/math.hpp\"\n#include \"mpi_cpp_tools/dynamical_systems.hpp\"\n\n\nusing namespace mct;\n\ndouble epsilon = 1e-10;\n\n\n\n\nTEST(linear_dynamics, evolution_with_zero_initial_position)\n{\n    double jerk = 1.0;\n    LinearDynamics linear_dynamics(jerk, 0.0, 0.0, 0.0);\n\n    for(size_t t = 0; t < 100; t++)\n    {\n        EXPECT_TRUE(approx_equal(linear_dynamics.get_acceleration(t),\n                                 t * jerk));\n        EXPECT_TRUE(approx_equal(linear_dynamics.get_velocity(t),\n                                 0.5 * t * t * jerk));\n        EXPECT_TRUE(approx_equal(linear_dynamics.get_position(t),\n                                 0.5 / 3.0 * t * t * t * jerk));\n    }\n}\n\n// should be linear in initial state and control\nTEST(linear_dynamics, check_linearity)\n{\n    Eigen::Vector4d parameters_a = Eigen::Vector4d(3.4, -5.6, 2.3, 7.2);\n    Eigen::Vector4d parameters_b = Eigen::Vector4d(-2.1, -3.0, 5.5, -10.2);\n\n    LinearDynamics linear_dynamics_a(parameters_a);\n    LinearDynamics linear_dynamics_b(parameters_b);\n    LinearDynamics linear_dynamics_sum(parameters_a + parameters_b);\n\n    for(size_t t = 0; t < 100; t++)\n    {\n        EXPECT_TRUE(approx_equal(linear_dynamics_a.get_acceleration(t) +\n                                 linear_dynamics_b.get_acceleration(t),\n                                 linear_dynamics_sum.get_acceleration(t),\n                                 1e-6));\n        EXPECT_TRUE(approx_equal(linear_dynamics_a.get_velocity(t) +\n                                 linear_dynamics_b.get_velocity(t),\n                                 linear_dynamics_sum.get_velocity(t),\n                                 1e-6));\n        EXPECT_TRUE(approx_equal(linear_dynamics_a.get_position(t) +\n                                 linear_dynamics_b.get_position(t),\n                                 linear_dynamics_sum.get_position(t),\n                                 1e-6));\n    }\n}\n\n\nTEST(linear_dynamics, test_find_t_given_velocity_basic)\n{\n    Eigen::Vector4d parameters_basic = Eigen::Vector4d(1.0, -2.0, 0.0, 0.0);\n    LinearDynamics dynamics_basic(parameters_basic);\n\n    LinearDynamics::Vector solutions =\n            dynamics_basic.find_t_given_velocity(- 3.0 / 2.0);\n\n    EXPECT_TRUE(solutions.size() == 2);\n    EXPECT_TRUE(contains(solutions, 1));\n    EXPECT_TRUE(contains(solutions, 3));\n    EXPECT_FALSE(contains(solutions, 4));\n}\n\n\nTEST(linear_dynamics, test_find_t_given_velocity_consistency)\n{\n    Eigen::Vector4d parameters_a = Eigen::Vector4d(3.4, -5.6, 2.3, 7.2);\n    Eigen::Vector4d parameters_b = Eigen::Vector4d(-2.1, -3.0, 5.5, -10.2);\n    LinearDynamics linear_dynamics_a(parameters_a);\n    LinearDynamics linear_dynamics_b(parameters_b);\n\n    for(size_t t = 0; t < 100; t++)\n    {\n        auto solutions_a = linear_dynamics_a.find_t_given_velocity(\n                    linear_dynamics_a.get_velocity(t));\n        EXPECT_TRUE(contains(solutions_a, t));\n        auto solutions_b = linear_dynamics_b.find_t_given_velocity(\n                    linear_dynamics_b.get_velocity(t));\n        EXPECT_TRUE(contains(solutions_b, t));\n    }\n}\n\n\n\nTEST(linear_dynamics_with_acceleration_constraint, test_time_evolution)\n{\n    Eigen::Matrix<double, 5, 1> parameters;\n    parameters << -2.0, 15.0, 5.5, -10.2, 17.0;\n    double jerk_duration = (17.0 + 15.0) / 2.0;\n\n\n    LinearDynamicsWithAccelerationConstraint constrained_dynamics(parameters);\n    LinearDynamics dynamics(parameters.topRows(4));\n    LinearDynamicsWithAccelerationConstraint\n            constrained_dynamics_b(-2.0,\n                                   dynamics.get_acceleration(jerk_duration),\n                                   dynamics.get_velocity(jerk_duration),\n                                   dynamics.get_position(jerk_duration), 17.0);\n\n    EXPECT_TRUE(approx_equal(dynamics.get_acceleration(jerk_duration), -17));\n    EXPECT_TRUE(approx_equal(-17, constrained_dynamics.get_acceleration(\n                                 jerk_duration + 100)));\n    EXPECT_TRUE(approx_equal(dynamics.get_position(jerk_duration),\n                             constrained_dynamics_b.get_position(0)));\n\n\n    // make sure that ther is no discontinuity at jerk_duration ----------------\n    double large_epsilon = std::sqrt(epsilon) / 100.0;\n    double numeric, exact;\n\n    numeric = constrained_dynamics.get_position(jerk_duration)\n            + large_epsilon * constrained_dynamics.get_velocity(jerk_duration);\n    exact = constrained_dynamics.get_position(jerk_duration + large_epsilon);\n    ASSERT_TRUE(approx_equal(numeric, exact));\n\n    numeric = constrained_dynamics.get_position(jerk_duration)\n            - large_epsilon * constrained_dynamics.get_velocity(jerk_duration);\n    exact = constrained_dynamics.get_position(jerk_duration - large_epsilon);\n    ASSERT_TRUE(approx_equal(numeric, exact));\n\n    // make sure dynamics coincide\n    for(size_t t = 0; t < 10000; t++)\n    {\n        double acceleration_b = dynamics.get_acceleration(jerk_duration);\n        double velocity_b =\n                dynamics.get_velocity(jerk_duration) +\n                dynamics.get_acceleration(jerk_duration) * t;\n        double position_b =\n                dynamics.get_position(jerk_duration) +\n                dynamics.get_velocity(jerk_duration) * t +\n                dynamics.get_acceleration(jerk_duration) * 0.5 * pow(t, 2);\n        EXPECT_TRUE(approx_equal(acceleration_b,\n                                 constrained_dynamics_b.get_acceleration(t)));\n        EXPECT_TRUE(approx_equal(velocity_b,\n                                 constrained_dynamics_b.get_velocity(t)));\n        EXPECT_TRUE(approx_equal(position_b,\n                                 constrained_dynamics_b.get_position(t)));\n\n\n\n        EXPECT_TRUE(contains(constrained_dynamics.find_t_given_velocity(\n                                 constrained_dynamics.get_velocity(t)), t));\n\n\n        if(t <= jerk_duration)\n        {\n            EXPECT_TRUE(approx_equal(dynamics.get_acceleration(t),\n                                     constrained_dynamics.get_acceleration(t)));\n            EXPECT_TRUE(approx_equal(dynamics.get_velocity(t),\n                                     constrained_dynamics.get_velocity(t)));\n            EXPECT_TRUE(approx_equal(dynamics.get_position(t),\n                                     constrained_dynamics.get_position(t)));\n        }\n        else\n        {\n            EXPECT_TRUE(approx_equal(constrained_dynamics_b.get_acceleration(t - jerk_duration),\n                                     constrained_dynamics.get_acceleration(t)));\n            EXPECT_TRUE(approx_equal(constrained_dynamics_b.get_velocity(t - jerk_duration),\n                                     constrained_dynamics.get_velocity(t)));\n            EXPECT_TRUE(approx_equal(constrained_dynamics_b.get_position(t - jerk_duration),\n                                     constrained_dynamics.get_position(t)));\n        }\n    }\n}\n\nTEST(linear_dynamics_with_acceleration_constraint, consistency_with_linear_dynamics)\n{\n\n    LinearDynamicsWithAccelerationConstraint\n            constrained_dynamics(-1.5, -13.0, 5.5, 10.2, 13.0);\n    LinearDynamics  dynamics(0.0, -13.0, 5.5, 10.2);\n\n    // make sure dynamics coincide\n    for(size_t t = 0; t < 100; t++)\n    {\n\n        EXPECT_TRUE(approx_equal(dynamics.get_acceleration(t),\n                                 constrained_dynamics.get_acceleration(t)));\n        EXPECT_TRUE(approx_equal(dynamics.get_velocity(t),\n                                 constrained_dynamics.get_velocity(t)));\n        EXPECT_TRUE(approx_equal(dynamics.get_position(t),\n                                 constrained_dynamics.get_position(t)));\n\n        LinearDynamics::Vector solutions =\n                dynamics.find_t_given_velocity(t - 50.0);\n        LinearDynamics::Vector constrained_solutions =\n                constrained_dynamics.find_t_given_velocity(t - 50.0);\n\n        EXPECT_TRUE(solutions.size() == constrained_solutions.size());\n\n        for(size_t i = 0; i < solutions.size(); i++)\n        {\n            EXPECT_TRUE(contains(solutions, constrained_solutions[i]));\n            EXPECT_TRUE(contains(constrained_solutions, solutions[i]));\n            EXPECT_TRUE(approx_equal(solutions[i], - (t - 50.0 -5.5) / 13.0));\n        }\n    }\n}\n\nTEST(linear_dynamics_with_acceleration_constraint,\n     test_find_t_given_velocity_basic_1)\n{\n    LinearDynamicsWithAccelerationConstraint\n            dynamics_basic(1.0, -2.0, 0.0, 0.0, 100.0);\n\n    LinearDynamics::Vector solutions =\n            dynamics_basic.find_t_given_velocity(- 3.0 / 2.0);\n\n    EXPECT_TRUE(solutions.size() == 2);\n    EXPECT_TRUE(contains(solutions, 1));\n    EXPECT_TRUE(contains(solutions, 3));\n    EXPECT_FALSE(contains(solutions, 4));\n}\n\n\nTEST(linear_dynamics_with_acceleration_constraint,\n     test_find_t_given_velocity_basic_2)\n{\n    LinearDynamicsWithAccelerationConstraint\n            dynamics_basic(1.0, -5.0, 3.0, -10.0, 10.0);\n\n    LinearDynamics::Vector solutions =\n            dynamics_basic.find_t_given_velocity(-9);\n\n    EXPECT_TRUE(solutions.size() == 2);\n    EXPECT_TRUE(contains(solutions, 4));\n    EXPECT_TRUE(contains(solutions, 6));\n    EXPECT_FALSE(contains(solutions, 7));\n}\n\n\nTEST(linear_dynamics_with_acceleration_constraint,\n     test_find_t_given_velocity_basic_3)\n{\n    LinearDynamicsWithAccelerationConstraint\n            dynamics(1.0, -1.0, 3.0, -2.0, 2.0);\n\n    EXPECT_TRUE(approx_equal(dynamics.get_velocity(10.0), 18.5));\n\n    LinearDynamics::Vector solutions = dynamics.find_t_given_velocity(18.5);\n\n    EXPECT_TRUE(solutions.size() == 1);\n    EXPECT_TRUE(approx_equal(solutions[0], 10.0));\n}\n\n\nTEST(linear_dynamics_with_acceleration_constraint,\n     test_find_t_given_velocity_consistency)\n{\n    LinearDynamicsWithAccelerationConstraint\n            dynamics_a(3.4, -5.6, 2.3, 7.2, 20);\n    LinearDynamicsWithAccelerationConstraint\n            dynamics_b(-2.1, -3.0, 5.5, -10.2, 44.3);\n\n    for(size_t t = 0; t < 100; t++)\n    {\n        auto solutions_a = dynamics_a.find_t_given_velocity(\n                    dynamics_a.get_velocity(t));\n        EXPECT_TRUE(contains(solutions_a, t));\n        auto solutions_b = dynamics_b.find_t_given_velocity(\n                    dynamics_b.get_velocity(t));\n        EXPECT_TRUE(contains(solutions_b, t));\n    }\n}\n\n\nTEST(linear_dynamics_with_acceleration_constraint,\n     will_exceed_jointly)\n{\n    LinearDynamicsWithAccelerationConstraint\n            dynamics(-0.4, 2.6, 200.3, 7.2, 3);\n    double max_t = dynamics.find_t_given_velocity(0).maxCoeff() * 2;\n\n    std::vector<Eigen::Vector2d> trajectory;\n    size_t n_iterations = 1000;\n    for(size_t i = 0; i < n_iterations; i++)\n    {\n        double t = double(i) / n_iterations * max_t;\n\n        Eigen::Vector2d point;\n        point[0] = dynamics.get_velocity(t);\n        point[1] = dynamics.get_position(t);\n        trajectory.push_back(point);\n    }\n\n    for(auto& point : trajectory)\n    {\n        std::vector<Eigen::Vector2d> constraints;\n        constraints.push_back(point + Eigen::Vector2d(0.001, 0.001));\n        constraints.push_back(point - Eigen::Vector2d(epsilon, epsilon));\n\n        constraints.push_back(point + Eigen::Vector2d(-epsilon, std::numeric_limits<double>::infinity()));\n        constraints.push_back(point + Eigen::Vector2d(-epsilon, -std::numeric_limits<double>::infinity()));\n        constraints.push_back(point + Eigen::Vector2d(0.001, -std::numeric_limits<double>::infinity()));\n\n        constraints.push_back(point + Eigen::Vector2d(std::numeric_limits<double>::infinity(), -epsilon));\n        constraints.push_back(point + Eigen::Vector2d(-std::numeric_limits<double>::infinity(), -epsilon));\n        constraints.push_back(point + Eigen::Vector2d(-std::numeric_limits<double>::infinity(), 0.001));\n\n        for(auto& constraint : constraints)\n        {\n\n            bool label = false;\n            for(auto& point : trajectory)\n            {\n                if(point[0] > constraint[0] && point[1] > constraint[1])\n                {\n                    //                    std::cout << \"point: \" << point.transpose() << std::endl;\n                    label = true;\n                    break;\n                }\n            }\n\n            double certificate_time;\n            bool assigned_label =\n                    dynamics.will_exceed_jointly(constraint[0], constraint[1],\n                    certificate_time);\n\n            if(label != assigned_label)\n            {\n                std::cout << \"---------------------\" << std::endl;\n                std::cout << \"constraint: \" << constraint.transpose() << std::endl;\n\n                std::cout << \"label: \" << label << \"  assigned_label: \" << assigned_label << std::endl;\n                std::cout << \"certificate time: \" << certificate_time\n                          << \" certificate point: \"\n                          << dynamics.get_velocity(certificate_time) << \", \"\n                          << dynamics.get_position(certificate_time) << std::endl;\n            }\n            EXPECT_TRUE(label == assigned_label);\n        }\n    }\n}\n\n\n\nTEST(linear_dynamics_with_acceleration_constraint,\n     will_exceed_jointly_2)\n{\n    LinearDynamicsWithAccelerationConstraint\n            dynamics(-0.4, 20.6, -2.3, 7.2, 30);\n    double max_t = dynamics.find_t_given_velocity(0).maxCoeff() * 2;\n\n    std::vector<Eigen::Vector2d> trajectory;\n    size_t n_iterations = 1000;\n    for(size_t i = 0; i < n_iterations; i++)\n    {\n        double t = double(i) / n_iterations * max_t;\n\n        Eigen::Vector2d point;\n        point[0] = dynamics.get_velocity(t);\n        point[1] = dynamics.get_position(t);\n        trajectory.push_back(point);\n    }\n\n    for(auto& point : trajectory)\n    {\n        std::vector<Eigen::Vector2d> constraints;\n        constraints.push_back(point + Eigen::Vector2d(0.001, 0.001));\n        constraints.push_back(point - Eigen::Vector2d(epsilon, epsilon));\n\n        constraints.push_back(point + Eigen::Vector2d(-epsilon, std::numeric_limits<double>::infinity()));\n        constraints.push_back(point + Eigen::Vector2d(-epsilon, -std::numeric_limits<double>::infinity()));\n        constraints.push_back(point + Eigen::Vector2d(0.001, -std::numeric_limits<double>::infinity()));\n\n        constraints.push_back(point + Eigen::Vector2d(std::numeric_limits<double>::infinity(), -epsilon));\n        constraints.push_back(point + Eigen::Vector2d(-std::numeric_limits<double>::infinity(), -epsilon));\n        constraints.push_back(point + Eigen::Vector2d(-std::numeric_limits<double>::infinity(), 0.001));\n\n        for(auto& constraint : constraints)\n        {\n\n            bool label = false;\n            for(auto& point : trajectory)\n            {\n                if(point[0] > constraint[0] && point[1] > constraint[1])\n                {\n                    //                    std::cout << \"point: \" << point.transpose() << std::endl;\n                    label = true;\n                    break;\n                }\n            }\n\n            double certificate_time;\n            bool assigned_label =\n                    dynamics.will_exceed_jointly(constraint[0], constraint[1],\n                    certificate_time);\n\n            if(label != assigned_label)\n            {\n                std::cout << \"---------------------\" << std::endl;\n                std::cout << \"constraint: \" << constraint.transpose() << std::endl;\n\n                std::cout << \"label: \" << label << \"  assigned_label: \" << assigned_label << std::endl;\n                std::cout << \"certificate time: \" << certificate_time\n                          << \" certificate point: \"\n                          << dynamics.get_velocity(certificate_time) << \", \"\n                          << dynamics.get_position(certificate_time) << std::endl;\n            }\n            EXPECT_TRUE(label == assigned_label);\n        }\n    }\n}\n\n\nTEST(linear_dynamics_with_acceleration_constraint,\n     will_deceed_jointly)\n{\n    LinearDynamicsWithAccelerationConstraint\n            dynamics(0.4, 2.6, -200.3, 7.2, 3);\n    double max_t = dynamics.find_t_given_velocity(0).maxCoeff() * 2;\n\n    std::vector<Eigen::Vector2d> trajectory;\n    size_t n_iterations = 1000;\n    for(size_t i = 0; i < n_iterations; i++)\n    {\n        double t = double(i) / n_iterations * max_t;\n\n        Eigen::Vector2d point;\n        point[0] = dynamics.get_velocity(t);\n        point[1] = dynamics.get_position(t);\n        trajectory.push_back(point);\n    }\n\n    for(auto& point : trajectory)\n    {\n        std::vector<Eigen::Vector2d> constraints;\n        constraints.push_back(point - Eigen::Vector2d(0.001, 0.001));\n        constraints.push_back(point + Eigen::Vector2d(epsilon, epsilon));\n\n        constraints.push_back(point + Eigen::Vector2d(epsilon, std::numeric_limits<double>::infinity()));\n        constraints.push_back(point + Eigen::Vector2d(epsilon, -std::numeric_limits<double>::infinity()));\n        constraints.push_back(point + Eigen::Vector2d(-0.001, std::numeric_limits<double>::infinity()));\n\n        constraints.push_back(point + Eigen::Vector2d(std::numeric_limits<double>::infinity(), epsilon));\n        constraints.push_back(point + Eigen::Vector2d(-std::numeric_limits<double>::infinity(), epsilon));\n        constraints.push_back(point + Eigen::Vector2d(std::numeric_limits<double>::infinity(), -0.001));\n\n        for(auto& constraint : constraints)\n        {\n\n            bool label = false;\n            for(auto& point : trajectory)\n            {\n                if(point[0] < constraint[0] && point[1] < constraint[1])\n                {\n                    //                    std::cout << \"point: \" << point.transpose() << std::endl;\n                    label = true;\n                    break;\n                }\n            }\n\n            double certificate_time;\n            bool assigned_label =\n                    dynamics.will_deceed_jointly(constraint[0], constraint[1],\n                    certificate_time);\n\n            if(label != assigned_label)\n            {\n                std::cout << \"---------------------\" << std::endl;\n                std::cout << \"constraint: \" << constraint.transpose() << std::endl;\n\n                std::cout << \"label: \" << label << \"  assigned_label: \" << assigned_label << std::endl;\n                std::cout << \"certificate time: \" << certificate_time\n                          << \" certificate point: \"\n                          << dynamics.get_velocity(certificate_time) << \", \"\n                          << dynamics.get_position(certificate_time) << std::endl;\n            }\n            EXPECT_TRUE(label == assigned_label);\n        }\n    }\n}\n\ndouble sample_uniformely(const double& min, const double& max)\n{\n    return min + double(rand()) / RAND_MAX * (max - min);\n}\n\nTEST(find_max_admissible_acceleration, generated_trajectories)\n{\n    srand(0);\n\n    for(size_t unused = 0; unused < 100; unused++)\n    {\n        // initialize parameters randomly --------------------------------------\n\n\n        double initial_velocity = sample_uniformely(-20.0, 20.0);\n        double initial_position = sample_uniformely(-20.0, 20.0);\n        NonnegDouble abs_jerk_limit = sample_uniformely(epsilon, 20.0);\n        NonnegDouble abs_acceleration_limit = sample_uniformely(epsilon, 20.0);\n\n        double initial_acceleration = sample_uniformely(-abs_acceleration_limit,\n                                                        abs_acceleration_limit);\n\n\n\n        // find some constraints which is just barely satisfied --------------------\n        LinearDynamicsWithAccelerationConstraint dynamics(-abs_jerk_limit,\n                                                          initial_acceleration,\n                                                          initial_velocity,\n                                                          initial_position,\n                                                          abs_acceleration_limit);\n\n        double max_t = 20.0;\n        if(dynamics.find_t_given_velocity(0).size() > 0)\n        {\n            max_t = dynamics.find_t_given_velocity(0).maxCoeff() * 2;\n        }\n\n        size_t n_iterations = 10000;\n        int T = rand() % n_iterations;\n        Eigen::Vector2d constraint;\n        constraint[0] = dynamics.get_velocity(T);\n        constraint[1] = dynamics.get_position(T);\n\n        Eigen::Vector2d position_constraint(-std::numeric_limits<double>::infinity(),\n                                            -std::numeric_limits<double>::infinity());\n        Eigen::Vector2d velocity_constraint(-std::numeric_limits<double>::infinity(),\n                                            -std::numeric_limits<double>::infinity());\n\n        for(size_t i = 0; i < n_iterations; i++)\n        {\n            double t = double(i) / n_iterations * max_t;\n            Eigen::Vector2d point;\n            point[0] = dynamics.get_velocity(t);\n            point[1] = dynamics.get_position(t);\n            if(point[0] > constraint[0] && point[1] > constraint[1])\n                constraint = point;\n            velocity_constraint[0] = std::max(velocity_constraint[0], point[0]);\n            position_constraint[1] = std::max(position_constraint[1], point[1]);\n        }\n\n        // test that we get the same initial acceleration --------------------------\n        for(auto& c : {constraint, position_constraint, velocity_constraint})\n        {\n\n\n            double max_admissible_initial_acceleration =\n                    find_max_admissible_acceleration(\n                        initial_velocity,\n                        initial_position,\n                        c[0],\n                    c[1],\n                    abs_jerk_limit,\n                    abs_acceleration_limit);\n\n            if(std::fabs(initial_acceleration -\n                         max_admissible_initial_acceleration) > 0.02)\n            {\n                if(max_admissible_initial_acceleration - 0.0001 >\n                        -abs_acceleration_limit)\n                {\n                    LinearDynamicsWithAccelerationConstraint\n                            below_limit_dynamics(-abs_jerk_limit,\n                                                 max_admissible_initial_acceleration\n                                                 - 0.0001,\n                                                 initial_velocity,\n                                                 initial_position,\n                                                 abs_acceleration_limit);\n                    ASSERT_TRUE(below_limit_dynamics.will_exceed_jointly(c[0], c[1])\n                            == false);\n                }\n\n\n                if(max_admissible_initial_acceleration + 0.0001 <\n                        abs_acceleration_limit)\n                {\n                    LinearDynamicsWithAccelerationConstraint\n                            above_limit_dynamics(-abs_jerk_limit,\n                                                 max_admissible_initial_acceleration\n                                                 + 0.0001,\n                                                 initial_velocity,\n                                                 initial_position,\n                                                 abs_acceleration_limit);\n                    ASSERT_TRUE(above_limit_dynamics.will_exceed_jointly(c[0], c[1])\n                            == true);\n                }\n\n\n                //                std::cout << \"------------------------------------  \" << std::endl;\n\n\n                //                dynamics.print_parameters();\n\n                //                std::cout << \"constraint \" << c << std::endl;\n\n                //                std::cout << \" initial_acceleration \" << initial_acceleration\n                //                          << \" max_admissible_initial_acceleration \"\n                //                          << max_admissible_initial_acceleration << std::endl;\n\n                //                bool will_exceed_epsilon = dynamics.will_exceed_jointly(c[0], c[1]);\n\n                //                bool will_exceed_minus_epsilon = dynamics.will_exceed_jointly(c[0] - epsilon, c[1] - epsilon);\n\n\n                //                bool limit_dynamics_will_exceed = limit_dynamics.will_exceed_jointly(c[0] - epsilon, c[1] - epsilon);\n\n\n\n                //                std::cout << \" will_exceed_epsilon \" << will_exceed_epsilon\n                //                          << \" will_exceed_minus_epsilon \" << will_exceed_minus_epsilon\n                //                          << \" limit_dynamics_will_exceed \" << limit_dynamics_will_exceed\n\n                //                          << std::endl;\n\n                ASSERT_TRUE(approx_equal(c[0], initial_velocity) ||\n                        approx_equal(c[1], initial_position));\n            }\n\n            //            ASSERT_TRUE(std::fabs(initial_acceleration -\n            //                                  max_admissible_initial_acceleration) <= 0.001);\n        }\n    }\n}\n\n\nTEST(find_max_admissible_acceleration, random_points)\n{\n    srand(0);\n\n    for(size_t unused = 0; unused < 10000; unused++)\n    {\n        // initialize parameters randomly --------------------------------------\n        double initial_velocity = sample_uniformely(-20.0, 20.0);\n        double initial_position = sample_uniformely(-20.0, 20.0);\n\n        double max_velocity = sample_uniformely(-20.0, 20.0);\n        double max_position = sample_uniformely(-20.0, 20.0);\n\n        NonnegDouble abs_jerk_limit = sample_uniformely(epsilon, 20.0);\n        NonnegDouble abs_acceleration_limit = sample_uniformely(epsilon, 20.0);\n\n\n        double max_admissible_acceleration =\n                find_max_admissible_acceleration(\n                    initial_velocity,\n                    initial_position,\n                    max_velocity,\n                    max_position,\n                    abs_jerk_limit,\n                    abs_acceleration_limit);\n\n        if(std::fabs(max_admissible_acceleration - 0.0001) <=\n                abs_acceleration_limit)\n        {\n            LinearDynamicsWithAccelerationConstraint\n                    below_limit_dynamics(-abs_jerk_limit,\n                                         max_admissible_acceleration\n                                         - 0.0001,\n                                         initial_velocity,\n                                         initial_position,\n                                         abs_acceleration_limit);\n            ASSERT_TRUE(below_limit_dynamics.will_exceed_jointly(max_velocity, max_position)\n                        == false);\n        }\n        if(std::fabs(max_admissible_acceleration + 0.0001) <=\n                abs_acceleration_limit)\n        {\n            LinearDynamicsWithAccelerationConstraint\n                    above_limit_dynamics(-abs_jerk_limit,\n                                         max_admissible_acceleration\n                                         + 0.0001,\n                                         initial_velocity,\n                                         initial_position,\n                                         abs_acceleration_limit);\n            ASSERT_TRUE(above_limit_dynamics.will_exceed_jointly(max_velocity, max_position)\n                        == true);\n        }\n    }\n}\n\n\nTEST(find_min_admissible_acceleration, random_points)\n{\n    srand(0);\n\n    for(size_t unused = 0; unused < 10; unused++)\n    {\n        // initialize parameters randomly --------------------------------------\n        double initial_velocity = sample_uniformely(-20.0, 20.0);\n        double initial_position = sample_uniformely(-20.0, 20.0);\n\n        double min_velocity = sample_uniformely(-20.0, 20.0);\n        double min_position = sample_uniformely(-20.0, 20.0);\n\n        NonnegDouble abs_jerk_limit = sample_uniformely(epsilon, 20.0);\n        NonnegDouble abs_acceleration_limit = sample_uniformely(epsilon, 20.0);\n\n\n        double min_admissible_acceleration =\n                find_min_admissible_acceleration(\n                    initial_velocity,\n                    initial_position,\n                    min_velocity,\n                    min_position,\n                    abs_jerk_limit,\n                    abs_acceleration_limit);\n\n        if(std::fabs(min_admissible_acceleration - 0.0001) <=\n                abs_acceleration_limit)\n        {\n            LinearDynamicsWithAccelerationConstraint\n                    below_limit_dynamics(abs_jerk_limit,\n                                         min_admissible_acceleration\n                                         - 0.0001,\n                                         initial_velocity,\n                                         initial_position,\n                                         abs_acceleration_limit);\n            ASSERT_TRUE(below_limit_dynamics.will_deceed_jointly(min_velocity,\n                                                                 min_position)\n                        == true);\n        }\n        if(std::fabs(min_admissible_acceleration + 0.0001) <=\n                abs_acceleration_limit)\n        {\n            LinearDynamicsWithAccelerationConstraint\n                    above_limit_dynamics(abs_jerk_limit,\n                                         min_admissible_acceleration\n                                         + 0.0001,\n                                         initial_velocity,\n                                         initial_position,\n                                         abs_acceleration_limit);\n            ASSERT_TRUE(above_limit_dynamics.will_deceed_jointly(min_velocity,\n                                                                 min_position)\n                        == false);\n        }\n    }\n}\n\n\n\n\n", "meta": {"hexsha": "d0028fcbd3e2d13e1738fdfb29d16acc3d2cf460", "size": 29635, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_linear_dynamics.cpp", "max_stars_repo_name": "open-dynamic-robot-initiative/mpi_cpp_tools", "max_stars_repo_head_hexsha": "d6c09b96f3370b8d4f31ac96ac04bca37a9846d1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-07-06T01:18:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T03:14:42.000Z", "max_issues_repo_path": "tests/test_linear_dynamics.cpp", "max_issues_repo_name": "open-dynamic-robot-initiative/mpi_cpp_tools", "max_issues_repo_head_hexsha": "d6c09b96f3370b8d4f31ac96ac04bca37a9846d1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-11-18T14:21:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-20T14:20:37.000Z", "max_forks_repo_path": "tests/test_linear_dynamics.cpp", "max_forks_repo_name": "open-dynamic-robot-initiative/mpi_cpp_tools", "max_forks_repo_head_hexsha": "d6c09b96f3370b8d4f31ac96ac04bca37a9846d1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-27T17:46:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-27T17:46:46.000Z", "avg_line_length": 39.5660881175, "max_line_length": 135, "alphanum_fraction": 0.5557280243, "num_tokens": 6095, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147439, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7459845140964723}}
{"text": "#include \"convhull_volume.h\"\n#define CONVHULL_3D_ENABLE\n#include \"convhull_3d.h\"\n#include <Eigen/Dense>\n\ndouble convexHullVolume(const Eigen::MatrixXd& verts)\n{\n  // convert data\n  int nVerts = verts.cols();\n  ch_vertex* vertices;\n  vertices = (ch_vertex*)malloc(nVerts*sizeof(ch_vertex));\n  for (int i = 0; i < nVerts; i++) {\n    vertices[i].x = verts(0, i);\n    vertices[i].y = verts(1, i);\n    vertices[i].z = verts(2, i);\n  }\n  int* faceIndices = NULL;\n  int nFaces;\n  convhull_3d_build(vertices, nVerts, &faceIndices, &nFaces);\n  Eigen::Map<Eigen::MatrixXi> faces(faceIndices, 3, nFaces);\n  double vol = polygonVolume(verts, faces);\n  free(vertices);\n  free(faceIndices);\n  return vol;\n}\n\ndouble polygonVolume(const Eigen::MatrixXd& vertices, const Eigen::MatrixXi& faces)\n{\n  double vol = 0;\n  Eigen::Vector3d com = vertices.rowwise().mean();\n  for (int i=0; i < faces.cols(); i++)\n  {\n    Eigen::Vector3i f = faces.col(i);\n    Eigen::Vector3d a = vertices.col(f(0)) - com;\n    Eigen::Vector3d b = vertices.col(f(1)) - com;\n    Eigen::Vector3d c = vertices.col(f(2)) - com;\n\n    double e_vol = a.cross(b).dot(c);\n    vol += e_vol;\n  }\n  vol /= 6.0;\n  return vol;\n}\n", "meta": {"hexsha": "b791e6efc374372362c65eb4afefd79851acd616", "size": 1171, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Kinematic/convhull/convhull_volume.cpp", "max_stars_repo_name": "arpspoof/Jump", "max_stars_repo_head_hexsha": "1c9c1bd5c499e24bab25eb7decaa772b60798794", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 46.0, "max_stars_repo_stars_event_min_datetime": "2021-04-25T03:36:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-19T00:23:59.000Z", "max_issues_repo_path": "Kinematic/convhull/convhull_volume.cpp", "max_issues_repo_name": "squalidux/Jump", "max_issues_repo_head_hexsha": "1c9c1bd5c499e24bab25eb7decaa772b60798794", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-05-25T10:04:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-22T01:54:00.000Z", "max_forks_repo_path": "Kinematic/convhull/convhull_volume.cpp", "max_forks_repo_name": "squalidux/Jump", "max_forks_repo_head_hexsha": "1c9c1bd5c499e24bab25eb7decaa772b60798794", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2021-04-25T03:05:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-05T19:58:01.000Z", "avg_line_length": 26.6136363636, "max_line_length": 83, "alphanum_fraction": 0.6498719044, "num_tokens": 367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625107731764, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.7458145781982789}}
{"text": "/** @file main.cpp Demonstrates purely functional, tail-recursive,\n  * arbitrary-precision factorial and Fibonacci functions using\n  * Boost.Multiprecision.\n  *\n  * @note That this implementation passes parameters by constant reference, but\n  * returns by value.  This approach strikes a balance between high- and\n  * low-level concerns.\n  *\n  * @see pretty.cpp for less noisy (but potentially less efficient) code.\n  *\n  * @see control.cpp for tighter control over memory.\n  */\n\n#include <boost/multiprecision/cpp_int.hpp>\n#include <iostream>\n\nusing big_int = boost::multiprecision::cpp_int;\n\nbig_int factorial(int n, big_int const& r =1)\n{\n    return n ? factorial(n - 1, r * n) : r;\n}\n\nbig_int fibonacci(int n, big_int const& a =1, big_int const& b =1)\n{\n    return n ? fibonacci(n - 1, b, a + b) : a;\n}\n\nint main()\n{\n    for (int i = 0; i < 100; ++i) {\n        std::cout << i << ' ' << factorial(i) << ' ' << fibonacci(i) << '\\n';\n    }\n}\n", "meta": {"hexsha": "2fe52cf5c29e12f59053d0a7765e19fc3bff2e4d", "size": 943, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "jeffs/fac-fib", "max_stars_repo_head_hexsha": "53b93389f123c726e28424bf8b0c31058366317b", "max_stars_repo_licenses": ["BSL-1.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": "src/main.cpp", "max_issues_repo_name": "jeffs/fac-fib", "max_issues_repo_head_hexsha": "53b93389f123c726e28424bf8b0c31058366317b", "max_issues_repo_licenses": ["BSL-1.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": "src/main.cpp", "max_forks_repo_name": "jeffs/fac-fib", "max_forks_repo_head_hexsha": "53b93389f123c726e28424bf8b0c31058366317b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9428571429, "max_line_length": 79, "alphanum_fraction": 0.6542948038, "num_tokens": 258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693617046216, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.745783503524588}}
{"text": "//author: snassr\n#pragma once\n\n//.includes\n//..stl library\n#include <string>\n\t//for std::string\n#include <algorithm>\n\t//for std::max\n#include <vector>\n\t//for std::vector\n//..armadillo library\n#include <armadillo>\n\t//for arma::mat\n//..sLab library\n#include \"EditDistance.hpp\"\n\n\n//.globals and declarations\n/*\n*\n*\n*/\n\n\n\n\n/* Levenshtein Minimum Edit Distance\n*\n* Definition:\n* -----------\n* A computation of the distance between two strings D(n,m)\n* \t\t[where n= length of stringOne, m = length of stringTwo]\n* This is done via a tabular (matrix) computation by combining solutions to subproblems.\n*\n* Specific-to-General Solution:\n* -----------------------------\n* \t1. compute D(i,j) for small i,j (origin 0)\n* \t2. compute D(i,j) for consequently larger substrings via character appension until both strings are fully compared at D(n,m)\n* \t\t\t- compute D(i,j) for all i(0 < i < n) and j(0 < j < m)\n*\n* Formula:\n* --------\n* D(i,j) = Min( { D(i-1,j) + 1, //deletion operation from i to compare j\n* \t\t\t\t{ D(i,j-1) + 1, //insertion operation to i to compare j\n* \t\t\t\t{ D(i-1, j-1) +  2; x(i) != y(j) //substitution character operation in i (deletion & insertion)\n* \t\t\t\t{\t\t\t\t 0; x(i) == y(j))// to compare j, cost is 0 if no substitution is required, otherwise x (x:the set value of subCost)\n*\t\t\t  )\n*\n*/\n\n\n\n\nclass LevenshteinDistance : public EditDistance\n{\n\t//...member functions\n\t//...public interface\npublic:\n\t//.....overload operators\n\t//....constructors\n\t//.....default constructor\n\t//.....parameterized constructor\n\t\tLevenshteinDistance(std::string stringOne, std::string stringTwo, int inSubstitutionCost);\n\t//.....destructor\n\t//....operations\n\t//.....observers\n\t\tdouble calculateDistance();\n\t\tdouble averageStringLengthSimilarity();\n\t\tdouble maximizedStringLengthSimilarity();\n\t\tdouble maximizedStringElementSimilarity();\n\t//.....mutators\n\t//...private members\nprivate:\n\t//....data members\n\t//....functions\n};\n\n//non-member functions\n\n\n\n\n//-------------------------------------------------------------------------------------------implementation---\nLevenshteinDistance::LevenshteinDistance(std::string inStringOne, std::string inStringTwo, int inCost) {\n\tsetStringOne(inStringOne);\n\tsetStringTwo(inStringTwo);\n\tsetSubstitutionCost(inCost);\n}\n\ndouble LevenshteinDistance::calculateDistance() {\n\tstd::string strOne = getStringOne();\n\tstd::string strTwo = getStringTwo();\n\tchar charInStrOne = 0;\n\tchar charInStrTwo = 0;\n\tint matrixRows = getStringOneLength() + 1;\n\tint matrixCols = getStringTwoLength() + 1;\n\tint cost;\n\n\tarma::mat distanceMatrix(matrixRows, matrixCols, arma::fill::zeros);\n\n\n\tfor (int a = 0; a < matrixRows; a++)\n\t\tdistanceMatrix(a, 0) = a;\n\tfor (int b = 0; b < matrixCols; b++)\n\t\tdistanceMatrix(0, b) = b;\n\n\tfor (int rowNum = 1; rowNum < matrixRows; rowNum++) {\n\t\tcharInStrOne = strOne.at(rowNum - 1);\n\n\t\tfor (int colNum = 1; colNum < matrixCols; colNum++) {\n\t\t\tcharInStrTwo = strTwo.at(colNum - 1);\n\t\t\tif (charInStrOne == charInStrTwo)\n\t\t\t\tcost = 0;\n\t\t\telse\n\t\t\t\tcost = getSubstitutionCost();\n\n\t\tdistanceMatrix(rowNum, colNum) = findMinimum(distanceMatrix(rowNum - 1, colNum) + 1, distanceMatrix(rowNum, colNum - 1) + 1, distanceMatrix(rowNum - 1, colNum - 1) + cost);\n\t\t}\n\t}\n\treturn distanceMatrix(getStringOneLength(), getStringTwoLength());\n}\n\ndouble LevenshteinDistance::averageStringLengthSimilarity() { return 0.0; }\n\ndouble LevenshteinDistance::maximizedStringLengthSimilarity() { return 0.0; }\n\ndouble LevenshteinDistance::maximizedStringElementSimilarity() { return 0.0; }\n", "meta": {"hexsha": "af5f26fa6d8fddfd44f8075f2ad35083bee042aa", "size": 3497, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "algorithms/edit_distance/LevenshteinDistance.hpp", "max_stars_repo_name": "snassr/sLab", "max_stars_repo_head_hexsha": "ed2262870a7f77a16edc2149592ae7d4d28faeb3", "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": "algorithms/edit_distance/LevenshteinDistance.hpp", "max_issues_repo_name": "snassr/sLab", "max_issues_repo_head_hexsha": "ed2262870a7f77a16edc2149592ae7d4d28faeb3", "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": "algorithms/edit_distance/LevenshteinDistance.hpp", "max_forks_repo_name": "snassr/sLab", "max_forks_repo_head_hexsha": "ed2262870a7f77a16edc2149592ae7d4d28faeb3", "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.1085271318, "max_line_length": 174, "alphanum_fraction": 0.6642836717, "num_tokens": 986, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107914029486, "lm_q2_score": 0.7956580927949807, "lm_q1q2_score": 0.7456993508345445}}
{"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, dual p)\n{\n    return x.cwiseProduct(x).sum() * exp(p); // sum([x(i) * x(i) for i = 1:5]) * exp(p)\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 p = 3;    // the input parameter vector p with 3 variables\n\n    dual u;  // the output scalar u = f(x, p) evaluated together with gradient below\n\n    VectorXd gpx = gradient(f, wrtpack(p, x), at(x, p), u);  // evaluate the function value u and its gradient vector gp = [du/dp, du/dx]  \n\n    cout << \"u = \" << u << endl;    // print the evaluated output u\n    cout << \"gpx = \\n\" << gpx << endl;  // print the evaluated gradient vector gp = [du/dp, du/dx]\n}\n", "meta": {"hexsha": "25282dbb30d38bdce33b9d1dbfdbdcf4e5e0ce00", "size": 1016, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/forward/example-forward-gradient-derivatives-using-eigen-with-scalar.cpp", "max_stars_repo_name": "ludkinm/autodiff", "max_stars_repo_head_hexsha": "982ee0f63726c71843e2141b8b4b037590c2ad46", "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": "examples/forward/example-forward-gradient-derivatives-using-eigen-with-scalar.cpp", "max_issues_repo_name": "ludkinm/autodiff", "max_issues_repo_head_hexsha": "982ee0f63726c71843e2141b8b4b037590c2ad46", "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": "examples/forward/example-forward-gradient-derivatives-using-eigen-with-scalar.cpp", "max_forks_repo_name": "ludkinm/autodiff", "max_forks_repo_head_hexsha": "982ee0f63726c71843e2141b8b4b037590c2ad46", "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.8823529412, "max_line_length": 139, "alphanum_fraction": 0.6279527559, "num_tokens": 322, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088045171238, "lm_q2_score": 0.8031738034238806, "lm_q1q2_score": 0.7456736306562364}}
{"text": "#include <iostream>\n#include <fstream>\n#include <string>\n#include <Eigen/Core>\n\n#include <g2o/core/base_vertex.h>\n#include <g2o/core/base_binary_edge.h>\n#include <g2o/core/block_solver.h>\n#include <g2o/core/optimization_algorithm_levenberg.h>\n#include <g2o/solvers/eigen/linear_solver_eigen.h>\n\n#include <sophus/se3.hpp>\n\nusing namespace std;\nusing namespace Eigen;\n\nstd::ofstream debug(\"debug_g2o.txt\");\n\nclass VertexSE3LieAlgebra : public g2o::BaseVertex<6, Sophus::SE3d>\n{\n    public:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n    virtual void setToOriginImpl() override {\n        _estimate = Sophus::SE3d();\n    }\n\n    virtual void oplusImpl(const double* update) override {\n        Eigen::Map<const Eigen::Matrix<double, 6, 1>> update_v(update);\n        _estimate = Sophus::SE3d::exp(update_v) * _estimate;\n    }\n\n\n    virtual bool read(istream &is) override {\n        double data[7];\n        for (int i = 0; i < 7; i++)\n            is >> data[i];\n        _estimate = Sophus::SE3d(\n            Quaterniond(data[6], data[3], data[4], data[5]),\n            Vector3d(data[0], data[1], data[2])\n        );\n        return true;\n    }\n\n    virtual bool write(ostream &os) const override {\n        os << id() << \" \";\n        Quaterniond q = _estimate.unit_quaternion();\n        os << _estimate.translation().transpose() << \" \";\n        os << q.coeffs()[0] << \" \" << q.coeffs()[1] << \" \" << q.coeffs()[2] << \" \" << q.coeffs()[3] << endl;\n        return true;\n    }\n\n};\n\nclass EdgeSE3LieAlgebra : public g2o::BaseBinaryEdge<6, Sophus::SE3d, VertexSE3LieAlgebra, VertexSE3LieAlgebra>\n{\n    public:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n    virtual void computeError() override {\n        auto* v0 = dynamic_cast<VertexSE3LieAlgebra*>(_vertices[0]);\n        auto* v1 = dynamic_cast<VertexSE3LieAlgebra*>(_vertices[1]);\n        _error = (_measurement.inverse() * v0->estimate().inverse() * v1->estimate()).log();\n\n        Sophus::SE3d rt0 = v0->estimate();\n        Sophus::SE3d rt1 = v1->estimate();\n        debug << v0->id() << \" \" << v1->id() << \" \";\n        // debug << rt0.translation().transpose();\n        auto q = _measurement.unit_quaternion();\n        debug << q.x() << \" \" << q.y() << \" \" << q.z() << \" \" << q.w();\n        // for (int i = 0; i < 6; ++i)\n        // debug << _error[i] << \" \";\n        // debug << _error.transpose();\n        debug << \"\\n\";\n    }\n\n    virtual void linearizeOplus() override {\n        // auto* v0 = dynamic_cast<VertexSE3LieAlgebra*>(_vertices[0]);\n        auto* v1 = dynamic_cast<VertexSE3LieAlgebra*>(_vertices[1]);\n        // auto T0 = v0->estimate();\n        auto T1 = v1->estimate();\n\n        Sophus::SE3d e = Sophus::SE3d::exp(_error);\n        Eigen::Matrix<double, 6, 6> J_inv = Eigen::Matrix<double, 6, 6>::Zero();\n        J_inv.block<3, 3>(0, 0) = Sophus::SO3d::hat(e.so3().log());\n        J_inv.block<3, 3>(3, 3) = Sophus::SO3d::hat(e.so3().log());\n        J_inv.block<3, 3>(0, 3) = Sophus::SO3d::hat(e.translation());\n        J_inv *= 0.5;\n        J_inv += Eigen::Matrix<double, 6, 6>::Identity();\n\n\n        // also possible to approximate J_inv with Identity\n\n        _jacobianOplusXi = -J_inv * T1.inverse().Adj();\n        _jacobianOplusXj = J_inv * T1.inverse().Adj();\n    }\n\n    virtual bool read(std::istream& is) override {\n        double data[7];\n        for (int i = 0; i < 7; ++i)\n            is >> data[i];\n        Eigen::Quaterniond q(data[6], data[3], data[4], data[5]);\n        q.normalize();\n        Eigen::Vector3d t(data);\n        _measurement = Sophus::SE3d(q, t);\n        for (int i = 0; i < _information.rows() && is.good(); ++i)\n        {\n            for (int j = i; j < _information.cols() && is.good(); ++j)\n            {\n                is >> _information(i, j);\n                _information(j, i) = _information(i, j);\n            }\n        }\n        return true;\n    }\n\n    virtual bool write(std::ostream& os) const override {\n        auto *v0 = dynamic_cast<VertexSE3LieAlgebra*>(_vertices[0]);\n        auto *v1 = dynamic_cast<VertexSE3LieAlgebra*>(_vertices[1]);\n        os << v0->id() << \" \" << v1->id() << \" \";\n        auto q = _measurement.unit_quaternion();\n        auto t = _measurement.translation();\n        os << t.x() << \" \" << t.y() << \" \" << t.z() << \" \";\n        os << q.x() << \" \" << q.y() << \" \" << q.z() << \" \" << q.w() << \" \";\n\n        for (int i = 0; i < _information.rows(); ++i)\n        {\n            for (int j = i; j < _information.cols(); ++j)\n            {\n                os << _information(i, j) << \" \";\n            }\n        }\n        os << std::endl;\n        return true;\n    }\n\n};\n\nint main(int argc, char **argv) {\n    if (argc != 2) {\n        cout << \"Usage: pose_graph_g2o_SE3_lie sphere.g2o\" << endl;\n        return 1;\n    }\n    ifstream fin(argv[1]);\n    if (!fin) {\n        cout << \"file \" << argv[1] << \" does not exist.\" << endl;\n        return 1;\n    }\n\n    // \u8bbe\u5b9ag2o\n    typedef g2o::BlockSolver<g2o::BlockSolverTraits<6, 6>> BlockSolverType;\n    typedef g2o::LinearSolverEigen<BlockSolverType::PoseMatrixType> LinearSolverType;\n    auto solver = new g2o::OptimizationAlgorithmLevenberg(\n        g2o::make_unique<BlockSolverType>(g2o::make_unique<LinearSolverType>()));\n    g2o::SparseOptimizer optimizer;\n    optimizer.setAlgorithm(solver);\n    optimizer.setVerbose(true);\n\n    int vertexCnt = 0, edgeCnt = 0;\n\n    vector<VertexSE3LieAlgebra *> vectices;\n    vector<EdgeSE3LieAlgebra *> edges;\n    while (!fin.eof()) {\n        string name;\n        fin >> name;\n        if (name == \"VERTEX_SE3:QUAT\") {\n            // \u9876\u70b9\n            VertexSE3LieAlgebra *v = new VertexSE3LieAlgebra();\n            int index = 0;\n            fin >> index;\n            v->setId(index);\n            v->read(fin);\n            optimizer.addVertex(v);\n            vertexCnt++;\n            vectices.push_back(v);\n            if (index == 0)\n                v->setFixed(true);\n        } else if (name == \"EDGE_SE3:QUAT\") {\n            // SE3-SE3 \u8fb9\n            EdgeSE3LieAlgebra *e = new EdgeSE3LieAlgebra();\n            int idx1, idx2;\n            fin >> idx1 >> idx2;\n            e->setId(edgeCnt++);\n            e->setVertex(0, optimizer.vertices()[idx1]);\n            e->setVertex(1, optimizer.vertices()[idx2]);\n            e->read(fin);\n            optimizer.addEdge(e);\n            edges.push_back(e);\n        }\n        if (!fin.good()) break;\n    }\n\n    cout << \"read total \" << vertexCnt << \" vertices, \" << edgeCnt << \" edges.\" << endl;\n\n    cout << \"optimizing ...\" << endl;\n    optimizer.initializeOptimization();\n    optimizer.optimize(1);\n\n    cout << \"saving optimization results ...\" << endl;\n\n    ofstream fout(\"result_lie.g2o\");\n    for (VertexSE3LieAlgebra *v:vectices) {\n        fout << \"VERTEX_SE3:QUAT \";\n        v->write(fout);\n    }\n    for (EdgeSE3LieAlgebra *e:edges) {\n        fout << \"EDGE_SE3:QUAT \";\n        e->write(fout);\n    }\n    fout.close();\n    debug.close();\n    return 0;\n}\n", "meta": {"hexsha": "3a26df1f93307a80bdda0dd39295ee7b51ed66aa", "size": 6889, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch10/pose_graph_g2o_lie_algebra_custom.cpp", "max_stars_repo_name": "zinsmatt/slambook2", "max_stars_repo_head_hexsha": "3648caff838241553d9f3de332068eb0d501a7dc", "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": "ch10/pose_graph_g2o_lie_algebra_custom.cpp", "max_issues_repo_name": "zinsmatt/slambook2", "max_issues_repo_head_hexsha": "3648caff838241553d9f3de332068eb0d501a7dc", "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": "ch10/pose_graph_g2o_lie_algebra_custom.cpp", "max_forks_repo_name": "zinsmatt/slambook2", "max_forks_repo_head_hexsha": "3648caff838241553d9f3de332068eb0d501a7dc", "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.191588785, "max_line_length": 111, "alphanum_fraction": 0.5386848599, "num_tokens": 1970, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087946129328, "lm_q2_score": 0.8031737892899222, "lm_q1q2_score": 0.7456736095793584}}
{"text": "// Copyright John Maddock 2006\n// Copyright Paul A. Bristow 2007, 2008, 2010\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#ifdef _MSC_VER\n#  pragma warning(disable: 4512) // assignment operator could not be generated.\n#  pragma warning(disable: 4510) // default constructor could not be generated.\n#  pragma warning(disable: 4610) // can never be instantiated - user defined constructor required.\n#  pragma warning(disable: 4180) // qualifier has no effect (in Fusion).\n#endif\n\n#include <iostream>\nusing std::cout; using std::endl;\nusing std::left; using std::fixed; using std::right; using std::scientific;\n#include <iomanip>\nusing std::setw;\nusing std::setprecision;\n\n#include <boost/math/distributions/fisher_f.hpp>\n\nvoid f_test(\n       double sd1,     // Sample 1 std deviation\n       double sd2,     // Sample 2 std deviation\n       double N1,      // Sample 1 size\n       double N2,      // Sample 2 size\n       double alpha)  // Significance level\n{\n   //\n   // An F test applied to two sets of data.\n   // We are testing the null hypothesis that the\n   // standard deviation of the samples is equal, and\n   // that any variation is down to chance.  We can\n   // also test the alternative hypothesis that any\n   // difference is not down to chance.\n   // See http://www.itl.nist.gov/div898/handbook/eda/section3/eda359.htm\n   //\n   // Avoid \"using namespace boost::math;\" because of potential name ambiguity.\n   using boost::math::fisher_f;\n\n   // Print header:\n   cout <<\n      \"____________________________________\\n\"\n      \"F test for equal standard deviations\\n\"\n      \"____________________________________\\n\\n\";\n   cout << setprecision(5);\n   cout << \"Sample 1:\\n\";\n   cout << setw(55) << left << \"Number of Observations\" << \"=  \" << N1 << \"\\n\";\n   cout << setw(55) << left << \"Sample Standard Deviation\" << \"=  \" << sd1 << \"\\n\\n\";\n   cout << \"Sample 2:\\n\";\n   cout << setw(55) << left << \"Number of Observations\" << \"=  \" << N2 << \"\\n\";\n   cout << setw(55) << left << \"Sample Standard Deviation\" << \"=  \" << sd2 << \"\\n\\n\";\n   //\n   // Now we can calculate and output some stats:\n   //\n   // F-statistic:\n   double F = (sd1 / sd2);\n   F *= F;\n   cout << setw(55) << left << \"Test Statistic\" << \"=  \" << F << \"\\n\\n\";\n   //\n   // Finally define our distribution, and get the probability:\n   //\n   fisher_f dist(N1 - 1, N2 - 1);\n   double p = cdf(dist, F);\n   cout << setw(55) << left << \"CDF of test statistic: \" << \"=  \"\n      << setprecision(3) << scientific << p << \"\\n\";\n   double ucv = quantile(complement(dist, alpha));\n   double ucv2 = quantile(complement(dist, alpha / 2));\n   double lcv = quantile(dist, alpha);\n   double lcv2 = quantile(dist, alpha / 2);\n   cout << setw(55) << left << \"Upper Critical Value at alpha: \" << \"=  \"\n      << setprecision(3) << scientific << ucv << \"\\n\";\n   cout << setw(55) << left << \"Upper Critical Value at alpha/2: \" << \"=  \"\n      << setprecision(3) << scientific << ucv2 << \"\\n\";\n   cout << setw(55) << left << \"Lower Critical Value at alpha: \" << \"=  \"\n      << setprecision(3) << scientific << lcv << \"\\n\";\n   cout << setw(55) << left << \"Lower Critical Value at alpha/2: \" << \"=  \"\n      << setprecision(3) << scientific << lcv2 << \"\\n\\n\";\n   //\n   // Finally print out results of null and alternative hypothesis:\n   //\n   cout << setw(55) << left <<\n      \"Results for Alternative Hypothesis and alpha\" << \"=  \"\n      << setprecision(4) << fixed << alpha << \"\\n\\n\";\n   cout << \"Alternative Hypothesis                                    Conclusion\\n\";\n   cout << \"Standard deviations are unequal (two sided test)          \";\n   if((ucv2 < F) || (lcv2 > F))\n      cout << \"NOT REJECTED\\n\";\n   else\n      cout << \"REJECTED\\n\";\n   cout << \"Standard deviation 1 is less than standard deviation 2    \";\n   if(lcv > F)\n      cout << \"NOT REJECTED\\n\";\n   else\n      cout << \"REJECTED\\n\";\n   cout << \"Standard deviation 1 is greater than standard deviation 2 \";\n   if(ucv < F)\n      cout << \"NOT REJECTED\\n\";\n   else\n      cout << \"REJECTED\\n\";\n   cout << endl << endl;\n}\n\nint main()\n{\n   //\n   // Run tests for ceramic strength data:\n   // see http://www.itl.nist.gov/div898/handbook/eda/section4/eda42a1.htm\n   // The data for this case study were collected by Said Jahanmir of the\n   // NIST Ceramics Division in 1996 in connection with a NIST/industry\n   // ceramics consortium for strength optimization of ceramic strength.\n   //\n   f_test(65.54909, 61.85425, 240, 240, 0.05);\n   //\n   // And again for the process change comparison:\n   // see http://www.itl.nist.gov/div898/handbook/prc/section3/prc32.htm\n   // A new procedure to assemble a device is introduced and tested for\n   // possible improvement in time of assembly. The question being addressed\n   // is whether the standard deviation of the new assembly process (sample 2) is\n   // better (i.e., smaller) than the standard deviation for the old assembly\n   // process (sample 1).\n   //\n   f_test(4.9082, 2.5874, 11, 9, 0.05);\n   return 0;\n}\n\n/*\n\nOutput:\n\n  f_test.cpp\n  F-test_example1.vcxproj -> J:\\Cpp\\MathToolkit\\test\\Math_test\\Debug\\F_test_example1.exe\n  ____________________________________\n  F test for equal standard deviations\n  ____________________________________\n  \n  Sample 1:\n  Number of Observations                                 =  240\n  Sample Standard Deviation                              =  65.549\n  \n  Sample 2:\n  Number of Observations                                 =  240\n  Sample Standard Deviation                              =  61.854\n  \n  Test Statistic                                         =  1.123\n  \n  CDF of test statistic:                                 =  8.148e-001\n  Upper Critical Value at alpha:                         =  1.238e+000\n  Upper Critical Value at alpha/2:                       =  1.289e+000\n  Lower Critical Value at alpha:                         =  8.080e-001\n  Lower Critical Value at alpha/2:                       =  7.756e-001\n  \n  Results for Alternative Hypothesis and alpha           =  0.0500\n  \n  Alternative Hypothesis                                    Conclusion\n  Standard deviations are unequal (two sided test)          REJECTED\n  Standard deviation 1 is less than standard deviation 2    REJECTED\n  Standard deviation 1 is greater than standard deviation 2 REJECTED\n  \n  \n  ____________________________________\n  F test for equal standard deviations\n  ____________________________________\n  \n  Sample 1:\n  Number of Observations                                 =  11.00000\n  Sample Standard Deviation                              =  4.90820\n  \n  Sample 2:\n  Number of Observations                                 =  9.00000\n  Sample Standard Deviation                              =  2.58740\n  \n  Test Statistic                                         =  3.59847\n  \n  CDF of test statistic:                                 =  9.589e-001\n  Upper Critical Value at alpha:                         =  3.347e+000\n  Upper Critical Value at alpha/2:                       =  4.295e+000\n  Lower Critical Value at alpha:                         =  3.256e-001\n  Lower Critical Value at alpha/2:                       =  2.594e-001\n  \n  Results for Alternative Hypothesis and alpha           =  0.0500\n  \n  Alternative Hypothesis                                    Conclusion\n  Standard deviations are unequal (two sided test)          REJECTED\n  Standard deviation 1 is less than standard deviation 2    REJECTED\n  Standard deviation 1 is greater than standard deviation 2 NOT REJECTED\n  \n  \n  ____________________________________\n  F test for equal standard deviations\n  ____________________________________\n  \n  Sample 1:\n  Number of Observations                                 =  240\n  Sample Standard Deviation                              =  65.549\n  \n  Sample 2:\n  Number of Observations                                 =  240\n  Sample Standard Deviation                              =  61.854\n  \n  Test Statistic                                         =  1.123\n  \n  CDF of test statistic:                                 =  8.148e-001\n  Upper Critical Value at alpha:                         =  1.238e+000\n  Upper Critical Value at alpha/2:                       =  1.289e+000\n  Lower Critical Value at alpha:                         =  8.080e-001\n  Lower Critical Value at alpha/2:                       =  7.756e-001\n  \n  Results for Alternative Hypothesis and alpha           =  0.0500\n  \n  Alternative Hypothesis                                    Conclusion\n  Standard deviations are unequal (two sided test)          REJECTED\n  Standard deviation 1 is less than standard deviation 2    REJECTED\n  Standard deviation 1 is greater than standard deviation 2 REJECTED\n  \n  \n  ____________________________________\n  F test for equal standard deviations\n  ____________________________________\n  \n  Sample 1:\n  Number of Observations                                 =  11.00000\n  Sample Standard Deviation                              =  4.90820\n  \n  Sample 2:\n  Number of Observations                                 =  9.00000\n  Sample Standard Deviation                              =  2.58740\n  \n  Test Statistic                                         =  3.59847\n  \n  CDF of test statistic:                                 =  9.589e-001\n  Upper Critical Value at alpha:                         =  3.347e+000\n  Upper Critical Value at alpha/2:                       =  4.295e+000\n  Lower Critical Value at alpha:                         =  3.256e-001\n  Lower Critical Value at alpha/2:                       =  2.594e-001\n  \n  Results for Alternative Hypothesis and alpha           =  0.0500\n  \n  Alternative Hypothesis                                    Conclusion\n  Standard deviations are unequal (two sided test)          REJECTED\n  Standard deviation 1 is less than standard deviation 2    REJECTED\n  Standard deviation 1 is greater than standard deviation 2 NOT REJECTED\n  \n \n\n*/\n\n", "meta": {"hexsha": "f7fabdee3967e4a31dbb66887960d3ef3d736b9c", "size": 10033, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/math/example/f_test.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/f_test.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/f_test.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": 39.9721115538, "max_line_length": 98, "alphanum_fraction": 0.5784909798, "num_tokens": 2487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789454880027, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7456500585254254}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  MatrixXf A = MatrixXf::Random(4,4);\nMatrixXf B = MatrixXf::Random(4,4);\nRealQZ<MatrixXf> qz(4); // preallocate space for 4x4 matrices\nqz.compute(A,B);  // A = Q S Z,  B = Q T Z\n\n// print original matrices and result of decomposition\ncout << \"A:\\n\" << A << \"\\n\" << \"B:\\n\" << B << \"\\n\";\ncout << \"S:\\n\" << qz.matrixS() << \"\\n\" << \"T:\\n\" << qz.matrixT() << \"\\n\";\ncout << \"Q:\\n\" << qz.matrixQ() << \"\\n\" << \"Z:\\n\" << qz.matrixZ() << \"\\n\";\n\n// verify precision\ncout << \"\\nErrors:\"\n  << \"\\n|A-QSZ|: \" << (A-qz.matrixQ()*qz.matrixS()*qz.matrixZ()).norm()\n  << \", |B-QTZ|: \" << (B-qz.matrixQ()*qz.matrixT()*qz.matrixZ()).norm()\n  << \"\\n|QQ* - I|: \" << (qz.matrixQ()*qz.matrixQ().adjoint() - MatrixXf::Identity(4,4)).norm()\n  << \", |ZZ* - I|: \" << (qz.matrixZ()*qz.matrixZ().adjoint() - MatrixXf::Identity(4,4)).norm()\n  << \"\\n\";\n\n  return 0;\n}\n", "meta": {"hexsha": "81538e56804cbdeeb6e9b56d5070c2d4ee793ef1", "size": 970, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_RealQZ_compute.cpp", "max_stars_repo_name": "TANHAIYU/Self-calibration-using-Homography-Constraints", "max_stars_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-03-17T16:34:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-17T18:30:13.000Z", "max_issues_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_RealQZ_compute.cpp", "max_issues_repo_name": "TANHAIYU/planecalib", "max_issues_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "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": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_RealQZ_compute.cpp", "max_forks_repo_name": "TANHAIYU/planecalib", "max_forks_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "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.3333333333, "max_line_length": 94, "alphanum_fraction": 0.5494845361, "num_tokens": 369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026573249612, "lm_q2_score": 0.8128673201042493, "lm_q1q2_score": 0.7456453527842478}}
{"text": "/**\n * @file matode.cc\n * @brief NPDE homework MatODE code\n * @copyright Developed at ETH Zurich\n */\n\n#include <Eigen/Dense>\n\nnamespace MatODE {\n\n/* SAM_LISTING_BEGIN_3 */\nEigen::MatrixXd eeulstep(const Eigen::MatrixXd& A, const Eigen::MatrixXd& Y0,\n                         double h) {\n  //====================\n  // Your code goes here\n\n  // explicit Euler step\n  return Y0 + h * A * Y0;\n\n  //====================\n  //return Y0;\n}\n/* SAM_LISTING_END_3 */\n\n/* SAM_LISTING_BEGIN_4 */\nEigen::MatrixXd ieulstep(const Eigen::MatrixXd& A, const Eigen::MatrixXd& Y0,\n                         double h) {\n  //====================\n  // Your code goes here\n\n  // implicit Euler step\n  \n  return (Eigen::MatrixXd::Identity(Y0.rows(), Y0.cols()) - h*A).lu().solve(Y0);\n\n  //====================\n  //return Y0;\n}\n/* SAM_LISTING_END_4 */\n\n/* SAM_LISTING_BEGIN_5 */\nEigen::MatrixXd impstep(const Eigen::MatrixXd& A, const Eigen::MatrixXd& Y0,\n                        double h) {\n  //====================\n  // Your code goes here\n\n  return (Eigen::MatrixXd::Identity(Y0.rows(), Y0.cols()) - h/2. * A).lu().solve(Y0 + h/2. * A * Y0);\n\n  //====================\n  //return Y0;\n}\n/* SAM_LISTING_END_5 */\n\n}  // namespace MatODE\n", "meta": {"hexsha": "701489794d13c270fa35a1d43d6fedd82fa05738", "size": 1209, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/MatODE/mysolution/matode.cc", "max_stars_repo_name": "rjs02/NPDECODES", "max_stars_repo_head_hexsha": "e15e492f7fd5a0a02a6c27c31673d2afc925b7d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-22T10:59:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T10:59:19.000Z", "max_issues_repo_path": "homeworks/MatODE/mysolution/matode.cc", "max_issues_repo_name": "rjs02/NPDECODES", "max_issues_repo_head_hexsha": "e15e492f7fd5a0a02a6c27c31673d2afc925b7d5", "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": "homeworks/MatODE/mysolution/matode.cc", "max_forks_repo_name": "rjs02/NPDECODES", "max_forks_repo_head_hexsha": "e15e492f7fd5a0a02a6c27c31673d2afc925b7d5", "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.3888888889, "max_line_length": 101, "alphanum_fraction": 0.535153019, "num_tokens": 325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412809, "lm_q2_score": 0.8652240860523328, "lm_q1q2_score": 0.7454236160060866}}
{"text": "#include <iostream>\r\nstruct init {\r\n  init() { std::cout << \"[\" << \"init\" << \"]\" << std::endl; }\r\n};\r\ninit init_obj;\r\n// [init]\r\n#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  MatrixXd A(2,2);\r\n  A << 2, -1, 1, 3;\r\n  cout << \"Here is the input matrix A before decomposition:\\n\" << A << endl;\r\ncout << \"[init]\" << endl;\r\n\r\ncout << \"[declaration]\" << endl;\r\n  PartialPivLU<Ref<MatrixXd> > lu(A);\r\n  cout << \"Here is the input matrix A after decomposition:\\n\" << A << endl;\r\ncout << \"[declaration]\" << endl;\r\n\r\ncout << \"[matrixLU]\" << endl;\r\n  cout << \"Here is the matrix storing the L and U factors:\\n\" << lu.matrixLU() << endl;\r\ncout << \"[matrixLU]\" << endl;\r\n\r\ncout << \"[solve]\" << endl;\r\n  MatrixXd A0(2,2); A0 << 2, -1, 1, 3;\r\n  VectorXd b(2);    b << 1, 2;\r\n  VectorXd x = lu.solve(b);\r\n  cout << \"Residual: \" << (A0 * x - b).norm() << endl;\r\ncout << \"[solve]\" << endl;\r\n\r\ncout << \"[modifyA]\" << endl;\r\n  A << 3, 4, -2, 1;\r\n  x = lu.solve(b);\r\n  cout << \"Residual: \" << (A0 * x - b).norm() << endl;\r\ncout << \"[modifyA]\" << endl;\r\n\r\ncout << \"[recompute]\" << endl;\r\n  A0 = A; // save A\r\n  lu.compute(A);\r\n  x = lu.solve(b);\r\n  cout << \"Residual: \" << (A0 * x - b).norm() << endl;\r\ncout << \"[recompute]\" << endl;\r\n\r\ncout << \"[recompute_bis0]\" << endl;\r\n  MatrixXd A1(2,2);\r\n  A1 << 5,-2,3,4;\r\n  lu.compute(A1);\r\n  cout << \"Here is the input matrix A1 after decomposition:\\n\" << A1 << endl;\r\ncout << \"[recompute_bis0]\" << endl;\r\n\r\ncout << \"[recompute_bis1]\" << endl;\r\n  x = lu.solve(b);\r\n  cout << \"Residual: \" << (A1 * x - b).norm() << endl;\r\ncout << \"[recompute_bis1]\" << endl;\r\n\r\n}\r\n", "meta": {"hexsha": "90a1e3a58130d29c9e37aaf788e2ab800da2008f", "size": 1650, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/eigen-eigen-323c052e1731/doc/examples/TutorialInplaceLU.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/TutorialInplaceLU.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/TutorialInplaceLU.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": 26.6129032258, "max_line_length": 88, "alphanum_fraction": 0.5266666667, "num_tokens": 545, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381952105441, "lm_q2_score": 0.865224073888819, "lm_q1q2_score": 0.7454235870708875}}
{"text": "#include \"hpcpp/ex1.hpp\"\n#include <Eigen/Dense>\n\nnamespace hpcpp {\n\nvoid matmul1(const std::vector<double> &matrix,\n             const std::vector<double> &vector, std::vector<double> &result) {\n  const std::size_t n{vector.size()};\n  result.resize(n, 0.0);\n  std::fill(begin(result), end(result), 0);\n  for (std::size_t j = 0; j < n; ++j) {\n    for (std::size_t i = 0; i < n; ++i) {\n      result[i] += matrix[i * n + j] * vector[j];\n    }\n  }\n}\n\nvoid matmul2(const std::vector<double> &matrix,\n             const std::vector<double> &vector, std::vector<double> &result) {\n  const std::size_t n{vector.size()};\n  result.resize(n, 0.0);\n  std::fill(begin(result), end(result), 0);\n  for (std::size_t i = 0; i < n; ++i) {\n    for (std::size_t j = 0; j < n; ++j) {\n      result[i] += matrix[i * n + j] * vector[j];\n    }\n  }\n}\n\nvoid matmul3(const std::vector<double> &matrix,\n             const std::vector<double> &vector, std::vector<double> &result) {\n  const std::size_t n{vector.size()};\n  result.resize(n, 0.0);\n  std::fill(begin(result), end(result), 0);\n  for (std::size_t i = 0; i < n; ++i) {\n    double r{0};\n#pragma omp simd reduction(+ : r)\n    // note: using signed int for MSVC OpenMP:\n    // https://docs.microsoft.com/en-us/cpp/error-messages/compiler-errors-2/compiler-error-c3016?view=msvc-170\n    for (int j = 0; j < n; ++j) {\n      r += matrix[i * n + j] * vector[j];\n    }\n    result[i] = r;\n  }\n}\n\nvoid matmul4(const std::vector<double> &matrix,\n             const std::vector<double> &vector, std::vector<double> &result) {\n  const std::size_t n{vector.size()};\n  result.resize(n, 0.0);\n  std::fill(begin(result), end(result), 0);\n#pragma omp parallel for schedule(static) default(none)                        \\\n    shared(n, matrix, vector, result)\n  for (int i = 0; i < n; ++i) {\n    double r{0};\n#pragma omp simd reduction(+ : r)\n    for (int j = 0; j < n; ++j) {\n      r += matrix[i * n + j] * vector[j];\n    }\n    result[i] = r;\n  }\n}\n\nvoid matmul5(const std::vector<double> &matrix,\n             const std::vector<double> &vector, std::vector<double> &result) {\n  const std::size_t n{vector.size()};\n  result.resize(n, 0.0);\n  Eigen::Map<const Eigen::MatrixXd> m(matrix.data(), n, n);\n  Eigen::Map<const Eigen::VectorXd> v(vector.data(), n);\n  Eigen::Map<Eigen::VectorXd> r(result.data(), n);\n  r = m.transpose() * v;\n}\n\n} // namespace hpcpp\n", "meta": {"hexsha": "e93d74471d3ab391e45d3bd9eb45f6842e134a3b", "size": 2369, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ex1.cpp", "max_stars_repo_name": "ssciwr/high-performance-cpp", "max_stars_repo_head_hexsha": "dfe5e92ce90c36cf86df51568688b9503c76b0fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-11T08:31:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T08:31:19.000Z", "max_issues_repo_path": "src/ex1.cpp", "max_issues_repo_name": "ssciwr/high-performance-cpp", "max_issues_repo_head_hexsha": "dfe5e92ce90c36cf86df51568688b9503c76b0fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2022-03-16T08:58:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-17T09:29:20.000Z", "max_forks_repo_path": "src/ex1.cpp", "max_forks_repo_name": "ssciwr/high-performance-cpp", "max_forks_repo_head_hexsha": "dfe5e92ce90c36cf86df51568688b9503c76b0fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-09T16:03:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T16:03:04.000Z", "avg_line_length": 31.5866666667, "max_line_length": 111, "alphanum_fraction": 0.5821021528, "num_tokens": 739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.8289388040954684, "lm_q1q2_score": 0.7453166036922826}}
{"text": "//\n// OpenTissue, A toolbox for physical based simulation and animation.\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\n//\n#include <OpenTissue/configuration.h>\n\n#include <OpenTissue/core/math/big/big_types.h>\n#include <OpenTissue/core/math/optimization/optimization_projected_bfgs.h>\n#include <OpenTissue/core/math/big/big_generate_random.h>\n#include <OpenTissue/core/math/big/big_generate_PD.h>\n#include <OpenTissue/core/math/big/io/big_matlab_write.h>\n#include <OpenTissue/core/math/optimization/optimization_project.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <OpenTissue/utility/utility_push_boost_filter.h>\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n#include <OpenTissue/utility/utility_pop_boost_filter.h>\n\ntypedef double real_type;\ntypedef ublas::compressed_matrix<real_type> matrix_type;\ntypedef ublas::vector<real_type>            vector_type;\ntypedef vector_type::size_type              size_type;\n\nclass F\n{\npublic:\n  matrix_type const & m_A;\n  vector_type const & m_b;\n\n  F(matrix_type const & A, vector_type const & b)\n    : m_A(A)\n    , m_b(b)\n  {}\n\n  real_type operator()( vector_type const & x ) const\n  {\n    return ublas::inner_prod(x, ublas::prod(m_A,x)) - inner_prod(m_b, x);\n  }\n};\n\nclass nabla_F\n{\npublic:\n  matrix_type const & m_A;\n  vector_type const & m_b;\n\n  nabla_F(matrix_type const & A, vector_type const & b)\n    : m_A(A)\n    , m_b(b)\n  {}\n\n  vector_type operator()( vector_type const & x ) const\n  {\n    return  vector_type( 2*ublas::prod(m_A,x) - m_b );\n  }\n};\n\nclass ProjectionOperator\n{\npublic:\n  vector_type const & m_l;\n  vector_type const & m_u;\n\n  ProjectionOperator(vector_type const & l, vector_type const & u)\n    : m_l(l)\n    , m_u(u)\n  {}\n\n  vector_type operator()( vector_type const & x ) const\n  {\n    vector_type y;\n    y.resize(x.size());\n    OpenTissue::math::optimization::project(x,m_l,m_u,y);\n    return  y;\n  }\n};\n\n\n\n\nvoid do_test(F & f, nabla_F & nabla_f, vector_type & x, matrix_type & H, ProjectionOperator & P, vector_type const & y)\n{\n  using namespace OpenTissue::math::big;\n\n  size_type max_iterations       = 100;\n  real_type absolute_tolerance   = boost::numeric_cast<real_type>(1e-6);\n  real_type relative_tolerance   = boost::numeric_cast<real_type>(0.000000001);\n  real_type stagnation_tolerance = boost::numeric_cast<real_type>(0.000000001);\n  size_t status = 0;\n  size_type iteration = 0;\n  real_type accuracy = boost::numeric_cast<real_type>(0.0);\n  real_type alpha = boost::numeric_cast<real_type>(0.0001);\n  real_type beta = boost::numeric_cast<real_type>(0.5);\n\n  OpenTissue::math::optimization::projected_bfgs(\n    f\n    , nabla_f\n    , H\n    , x \n    , P\n    , max_iterations\n    , absolute_tolerance\n    , relative_tolerance\n    , stagnation_tolerance\n    , status\n    , iteration\n    , accuracy\n    , alpha\n    , beta\n    );\n\n  std::cout << \"status     = \" \n    << OpenTissue::math::optimization::get_error_message(status) \n    << std::endl;\n  std::cout << \"absolute   = \" \n    << accuracy  \n    << std::endl;\n  std::cout << \"iterations = \" \n    << iteration \n    << std::endl;\n  std::cout << \"x          = \" \n    << x \n    << std::endl;\n\n  if(status==OpenTissue::math::optimization::ABSOLUTE_CONVERGENCE)\n  {\n    BOOST_CHECK( accuracy < absolute_tolerance );\n    BOOST_CHECK( iteration <= max_iterations );\n  }\n\n  double tol = 0.001;\n  for(size_t i = 0;i<x.size();++i)\n    BOOST_CHECK_CLOSE( x(i), y(i), tol);\n}\n\nBOOST_AUTO_TEST_SUITE(opentissue_math_big_projected_bfgs);\n\nBOOST_AUTO_TEST_CASE(unconstrained_global_minimizer)\n{\n  using namespace OpenTissue::math::big;\n\n  // We are solving the problem\n  //\n  //   min_x Q(x) = x^T A x - b^T x\n  //\n  // where the gradient is given by\n  //\n  //   nabla Q(x) = 2 A x - b = 0\n  //\n  // and the exact Hessian is\n  //\n  //   H = nabla^2 Q(x) = 2 A\n  //\n  // The stationary points are given by \n  //\n  //  | 4 0| |x_1| + | -1| = 0\n  //  | 0 4| |x_2|   | -2|\n  //\n  // and has the unique solution x = [-0.25, -0.5]^T\n  //\n  size_type N = 2;\n\n  matrix_type A;\n  A.resize(N,N,false);\n\n  vector_type b;\n  b.resize(N,false);\n\n  A(0,0) = 2.0;  A(0,1) = 0.0;\n  A(1,0) = 0.0;  A(1,1) = 2.0;  \n\n  b(0) = -1.0;\n  b(1) = -2.0;\n\n  F f(A,b);\n  nabla_F nabla_f(A,b);\n\n  vector_type x;\n  x.resize(N,false);\n\n  vector_type y;\n  y.resize(N,false);\n  y(0) = -0.25;\n  y(1) = -0.5;\n\n  matrix_type H;\n  H.resize(N,N,false);\n\n  vector_type l;\n  vector_type u;\n\n  l.resize(N,false);\n  u.resize(N,false);\n\n  l(0) = -1.0;\n  l(1) = -1.0;\n  u(0) =  1.0;\n  u(1) =  1.0;\n\n  ProjectionOperator P(l,u);\n\n  // use H = I/4, and x = 0\n  x.clear();\n  H(0,0) = 0.25;   H(0,1) = 0.0;\n  H(1,0) = 0.0;    H(1,1) = 0.25;   \n  do_test(f,nabla_f,x,H,P,y);\n\n  // use H = I, and x = 0\n  x.clear();\n  H(0,0) = 1.0;   H(0,1) = 0.0;\n  H(1,0) = 0.0;    H(1,1) = 1.0;   \n  do_test(f,nabla_f,x,H,P,y);\n\n  // use H = 4*I, and x = 0\n  x.clear();\n  H(0,0) = 4.0;   H(0,1) = 0.0;\n  H(1,0) = 0.0;    H(1,1) = 4.0;   \n  do_test(f,nabla_f,x,H,P,y);\n\n  // use H = I/4, and x = random\n  OpenTissue::math::big::generate_random( 2, x);\n  H(0,0) = 0.25;   H(0,1) = 0.0;\n  H(1,0) = 0.0;    H(1,1) = 0.25;   \n  do_test(f,nabla_f,x,H,P,y);\n\n  // use H = I, and x = random\n  OpenTissue::math::big::generate_random( 2, x);\n  H(0,0) = 1.0;   H(0,1) = 0.0;\n  H(1,0) = 0.0;    H(1,1) = 1.0;   \n  do_test(f,nabla_f,x,H,P,y);\n\n  // use H = 4*I, and x = random\n  OpenTissue::math::big::generate_random( 2, x);\n  H(0,0) = 4.0;   H(0,1) = 0.0;\n  H(1,0) = 0.0;    H(1,1) = 4.0;   \n  do_test(f,nabla_f,x,H,P,y);\n\n  // use H = random PD, and x = 0\n  x.clear();\n  OpenTissue::math::big::generate_PD(2, H);\n  do_test(f,nabla_f,x,H,P,y);\n\n  // use H = random PD, and x = random\n  OpenTissue::math::big::generate_random( 2, x);\n  OpenTissue::math::big::generate_PD(2, H);\n  do_test(f,nabla_f,x,H,P,y);\n\n  // H = g g^T, x = 0\n  x.clear();\n  vector_type g;\n  g.resize(N,false);\n  g = nabla_f(x);\n  H = ublas::outer_prod(g,g);\n  do_test(f,nabla_f,x,H,P,y);\n\n  // H = g g^T, x = random\n  OpenTissue::math::big::generate_random( 2, x);\n  g = nabla_f(x);\n  H = ublas::outer_prod(g,g);\n  do_test(f,nabla_f,x,H,P,y);\n\n  // H = exact Hessian, x = solution!\n  x(0) = -0.25;\n  x(1) = -0.5;\n  H(0,0) = 4.0;   H(0,1) = 0.0;\n  H(1,0) = 0.0;    H(1,1) = 4.0;   \n  do_test(f,nabla_f,x,H,P,y);\n\n}\n\n\nBOOST_AUTO_TEST_CASE(constrained_global_minimizer)\n{\n  using namespace OpenTissue::math::big;\n\n  // We are solving the problem\n  //\n  //   min_x Q(x) = x^T A x - b^T x\n  //\n  // where the gradient is given by\n  //\n  //   nabla Q(x) = 2 A x - b = 0\n  //\n  // and the exact Hessian is\n  //\n  //   H = nabla^2 Q(x) = 2 A\n  //\n  // The stationary points are given by \n  //\n  //  | 4 0| |x_1| + | -1| = 0\n  //  | 0 4| |x_2|   | -2|\n  //\n  // and has the unique solution x = [-0.25, -0.5]^T\n  //\n  size_type N = 2;\n\n  matrix_type A;\n  A.resize(N,N,false);\n\n  vector_type b;\n  b.resize(N,false);\n\n  A(0,0) = 2.0;  A(0,1) = 0.0;\n  A(1,0) = 0.0;  A(1,1) = 2.0;  \n\n  b(0) = -1.0;\n  b(1) = -2.0;\n\n  F f(A,b);\n  nabla_F nabla_f(A,b);\n\n  vector_type x;\n  x.resize(N,false);\n\n  vector_type l;\n  vector_type u;\n  l.resize(N,false);\n  u.resize(N,false);\n  l(0) = 0.0;\n  l(1) = -1.0;\n  u(0) =  1.0;\n  u(1) =  1.0;\n\n  vector_type y;\n  y.resize(N,false);\n  y(0) = 0.0;\n  y(1) = -0.5;\n\n  matrix_type H;\n  H.resize(N,N,false);\n\n  ProjectionOperator P(l,u);\n\n  // use H = I/4, and x = 0\n  x.clear();\n  H(0,0) = 0.25;   H(0,1) = 0.0;\n  H(1,0) = 0.0;    H(1,1) = 0.25;   \n  do_test(f,nabla_f,x,H,P,y);\n\n  // use H = I, and x = 0\n  x.clear();\n  H(0,0) = 1.0;   H(0,1) = 0.0;\n  H(1,0) = 0.0;    H(1,1) = 1.0;   \n  do_test(f,nabla_f,x,H,P,y);\n\n  // use H = 4*I, and x = 0\n  x.clear();\n  H(0,0) = 4.0;   H(0,1) = 0.0;\n  H(1,0) = 0.0;    H(1,1) = 4.0;   \n  do_test(f,nabla_f,x,H,P,y);\n\n  // use H = I/4, and x = random\n  OpenTissue::math::big::generate_random( 2, x);\n  H(0,0) = 0.25;   H(0,1) = 0.0;\n  H(1,0) = 0.0;    H(1,1) = 0.25;   \n  do_test(f,nabla_f,x,H,P,y);\n\n  // use H = I, and x = random\n  OpenTissue::math::big::generate_random( 2, x);\n  H(0,0) = 1.0;   H(0,1) = 0.0;\n  H(1,0) = 0.0;    H(1,1) = 1.0;   \n  do_test(f,nabla_f,x,H,P,y);\n\n  // use H = 4*I, and x = random\n  OpenTissue::math::big::generate_random( 2, x);\n  H(0,0) = 4.0;   H(0,1) = 0.0;\n  H(1,0) = 0.0;    H(1,1) = 4.0;   \n  do_test(f,nabla_f,x,H,P,y);\n\n  // use H = random PD, and x = 0\n  x.clear();\n  OpenTissue::math::big::generate_PD(2, H);\n  do_test(f,nabla_f,x,H,P,y);\n\n  // use H = random PD, and x = random\n  OpenTissue::math::big::generate_random( 2, x);\n  OpenTissue::math::big::generate_PD(2, H);\n  do_test(f,nabla_f,x,H,P,y);\n\n  // H = g g^T, x = 0\n  x.clear();\n  vector_type g;\n  g.resize(N,false);\n  g = nabla_f(x);\n  H = ublas::outer_prod(g,g);\n  do_test(f,nabla_f,x,H,P,y);\n\n  // H = g g^T, x = random\n  OpenTissue::math::big::generate_random( 2, x);\n  g = nabla_f(x);\n  H = ublas::outer_prod(g,g);\n  do_test(f,nabla_f,x,H,P,y);\n\n  // H = exact Hessian, x = solution!\n  x(0) = -0.25;\n  x(1) = -0.5;\n  H(0,0) = 4.0;   H(0,1) = 0.0;\n  H(1,0) = 0.0;    H(1,1) = 4.0;   \n  do_test(f,nabla_f,x,H,P,y);\n\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "445d48a7420e1e6afe0f707774642d5c61c004dc", "size": 9171, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/core/math/optimization/projected_bfgs/src/unit_projected_bfgs.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:45:06.000Z", "max_issues_repo_path": "unit_tests/core/math/optimization/projected_bfgs/src/unit_projected_bfgs.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-20T14:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T15:26:45.000Z", "max_forks_repo_path": "unit_tests/core/math/optimization/projected_bfgs/src/unit_projected_bfgs.cpp", "max_forks_repo_name": "ricortiz/OpenTissue", "max_forks_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T01:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:06:49.000Z", "avg_line_length": 22.5331695332, "max_line_length": 119, "alphanum_fraction": 0.5783447825, "num_tokens": 3631, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045817875224, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.7450158200430068}}
{"text": "//! [example1]\n#include <Eigen/Dense>\n#include <iostream>\n#include \"../../include/model.h\"\n\n\nint main(){\n\t//using the Eigen library to implement the exact same class (conceptually) as above\t\n\tclass odeSimpleExampleEigen: public continuousModel<Eigen::VectorXd>{\n\t\tprivate:\n\t\t\tEigen::MatrixXd modelMatrix;\n\t\tpublic:\n\t\t\t//can add constructor to make your model more adjustable and reusable\n\t\t\todeSimpleExampleEigen(double exp){\n\t\t\t\tEigen::MatrixXd tmp(1,1);\n\t\t\t\ttmp<<exp;\n\t\t\t\tmodelMatrix = tmp;\n\t\t\t}\n\t\t\tEigen::VectorXd function(const Eigen::VectorXd & val, const double time) const override{\n\t\t\t\treturn modelMatrix*val;\n\t\t\t}\n\t};\n\n\tdouble exponent = -0.1;\n\todeSimpleExampleEigen ose2(exponent);\n\t\n\tdouble timeEvaluatedAt = 10;\n\tdouble valueAtTime = 1;\n\tEigen::VectorXd tmp(1); tmp<<valueAtTime;\n\n\tstd::cout<<ose2.function(tmp,timeEvaluatedAt) <<std::endl;\n\t/* produces the output:\n\t * -0.1\n\t */\n};\n//! [example1]\n", "meta": {"hexsha": "0638f9734256ffaeff80a65290e54965cddbacaf", "size": 910, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++_implementation/examples/model/continuousModel2.cpp", "max_stars_repo_name": "mannyray/KalmanFilter", "max_stars_repo_head_hexsha": "c744b0ef8a004643b373fa4cfd1440f32d5725b7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2019-08-12T04:47:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T13:00:09.000Z", "max_issues_repo_path": "c++_implementation/examples/model/continuousModel2.cpp", "max_issues_repo_name": "mannyray/KalmanFilter", "max_issues_repo_head_hexsha": "c744b0ef8a004643b373fa4cfd1440f32d5725b7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-03-27T00:49:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-27T02:03:37.000Z", "max_forks_repo_path": "c++_implementation/examples/model/continuousModel2.cpp", "max_forks_repo_name": "mannyray/KalmanFilter", "max_forks_repo_head_hexsha": "c744b0ef8a004643b373fa4cfd1440f32d5725b7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2020-02-03T09:05:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-18T15:22:08.000Z", "avg_line_length": 24.5945945946, "max_line_length": 91, "alphanum_fraction": 0.7010989011, "num_tokens": 242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837706, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.74496975252995}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  MatrixXd X = MatrixXd::Random(5,5);\nMatrixXd A = X + X.transpose();\ncout << \"Here is a random symmetric 5x5 matrix, A:\" << endl << A << endl << endl;\n\nSelfAdjointEigenSolver<MatrixXd> es(A);\ncout << \"The eigenvalues of A are:\" << endl << es.eigenvalues() << endl;\ncout << \"The matrix of eigenvectors, V, is:\" << endl << es.eigenvectors() << endl << endl;\n\ndouble lambda = es.eigenvalues()[0];\ncout << \"Consider the first eigenvalue, lambda = \" << lambda << endl;\nVectorXd v = es.eigenvectors().col(0);\ncout << \"If v is the corresponding eigenvector, then lambda * v = \" << endl << lambda * v << endl;\ncout << \"... and A * v = \" << endl << A * v << endl << endl;\n\nMatrixXd D = es.eigenvalues().asDiagonal();\nMatrixXd V = es.eigenvectors();\ncout << \"Finally, V * D * V^(-1) = \" << endl << V * D * V.inverse() << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "168e1bd213943fabf7725ae8f6c08505264d71a1", "size": 967, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_SelfAdjointEigenSolver_SelfAdjointEigenSolver_MatrixType.cpp", "max_stars_repo_name": "TANHAIYU/Self-calibration-using-Homography-Constraints", "max_stars_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-03-17T16:34:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-17T18:30:13.000Z", "max_issues_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_SelfAdjointEigenSolver_SelfAdjointEigenSolver_MatrixType.cpp", "max_issues_repo_name": "TANHAIYU/planecalib", "max_issues_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "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": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_SelfAdjointEigenSolver_SelfAdjointEigenSolver_MatrixType.cpp", "max_forks_repo_name": "TANHAIYU/planecalib", "max_forks_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "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.2333333333, "max_line_length": 98, "alphanum_fraction": 0.6235780765, "num_tokens": 282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600902, "lm_q2_score": 0.8221891348788759, "lm_q1q2_score": 0.7448949908040954}}
{"text": "/*\nThe following code inverts the matrix input using LU-decomposition with backsubstitution of unit vectors. Reference: Numerical Recipies in C, 2nd ed., by Press, Teukolsky, Vetterling & Flannery.\n\nyou can solve Ax=b using three lines of ublas code:\n\npermutation_matrix<> piv;\nlu_factorize(A, piv);\nlu_substitute(A, piv, x);\n\n*/\n #ifndef INVERT_MATRIX_HPP\n #define INVERT_MATRIX_HPP\n\n // REMEMBER to update \"lu.hpp\" header includes from boost-CVS\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/triangular.hpp>\n #include <boost/numeric/ublas/lu.hpp>\n #include <boost/numeric/ublas/io.hpp>\n\nnamespace bnu = boost::numeric::ublas;\n\n/* Matrix inversion routine.\nUses lu_factorize and lu_substitute in uBLAS to invert a matrix */\ntemplate<class T>\nbool InvertMatrix(const boost::numeric::ublas::matrix<T>& input, boost::numeric::ublas::matrix<T>& inverse)\n{\n   typedef boost::numeric::ublas::permutation_matrix<std::size_t> pmatrix;\n\n   // create a working copy of the input\n   boost::numeric::ublas::matrix<T> A(input);\n\n   // create a permutation matrix for the LU-factorization\n   pmatrix pm(A.size1());\n\n   // perform LU-factorization\n   int res = boost::numeric::ublas::lu_factorize(A, pm);\n   if (res != 0)\n       return false;\n\n   // create identity matrix of \"inverse\"\n   inverse.assign(boost::numeric::ublas::identity_matrix<T> (A.size1()));\n\n   // backsubstitute to get the inverse\n   boost::numeric::ublas::lu_substitute(A, pm, inverse);\n\n   return true;\n}\n\n\n \nint determinant_sign(const bnu::permutation_matrix<std ::size_t>& pm)\n{\n    int pm_sign=1;\n    std::size_t size = pm.size();\n    for (std::size_t i = 0; i < size; ++i)\n        if (i != pm(i))\n            pm_sign *= -1.0; // swap_rows would swap a pair of rows here, so we change sign\n    return pm_sign;\n}\n \ndouble determinant( bnu::matrix<double>& m ) {\n    bnu::permutation_matrix<std ::size_t> pm(m.size1());\n    double det = 1.0;\n    if( bnu::lu_factorize(m,pm) ) {\n        det = 0.0;\n    } else {\n        for(int i = 0; i < m.size1(); i++)\n            det *= m(i,i); // multiply by elements on diagonal\n        det = det * determinant_sign( pm );\n    }\n    return det;\n}\n\n #endif //INVERT_MATRIX_HPP\n", "meta": {"hexsha": "b7d57d7714d938bc37d0e7953d7b53e7c549a9c2", "size": 2292, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "invert_matrix.hpp", "max_stars_repo_name": "zernexz/posys2", "max_stars_repo_head_hexsha": "3910631dd99663e6392f2e9862d4d9672ac337d2", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-11-27T21:22:06.000Z", "max_stars_repo_stars_event_max_datetime": "2016-11-27T21:22:06.000Z", "max_issues_repo_path": "invert_matrix.hpp", "max_issues_repo_name": "zernexz/posys2", "max_issues_repo_head_hexsha": "3910631dd99663e6392f2e9862d4d9672ac337d2", "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": "invert_matrix.hpp", "max_forks_repo_name": "zernexz/posys2", "max_forks_repo_head_hexsha": "3910631dd99663e6392f2e9862d4d9672ac337d2", "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": 29.7662337662, "max_line_length": 194, "alphanum_fraction": 0.6788830716, "num_tokens": 638, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834278, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7448949826827885}}
{"text": "#include <iostream>\n#include <tuple>\n#include <Eigen/Dense>\n#include \"linear_algebra_addon.hpp\"\nusing namespace Eigen;\nusing namespace std;\n\nMatrixXcd bl_bicg_rq(const MatrixXcd& A, const MatrixXcd& B, const double& tol, const int& itermax)\n{\n    // Rashedi et al 2016, On short recurrence Krylov type methods for linear systems with many right-hand sides\n  double Bnorm= B.norm();\n  MatrixXcd X= MatrixXcd::Zero(B.rows(),B.cols()); // Initial guess of X (zeros)\n  MatrixXcd R= B-A*X;\n  MatrixXcd R_hat= R; // or Rhat= R.conjugate();\n  MatrixXcd Q;\n  MatrixXcd C;\n  tie(Q,C)= qr_reduced(R);\n  MatrixXcd Q_hat;\n  MatrixXcd C_hat;\n  tie(Q_hat,C_hat)= qr_reduced(R_hat);\n  MatrixXcd V= Q;\n  MatrixXcd V_hat= Q_hat;\n\n  for(int k= 0; k < itermax; ++k){\n      MatrixXcd W= A*V;\n      MatrixXcd W_hat= A.adjoint()*V_hat;\n\n      MatrixXcd alpha= (V_hat.adjoint()*W).fullPivLu().solve(Q_hat.adjoint()*Q);\n      MatrixXcd alpha_hat= (V.adjoint()*W_hat).fullPivLu().solve(Q.adjoint()*Q_hat);\n\n      X= X+V*alpha*C;\n\n      MatrixXcd Qnew;\n      MatrixXcd S;\n      tie(Qnew,S)= qr_reduced(Q-W*alpha);\n      C= S*C;\n\n      MatrixXcd Qnew_hat;\n      MatrixXcd S_hat;\n      tie(Qnew_hat,S_hat)= qr_reduced(Q_hat-W_hat*alpha_hat);\n      C_hat= S_hat*C_hat;\n\n      double err= C.norm()/Bnorm;\n      cout << \"bl_bicg_rq: \" << \"iter= \" << k << \" relative err= \" << err << endl;\n      if(err < tol) break;\n\n      MatrixXcd beta= (Q_hat.adjoint()*Q).fullPivLu().solve(S_hat.adjoint()*Qnew_hat.adjoint()*Qnew);\n      MatrixXcd beta_hat= (Q.adjoint()*Q_hat).fullPivLu().solve(S.adjoint()*Qnew.adjoint()*Qnew_hat);\n\n      Q= Qnew;\n      Q_hat= Qnew_hat;\n\n      V= Q+V*beta;\n      V_hat= Q_hat+V_hat*beta_hat;\n  }\n\n  if((A*X-B).norm()/Bnorm > 10*tol){\n      cerr << \"bl_bicg_rq did not converge to solution within error tolerance !\" << endl;\n     // exit(EXIT_FAILURE);\n  }\n\n  return X;\n}\n", "meta": {"hexsha": "987f2797fb954c04a6fc64e6aa277b1710a1e860", "size": 1863, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bl_bicg_rq.cpp", "max_stars_repo_name": "nmoteki/block-Krylov-linear-solvers", "max_stars_repo_head_hexsha": "0c123f474296219c1b944ad83f8e3c7abbf0c2b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-27T08:44:06.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-27T08:44:06.000Z", "max_issues_repo_path": "bl_bicg_rq.cpp", "max_issues_repo_name": "nmoteki/block-Krylov-linear-solvers", "max_issues_repo_head_hexsha": "0c123f474296219c1b944ad83f8e3c7abbf0c2b0", "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": "bl_bicg_rq.cpp", "max_forks_repo_name": "nmoteki/block-Krylov-linear-solvers", "max_forks_repo_head_hexsha": "0c123f474296219c1b944ad83f8e3c7abbf0c2b0", "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.109375, "max_line_length": 112, "alphanum_fraction": 0.639828234, "num_tokens": 607, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632896242073, "lm_q2_score": 0.8031737869342623, "lm_q1q2_score": 0.7448338851912897}}
{"text": "#include <iostream>\n#include <vector>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <Eigen/SparseLU>\n\nusing Triplet = Eigen::Triplet<double>;\nusing Triplets = std::vector<Triplet>;\n\nusing Vector = Eigen::VectorXd;\nusing Matrix = Eigen::SparseMatrix<double>;\n\n//! \\brief Efficiently construct the sparse matrix A given c, i_0 and j_0\n//! \\param[in] c contains entries c_i for matrix A\n//! \\param[in] i0 row index i_0\n//! \\param[in] j0 column index j_0\n//! \\return Sparse matrix A\nMatrix buildA(const Vector & c, unsigned int i0, unsigned int j0) {\n    assert(i0 > j0);\n    \n    unsigned int n = c.size() + 1;\n    Matrix A(n,n);\n    Triplets triplets;\n    \n    // TODO: problem 2a, construct and return the matrix A given c, i0 and j0\n    \n    return A;\n}\n\n//! \\brief Solve the system Ax = b with optimal complexity O(n)\n//! \\param[in] c contains entries c_i for matrix A\n//! \\param[in] b r.h.s. vector\n//! \\param[in] i0 row index\n//! \\param[in] j0 column index\n//! \\return Solution x, s.t. Ax = b\nVector solveLSE(const Vector & c, const Vector & b, unsigned int i0, unsigned int j0) {\n    assert(c.size() == b.size()-1 && \"Size mismatch!\");\n    assert(i0 > j0);\n    \n    // Allocate solution vector\n    Vector ret(b.size());\n    \n    // TODO: problem 2b, solve system Ax = b in O(n)\n    \n    return ret;\n}\n\nint main(int, char**) {\n    // Setup data for problem\n    unsigned int n = 15; // A is n x n matrix, b has length x\n    \n    unsigned int i0 = 6, j0 = 4;\n    \n    Vector b = Vector::Random(n); // Random vector for b\n    Vector c = Vector::Random(n-1); // Random vector for c\n    \n    //// PROBLEM 2a\n    std::cout << \"*** PROBLEM 2a:\" << std::endl;\n    \n    // Solve sparse system using sparse LU and our own routine\n    Matrix A = buildA(c, i0, j0);\n    A.makeCompressed();\n    Eigen::SparseLU<Matrix> splu;\n    splu.analyzePattern(A); \n    splu.factorize(A);\n    \n    std::cout << \"Error: \" << std::endl << ( splu.solve(b) - solveLSE(c, b, i0, j0) ).norm() << std::endl;\n}\n", "meta": {"hexsha": "b3782f940f7b4cedaeaf69ba4f9a901aacaf6396", "size": 1991, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mockExam/ex_sparseLS/template_sparse_solver.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": "mockExam/ex_sparseLS/template_sparse_solver.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": "mockExam/ex_sparseLS/template_sparse_solver.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": 28.8550724638, "max_line_length": 106, "alphanum_fraction": 0.6192867906, "num_tokens": 587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278540866548, "lm_q2_score": 0.8438950966654774, "lm_q1q2_score": 0.7446765392247673}}
{"text": "/* \nA palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 \u00d7 99.\nFind the largest palindrome made from the product of two 3 - digit numbers.\n*/\n\n#include <iostream>\n#include <math.h>\n#include <string>\n#include <sstream>\n#include <Eigen/Dense>\nusing namespace std;\n\nint is_palindrome(int n) {\n    string digits = to_string(n);\n    int n_size = digits.length();\n    bool result = true;\n    for (int i = 0; i < n_size/2; i++) {\n        result = result && (digits[i] == digits[n_size - i - 1]);\n    }\n    if (result){\n        return 1;\n    }\n    else {\n        return 0;\n    }\n}\n\nint main()\n{\n\n    int min_number = 100;\n    int max_number = 999;\n    int size = max_number - min_number + 1;\n\n    Eigen::VectorXi vec(size);\n    for (int i = 0; i < size; i++) {\n        vec(i) = min_number + i;\n    }\n    Eigen::MatrixXi tab(size, size);\n    for (int i = 0; i < size; i++) {\n        for (int j = 0; j < size; j++) {\n            tab(i, j) = vec(i) * vec(j);\n        }\n    }\n    Eigen::MatrixXi tab_palindrome(size, size);\n    for (int i = 0; i < size; i++) {\n        for (int j = 0; j < size; j++) {\n            tab_palindrome(i, j) = is_palindrome(tab(i, j));\n        }\n    }\n\n    int k = 2 * (size - 1);\n    bool condition = (k >= 0);\n    int result = 0;\n    while (condition) {\n        // std::cout << k << std::endl;\n        for (int i = 0; i <= k; i++) {\n            int j = k - i;\n            if (i < size && j < size) {\n                if (tab_palindrome(i, j) && tab(i, j) > result) {\n                    result = tab(i, j);\n                    condition = false;\n                }\n            }\n        }\n        k--;\n        condition = condition && k >= 0;\n    }\n        \n    // std::cout << vec << std::endl;\n    // std::cout << tab << std::endl;\n    // std::cout << tab_palindrome << std::endl;\n    std::cout << result << std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "b35dea7106f3a75eaf61122b4d12450ab4b8ad4a", "size": 1928, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problem_004.cpp", "max_stars_repo_name": "JlnZhou/ProjtecEuler", "max_stars_repo_head_hexsha": "6bbc4cbed2bf6596346d6d84e07b5355a36304c9", "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": "problem_004.cpp", "max_issues_repo_name": "JlnZhou/ProjtecEuler", "max_issues_repo_head_hexsha": "6bbc4cbed2bf6596346d6d84e07b5355a36304c9", "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": "problem_004.cpp", "max_forks_repo_name": "JlnZhou/ProjtecEuler", "max_forks_repo_head_hexsha": "6bbc4cbed2bf6596346d6d84e07b5355a36304c9", "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.038961039, "max_line_length": 133, "alphanum_fraction": 0.4875518672, "num_tokens": 563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096112990283, "lm_q2_score": 0.8128673110375457, "lm_q1q2_score": 0.7446755563522924}}
{"text": "static bool eigen_did_assert = false;\n#define eigen_assert(X) if(!eigen_did_assert && !(X)){ std::cout << \"### Assertion raised in \" << __FILE__ << \":\" << __LINE__ << \":\\n\" #X << \"\\n### The following would happen without assertions:\\n\"; eigen_did_assert = true;}\n\n#include <iostream>\n#include <Eigen/Eigen>\n\n#ifndef M_PI\n#define M_PI 3.1415926535897932384626433832795\n#endif\n\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  MatrixXd A(3,3);\nA << 4,-1,2, -1,6,0, 2,0,5;\ncout << \"The matrix A is\" << endl << A << endl;\n\nLLT<MatrixXd> lltOfA(A); // compute the Cholesky decomposition of A\nMatrixXd L = lltOfA.matrixL(); // retrieve factor L  in the decomposition\n// The previous two lines can also be written as \"L = A.llt().matrixL()\"\n\ncout << \"The Cholesky factor L is\" << endl << L << endl;\ncout << \"To check this, let us compute L * L.transpose()\" << endl;\ncout << L * L.transpose() << endl;\ncout << \"This should equal the matrix A\" << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "24b46a22da0d7bdca5bb0ec585b2734ab4699efa", "size": 1003, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/snippets/compile_LLT_example.cpp", "max_stars_repo_name": "mousepawmedia/libdeps", "max_stars_repo_head_hexsha": "b004d58d5b395ceaf9fdc993cfb00e91334a5d36", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2021-02-27T11:00:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T10:31:46.000Z", "max_issues_repo_path": "doc/snippets/compile_LLT_example.cpp", "max_issues_repo_name": "mousepawmedia/libdeps", "max_issues_repo_head_hexsha": "b004d58d5b395ceaf9fdc993cfb00e91334a5d36", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-11-14T23:14:58.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-14T23:14:58.000Z", "max_forks_repo_path": "doc/snippets/compile_LLT_example.cpp", "max_forks_repo_name": "mousepawmedia/libdeps", "max_forks_repo_head_hexsha": "b004d58d5b395ceaf9fdc993cfb00e91334a5d36", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-03-13T13:28:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-05T02:26:02.000Z", "avg_line_length": 30.3939393939, "max_line_length": 224, "alphanum_fraction": 0.6600199402, "num_tokens": 301, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096067182449, "lm_q2_score": 0.8128673087708699, "lm_q1q2_score": 0.7446755505521998}}
{"text": "#include <iostream>\n#include <Eigen/Eigen>\n\nint main() {\n    // Declare vectors and matrices and initialize them directly\n    std::cout << \"Initialize Matrices and Vectors with zeros\" << std::endl;\n    Eigen::RowVectorXd vec1 = Eigen::RowVectorXd::Zero(3);      // Declare row vector 1x3\n    Eigen::VectorXd vec2 = Eigen::VectorXd::Zero(3);            // Declare column vector 3x1\n    Eigen::MatrixXd matrix1 = Eigen::MatrixXd::Zero(3,3);       // Declare matrix 3x3    \n    std::cout << \"Row vector: \" << std::endl;\n    std::cout << vec1 << std::endl;\n    std::cout << \"Column vector: \" << std::endl;\n    std::cout << vec2 << std::endl;\n    std::cout << \"Matrix: \" << std::endl;\n    std::cout << matrix1 << std::endl;\n    // Create Random Matrix\n    std::cout << \"Initialize Matrices with random values\" << std::endl;\n    Eigen::MatrixXd matrix2 = Eigen::MatrixXd::Random(3,3);      // Declare matrix and initialize with random values.\n    std::cout << matrix2 << std::endl;\n}\n\n", "meta": {"hexsha": "733902a7b0443ea4849ac49adb43b2dd0e18d6c5", "size": 979, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example-03/example_three.cpp", "max_stars_repo_name": "JuliusDiestra/eigen-examples", "max_stars_repo_head_hexsha": "6b43b9390058d1ae747e3cb3ae94db1751976fe8", "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": "example-03/example_three.cpp", "max_issues_repo_name": "JuliusDiestra/eigen-examples", "max_issues_repo_head_hexsha": "6b43b9390058d1ae747e3cb3ae94db1751976fe8", "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": "example-03/example_three.cpp", "max_forks_repo_name": "JuliusDiestra/eigen-examples", "max_forks_repo_head_hexsha": "6b43b9390058d1ae747e3cb3ae94db1751976fe8", "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.5, "max_line_length": 117, "alphanum_fraction": 0.6210418795, "num_tokens": 267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648678, "lm_q2_score": 0.8519528019683105, "lm_q1q2_score": 0.744672549635423}}
{"text": "// Copyright (C) 2018 Thanaphon Chavengsaksongkram <as12production@gmail.com>, He Sun <he.sun@ed.ac.uk>\n// This file is subject to the license terms in the LICENSE file\n// found in the top-level directory of this distribution.\n\n#ifndef GSPARSE_UTIL_JL_HPP\n#define GSPARSE_UTIL_JL_HPP\n\n#include \"../Config.hpp\"\n#include <Eigen/Dense>\n\nnamespace gSparse\n{\n    namespace Util\n    {\n        //! randomProjectionMatrix creates a Johnson-Lindenstrauss lemma projection matrix.\n        /*!\n        \\param rows: Number of rows for generated matrix.\n        \\param cols: Number of columns for generated matrix.\n        \\param scale: square root of Scale will divide the value of the JL Matrix. Default is 1.0.\n        \\param tolProb: Tolerance threshold value between 0.0 and 1.0. Higher tolerance means less likely to get positive matrix. Default is 0.5.\n        */\n\t\tinline gSparse::PrecisionMatrix\n\t\t    randomProjectionMatrix(std::size_t rows,\n\t\t\t\tstd::size_t cols,\n\t\t\t\tdouble scale = 1.0f,\n\t\t\t\tdouble tolProb = 0.5f)\n\t\t{\n\t\t\t#ifndef NDEBUG\n                assert (tolProb <= 1.0f);  \n                assert (tolProb >= 0.0f);  \n                assert (scale != 0.0f); \n                assert (rows > 0 ); \n                assert (cols > 0 ); \n            #endif \n\n            gSparse::PrecisionMatrix result =\n\t\t\t\t(gSparse::PrecisionMatrix::Random(rows, cols).array() + 1.0) / 2.0;\n            \n\t\t\tresult = result.unaryExpr([=](gSparse::PRECISION x)\n\t\t\t{\n\t\t\t\treturn x > tolProb ? 1.0 / sqrt(scale) : -1.0 / std::sqrt(scale);\n\t\t\t});\n            // Copy elision will optimize return by value.\n\t\t\treturn result;\n\t\t}\n    }\n}\n\n#endif", "meta": {"hexsha": "86a882aff06537c6cecc7230d3e5edc2a5a8b469", "size": 1623, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/gSparse/Util/JL.hpp", "max_stars_repo_name": "As-12/gSparse", "max_stars_repo_head_hexsha": "66c7d60544565d4bdafbffa0ba08d62db620f9d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-09-14T09:38:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-11T13:03:55.000Z", "max_issues_repo_path": "include/gSparse/Util/JL.hpp", "max_issues_repo_name": "As-12/gSparse", "max_issues_repo_head_hexsha": "66c7d60544565d4bdafbffa0ba08d62db620f9d1", "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": "include/gSparse/Util/JL.hpp", "max_forks_repo_name": "As-12/gSparse", "max_forks_repo_head_hexsha": "66c7d60544565d4bdafbffa0ba08d62db620f9d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-11T13:03:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-11T13:03:58.000Z", "avg_line_length": 33.1224489796, "max_line_length": 145, "alphanum_fraction": 0.6223043746, "num_tokens": 429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418283357703, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.7445184019349329}}
{"text": "/*\r\n * schroedinger.cpp\r\n *\r\n *  Created on: 02.06.2017\r\n *      Author: marcel\r\n */\r\n\r\n#define _USE_MATH_DEFINES\r\n\r\n#include <iostream>\r\n#include <stdio.h>\r\n#include <time.h>\r\n#include <random>\r\n#include <complex>\r\n#include <cstdlib>\r\n#include <vector>\r\n#include <cmath>\r\n#include <sstream>\r\n#include <utility>\r\n#include <math.h>\r\n#include <random>\r\n#include <string>\r\n#include <fstream>\r\n#include <Eigen/Dense>\r\n\r\nusing namespace std;\r\n\r\nconst double dxi = 0.1;\r\nconst double dtau = 0.01;\r\nconst double sigma = 1.;\r\nconst double xi0 = -5.;\r\nconst double k0 = 5.5;\r\nconst int dim = 201;\r\nconst double b = 1.;\r\nconst complex<double> i(0, 1);\r\nconst double normierung = pow(2 * M_PI * sigma, -0.25);\r\n\r\ndouble theta(double x) {\r\n\tif (x >= 0)\r\n\t\treturn 1.;\r\n\telse\r\n\t\treturn 0;\r\n}\r\n\r\nEigen::MatrixXcd hamilton(double V) {\r\n\tEigen::MatrixXcd H(dim, dim);\r\n\tfor (int i = 0; i < dim; i++) {\r\n\t\tfor (int j = 0; j < dim; j++) {\r\n\t\t\tif (i == j) {\r\n\t\t\t\tH(i, j) = 2. / (dxi * dxi)\r\n\t\t\t\t\t\t+ V * theta((b / 2) - abs(-10 + j * dxi));\r\n\t\t\t}\r\n\t\t\tif (i == j + 1 || i == j - 1) {\r\n\t\t\t\tH(i, j) = -1. / (dxi * dxi);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn H;\r\n}\r\n\r\nEigen::MatrixXcd SH(double V) {\r\n\tEigen::MatrixXcd M(dim, dim);\r\n\tEigen::MatrixXcd H = hamilton(V);\r\n\r\n\tfor (int n = 0; n < dim; n++) {\r\n\t\tfor (int m = 0; m < dim; m++) {\r\n\t\t\tM(n, m) = H(n, m) * 0.5 * i + dtau;\r\n\t\t}\r\n\t}\r\n\r\n\treturn (Eigen::MatrixXcd::Identity(dim,dim) + M).inverse() * (Eigen::MatrixXcd::Identity(dim,dim) - M);\r\n}\r\n\r\nEigen::VectorXcd PSI() {\r\n\r\n\tEigen::VectorXcd Phi(dim);\r\n\tfor (int m = 0; m < dim; m++) {\r\n\t\tPhi(m) = normierung\r\n\t\t\t\t* exp(\r\n\t\t\t\t\t\t-(-10 + m * dxi - xi0) * (-10 + m * dxi - xi0)\r\n\t\t\t\t\t\t\t\t/ (4 * sigma)) * exp(i * k0 * (-10 + m * dxi));\r\n\t}\r\n\treturn Phi;\r\n}\r\n\r\ndouble T(Eigen::VectorXcd psi) {\r\n\tdouble sum = 0;\r\n\tfor (int j = 100; j < dim; j++) {\r\n\t\tsum += psi.real()(j);\r\n\t}\r\n\treturn sum * dxi;\r\n}\r\n\r\nvoid Crank_Nicolson(double V, string dateiname) {\r\n\t// ===============================\r\n\tofstream crank;\r\n\tcrank.open(\"psi_\" + dateiname + \".txt\");\r\n\tcrank.precision(10);\r\n\t// ===============================\r\n\t// ===============================\r\n\tofstream data;\r\n\tdata.open(\"transmission\" + dateiname + \".txt\");\r\n\tdata.precision(10);\r\n\t// ===============================\r\n\tEigen::VectorXcd psi = PSI();\r\n\tEigen::MatrixXcd U = SH(V);\r\n\tEigen::VectorXcd psiquad(dim);\r\n\r\n\tfor (int j = 0; j < dim; j++) {\r\n\t\tpsiquad(j) = psi.conjugate()(j) * psi(j);\r\n\t\tcrank << -10 + j * dxi << \"\\t\" << psiquad.real()(j) << \"\\n\";\r\n\t}\r\n\tcrank << \"\\n\";\r\n\r\n\tfor (double t = 0; t <= 1; t += dtau) {\r\n\t\tpsi = U * psi;\r\n\t\tfor (int j = 0; j < dim; j++) {\r\n\t\t\tpsiquad(j) = psi.conjugate()(j) * psi(j);\r\n\t\t\tcrank << -10 + j * dxi << \"\\t\" << psiquad.real()(j) << \"\\n\";\r\n\t\t}\r\n\t\tcrank << \"\\n\";\r\n\t\tdata << t << \"\\t\" << T(psiquad) << \"\\n\";\r\n\r\n\t}\r\n\r\n\tcrank.close();\r\n\tdata.close();\r\n}\r\n\r\nvoid Potential_Plot(double V_0) {\r\n\r\n\tofstream Potential;\r\n\tPotential.open(\"Potential_Plot.txt\");\r\n\tPotential.precision(10);\r\n\r\n\tfor(double xi = -10.; xi <= 10; xi += dxi) {\r\n\t\tPotential << xi << \"\\t\" << V_0 * theta((b / 2) - abs(xi)) << \"\\n\";\r\n\t}\r\n\r\n\tPotential.close();\r\n}\r\n\r\nint main() {\r\n\tCrank_Nicolson(0, \"V=0\");\r\n\tCrank_Nicolson(10, \"V=10\");\r\n\tCrank_Nicolson(30, \"V=30\");\r\n\tCrank_Nicolson(50, \"V=50\");\r\n\r\n\tPotential_Plot(10);\r\n\treturn 0;\r\n}\r\n", "meta": {"hexsha": "ce6f49b945010f7d3d090ea89776d252f21f1b22", "size": 3267, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Blatt_06/Abgabe_FelixMarcelRigo/Code/CP_06_01.cpp", "max_stars_repo_name": "KevSed/Computational_Physics", "max_stars_repo_head_hexsha": "6ebfcd07ae5ceb2bfe5b429e8d1425b6877037d1", "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": "Blatt_06/Abgabe_FelixMarcelRigo/Code/CP_06_01.cpp", "max_issues_repo_name": "KevSed/Computational_Physics", "max_issues_repo_head_hexsha": "6ebfcd07ae5ceb2bfe5b429e8d1425b6877037d1", "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": "Blatt_06/Abgabe_FelixMarcelRigo/Code/CP_06_01.cpp", "max_forks_repo_name": "KevSed/Computational_Physics", "max_forks_repo_head_hexsha": "6ebfcd07ae5ceb2bfe5b429e8d1425b6877037d1", "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.4934210526, "max_line_length": 105, "alphanum_fraction": 0.5084175084, "num_tokens": 1113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418116217418, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.7445183906259267}}
{"text": "#include \"writer.hpp\"\n#include <Eigen/Sparse>\n#include <Eigen/SparseCholesky>\n#include <cmath>\n#include <functional>\n#include <iostream>\n#include <stdexcept>\n\n//! Sparse Matrix type. Makes using this type easier.\ntypedef Eigen::SparseMatrix<double> SparseMatrix;\n\n//! Used for filling the sparse matrix.\ntypedef Eigen::Triplet<double> Triplet;\n\n//! Vector type\ntypedef Eigen::VectorXd Vector;\n\n//! Create the 1D Poisson matrix\n//! @param[out] A will contain the Poisson matrix\n//! @param[in] N the number of interior points\nvoid createPoissonMatrix(SparseMatrix &A, int N) {\n\t// (write your solution here)\n}\n\n/// Uses the explicit Euler method to compute u from time 0 to time T\n///\n/// @param[out] u at all time steps up to time T, each column corresponding to a time step (including the initial condition as first column)\n/// @param[out] time the time levels\n/// @param[in] u0 the initial data, as column vector\n/// @param[in] dt the time step size\n/// @param[in] T the final time at which to compute the solution (which we assume to be a multiple of dt)\n/// @param[in] N the number of interior grid points\n/// @param[in] gL function of time with the Dirichlet condition at left boundary\n/// @param[in] gR function of time with the Dirichlet condition at right boundary\n///\n\nvoid explicitEuler(Eigen::MatrixXd &u, Vector &time, const Vector u0, double dt, double T, int N, const std::function<double(double)> &gL, const std::function<double(double)> &gR) {\n\tconst unsigned int nsteps = round(T / dt);\n\tconst double       h      = 1. / (N + 1);\n\tu.resize(N, nsteps + 1);\n\ttime.resize(nsteps + 1);\n\n\t// (write your solution here)\n}\n\n/// Uses the Crank-Nicolson method to compute u from time 0 to time T\n///\n/// @param[out] u at all time steps up to time T, each column corresponding to a time step (including the initial condition as first column)\n/// @param[out] time the time levels\n/// @param[in] u0 the initial data, as column vector\n/// @param[in] dt the time step size\n/// @param[in] T the final time at which to compute the solution (which we assume to be a multiple of dt)\n/// @param[in] N the number of interior grid points\n/// @param[in] gL function of time with the Dirichlet condition at left boundary\n/// @param[in] gR function of time with the Dirichlet condition at right boundary\n///\n\nvoid CrankNicolson(Eigen::MatrixXd &u, Vector &time, const Vector u0, double dt, double T, int N, const std::function<double(double)> &gL, const std::function<double(double)> &gR) {\n\t// (write your solution here)\n}\n\ndouble U0(double x) {\n\treturn 1 + std::min(2 * x, 2 - 2 * x);\n}\n\nint main(int, char **) {\n\tdouble T  = 0.3;\n\tdouble dt = 0.0002; // Change this for explicit / implicit time stepping comparison\n\tint    N  = 40;\n\tVector u0(N);\n\tdouble h = 1. / (N + 1);\n\t/* Initialize u0 */\n\tfor (int i = 0; i < u0.size(); i++)\n\t\tu0[i]    = U0(h * (i + 1));\n\tauto gR    = [](double t) { return std::exp(-10 * t); };\n\tauto gL    = [](double t) { return std::exp(-10 * t); };\n\tEigen::MatrixXd     u_euler;\n\tVector              time;\n\texplicitEuler(u_euler, time, u0, dt, T, N, gL, gR);\n\twriteToFile(\"time.txt\", time);\n\twriteMatrixToFile(\"u_explEuler.txt\", u_euler);\n\tEigen::MatrixXd u_cn;\n\tCrankNicolson(u_cn, time, u0, dt, T, N, gL, gR);\n\twriteMatrixToFile(\"u_cn.txt\", u_cn);\n}\n", "meta": {"hexsha": "6c2a1b3a85a240301b0c11c50bd5ddddb72c665b", "size": 3275, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "series3_warmup/heat-eqn-1d/heat_1dfd.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": "series3_warmup/heat-eqn-1d/heat_1dfd.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": "series3_warmup/heat-eqn-1d/heat_1dfd.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": 38.0813953488, "max_line_length": 181, "alphanum_fraction": 0.6848854962, "num_tokens": 918, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869786798663, "lm_q2_score": 0.8499711737573762, "lm_q1q2_score": 0.7443936862299522}}
{"text": "/// @file kalman_filter.hpp Kalman filter and Rauch\u2013Tung\u2013Striebel smoother for track observations\n\n#ifndef BIGGLES_KALMAN_FILTER_HPP__\n#define BIGGLES_KALMAN_FILTER_HPP__\n\n#include <Eigen/Dense>\n#include <deque>\n\n#include \"observation.hpp\"\n#include \"track.hpp\"\n#include \"detail/physics.hpp\"\n\nnamespace biggles\n{\n\n/// @brief A Kalman filter for predicting missing observations in tracks.\n///\n/// A Kalman filter is the optimal linear state space evaluator for tracking a hidden state given noisy observations.\n/// Specifically we assume some hidden state vector at time \\f$ T \\f$, \\f$ x_t \\f$ which evolves with the following\n/// model:\n///\n/// \\f[\n/// x_t = A x_{t-1} + V_t\n/// \\f]\n///\n/// where \\f$ A \\f$ is some state evolution matrix and \\f$ V_t \\f$ is a zero-mean Gaussian process with (known)\n/// covariance matrix \\f$ Q \\f$.\n///\n/// We assume that we can make a noisy observation, \\f$ y_t \\f$:\n///\n/// \\f[\n/// y_t = B x_t + W_t\n/// \\f]\n///\n/// where \\f$ B \\f$ is an observation matrix and \\f$ W_t \\f$ is a zero-mean Gaussian process with (known) covariance\n/// matrix \\f$ R \\f$.\n///\n/// A Kalman filter consists of a prediction step followed by an update step. In the prediction step, the current\n/// estimate of the hidden state, \\f$ \\hat{x}_t \\f$, is evolved via the state evolution matrix. In the update step, this\n/// estimate is refined by fusing any observations made. In this implementation the lack of an observation causes this\n/// update step to be skipped and the refined estimate is assumed to be equal to the prediction.\n///\n/// The prediction step is represented by the following recurrence relations:\n///\n/// \\f[\n/// \\hat{x}_{t|t-1} = A \\hat{x}_{t-1|t-1}, \\quad P_{t|t-1} = A P_{t-1|t-1} A^T + Q\n/// \\f]\n///\n/// where \\f$ P_{t|t-1} \\f$ and \\f$ P_{t|t} \\f$ are, respectively, our prediction of the state estimation error and our\n/// refined prediction of the state estimation error.\n///\n/// The update step is represented by the following recurrence relations:\n///\n/// \\f[\n/// \\hat{x}_{t|t} = \\hat{x}_{t|t-1} + K_t \\tilde{z}_t, \\quad P_{t|t} = (I - K_t B) P_{t|t-1}\n/// \\f]\n///\n/// where\n///\n/// \\f[\n/// \\tilde{z}_t = y_t - B \\hat{x}_{t|t-1}, \\quad K_t = P_{t|t-1} B^T + S_t^{-1}, \\quad S_t = B P_{t|t-1} B^T + R.\n/// \\f]\n///\n/// We initialise the filter by choosing some arbitrary initial state estimate, \\f$ \\hat{x}_{0|0} \\f$, and setting the\n/// initial state covariance matrix, \\f$ P_{0|0} \\f$, to some sufficiently large multiple of \\f$ I \\f$ so as to specify\n/// almost no certainty on the initial estimate. We use the recurrence relations to compute estimates of states and\n/// estimation error covariances up until the last time stamp for the track.\n///\n/// In our system, the state is a position and instantaneous velocity:\n///\n/// \\f[\n/// x_t = [ x, x', y, y' ]^T\n/// \\f]\n///\n/// States evolve using first order dynamics and the velocity is hidden:\n///\n/// \\f[\n/// A = \\left[\n/// \\begin{array}{cccc}\n/// 1 & d & 0 & 0 \\\\ 0 & 1 & 0 & 0 \\\\ 0 & 0 & 1 & d \\\\ 0 & 0 & 0 & 1\n/// \\end{array}\n/// \\right], \\quad\n///\n/// B = \\left[\n/// \\begin{array}{cccc}\n/// 1 & 0 & 0 & 0 \\\\ 0 & 0 & 1 & 0\n/// \\end{array}\n/// \\right].\n/// \\f]\n///\n/// The matrix \\f$ R \\f$ and dynamic drag \\f$ d \\f$ are given as parameters to the constructor. The matrix Q is set to\n/// the following by default:\n///\n/// \\f[\n/// Q = \\left[\n/// \\begin{array}{cccc}\n/// 0.8^2 & 0 & 0 & 0 \\\\ 0 & 0.2^2 & 0 & 0 \\\\ 0 & 0 & 0.8^2 & 0 \\\\ 0 & 0 & 0 & 0.2^2\n/// \\end{array}\n/// \\right].\n/// \\f]\n///\n/// @sa rts_smooth()\n/// @sa http://en.wikipedia.org/wiki/Kalman_filter\n/// @sa http://automation.berkeley.edu/resources/KalmanSmoothing.ppt\nclass kalman_filter\n{\npublic:\n    /// @brief The underlying state vector type.\n    ///\n    /// The state vector represents the instantaneous position and velocity of the molecule as a vector \\f$ X \\equiv [x,\n    /// x', y, y'] \\f$.\n    typedef Eigen::Vector4f state_vector;\n\n    /// @brief The covariance of the state.\n    ///\n    /// The Kalman filter maintains an estimate of the instantaneous error in state estimation as a state covariance\n    /// matrix \\f$ \\Sigma \\equiv E(XX^T) - E(X)E(X)^T \\f$.\n    typedef Eigen::Matrix4f covariance_matrix;\n\n    /// @brief A pair holding an interpolated state vector and its associated covariance.\n    typedef std::pair<state_vector, covariance_matrix> state_covariance_pair;\n\n    /// @brief The collection type used to hold states and covariances.\n    //typedef std::deque<state_covariance_pair, Eigen::aligned_allocator<state_covariance_pair> > states_and_cov_deque;\n    typedef std::deque<state_covariance_pair> states_and_cov_deque;\n\n    /// @brief The default observation covariance.\n    ///\n    /// The default value is\n    /// \\f[\n    /// R = \\left[\n    /// \\begin{array}{cc}\n    /// 0.1^2 & 0 \\\\ 0 & 0.1^2\n    /// \\end{array}\n    /// \\right]\n    /// \\f]\n    static const Eigen::Matrix2f default_observation_covariance;\n\n    /// @brief Default constructor.\n    kalman_filter() : dynamic_drag_(1.f) { }\n\n    /// @brief Initialise filter from a track's observations.\n    ///\n    /// This constructor uses the observations from a track to interpolate states for all timestamps within a track.\n    ///\n    /// @param t The track to initialise from.\n    /// @param observation_covariance The observation covariance matrix \\f$ R \\f$. The default is default_observation_covariance.\n    kalman_filter(const track& t, const matrix2f &R, const matrix4f &Q)\n    {\n        reinitialise(t.first_time_stamp(), t.last_time_stamp(), t.begin(), t.end(), R, Q, t.dynamic_drag());\n    }\n\n    /// @brief Initialise filter with a set of observations.\n    ///\n    /// @tparam InputIterator An InputIterator yielding biggles::observation instances.\n    /// @param first_time_stamp The first time stamp of the track.\n    /// @param last_time_stamp The time stamp immediately after the last time stamp of the track: \\p first_time_stamp +\n    /// duration.\n    /// @param first The first observation for the track.\n    /// @param last Just beyond the last observation for the track.\n    /// @param observation_covariance The observation covariance matrix \\f$ R \\f$.\n    /// @param dynamic_drag The dynamic drag factor.\n    //template<typename InputIterator>\n    kalman_filter(time_stamp first_time_stamp,\n                  time_stamp last_time_stamp,\n                  track::const_iterator first, track::const_iterator last,\n                  const matrix2f &R, const matrix4f &Q,\n                  float dynamic_drag)\n    {\n        reinitialise(first_time_stamp, last_time_stamp, first, last, R, Q, dynamic_drag);\n    }\n\n    /// @brief Copy constructor.\n    ///\n    /// @param kf The biggles::kalman_filter instance to copy.\n    kalman_filter(const kalman_filter& kf)\n        : prediction_states_and_covs_(kf.prediction_states_and_covs_)\n        , correction_states_and_covs_(kf.correction_states_and_covs_)\n        , dynamic_drag_(kf.dynamic_drag_)\n    { }\n\n    /// @brief Assignment operator.\n    ///\n    /// @param kf The biggles::kalman_filter instance to copy.\n    const kalman_filter& operator = (const kalman_filter& kf)\n    {\n        prediction_states_and_covs_ = kf.prediction_states_and_covs_;\n        correction_states_and_covs_ = kf.correction_states_and_covs_;\n        dynamic_drag_ = kf.dynamic_drag_;\n        return *this;\n    }\n\n    /// @brief Re-initialise filter with a set of observations.\n    ///\n    /// @tparam InputIterator An InputIterator yielding biggles::observation instances.\n    /// @param first_time_stamp The first time stamp of the track.\n    /// @param last_time_stamp The time stamp immediately after the last time stamp of the track: \\p first_time_stamp +\n    /// duration.\n    /// @param first The first observation for the track.\n    /// @param last Just beyond the last observation for the track.\n    /// @param observation_covariance The observation covariance matrix \\f$ R \\f$.\n    /// @param dynamic_drag The dynamic drag factor.\n    //template<typename InputIterator>\n    void reinitialise(time_stamp first_time_stamp, time_stamp last_time_stamp,\n                      track::const_iterator first, track::const_iterator last,\n                      const matrix2f &R, const matrix4f &Q,\n                      float dynamic_drag);\n\n    /// @brief The predicted states and covariances.\n    ///\n    /// A collection of predicted states, \\f$ x_{t|t-1} \\f$, and covariances, \\f$ P_{t|t-1} \\f$, for all time stamps\n    /// covered by the input range.\n    const states_and_cov_deque& predictions() const { return prediction_states_and_covs_; }\n\n    /// @brief The corrected states and covariances.\n    ///\n    /// A collection of corrected states, \\f$ x_{t|t} \\f$, and covariances, \\f$ P_{t|t} \\f$, for all time stamps\n    /// covered by the input range.\n    const states_and_cov_deque& corrections() const { return correction_states_and_covs_; }\n\n    /// @brief The dynamic drag factor associated with this filter.\n    float dynamic_drag() const { return dynamic_drag_; }\n\nprotected:\n    // NOTE: The situation with storing Eigen dense matrices in a std::vector is complex. To avoid this, we use a deque\n    // here even though our usage pattern would suggest a vector be more appropriate.\n    //\n    // See: http://eigen.tuxfamily.org/dox-devel/TopicStlContainers.html\n\n    /// @brief The collection of interpolated states and covariances of their errors.\n    states_and_cov_deque prediction_states_and_covs_;\n\n    /// @brief The collection of interpolated states and covariances of their errors.\n    states_and_cov_deque correction_states_and_covs_;\n\n    /// @brief The dynamic drag factor to use in state evolution matrices.\n    float dynamic_drag_;\n\n\n};\n\n/// @brief Perform a Rauch\u2013Tung\u2013Striebel backwards smoothing step on the Kalman filter predicted and corrected states.\n///\n/// @note Since this is a <em>backward</em> process, the results are written to \\p\n/// output_reversed_states_and_covariances in <em>reverse</em> order; i.e. the smoothed state and covariance for the\n/// <em>last</em> time stamp is the first written out.\n///\n/// Once the forward prediction-update step has been completed for a Kalman filter, we can use a Rauch\u2013Tung\u2013Striebel\n/// smoother to refine our earlier state estimates. This is a backwards step which starts from the final estimated state\n/// (i.e. the one which has been influenced by all observed observations) and works backwards creating optimal estimates\n/// of the hidden state, \\f$ \\hat{x}_{t|T} \\f$, and estimation error covariance, \\f$ P_{t|T} \\f$. Note that these\n/// estimates have been computed given all observations.\n///\n/// The estimates are computed via the following recurrence relations:\n///\n/// \\f[\n/// \\hat{x}_{t|T} = \\hat{x}_{t|t} + L_t ( \\hat{x}_{t+1|T} - \\hat{x}_{t+1|t} ), \\quad\n/// P_{t|T} = P_{t|t} + L_t ( P_{t+1|T} - P_{t+1|t} ) L^T_t\n/// \\f]\n///\n/// where \\f$ L_t = P_{t|t} A^T P_{t+1|t}^{-1} \\f$.\n///\n/// These smoothed estimates of state and estimation error generated by this function may be used as mean and\n/// covariances of a multi-variate Gaussian in order to sample possible state-space configurations for a track. Biggles\n/// uses these estimates not only as mean and covariances for evaluation log-likelihoods on track configurations but\n/// also for sampling missing data from tracks.\n///\n/// @sa biggles::kalman_filter\n///\n/// @tparam OutputIterator Where entries of type kalman_filter::state_covariance_pair are written.\n/// @param kalman A Kalman filter to take predicted and corrected states and covariances from.\n/// @param output_reversed_states_and_covariances An iterator to write smoothed states and covariances to <em>in reverse\n/// order</em>.\ntemplate<typename OutputIterator>\nvoid rts_smooth(const kalman_filter& kalman,\n                OutputIterator output_reversed_states_and_covariances);\n\n}\n\n#define WITHIN_BIGGLES_KALMAN_FILTER_HPP__\n#include \"kalman_filter.tcc\"\n#undef WITHIN_BIGGLES_KALMAN_FILTER_HPP__\n\n#endif // BIGGLES_KALMAN_FILTER_HPP__\n", "meta": {"hexsha": "c890f4a1ede3797cd6a6cbecc1274e1bdef339e4", "size": 11926, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/biggles/kalman_filter.hpp", "max_stars_repo_name": "fbi-octopus/biggles", "max_stars_repo_head_hexsha": "2dac4f1748ab87242951239caf274f302be1143a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-15T14:01:59.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-15T14:01:59.000Z", "max_issues_repo_path": "include/biggles/kalman_filter.hpp", "max_issues_repo_name": "fbi-octopus/biggles", "max_issues_repo_head_hexsha": "2dac4f1748ab87242951239caf274f302be1143a", "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": "include/biggles/kalman_filter.hpp", "max_forks_repo_name": "fbi-octopus/biggles", "max_forks_repo_head_hexsha": "2dac4f1748ab87242951239caf274f302be1143a", "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": 41.8456140351, "max_line_length": 129, "alphanum_fraction": 0.6792721784, "num_tokens": 3160, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404077216355, "lm_q2_score": 0.8006920020959543, "lm_q1q2_score": 0.7441955008875164}}
{"text": "#include \"gtest/gtest.h\"\n#include <Eigen/Dense>\n\n\n/*\n * minimize     0.5 * x'.H.x + h'.x\n * subject to   l_i <= x_i <= u_i\n */\n\nclass GradProj {\npublic:\n    using Scalar = double;\n    using x_t = Eigen::Vector2d;\n    Eigen::Matrix2d H;\n    Eigen::Vector2d h;\n    Eigen::Vector2d l, u;\n    GradProj() {\n        H << 10, 0,\n             0, 0.1;\n        h << -1, -2;\n\n        l << -1, -1;\n        u << 1, 1;\n    }\n\n    Scalar f(const Eigen::Vector2d& x)\n    {\n        return 0.5 * x.dot(H * x) + h.dot(x);\n    }\n\n    Eigen::Vector2d grad_f(const Eigen::Vector2d& x)\n    {\n        Eigen::Vector2d grad;\n        grad << H * x + h;\n        return grad;\n    }\n\n    Eigen::Vector2d solve(const Eigen::Vector2d& x0)\n    {\n        Eigen::Vector2d x;\n        x = x0;\n\n        std::cout << \"x \" << x.transpose() << std::endl;\n\n        for (int iter = 1; iter <= 100; iter++) {\n            Scalar fx;\n            x_t grad;\n\n            fx = f(x);\n            grad = grad_f(x);\n\n            std::cout << \"grad \" << grad.transpose() << std::endl;\n\n            // backtracking line search\n            // Scalar alpha = 1.0;\n            Scalar alpha = 0.9;\n            const Scalar beta = 0.3; // 0 < beta < 1\n            const Scalar c = 1e-5; // 0 < c < 1\n            int i;\n            for (i = 1;; i++) {\n                x_t x_step;\n                x_t p;\n\n                p = alpha*grad;\n                // gradient projection\n                box_projection(p, l, u);\n                x_step = x - p;\n\n                if (f(x_step) <= fx - alpha * c * grad.dot(x_step - x)) {\n                    // std::cout << f(x_step) << \" f \" << fx << \" d \" << alpha * c * grad.dot(x_step - x) << \" alpha \" << alpha << std::endl;\n                    std::cout << \"alpha \" << alpha << \"  step \" << p.transpose() << std::endl;\n                    x = x_step;\n                    break;\n                } else {\n                    alpha = beta*alpha;\n                }\n            }\n            std::cout << \"x \" << x.transpose() << std::endl;\n        }\n\n        return x;\n    }\n\n    void box_projection(x_t& x, const x_t& l, const x_t& u) const\n    {\n        x = x.cwiseMax(l).cwiseMin(u);\n    }\n};\n\nTEST(GradProjTestCase, TestSimple) {\n    GradProj test;\n    Eigen::Vector2d x0(0, 0);\n    Eigen::Vector2d sol;\n\n    sol = test.solve(x0);\n\n    std::cout << \"sol \" << sol.transpose() << std::endl;\n}\n\nint main(int argc, char **argv) {\n  ::testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "5fe20f385a02f44245e9d37ef9a74aa849371c9f", "size": 2477, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "polympc/src/solvers/trust_region_tests/gradproj_test.cpp", "max_stars_repo_name": "alexandreguerradeoliveira/rocket_gnc", "max_stars_repo_head_hexsha": "164e96daca01d9edbc45bfaac0f6b55fe7324f24", "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": "polympc/src/solvers/trust_region_tests/gradproj_test.cpp", "max_issues_repo_name": "alexandreguerradeoliveira/rocket_gnc", "max_issues_repo_head_hexsha": "164e96daca01d9edbc45bfaac0f6b55fe7324f24", "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": "polympc/src/solvers/trust_region_tests/gradproj_test.cpp", "max_forks_repo_name": "alexandreguerradeoliveira/rocket_gnc", "max_forks_repo_head_hexsha": "164e96daca01d9edbc45bfaac0f6b55fe7324f24", "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.8173076923, "max_line_length": 141, "alphanum_fraction": 0.4343964473, "num_tokens": 719, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952893703477, "lm_q2_score": 0.8289388040954684, "lm_q1q2_score": 0.7441344596127915}}
{"text": "#include \"BezierSpline.h\"\n\n__pragma(warning(push, 0))\n#include <Eigen/Eigen>\n__pragma(warning(pop))\n\n#include <iostream>\n\n#include <omp.h>\n\nnamespace Chaf\n{\n\tvoid BezierSpline::createControlPoints(const std::vector<double>& input_x, const std::vector<double>& input_y, std::vector<double>& control_x, std::vector<double>& control_y)\n\t{\n\t\tsize_t n = input_x.size() - 1;\n\n\t\tstd::vector<double> delta(n);\n\t\tEigen::MatrixXd A(3 * n + 1, 3 * n + 1);\n\t\tEigen::MatrixXd b(3 * n + 1, 2);\n\t\tA.setZero();\n\t\tb.setZero();\n\n\t\t// Parameter -> delta\n\t\tswitch (parameter)\n\t\t{\n\t\tcase Parameter::Uniform:\n\t\t\tstd::fill(delta.begin(), delta.end(), static_cast<double>(uniform_val));\n\t\t\tbreak;\n\t\tcase Parameter::Chordal:\n\t\t\tfor (size_t i = 0; i < n; i++)\n\t\t\t{\n\t\t\t\tdelta[i] = sqrt((input_x[i] - input_x[i + 1]) * (input_x[i] - input_x[i + 1]) + (input_y[i] - input_y[i + 1]) * (input_y[i] - input_y[i + 1]));\n\t\t\t}\n\t\t\tbreak;\n\t\tcase Parameter::Centripetal:\n\t\t\tfor (size_t i = 0; i < n; i++)\n\t\t\t{\n\t\t\t\tdelta[i] = sqrt(sqrt((input_x[i] - input_x[i + 1]) * (input_x[i] - input_x[i + 1]) + (input_y[i] - input_y[i + 1]) * (input_y[i] - input_y[i + 1])));\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\tsize_t rows = 0;\n\t\t// Control point interpolation: 0~n-1\n#pragma omp parallel for\n\t\tfor (int64_t i = 0; i <= (int64_t)n; i++)\n\t\t{\n\t\t\tA(i, 3 * i) = 1;\n\t\t\tb(i, 0) = input_x[i];\n\t\t\tb(i, 1) = input_y[i];\n\t\t}\n\n\t\t// C1 continuity: n~2n-3\n#pragma omp parallel for\n\t\tfor (int64_t i = 1; i <= (int64_t)(n - 1); i++)\n\t\t{\n\t\t\tA(n + i , 3 * i - 1) = -delta[i];\n\t\t\tA(n + i , 3 * i) = delta[i - 1] + delta[i];\n\t\t\tA(n + i , 3 * i + 1) = -delta[i - 1];\n\t\t}\n\n\t\t// C2 continuity: 2n - 2  ~ 3n-5\n#pragma omp parallel for\n\t\tfor (int64_t i = 1; i <= (int64_t)(n - 1); i++)\n\t\t{\n\t\t\tA(2 * n + i - 1, 3 * i - 2) = delta[i] * delta[i];\n\t\t\tA(2 * n + i - 1, 3 * i - 1) = -2 * delta[i] * delta[i];\n\t\t\tA(2 * n + i - 1, 3 * i) = delta[i] * delta[i] - delta[i - 1] * delta[i - 1];\n\t\t\tA(2 * n + i - 1, 3 * i + 1) = 2 * delta[i - 1] * delta[i - 1];\n\t\t\tA(2 * n + i - 1, 3 * i + 2) = -delta[i - 1] * delta[i - 1];\n\t\t}\n\n\t\t// End condition: 3n-3, 3n-2\n\t\tswitch (end_condition)\n\t\t{\n\t\tcase EndCondition::Natural:\n\t\t\tA(3 * n - 1, 0) = 1;\n\t\t\tA(3 * n - 1, 1) = -2;\n\t\t\tA(3 * n - 1, 2) = 1;\n\n\t\t\trows++;\n\n\t\t\tA(3 * n, 3 * n - 2) = 1;\n\t\t\tA(3 * n, 3 * n - 1) = -2;\n\t\t\tA(3 * n, 3 * n) = 1;\n\t\t\tbreak;\n\t\tcase EndCondition::Bessel:\n\t\t\tA(3 * n - 1, 0) = -1;\n\t\t\tA(3 * n - 1, 1) = 1;\n\t\t\tb(3 * n - 1, 0) = delta[0] / 3.f * (-(delta[1] + 2 * delta[0]) / ((delta[0] + delta[1]) * delta[0]) * input_x[0] + (delta[0] + delta[1]) / (delta[0] * delta[1]) * input_x[1] - delta[0] / (delta[1] * (delta[0] + delta[1])) * input_x[2]);\n\t\t\tb(3 * n - 1, 1) = delta[0] / 3.f * (-(delta[1] + 2 * delta[0]) / ((delta[0] + delta[1]) * delta[0]) * input_y[0] + (delta[0] + delta[1]) / (delta[0] * delta[1]) * input_y[1] - delta[0] / (delta[1] * (delta[0] + delta[1])) * input_y[2]);\n\n\t\t\trows++;\n\n\t\t\tA(3 * n, 3 * n - 1) = -1;\n\t\t\tA(3 * n, 3 * n) = 1;\n\t\t\tb(3 * n, 0) = delta[n - 1] / 3.f * ((delta[n - 2] + 2 * delta[n - 1]) / ((delta[n - 2] + delta[n - 1]) * delta[n - 2]) * input_x[n] - (delta[n - 2] + delta[n - 1]) / (delta[n - 2] * delta[n - 1]) * input_x[n - 1] + delta[n - 1] / (delta[n - 2] * (delta[n - 2] + delta[n - 1])) * input_x[n - 2]);\n\t\t\tb(3 * n, 1) = delta[n - 1] / 3.f * ((delta[n - 2] + 2 * delta[n - 1]) / ((delta[n - 2] + delta[n - 1]) * delta[n - 2]) * input_y[n] - (delta[n - 2] + delta[n - 1]) / (delta[n - 2] * delta[n - 1]) * input_y[n - 1] + delta[n - 1] / (delta[n - 2] * (delta[n - 2] + delta[n - 1])) * input_y[n - 2]);\n\t\t\tbreak;\n\t\tcase EndCondition::Close:\n\t\t\tA(3 * n - 1, 0) = delta[0] + delta[n-1];\n\t\t\tA(3 * n - 1, 1) = -delta[n-1];\n\t\t\tA(3 * n - 1, 3*n - 1) = -delta[0];\n\n\t\t\trows++;\n\n\t\t\tA(3 * n, 0) = delta[0]*delta[0]-delta[n-1]*delta[n-1];\n\t\t\tA(3 * n, 1) = 2*delta[n-1]*delta[n-1];\n\t\t\tA(3 * n, 2) = -delta[n-1] * delta[n-1];\n\t\t\tA(3 * n, 3 * n - 2) = delta[0] * delta[0];\n\t\t\tA(3 * n, 3 * n - 1) = -2 * delta[0] * delta[0];\n\n\t\t\tbreak;\n\t\t}\n\n\t\tEigen::MatrixXd x = A.colPivHouseholderQr().solve(b);\n\n\t\tcontrol_x.resize(3 * n + 1);\n\t\tcontrol_y.resize(3 * n + 1);\n\n\t\tfor (size_t i = 0; i < 3 * n + 1; i++)\n\t\t{\n\t\t\tcontrol_x[i] = x(i, 0);\n\t\t\tcontrol_y[i] = x(i, 1);\n\t\t}\n\t}\n}", "meta": {"hexsha": "ccdf33dbec3c28cfb1a8b0dd68b40178d01381fb", "size": 4169, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Homework/Homeworks/Homework5/BezierSpline.cpp", "max_stars_repo_name": "Chaphlagical/CAGD", "max_stars_repo_head_hexsha": "55b79364a13fe062f6f7b8d061fb7bed236aa61d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-10-01T14:05:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-01T14:05:50.000Z", "max_issues_repo_path": "Homework/Homeworks/Homework5/BezierSpline.cpp", "max_issues_repo_name": "Chaphlagical/CAGD", "max_issues_repo_head_hexsha": "55b79364a13fe062f6f7b8d061fb7bed236aa61d", "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": "Homework/Homeworks/Homework5/BezierSpline.cpp", "max_forks_repo_name": "Chaphlagical/CAGD", "max_forks_repo_head_hexsha": "55b79364a13fe062f6f7b8d061fb7bed236aa61d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-10-01T14:47:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T14:47:48.000Z", "avg_line_length": 32.8267716535, "max_line_length": 298, "alphanum_fraction": 0.4883665148, "num_tokens": 1874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240177362488, "lm_q2_score": 0.7931059609645724, "lm_q1q2_score": 0.7440317505906532}}
{"text": "#include <boost/test/unit_test.hpp>\n#include \"matrice.h\"\n\n#include <boost/numeric/ublas/assignment.hpp>\n#include <boost/rational.hpp>\n\nBOOST_AUTO_TEST_SUITE(test_matrice)\n\n    BOOST_AUTO_TEST_CASE(puissance) {\n        matrice::matrice<long long> A(2, 2);\n        A <<= 1, 1,\n                1, 0;\n\n        auto F = matrice::puissance_matrice(A, 40);\n\n        const std::vector<long long> resultat{165580141, 102334155,\n                                              102334155, 63245986};\n\n        BOOST_CHECK_EQUAL(F.size1(), 2);\n        BOOST_CHECK_EQUAL(F.size2(), 2);\n        BOOST_CHECK_EQUAL(F(0, 0), 165580141);\n        BOOST_CHECK_EQUAL(F(1, 0), 102334155);\n        BOOST_CHECK_EQUAL(F(0, 1), 102334155);\n        BOOST_CHECK_EQUAL(F(1, 1), 63245986);\n\n        BOOST_CHECK_EQUAL_COLLECTIONS(resultat.begin(), resultat.end(),\n                                      F.data().begin(), F.data().end());\n    }\n\n    BOOST_AUTO_TEST_CASE(puissance_modulaire) {\n        matrice::matrice<long long> A(2, 2);\n        A <<= 1, 1,\n                1, 0;\n\n        auto F = matrice::puissance_matrice<long long>(A, 100, 1000000000);\n\n        const std::vector<long long> resultat{817084101, 261915075,\n                                              261915075, 555169026};\n\n        BOOST_CHECK_EQUAL(F.size1(), 2);\n        BOOST_CHECK_EQUAL(F.size2(), 2);\n        BOOST_CHECK_EQUAL(F(0, 0), 817084101);\n        BOOST_CHECK_EQUAL(F(1, 0), 261915075);\n        BOOST_CHECK_EQUAL(F(0, 1), 261915075);\n        BOOST_CHECK_EQUAL(F(1, 1), 555169026);\n\n        BOOST_CHECK_EQUAL_COLLECTIONS(resultat.begin(), resultat.end(),\n                                      F.data().begin(), F.data().end());\n    }\n\n    BOOST_AUTO_TEST_CASE(inversion1) {\n        typedef boost::rational<long long> fraction;\n\n        matrice::matrice<fraction> A(3, 3);\n        A <<= 2, -1, 0,\n                -1, 2, -1,\n                0, -1, 2;\n\n        matrice::matrice<fraction> resultat(3, 3);\n        resultat <<= 3, 2, 1,\n                2, 4, 2,\n                1, 2, 3;\n        resultat /= 4;\n\n        matrice::matrice<fraction> inverse(3, 3);\n\n        bool inversible = matrice::inversionLU(A, inverse);\n\n        BOOST_CHECK_EQUAL(inversible, true);\n        BOOST_CHECK_EQUAL_COLLECTIONS(resultat.data().begin(), resultat.data().end(),\n                                      inverse.data().begin(), inverse.data().end());\n\n        matrice::matrice<fraction> identite(3, 3);\n        identite <<= 1, 0, 0,\n                0, 1, 0,\n                0, 0, 1;\n\n        matrice::matrice<fraction> produit = boost::numeric::ublas::prod(A, inverse);\n\n        BOOST_CHECK_EQUAL_COLLECTIONS(produit.data().begin(), produit.data().end(),\n                                      identite.data().begin(), identite.data().end());\n    }\n\n    BOOST_AUTO_TEST_CASE(inversion2) {\n        typedef boost::rational<long long> fraction;\n\n        matrice::matrice<fraction> A(4, 4);\n        A <<= 1, 1, 1, -1,\n                1, 2, 6, 7,\n                1, 2, 9, 0,\n                2, 5, 9, 15;\n\n        matrice::matrice<fraction> resultat(4, 4);\n        resultat <<= 99, 132, -44, -55,\n                -18, -129, 29, 59,\n                -7, 14, 7, -7,\n                -3, 17, -8, -3;\n        resultat /= 77;\n\n        matrice::matrice<fraction> inverse(4, 4);\n\n        bool inversible = matrice::inversionLU(A, inverse);\n\n        BOOST_CHECK_EQUAL(inversible, true);\n        BOOST_CHECK_EQUAL_COLLECTIONS(resultat.data().begin(), resultat.data().end(),\n                                      inverse.data().begin(), inverse.data().end());\n\n        matrice::matrice<fraction> identite(4, 4);\n        identite <<= 1, 0, 0, 0,\n                0, 1, 0, 0,\n                0, 0, 1, 0,\n                0, 0, 0, 1;\n\n        matrice::matrice<fraction> produit = boost::numeric::ublas::prod(A, inverse);\n\n        BOOST_CHECK_EQUAL_COLLECTIONS(produit.data().begin(), produit.data().end(),\n                                      identite.data().begin(), identite.data().end());\n    }\n\n    BOOST_AUTO_TEST_CASE(resolution_vecteur) {\n        typedef boost::rational<long long> fraction;\n\n        matrice::matrice<fraction> A(3, 3);\n        A <<= 1, -1, 2,\n                3, 2, 1,\n                2, -3, -2;\n\n        matrice::vecteur<fraction> b(3);\n        b <<= 5, 10, -10;\n\n        matrice::vecteur<fraction> resultat(3);\n        resultat <<= 1, 2, 3;\n\n        matrice::vecteur<fraction> x(3);\n        bool solution = matrice::resolutionLU(A, b, x);\n\n        BOOST_CHECK_EQUAL(solution, true);\n        BOOST_CHECK_EQUAL_COLLECTIONS(x.data().begin(), x.data().end(),\n                                      resultat.data().begin(), resultat.data().end());\n\n        matrice::vecteur<fraction> produit = boost::numeric::ublas::prod(A, x);\n\n        BOOST_CHECK_EQUAL_COLLECTIONS(produit.data().begin(), produit.data().end(),\n                                      b.data().begin(), b.data().end());\n    }\n\n    BOOST_AUTO_TEST_CASE(resolution_matrice) {\n        typedef boost::rational<long long> fraction;\n\n        matrice::matrice<fraction> A(3, 3);\n        A <<= 1, -1, 2,\n                3, 2, 1,\n                2, -3, -2;\n\n        matrice::matrice<fraction> B(3, 3);\n        B <<= 5, 1, 1,\n                10, 1, 2,\n                -10, 6, 0;\n\n        matrice::matrice<fraction> resultat(3, 3);\n        resultat <<= 35, 39, 17,\n                70, -32, 4,\n                105, -18, 11;\n        resultat /= 35;\n\n        matrice::matrice<fraction> X(3, 3);\n        bool solution = matrice::resolutionLU(A, B, X);\n\n        BOOST_CHECK_EQUAL(solution, true);\n        BOOST_CHECK_EQUAL_COLLECTIONS(X.data().begin(), X.data().end(),\n                                      resultat.data().begin(), resultat.data().end());\n\n        matrice::matrice<fraction> produit = boost::numeric::ublas::prod(A, X);\n\n        BOOST_CHECK_EQUAL_COLLECTIONS(produit.data().begin(), produit.data().end(),\n                                      B.data().begin(), B.data().end());\n    }\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "21947fdf1c69ff9daa43d4e3ba7b82fcf4711ebf", "size": 6009, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/matrice.cpp", "max_stars_repo_name": "ZongoForSpeed/ProjectEuler", "max_stars_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-10-13T17:07:21.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-08T11:50:22.000Z", "max_issues_repo_path": "tests/matrice.cpp", "max_issues_repo_name": "ZongoForSpeed/ProjectEuler", "max_issues_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "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/matrice.cpp", "max_forks_repo_name": "ZongoForSpeed/ProjectEuler", "max_forks_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "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.3833333333, "max_line_length": 86, "alphanum_fraction": 0.5147279081, "num_tokens": 1647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037262250327, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.7439828825537598}}
{"text": "#include \"polynomial_solver.hh\"\r\n#include <Eigen/Dense>\r\n\r\n\r\nnamespace Geo {\r\n\r\ntemplate<size_t DegT>\r\nstd::multiset<double> polygon_roots(const double* _poly)\r\n{\r\n  std::multiset<double> res;\r\n  if constexpr(DegT == 0)\r\n    return res;\r\n  if (_poly[DegT] == 0)\r\n  {\r\n    res = polygon_roots<DegT - 1>(_poly);\r\n    res.insert(0.);\r\n  }\r\n  else\r\n  {\r\n    Eigen::Matrix<double, DegT, DegT> companion;\r\n    companion.setZero();\r\n    companion(0, DegT - 1) = -_poly[0] / _poly[DegT];\r\n    for (int i = 1; i < DegT; ++i)\r\n    {\r\n      companion(i, DegT - 1) = -_poly[i] / _poly[DegT];\r\n      companion(i, i - 1) = 1;\r\n    }\r\n    Eigen::Matrix<std::complex<double>, DegT, 1> roots = companion.eigenvalues();\r\n    for (auto i = roots.rows(); i-- > 0;)\r\n    {\r\n      std::complex<double> val = roots(i, 0);\r\n      if (val.imag() == 0)\r\n        res.insert(val.real());\r\n    }\r\n  }\r\n  return res;\r\n}\r\n\r\ntemplate<>\r\nstd::multiset<double> polygon_roots<0>(const double*)\r\n{\r\n  return std::multiset<double>();\r\n}\r\n\r\ntemplate<size_t DegT>\r\nstd::multiset<double> polygon_roots(const std::array<double, DegT + 1>& _poly)\r\n{\r\n  return polygon_roots<DegT>(_poly.data());\r\n}\r\n\r\ntemplate std::multiset<double> polygon_roots<2>(const std::array<double, 3>& _poly);\r\ntemplate std::multiset<double> polygon_roots<3>(const std::array<double, 4>& _poly);\r\n//template std::multiset<double> polygon_roots<4>(const std::array<double, 5>& _poly);\r\n//template std::multiset<double> polygon_roots<5>(const std::array<double, 6>& _poly);\r\n\r\n} // namespace Geo\r\n", "meta": {"hexsha": "2a47b5c8beaaca5b8dda33631566bf12be63247a", "size": 1529, "ext": "cc", "lang": "C++", "max_stars_repo_path": "main/src/Geo/polynomial_solver.cc", "max_stars_repo_name": "marcomanno/ploygon_triangulation", "max_stars_repo_head_hexsha": "c98b99e3f9598252ffc27eb202939f0183ac872b", "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": "main/src/Geo/polynomial_solver.cc", "max_issues_repo_name": "marcomanno/ploygon_triangulation", "max_issues_repo_head_hexsha": "c98b99e3f9598252ffc27eb202939f0183ac872b", "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": "main/src/Geo/polynomial_solver.cc", "max_forks_repo_name": "marcomanno/ploygon_triangulation", "max_forks_repo_head_hexsha": "c98b99e3f9598252ffc27eb202939f0183ac872b", "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": 26.8245614035, "max_line_length": 87, "alphanum_fraction": 0.6147809026, "num_tokens": 464, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380482, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.7439167398020284}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include <vector>\n#include <iomanip>\n\n#include \"rkintegrator.hpp\"\n\nusing namespace std;\nusing namespace Eigen;\n\n// This function approximates the order of convergence of the RK scheme defined by A and b when applied to the first order system y'=f(y), y(0)=y0. We are interested in the error of the solutions at the point T.\n\ntemplate <class Function>\nvoid errors(const Function &f, const double &T, const VectorXd &y0, const MatrixXd &A, const VectorXd &b) {\n    \n    RKIntegrator<VectorXd> rk(A,b);\n    vector<double> error(15);\n    vector<double> order(14);\n    double sum = 0;\n    int count = 0;\n    bool test = 1;\n    vector<VectorXd> y_exact = rk.solve(f,T,y0,pow(2,15));\n    \n    for(int k = 0; k < 15; k++) {\n        int N = pow(2,k+1);\n        vector<VectorXd> y1 = rk.solve(f,T,y0,N);\n        \n        error[k] = (y1[N]-y_exact[pow(2,15)]).norm();\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[k];\n        \n        if (error[k]<y0.size()*5e-14) test = 0;\n        if (k>0 && test) {\n            order[k-1]=log(error[k-1]/error[k])/log(2);\n            cout << left << setw(10) << setfill(' ') << \"Approximated order = \" << order[k-1] <<endl;\n            sum += order[k-1];\n            count = k;\n        }\n        else cout << endl;\n    }\n    cout << \"Average approximated order = \" << sum / count << endl << endl;\n}\n", "meta": {"hexsha": "4fc023376774d97b4e4a3c9e05f2171c0728ca17", "size": 1555, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/PS12/solutions_ps12/errors.hpp", "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/PS12/solutions_ps12/errors.hpp", "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/PS12/solutions_ps12/errors.hpp", "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.5555555556, "max_line_length": 211, "alphanum_fraction": 0.5498392283, "num_tokens": 454, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480666, "lm_q2_score": 0.819893340314393, "lm_q1q2_score": 0.7438992437696715}}
{"text": "#include <maths/premiers.h>\n#include <boost/math/constants/constants.hpp>\n\n#include \"problemes.h\"\n#include \"utilitaires.h\"\n\nnamespace {\n    long double integral(long double beta) {\n        return beta + (std::log(std::cos(beta)) - std::log(std::cos(0.0L))) / std::tan(beta);\n    }\n}\n\nENREGISTRER_PROBLEME(613, \"Pythagorean Ant\") {\n    // Dave is doing his homework on the balcony and, preparing a presentation about Pythagorean triangles, has just\n    // cut out a triangle with side lengths 30cm, 40cm and 50cm from some cardboard, when a gust of wind blows the\n    // triangle down into the garden.\n    //\n    // Another gust blows a small ant straight onto this triangle. The poor ant is completely disoriented and starts to\n    // crawl straight ahead in random direction in order to get back into the grass.\n    //\n    // Assuming that all possible positions of the ant within the triangle and all possible directions of moving on are\n    // equiprobable, what is the probability that the ant leaves the triangle along its longest side?\n    //\n    // Give your answer rounded to 10 digits after the decimal point.\n    const long double beta1 = std::acos(0.6L);\n    const long double beta2 = std::acos(0.8L);\n\n    long double resultat = 1.0L / 4 + (integral(beta1) + integral(beta2)) / (2 * M_PIl);\n    return std::to_fixed(resultat, 10);\n}\n", "meta": {"hexsha": "0c2b058c986e906b1615941a8dd0bfe15ec7dab0", "size": 1345, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problemes/probleme613.cpp", "max_stars_repo_name": "ZongoForSpeed/ProjectEuler", "max_stars_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-10-13T17:07:21.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-08T11:50:22.000Z", "max_issues_repo_path": "problemes/probleme613.cpp", "max_issues_repo_name": "ZongoForSpeed/ProjectEuler", "max_issues_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "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": "problemes/probleme613.cpp", "max_forks_repo_name": "ZongoForSpeed/ProjectEuler", "max_forks_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "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": 43.3870967742, "max_line_length": 119, "alphanum_fraction": 0.7018587361, "num_tokens": 340, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799472560581, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.7438872805791434}}
{"text": "#include <iostream>\nusing namespace std;\n#include <ctime>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\nint main()\n{\n    Eigen::Matrix<float,2,3>matrix_23;\n    matrix_23<<1,2,3,4,5,6;\n    //cout<<matrix_23<<endl;\n    \n    Eigen::Vector3d v_3d=Eigen::Vector3d::Zero();\n    Eigen::Matrix<float,3,1> vd_3d;\n    //cout<<v_3d<<endl;\n    //cout<<v_3d(2,0)<<endl;\n    v_3d<<3,2,1;\n    vd_3d<<4,5,6;\n    cout<<v_3d<<endl;\n    cout<<vd_3d<<endl;\n    \n    Eigen::Matrix<double,2,1>result=matrix_23.cast<double>()*v_3d;\n    cout<<result;\n    Eigen::Matrix<float,2,1>result2=matrix_23*vd_3d;\n    //cout<<result2<<endl;\n\n\n    return 0;\n}\n", "meta": {"hexsha": "207a8a074b07711d2d2060caf7413795af02209c", "size": 625, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch3/useEigen/test/eigenMatrix.cpp", "max_stars_repo_name": "linmeeka/slambook", "max_stars_repo_head_hexsha": "554a9fdd33fc50b2b7d375cdbf4a1a5f8b46e7b8", "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/test/eigenMatrix.cpp", "max_issues_repo_name": "linmeeka/slambook", "max_issues_repo_head_hexsha": "554a9fdd33fc50b2b7d375cdbf4a1a5f8b46e7b8", "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/test/eigenMatrix.cpp", "max_forks_repo_name": "linmeeka/slambook", "max_forks_repo_head_hexsha": "554a9fdd33fc50b2b7d375cdbf4a1a5f8b46e7b8", "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": 20.8333333333, "max_line_length": 66, "alphanum_fraction": 0.616, "num_tokens": 240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361580958427, "lm_q2_score": 0.8152324983301568, "lm_q1q2_score": 0.7438476087312437}}
{"text": "#include <vector>\n\n#include <NTL/ZZ.h>\n\n#include \"../src/elements/element.hpp\"\n#include \"../src/algorithms/utils.hpp\"\n\n/* Example: using the remainder tree algorithm to search for a counterexample to\n * Kurepa's conjecture.\n *\n * The left factorial function is the sum of lesser factorials:\n * !n = 0! + 1! + ... + (n-1)!\n *\n * Suppose we wish to find primes p for which p divides !p.\n *\n *       [n,  1]\n * R_n = [0,  1]\n *\n * Observe that !n is the top right entry of R_1 * R_2 ...* R_n\n * Our goal is to find !2 (mod 2), !3 (mod 3), !5 (mod 5) ...\n * Using remainder tree, set the moduli m_n to be n if n prime, 1 otherwise,\n * and set A_0 = Id, A_n = R_n. Apply remainder tree with the A, m. Then, at each index\n * take only the top right entry of the resulting matrix. If 0 appears in the output\n * for a prime index, then a counterexample has been found.\n */\n\nusing std::vector;\n\n/* Unlike the Wolstenholme example (see it for more details), we need to use\n * a matrix datatype. Thankfully NTL can provide one for us.\n */\nusing NTL::ZZ;\nusing NTL::Mat;\n//TODO: specialize methods for Elt<Mat<ZZ> >, including modding by ZZ\n\nvector<Elt<Mat<ZZ> > > gen_kurepa_multiplicand(long lower, long upper) {\n    vector<Elt<Mat<ZZ> > > output(upper-lower);\n\n    for(long i = lower; i < upper; i++) {\n        Mat<ZZ> M;\n        M.SetDims(2,2);\n\n        if(i == 0) {\n            M[0][0] = ZZ(1);\n            M[0][1] = ZZ(0);\n            M[1][0] = ZZ(0);\n            M[1][1] = ZZ(1);\n            output[i] = Elt<Mat<ZZ> >(M);\n        }\n        else {\n            M[0][0] = ZZ(i);\n            M[0][1] = ZZ(1);\n            M[1][0] = ZZ(0);\n            M[1][1] = ZZ(1);\n            output[i-lower] = Elt<Mat<ZZ> >(M);\n        }\n    }\n    return output;\n}\n\nvector<Elt<ZZ>> gen_prime(long lower, long upper) {\n    vector<Elt<ZZ>> output(upper-lower);\n    \n    for(long i = lower; i < upper; i++){\n        ZZ n(i);\n        if(ProbPrime(n)) { //Technically a sieve is faster & more correct, but shouldn't make a big difference.\n                            //This is just an example anyway.\n            output[i-lower] = Elt<ZZ>(n);\n        }\n        else{\n            output[i-lower] = Elt<ZZ>(1);\n        }\n    }\n    return output;\n}\n\n\n//TODO: combine the above and actually write a search function that takes the top right entry of each matrix\n//TODO: explain how to modify calculate_factorial and compute V", "meta": {"hexsha": "d850867a84445ef2f9bf54a1c625478724f1af3b", "size": 2393, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "examples/kurepa.hpp", "max_stars_repo_name": "adienes/remainder-tree", "max_stars_repo_head_hexsha": "0aa76214ab6f2a4389ec45a239ea660749989a90", "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": "examples/kurepa.hpp", "max_issues_repo_name": "adienes/remainder-tree", "max_issues_repo_head_hexsha": "0aa76214ab6f2a4389ec45a239ea660749989a90", "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": "examples/kurepa.hpp", "max_forks_repo_name": "adienes/remainder-tree", "max_forks_repo_head_hexsha": "0aa76214ab6f2a4389ec45a239ea660749989a90", "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.2911392405, "max_line_length": 111, "alphanum_fraction": 0.5699958211, "num_tokens": 716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.74369804079488}}
{"text": "#include <armadillo>\n#include <iostream>\n\nvoid testLinearity(std::vector<arma::fvec>& vectors){\narma::fmat target_matrix(vectors[0].size(),vectors.size());\n  for(int i = 0; i < vectors.size(); i++) {\n    target_matrix.col(i) = vectors[i];\n}\n\ntarget_matrix.print();\nstd::cout << rank(target_matrix) << std::endl;\n}\n\ndouble dotProduct(arma::fvec vec1, arma::fvec vec2)\n{\n  double result = 0;\n  if(vec1.size() != vec2.size()) {\n    std::cout << \"Wrong dot product operation!\";\n    exit(1);\n  }\n  else {\n    for(int i = 0; i < vec1.size(); i++) {\n      result += vec1[i] * vec2[i];\n    }\n  }\n\n  return result;\n}\n\narma::fvec projectionOp(arma::fvec vec1, arma::fvec vec2) {\n  double num = dotProduct(vec1, vec2);\n  double den = dotProduct(vec1, vec1);\n\n  return (num)/(den) * vec1;\n}\n\narma::fvec sumprojections(std::vector<arma::fvec> vectors, std::vector<arma::fvec> r_vectors, int k) {\n  arma::fvec r_vector(vectors[0].size());\n  r_vector.zeros();\n  \n  for(int i = 0; i < k; i++) {\n    r_vector += projectionOp(r_vectors[i],vectors[k]);\n  }\n\n  return r_vector;\n}\n\nstd::vector<arma::fvec> makeBasis(std::vector<arma::fvec> vectors) {\n  std::vector<arma::fvec> r_vectors;\n  r_vectors.reserve(vectors.size());\n  for(int i = 0; i < vectors.size(); i++) {\n    r_vectors.push_back(vectors[i] - sumprojections(vectors, r_vectors, i));\n  }\n  \n  return r_vectors;\n}\n\nvoid makeNormal(std::vector<arma::fvec>& vectors) {\n  for(int i = 0; i < vectors.size(); i++) {\n    vectors[i] = arma::normalise(vectors[i]);\n  }\n}\n\nint main() {\n  \n  //fvec column vector\n  \n  arma::fmat inMat;\n  arma::fvec v1;\n  arma::fvec v2;\n  arma::fvec v3;\n  \n  v1 = {1, 2, 3};\n  v2 = {2, 3, 4};\n  v3 = {3, 4, 9};\n  \n  std::vector<arma::fvec> v;\n  std::vector<arma::fvec> rv;\n  v.push_back(v1);\n  v.push_back(v2);\n  v.push_back(v3);\n\n  rv = makeBasis(v);\n  makeNormal(rv);\n  for(int i = 0; i < rv.size(); i++) {\n    rv[i].print();\n  }\n\n  inMat = {{1,2,3},{2,3,4},{3,4,9}};\n  std::cout << rank(inMat) << std::endl;\n  \n  //arma::fmat U;\n  //arma::fvec S;\n  //arma::fmat V;\n  \n\n  //arma::svd(U, S, V, inMat);\n  \n  //inMat.print(\"inMat = \");\n  //U.print(\"U = \");\n  //S.print(\"S = \");\n  //V.print(\"V = \");\n  \n  return 0;\n}\n", "meta": {"hexsha": "5882bbdfcdfbf7a0a639b6081c45f02198d39d74", "size": 2178, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "word2vec/grassmannian.cpp", "max_stars_repo_name": "uphere-co/nlp-prototype", "max_stars_repo_head_hexsha": "c4623927e5c5c5f9c3e702eb36497ea1d9fd1ff3", "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": "word2vec/grassmannian.cpp", "max_issues_repo_name": "uphere-co/nlp-prototype", "max_issues_repo_head_hexsha": "c4623927e5c5c5f9c3e702eb36497ea1d9fd1ff3", "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": "word2vec/grassmannian.cpp", "max_forks_repo_name": "uphere-co/nlp-prototype", "max_forks_repo_head_hexsha": "c4623927e5c5c5f9c3e702eb36497ea1d9fd1ff3", "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": 20.5471698113, "max_line_length": 102, "alphanum_fraction": 0.5831037649, "num_tokens": 758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336303, "lm_q2_score": 0.8128673087708699, "lm_q1q2_score": 0.7436930808492753}}
{"text": "/**\n * @file   InverseCartanMatrixTest.cpp\n * @author ALIKAWA Hidehisa <alleyhide@gmail.com>\n * @date   2018/09/01\n \n * \n * @brief  for the tests of inverse of Cartan matrix\n * \n * Released under the MIT license\n */\n#include <iostream>\n#include <boost/numeric/ublas/io.hpp>\n\n#include \"gweyl.hpp\"\n\nint main(int argc, char** argv){\n\n    char t = argv[1][0];\n\n    gweyl::Type X;\n    switch (t){\n    case 'A':\n        X=gweyl::Type::A;\n        break;\n    case 'B':\n        X=gweyl::Type::B;\n        break;\n    case 'C':\n        X=gweyl::Type::C;\n        break;\n    case 'D':\n        X=gweyl::Type::D;\n        break;\n    case 'E':\n        X=gweyl::Type::E;\n        break;                \n    case 'F':\n        X=gweyl::Type::F;\n        break;\n    case 'G':\n        X=gweyl::Type::G;\n        break;        \n    default:\n        std::cout << \"Error type \" << std::to_string(t);\n        return -1;\n    }\n\n    unsigned n = atoi(argv[2]);\n\n    \n    bool myCheck=false;\n    if (argc == 4){\n        myCheck = true;\n    }\n\n    try {\n        gweyl::Cartan T(X, n);\n        \n        gweyl::matrix P = T.InverseCartanMatrix();\n\n        if (myCheck == true){\n            gweyl::matrix A = T.CartanMatrix();\n            gweyl::matrix testmat1 = prod(A, P);\n            gweyl::matrix testmat2 = prod(P, A);\n            \n            //std::cout << testmat1 << std::endl;\n            //std::cout << testmat2 << std::endl;\n\n            unsigned m = A.size1();\n            unsigned n = A.size2();\n            for (unsigned i = 0;i<m; ++i){\n                for (unsigned j=0;j<n; ++j){\n                    if (i==j){\n                        if (testmat1(i,j) != 1){\n                            std::runtime_error e(\"AP is not identity matrix\");\n                            throw e;\n                        }\n                        if (testmat2(i,j) != 1){\n                            std::runtime_error e(\"PA is not identity matrix\");\n                            throw e;\n                        }\n                    }else {\n                        if (testmat1(i,j) != 0){\n                            std::runtime_error e(\"AP is not identity matrix\");\n                            throw e;\n                        }\n                        if (testmat2(i,j) != 0){\n                            std::runtime_error e(\"PA is not identity matrix\");\n                            throw e;\n                        }\n                    }\n                }\n            }\n            \n        }\n\n        std::cout << P << std::endl;\n        \n    } catch (std::exception &e){\n        std::cout << \"Exeption is caught \\n what(): \";\n        std::cout << e.what();\n        std::cout << \"\\nError test CartanMatrix InverseCartanMatrix\" << std::endl;\n    }\n    \n    return 0;\n}\n", "meta": {"hexsha": "1fe24b77e7957b4fcb07c17ecf47c41c5863d534", "size": 2738, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/InverseCartanMatrixTest.cpp", "max_stars_repo_name": "alleyhide/gweyl", "max_stars_repo_head_hexsha": "a632d0e42ad7141950f387a783774950dbf41a64", "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/InverseCartanMatrixTest.cpp", "max_issues_repo_name": "alleyhide/gweyl", "max_issues_repo_head_hexsha": "a632d0e42ad7141950f387a783774950dbf41a64", "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/InverseCartanMatrixTest.cpp", "max_forks_repo_name": "alleyhide/gweyl", "max_forks_repo_head_hexsha": "a632d0e42ad7141950f387a783774950dbf41a64", "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.5887850467, "max_line_length": 82, "alphanum_fraction": 0.4054054054, "num_tokens": 687, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206659843132, "lm_q2_score": 0.8244619220634457, "lm_q1q2_score": 0.7435992458261699}}
{"text": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union\u2019s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n\n#include \"../util/ScalerUtils.hpp\"\n#include \"../util/FluidEigenMappings.hpp\"\n#include \"../../data/TensorTypes.hpp\"\n#include <Eigen/Core>\n#include <cassert>\n#include <cmath>\n\nnamespace fluid {\nnamespace algorithm {\n\nclass Standardization\n{\npublic:\n  using ArrayXd = Eigen::ArrayXd;\n  using ArrayXXd = Eigen::ArrayXXd;\n\n  void init(RealMatrixView in)\n  {\n    using namespace Eigen;\n    using namespace _impl;\n    ArrayXXd input = asEigen<Array>(in);\n    mMean = input.colwise().mean();\n    mStd = ((input.rowwise() - mMean.transpose()).square().colwise().mean())\n               .sqrt();\n    handleZerosInScale(mStd);\n    mInitialized = true;\n  }\n\n  void init(const RealVectorView mean, const RealVectorView std)\n  {\n    using namespace Eigen;\n    using namespace _impl;\n    mMean = asEigen<Array>(mean);\n    mStd = asEigen<Array>(std);\n    handleZerosInScale(mStd);\n    mInitialized = true;\n  }\n\n  void processFrame(const RealVectorView in, RealVectorView out,\n                    bool inverse = false) const\n  {\n    using namespace Eigen;\n    using namespace _impl;\n    ArrayXd input = asEigen<Array>(in);\n    ArrayXd result;\n    if (!inverse) { result = (input - mMean) / mStd; }\n    else\n    {\n      result = (input * mStd) + mMean;\n    }\n    out <<= asFluid(result);\n  }\n\n  void process(const RealMatrixView in, RealMatrixView out,\n               bool inverse = false) const\n  {\n    using namespace Eigen;\n    using namespace _impl;\n    ArrayXXd input = asEigen<Array>(in);\n    ArrayXXd result;\n\n    if (!inverse)\n    {\n      result = (input.rowwise() - mMean.transpose());\n      result = result.rowwise() / mStd.transpose();\n    }\n    else\n    {\n      result = (input.rowwise() * mStd.transpose());\n      result = (result.rowwise() + mMean.transpose());\n    }\n    out <<= asFluid(result);\n  }\n\n  bool initialized() const { return mInitialized; }\n\n  void getMean(RealVectorView out) const { out <<= _impl::asFluid(mMean); }\n\n  void getStd(RealVectorView out) const { out <<= _impl::asFluid(mStd); }\n\n  index dims() const { return mMean.size(); }\n  index size() const { return 1; }\n\n  void clear()\n  {\n    mMean.setZero();\n    mStd.setZero();\n    mInitialized = false;\n  }\n\n  ArrayXd mMean;\n  ArrayXd mStd;\n  bool    mInitialized{false};\n};\n}// namespace algorithm\n}// namespace fluid\n", "meta": {"hexsha": "78ad13da77add9623166e1403465e0b18366af01", "size": 2709, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/public/Standardization.hpp", "max_stars_repo_name": "jamesb93/flucoma-core", "max_stars_repo_head_hexsha": "3e964dd569f6fff15bd5249a705dc0da8f7b2ad8", "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": "include/algorithms/public/Standardization.hpp", "max_issues_repo_name": "jamesb93/flucoma-core", "max_issues_repo_head_hexsha": "3e964dd569f6fff15bd5249a705dc0da8f7b2ad8", "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": "include/algorithms/public/Standardization.hpp", "max_forks_repo_name": "jamesb93/flucoma-core", "max_forks_repo_head_hexsha": "3e964dd569f6fff15bd5249a705dc0da8f7b2ad8", "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": 24.8532110092, "max_line_length": 76, "alphanum_fraction": 0.657807309, "num_tokens": 680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026528034425, "lm_q2_score": 0.8104789155369047, "lm_q1q2_score": 0.7434544592632598}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include <vector>\n\n\nstruct point {\n    double a;\n    double b;\n};\n\nvoid eigenMapExample()\n{\n    ////////////////////////////////////////First Example/////////////////////////////////////////\n    Eigen::VectorXd solutionVec(12,1);\n    solutionVec<<1,2,3,4,5,6,7,8,9,10,11,12;\n    Eigen::Map<Eigen::MatrixXd> solutionColMajor(solutionVec.data(),4,3);\n\n    Eigen::Map<Eigen::Matrix<double, 3, 4, Eigen::RowMajor> >solutionRowMajor (solutionVec.data());\n\n\n    std::cout << \"solutionColMajor: \"<< std::endl;\n    std::cout << solutionColMajor<< std::endl;\n\n    std::cout << \"solutionRowMajor\"<< std::endl;\n    std::cout << solutionRowMajor<< std::endl;\n\n    ////////////////////////////////////////Second Example/////////////////////////////////////////\n\n    // https://stackoverflow.com/questions/49813340/stdvectoreigenvector3d-to-eigenmatrixxd-eigen\n\n    int array[9];\n    for (int i = 0; i < 9; ++i) {\n        array[i] = i;\n    }\n\n    Eigen::MatrixXi a(9, 1);\n    a = Eigen::Map<Eigen::Matrix3i>(array);\n    std::cout << a << std::endl;\n\n    std::vector<point> pointsVec;\n    point point1, point2, point3;\n\n    point1.a = 1.0;\n    point1.b = 1.5;\n\n    point2.a = 2.4;\n    point2.b = 3.5;\n\n    point3.a = -1.3;\n    point3.b = 2.4;\n\n    pointsVec.push_back(point1);\n    pointsVec.push_back(point2);\n    pointsVec.push_back(point3);\n\n    Eigen::Matrix2Xd pointsMatrix2d = Eigen::Map<Eigen::Matrix2Xd>(\n        reinterpret_cast<double*>(pointsVec.data()), 2,  long(pointsVec.size()));\n\n    Eigen::MatrixXd pointsMatrixXd = Eigen::Map<Eigen::MatrixXd>(\n        reinterpret_cast<double*>(pointsVec.data()), 2, long(pointsVec.size()));\n\n    std::cout << pointsMatrix2d << std::endl;\n    std::cout << \"==============================\" << std::endl;\n    std::cout << pointsMatrixXd << std::endl;\n    std::cout << \"==============================\" << std::endl;\n\n    std::vector<Eigen::Vector3d> eigenPointsVec;\n    eigenPointsVec.push_back(Eigen::Vector3d(2, 4, 1));\n    eigenPointsVec.push_back(Eigen::Vector3d(7, 3, 9));\n    eigenPointsVec.push_back(Eigen::Vector3d(6, 1, -1));\n    eigenPointsVec.push_back(Eigen::Vector3d(-6, 9, 8));\n\n    Eigen::MatrixXd pointsMatrix = Eigen::Map<Eigen::MatrixXd>(eigenPointsVec[0].data(), 3, long(eigenPointsVec.size()));\n\n    std::cout << pointsMatrix << std::endl;\n    std::cout << \"==============================\" << std::endl;\n\n    pointsMatrix = Eigen::Map<Eigen::MatrixXd>(reinterpret_cast<double*>(eigenPointsVec.data()), 3, long(eigenPointsVec.size()));\n\n    std::cout << pointsMatrix << std::endl;\n\n    std::vector<double> aa = { 1, 2, 3, 4 };\n    Eigen::VectorXd b = Eigen::Map<Eigen::VectorXd, Eigen::Unaligned>(aa.data(), long(aa.size()));\n}\n\nint main()\n{\n    eigenMapExample();\n}\n", "meta": {"hexsha": "80d5a0eee708b444a9cb317e2322b8dd705a184a", "size": 2761, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/memory_mapping.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/memory_mapping.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/memory_mapping.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": 30.6777777778, "max_line_length": 129, "alphanum_fraction": 0.5747917421, "num_tokens": 783, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083608, "lm_q2_score": 0.8539127510928476, "lm_q1q2_score": 0.7434141085605016}}
{"text": "#include <stdio.h>\n#include <unistd.h>\n#include <iostream>\n#include <armadillo>\n#include <Linear_LS.hpp>\n\nint main(int argc, char* argv[]){\n\t\n\tstd::cout << \"Let's do a linear least squares interpolation of vectors x and y\\n\" << \"\\n\";\n\tstd::cout << \"x = [1, 2, 3, 4]'\\n\" << \"\\n\";\n\tstd::cout << \"y = [6, 5, 7, 10]'\\n\" << \"\\n\";\n\n        std::cout << \"A = [B1, 1*B2]\\n\" << \"\\n\";\n        std::cout << \"    [B1, 2*B2]\\n\" << \"\\n\";\n\tstd::cout << \"    [B1, 3*B2]\\n\" << \"\\n\";\n\tstd::cout << \"    [B1, 4*B2]\\n\" << \"\\n\";\n\n\tstd::cout << \"Where A = x * [B1, B2] \\n\" << \"\\n\";\n\n\tstd::cout << \"and we'd like to solve for the vector of params, p=[B1, B2], that we seek but is unknown!!!!\\n\" << \"\\n\";\n\n\tstd::cout << \"-- but, not to worry -- we'll have some help from Armadillo, with that.\\n\\n\";\n\n\tstd::array<double, 4> arr_x = {1, 2, 3, 4};\n        std::array<double, 4> arr_y = {6, 5, 7, 10};\n\n\tstd::cout << \"Substituting the values of x into A, we obtain\\n\" << \"\\n\";\n\n        // compute it \n        LLS::LLS_impl lls=LLS::LLS_impl(arr_x, arr_y, 4);\n\n\tdouble B1, B2;\n\n\t// check that this seems right ...\n\tlls.getParams(B1, B2);\n\n\tstd::cout << \"by doing p = A^[+] * y, where A^[+] is the pseudoinverse of A.\\n\" << \"\\n\";\n\n\tstd::cout << \"Solution::::\\n\\n\";\n\tstd::cout << \"B1: \" << B1 << \"\\n\";\n        std::cout << \"B2: \" << B2 << \"\\n\\n\";\n\n\tstd::cout << \"Note that, p = [3.5, 1.4]' parametrizes the line y[i] = B2*x[i] + B1 for i=1:N=4, \\n\\nwhich according to the LLS solution is actually the 'line of best fit'.\\n\";\n\n}\n\n", "meta": {"hexsha": "e7ef13b049b2370632b5d61dc6a27aac907eb91b", "size": 1498, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "LLS/app/main_app.cpp", "max_stars_repo_name": "Wolframm74/armadillo_armanpy", "max_stars_repo_head_hexsha": "f716cc62f0ba7fd06976cf1f1977d89af268a371", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-10-31T15:56:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-28T09:43:49.000Z", "max_issues_repo_path": "LLS/app/main_app.cpp", "max_issues_repo_name": "Wolframm74/armadillo_armanpy", "max_issues_repo_head_hexsha": "f716cc62f0ba7fd06976cf1f1977d89af268a371", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-09-22T14:44:36.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-27T20:18:30.000Z", "max_forks_repo_path": "LLS/app/main_app.cpp", "max_forks_repo_name": "Wolframm74/armadillo_armanpy", "max_forks_repo_head_hexsha": "f716cc62f0ba7fd06976cf1f1977d89af268a371", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-10-03T14:31:42.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-03T14:31:42.000Z", "avg_line_length": 31.8723404255, "max_line_length": 176, "alphanum_fraction": 0.526034713, "num_tokens": 560, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299550303293, "lm_q2_score": 0.8031737892899222, "lm_q1q2_score": 0.743120448946254}}
{"text": "/** \\file matrix_utils.hpp\n*  \\brief Miscellaneous math functions\n*\n*  Miscellaneous math functions used in FDCL are defined here\n*/\n\n/*\n * Copyright (c) 2020 Flight Dynamics and Control Lab\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in \n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\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 \"common_types.hpp\"\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 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 * value.\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 deriv_unit_vector(const Vector3 &A, const Vector3 &A_dot, \\\n * const Vector3 A_ddot, Vector3 &q, Vector3 &q_dot, Vector3 &q_ddot)\n * Outputs the time derivatives of a vector after normalizing it.\n * @param A Non-normal vector\n * @param A_dot Time derivative of A\n * @param A_ddot Time derivative of A_dot\n * @param \n */\nvoid deriv_unit_vector( \\\n    const Vector3 &A, const Vector3 &A_dot, const Vector3 &A_ddot, \\\n    Vector3 &q, Vector3 &q_dot, Vector3 &q_ddot\n);\n\n\n#endif\n", "meta": {"hexsha": "c04aab735e68d61971447ed61fb2b0043ad34cf5", "size": 2816, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cpp/include/fdcl/matrix_utils.hpp", "max_stars_repo_name": "fdcl-gwu/uav_geometric_control", "max_stars_repo_head_hexsha": "a3e6f2943668f61047bb1daa089c0073e6797a50", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2020-10-26T09:37:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T08:35:53.000Z", "max_issues_repo_path": "cpp/include/fdcl/matrix_utils.hpp", "max_issues_repo_name": "MAminSFV/uav_geometric_control", "max_issues_repo_head_hexsha": "79fb7a947d1c51d9c3f5e1c6a96d11b99deaf9e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-09-14T08:08:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-03T14:28:48.000Z", "max_forks_repo_path": "cpp/include/fdcl/matrix_utils.hpp", "max_forks_repo_name": "MAminSFV/uav_geometric_control", "max_forks_repo_head_hexsha": "79fb7a947d1c51d9c3f5e1c6a96d11b99deaf9e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2020-11-22T10:14:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T18:43:02.000Z", "avg_line_length": 35.2, "max_line_length": 80, "alphanum_fraction": 0.7443181818, "num_tokens": 690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869819218866, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.7426391188295327}}
{"text": "#ifndef MATHS_UTILS_HPP_\n#define MATHS_UTILS_HPP_\n\n#include <Eigen/Dense>\n\ntemplate <typename T, size_t N>\nusing Vector = Eigen::Matrix<T, N, 1>;\ntemplate <typename T>\nusing Quaternion = Eigen::Quaternion<T>;\n\nnamespace MathsUtils\n{\n  template <typename T>\n  Eigen::Matrix<T, 3, 3> skew_symmetric(Vector<T, 3> v)\n  {\n    Eigen::Matrix<T, 3, 3> m;\n    m <<    0, -v[2],  v[1],\n         v[2],     0, -v[0],\n        -v[1],  v[0],     0;\n    return m;\n  }\n\n  // Differentiation of qvqstar in http://web.cs.iastate.edu/~cs577/handouts/quaternion.pdf\n  // qvqstar = (qw^2 - norm(qv))v + 2(qv.v)qv + 2qw(qv x v)\n  // d(qvqstar) / dqw = 2 qw v + 2 (qv x v) // col - 0\n  // d(qvqstar) / dqv = 2 (-v qv' + v.v I + qvv' - qw [v]_{skew}) // col - 1,2,3\n  template <typename T>\n  Eigen::Matrix<T, 3, 4> diff_qvqstar_q(Quaternion<T> q, Vector<T, 3> v)\n  {\n    auto& qw = q.w();\n    Vector<T, 3> qv = q.vec();\n    Eigen::Matrix<T, 3, 4> D(3, 4);\n    D.col(0) = 2 * (qw * v + skew_symmetric(qv) * v);\n    D.template block<3, 3>(0, 1) = \n      2 * (-v * qv.transpose() + \n           v.dot(qv)*Eigen::Matrix<T, 3, 3>::Identity() + \n           qv*v.transpose() - \n           qw*skew_symmetric(v));\n    return D;\n  }\n\n  /**\n   * Returns \n   *  [\n   *    [qw*qw + qx*qx - qz*qz - qy*qy, -qz*qw + qy*qx - qw*qz + qx*qy,\tqy*qw + qz*qx + qx*qz + qw*qy\n   *     qx*qy + qw*qz + qz*qw + qy*qx,\t qy*qy - qz*qz + qw*qw - qx*qx,\tqz*qy + qy*qz - qx*qw - qw*qx\n   *     qx*qz - qw*qy + qz*qx - qy*qw,\t qy*qz + qz*qy + qw*qx + qx*qw,\tqz*qz - qy*qy - qx*qx + qw*qw]\n   *  ]\n   */ \n  template <typename T>\n  Eigen::Matrix<T, 3, 3> diff_qvqstar_v(Quaternion<T> q)\n  {\n    auto& qw = q.w();\n    Vector<T, 3> qv = q.vec();\n    Eigen::Matrix<T, 3, 3> D;\n    D = (qw*qw - qv.dot(qv))*Eigen::Matrix<T, 3, 3>::Identity() + 2*qv*qv.transpose() + 2*qw*skew_symmetric(qv);\n    return D; \n  }\n\n  template <typename T>\n  Eigen::Matrix<T, 4, 4> diff_pq_p(Quaternion<T> q)\n  {\n    auto& qw = q.w();\n    Vector<T, 3> qv = q.vec();\n    Eigen::Matrix<T, 4, 4> D;\n    D(0, 0) = qw;\n    D.template block<1, 3>(0, 1) = -qv.transpose();\n    D.template block<3, 1>(1, 0) = qv;\n    D.template block<3, 3>(1, 1) = Eigen::Matrix<T, 3, 3>::Identity()*qw - skew_symmetric(qv);\n    return D;\n  }\n\n  template <typename T>\n  //diff_(p*q) /diff_q\n  Eigen::Matrix<T, 4, 4> diff_pq_q(Quaternion<T> p)\n  {\n    auto& pw = p.w();\n    Vector<T, 3> pv = p.vec();\n    Eigen::Matrix<T, 4, 4> D;\n    D(0, 0) = pw;\n    D.template block<1, 3>(0, 1) = -pv.transpose();\n    D.template block<3, 1>(1, 0) = pv;\n    D.template block<3, 3>(1, 1) = Eigen::Matrix<T, 3, 3>::Identity()*pw + skew_symmetric(pv);\n    return D;\n  }\n}\n#endif", "meta": {"hexsha": "3d5f978577360642f2d9305aa35dd08a73c01dbd", "size": 2651, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "examples/GenericQuaternionImuModel/MathsUtils.hpp", "max_stars_repo_name": "saifullah3396/kalman-filters", "max_stars_repo_head_hexsha": "01b02c6b6d7d2b3428a00c6f324280004a9ee3e7", "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": "examples/GenericQuaternionImuModel/MathsUtils.hpp", "max_issues_repo_name": "saifullah3396/kalman-filters", "max_issues_repo_head_hexsha": "01b02c6b6d7d2b3428a00c6f324280004a9ee3e7", "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": "examples/GenericQuaternionImuModel/MathsUtils.hpp", "max_forks_repo_name": "saifullah3396/kalman-filters", "max_forks_repo_head_hexsha": "01b02c6b6d7d2b3428a00c6f324280004a9ee3e7", "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.4712643678, "max_line_length": 112, "alphanum_fraction": 0.531120332, "num_tokens": 1115, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067147399245, "lm_q2_score": 0.7879311956428946, "lm_q1q2_score": 0.7426304426464854}}
{"text": "#ifndef GOMOKU_ALGORITHMS_STATISTICAL_H_\n#define GOMOKU_ALGORITHMS_STATISTICAL_H_\n#include <random>\n#include <Eigen/Dense>\n\nnamespace Gomoku::Algorithms {\n\nstruct Stats {\n\n    template <typename Numeric>\n    static Numeric Sigmoid(Numeric x) { return 1 / (1 + std::exp(-x)); };\n\n    template <typename Numeric>\n    static Numeric ReLU(Numeric x) { return std::max(x, 0); };\n\n    template <typename Vector>\n    static Vector Softmax(Eigen::Ref<Vector> logits) {\n        Vector exp_logits = logits.array().exp();\n        return exp_logits / exp_logits.sum();\n    }\n\n    // 32\u4f4d\u968f\u673a\u6570\u53d1\u751f\u5668\n    static auto& RandomEngine() {\n        static std::mt19937 engine(std::random_device{}());\n        return engine;\n    }\n\n    // \u53c2\u8003: https://en.wikipedia.org/wiki/Dirichlet_distribution#Random_number_generation\n    static Eigen::VectorXf DirichletNoise(Eigen::Ref<Eigen::VectorXf> base, float alpha) {\n        std::gamma_distribution<float> gamma(alpha, 1.0f);\n        return base.unaryExpr([&gamma](float mask) {\n            return mask ? gamma(RandomEngine()) : 0.0f;\n        }).normalized();\n    }\n\n    // \u03c0 = norm(\u03c0^(1/\u03c4)) = softmax(log(\u03c0)/\u03c4), 0 < \u03c4 <= 1\n    static Eigen::VectorXf TempBasedProbs(Eigen::Ref<Eigen::VectorXf> logits, float temperature) {\n        Eigen::VectorXd temp_logits = ((logits.array() + Epsilon).log() / temperature).cast<double>();\n        return Softmax(Eigen::Ref<Eigen::VectorXd>(temp_logits)).cast<float>().unaryExpr([](float probs) {\n            return probs > Epsilon ? probs : 0;\n        });\n    }\n\n    inline static const float Epsilon = Eigen::NumTraits<float>::epsilon();\n\n};\n\n}\n\n#endif // !GOMOKU_ALGORITHMS_STATISTICAL_H_\n", "meta": {"hexsha": "579c1fe41f667e32e682ce7c98e858182c8fe8e5", "size": 1646, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "core/lib/include/algorithms/Statistical.hpp", "max_stars_repo_name": "DailinH/GomokuAI", "max_stars_repo_head_hexsha": "575fc9b7d732e564a833dd605eba4f5e55b6e392", "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": "core/lib/include/algorithms/Statistical.hpp", "max_issues_repo_name": "DailinH/GomokuAI", "max_issues_repo_head_hexsha": "575fc9b7d732e564a833dd605eba4f5e55b6e392", "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": "core/lib/include/algorithms/Statistical.hpp", "max_forks_repo_name": "DailinH/GomokuAI", "max_forks_repo_head_hexsha": "575fc9b7d732e564a833dd605eba4f5e55b6e392", "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.2745098039, "max_line_length": 106, "alphanum_fraction": 0.6537059538, "num_tokens": 442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377272885903, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.742467401640801}}
{"text": "#ifndef _MATH_HEADER__\n#define _MATH_HEADER__\n\n#include <cmath>\n\n#include <boost/math/special_functions/relative_difference.hpp>\n\n#include \"exceptions.hpp\"\n#include \"log.hpp\"\n\nnamespace cpp_utils {\n\n    /**\n     * @brief pi value\n     * \n     * @return constexpr double \n     */\n    constexpr double pi() {\n        return std::atan(1)*4;\n    }\n\n     /**\n     * @brief compute log 2\n     * \n     * @note\n     * this function allows for computation compile time\n     * \n     * @tparam T type of both the input and the output\n     * @param n input\n     * @return constexpr T \\f$log_{2}(n)\\f$\n     */\n    template <typename T>\n    constexpr T log2(T n) {\n        return (n<2) ? 0 : 1 + log2(n/2);\n    }\n\n    template <typename NUM>\n    constexpr NUM abs(const NUM& n) {\n        return n >= 0 ? n : -n;\n    }\n\n    namespace internal {\n\n        template <typename NUM, typename ...OTHER>\n        constexpr NUM _min2(const NUM& min, const NUM& f, const OTHER&... others) {\n            return _min2(f < min ? f : min, others...);\n        }\n\n        template <typename NUM>\n        constexpr NUM _min2(const NUM& min, const NUM& f) {\n            return f < min ? f : min;\n        }\n\n        template <typename NUM, typename ...OTHER>\n        constexpr NUM _max2(const NUM& max, const NUM& f, const OTHER&... others) {\n            return _max2(f > max ? f : max, others...);\n        }\n\n        template <typename NUM>\n        constexpr NUM _max2(const NUM& max, const NUM& f) {\n            return f > max ? f : max;\n        }\n\n    }\n\n    template <typename NUM, typename ...OTHER>\n    constexpr NUM min(const NUM& f, const OTHER&... n) {\n        return internal::_min2(f, n...);\n    }\n\n    template <typename NUM, typename ...OTHER>\n    constexpr NUM max(const NUM& f, const OTHER&... n) {\n        return internal::_max2(f, n...);\n    }\n\n    /**\n     * @brief compute the number of digits a number has\n     * \n     * @note\n     *  examples if `countZero` is false\n     * @code\n     *  getIntegerDigits(0); //0\n     *  getIntegerDigits(1); //1\n     *  getIntegerDigits(11); //2\n     *  getIntegerDigits(0.3); //0\n     *  getIntegerDigits(1.3); //1\n     *  getIntegerDigits(11.3); //2\n     * @endcode\n     * \n     * @tparam NUM type of the number involved\n     * @param n nuymber involved\n     * @param countZero if true, values like 0.3 will return 1, since \"0\" is treated as a normal digit. If false we will return 0 since \"0\" is not trated as a digit.\n     * @return constexpr int number of digit before the decimal part\n     */\n    template <typename NUM>\n    constexpr int getIntegerDigits(const NUM& n, bool countZero = true) {\n        debug(\"n=\", n);\n        if (n < 0) {\n            return getIntegerDigits(-n, countZero);\n        }\n\n        if (n < 1) {\n            return countZero ? 1 : 0;\n        }\n        return static_cast<int>(floor(log10(n))) + 1;    \n    }\n\n    \n\n    // template <typename NUM>\n    // NUM pow10(int a) {\n    //     NUM n{1};\n    //     return internal::_pow10(n, a);\n    // }\n\n    template <typename NUM>\n    NUM pow10(int a) {\n        static double pow[] = {\n            1e-20, 1e-19, 1e-18, 1e-17, 1e-16, \n            1e-15, 1e-14, 1e-13, 1e-12, 1e-11,\n            1e-10, 1e-9, 1e-8, 1e-7, 1e-6, \n            1e-5, 1e-4, 1e-3, 1e-2, 1e-1, \n            1,\n            1e+1, 1e+2, 1e+3, 1e+4, 1e+5, \n            1e+6, 1e+7, 1e+8, 1e+9, 1e+10, \n            1e+11, 1e+12, 1e+13, 1e+14, 1e+15, \n            1e+16, 1e+17, 1e+18, 1e+19, 1e+20, \n        };\n        debug(\"a=\", a);\n        assert(a >= -20 && a <= +20);\n        return static_cast<NUM>(pow[20 + a]);\n    }\n\n    /**\n     * @brief get angular coefficient of a line going through 2 points\n     * \n     * The linear equation is:\n     * ```\n     * y = mx + q\n     * ```\n     * \n     * @pre\n     *  @li \\f$ xa -xb \\not = 0 \\f$;\n     * \n     * @tparam NUM type fo the points\n     * @param xa x of the first point\n     * @param ya y of the first point\n     * @param xb x of the second point\n     * @param yb y of the second point\n     * @return m\n     */\n    template <typename NUM1, typename NUM2, typename NUM3, typename NUM4>\n    constexpr double getM(const NUM1& xa, const NUM2& ya, const NUM3& xb, const NUM4& yb) {\n        return (static_cast<double>(ya) - static_cast<double>(yb)) / (static_cast<double>(xa) - static_cast<double>(xb));\n    }\n\n    /**\n     * @brief get q of a line going through 2 points\n     * \n     * The linear equation is:\n     * ```\n     * y = mx + q\n     * ```\n     * \n     * @pre\n     *  @li \\f$ xa -xb \\not = 0 \\f$;\n     * \n     * @tparam NUM type fo the points\n     * @param xa x of the first point\n     * @param ya y of the first point\n     * @param xb x of the second point\n     * @param yb y of the second point\n     * @return q\n     */\n    template <typename NUM1, typename NUM2, typename NUM3, typename NUM4>\n    constexpr double getQ(const NUM1& xa, const NUM2& ya, const NUM3& xb, const NUM4& yb) {\n        return static_cast<double>(ya) - getM(xa, ya, xb, yb) * static_cast<double>(xa);\n    }\n\n    /**\n     * @brief get q of a line going through 2 points\n     * \n     * The linear equation is:\n     * ```\n     * y = mx + q\n     * ```\n     * \n     * @tparam NUM type fo the points\n     * @param xa x of the first point\n     * @param ya y of the first point\n     * @param m angular coefficient of the line\n     * @return q\n     */\n    template <typename NUM1, typename NUM2, typename NUM3>\n    constexpr double getQ(const NUM1& xa, const NUM2& ya, const NUM3& m) {\n        return static_cast<double>(ya) - static_cast<double>(m)*static_cast<double>(xa);\n    }\n\n    /**\n     * @brief transform a value linearly\n     * \n     * The transformation follows the following equation:\n     * ```\n     * y = mx + q\n     * ```\n     * \n     * @param x the value to transform\n     * @param m angular coefficient of the line\n     * @param q y of the point in x=0\n     * @return y transformed value\n     */\n    template <typename NUM1, typename NUM2, typename NUM3>\n    constexpr double linearTransform(const NUM1& x, const NUM2& m, const NUM3& q) {\n        return static_cast<double>(m)*static_cast<double>(x) + static_cast<double>(q);\n    }\n\n    /**\n     * @brief transform a value linearly\n     * \n     * The transformation follows the following equation:\n     * ```\n     * y = mx + q\n     * ```\n     * \n     * @param x the value to transform\n     * @param xa x of the first point the line go through\n     * @param ya y of the first point the line go through\n     * @param xb x of the second point the line go through\n     * @param yb y of the second point the line go through\n     * @return y\n     */\n    template <typename NUM1, typename NUM2, typename NUM3, typename NUM4, typename NUM5>\n    constexpr double linearTransform(const NUM1& x, const NUM2& xa, const NUM3& ya, const NUM4& xb, const NUM5& yb) {\n        auto m = getM(xa, ya, xb, yb);\n        auto q = getQ(xa, ya, m);\n        return linearTransform(x, m, q);\n    }\n\n    /**\n     * @brief Generate a bounded sigmoid\n     * \n     * Use this function when you need to generate a monotonically crescent number\n     * \n     * @image html images/sigmoid.png \"\"\n     * \n     * @tparam NUM0 type of x castable to double\n     * @tparam NUM1 type of xMin castable to double\n     * @tparam NUM2 type of xMax castable to double\n     * @tparam NUM3 type of yMin castable to double\n     * @tparam NUM4 type of yMax castable to double\n     * @tparam NUM5 type of steepness castable to double\n     * @tparam NUM6 type of steepnessLocation castable to double\n     * @param xMin the minimum value x can have\n     * @param xMax the maximum value x can have\n     * @param yMin the minimum value the output of the function can have (obtainable when `x = xMin`)\n     * @param yMax the maximum value the output of the function can have (obtainable when `x = xMax`)\n     * @param steepness how quickly the function increases in value. strictly greater than 0. number greater than 1 means that the sigmoid change is steep. number in (0,1) means that the sigmoid change si smooth. parameter set t 1 means no alterations to the sigmoid.\n     * @param steepnessLocation a number between 0 and 1. 0 means the sigmoid y-value change happens near `xMin', 1 means the sigmoi y-value change happens near `xMax`; 0.5 it happens in the middle\n     * @return constexpr double output of the sigmoid\n     */\n    template <typename NUM0, typename NUM1, typename NUM2, typename NUM3, typename NUM4, typename NUM5, typename NUM6>\n    constexpr double getSigmoid(const NUM0& x, const NUM1& xMin, const NUM2& xMax, const NUM3& yMin, const NUM4& yMax, const NUM5& steepness, const NUM6& steepnessLocation) {\n        return getSigmoid<double, double, double, double, double, double, double>(x, xMin, xMax, yMin, yMax, steepness, steepnessLocation);\n    }\n\n    template <>\n    constexpr double getSigmoid(const double& x, const double& xMin, const double& xMax, const double& yMin, const double& yMax, const double& steepness, const double& steepnessLocation) {\n        double deltax = xMin + steepnessLocation * (xMax - xMin);\n        double actualx = (x - deltax)/steepness;\n        return yMin + (yMax - yMin) * ((exp(actualx))/(exp(actualx) + 1));\n    }\n\n    template <typename NUM0, typename NUM1, typename NUM2, typename NUM3, typename NUM4, typename NUM5, typename NUM6>\n    constexpr double getInverseSigmoid(const NUM0& x, const NUM1& xMin, const NUM2& xMax, const NUM3& yMin, const NUM4& yMax, const NUM5& steepness, const NUM6& steepnessLocation) {\n        return getInverseSigmoid<double, double, double, double, double, double, double>(x, xMin, xMax, yMin, yMax, steepness, steepnessLocation);\n    }\n\n    template <>\n    constexpr double getInverseSigmoid(const double& x, const double& xMin, const double& xMax, const double& yMin, const double& yMax, const double& steepness, const double& steepnessLocation) {\n        double actualX = xMin + (xMax - x);\n        return getSigmoid<double, double, double, double, double, double, double>(actualX, xMin, xMax, yMin, yMax, steepness, 1. - steepnessLocation);\n    }\n\n    /**\n     * @brief get a function tha monotonically crescent. Starts from 0 up till 1\n     * \n     * The function will yield values monotonically crescent in a \"smooth way\"\n     * \n     * @note\n     * implementationwise, it uses atan function\n     * \n     * @pre\n     *  @li \\f$ x > 0 \\f$;\n     * \n     * @param x value\n     * @return a monotonically crescent value\n     */\n    template <typename NUM>\n    constexpr double getMonotonicallyCrescent(const NUM& x) {\n        return (2./cpp_utils::pi()) * std::atan(static_cast<double>(x));\n    }\n\n    /**\n     * @brief get a function tha monotonically crescent. Starts from `minY` up till `maxY`\n     * \n     * The function will yield values monotonically crescent in a \"smooth way\"\n     * \n     * @note\n     * implementationwise, it uses atan function\n     * \n     * @pre\n     *  @li \\f$ x > 0 \\f$;\n     * \n     * @param x value\n     * @param minY the minimum value the function can yield\n     * @param maxY the maximum value the function can yield\n     * @return a monotonically crescent value\n     */\n    template <typename NUM1, typename NUM2, typename NUM3>\n    constexpr double getMonotonicallyCrescent(const NUM1& x, const NUM2& minY, const NUM3& maxY) {\n        return static_cast<double>(minY) + (static_cast<double>(maxY) - static_cast<double>(minY)) * getMonotonicallyCrescent(x);\n    }\n\n    /**\n     * @brief get a function tha monotonically crescent. Starts from `minY` up till `maxY`\n     * \n     * The function will yield values monotonically crescent in a \"smooth way\"\n     * \n     * @note\n     * implementationwise, it uses atan function\n     * \n     * @pre\n     *  @li \\f$ x \\in [minX, maxX]\\f$;\n     *  @li  \\f$ ratio > 0 \\f$;\n     * \n     * @param x value\n     * @param ratio a number allowing you to determine how fast the function monotonically increment. 1 for normal increment. Values greater than 1 means that the function reaches maxY faster w.r.t of the same @c x. Values smaller than 0 means that the function reaches maxY slower w.r.t the same @c c.\n     * @param minX the minimum value @c x can have. if \\f$ x = minX \\f$, the functon yields @c minY. If \\f$x = maxX \\f$, the function yields @c maxY.\n     * @param maxX the maximum value @c x can have\n     * @param minY the minimum value the function can yield\n     * @param maxY the maximum value the function can yield\n     * @return a monotonically crescent value\n     */\n    template <typename NUM1, typename NUM2, typename NUM3, typename NUM4, typename NUM5, typename NUM6>\n    constexpr double getMonotonicallyCrescent(const NUM1& x, const NUM2& ratio, const NUM3& minX, const NUM4& maxX, const NUM5& minY, const NUM6& maxY) {\n        //we map the x from [minX, maxX] to [0,10000], since atan(0) = 0 and atan(1000) is about 1\n        auto bigN = 10000.;\n        auto m = getM(minX, 0., maxX, bigN);\n        auto q = getQ(minX, 0., m);\n        auto newX = linearTransform(x, m, q);\n        debug(\"m=\", m, \"q=\", q, \"x=\", x, \"newX=\", newX);\n        return getMonotonicallyCrescent(ratio * newX, minY, maxY);\n    }\n\n    /**\n     * @brief like ::getMonotonicallyCrescent but instead of repeatadly computing the same operation to fetch m and q, the developers gives them in input\n     * \n     * @code\n     *  minX = 5;\n     *  minY = 2;\n     *  maxX = 10;\n     *  maxY = 3;\n     * auto m = getM(minX, minY, maxX, maxY);\n     * auto q = getQ(minX, minY, m);\n     * //call several time the function\n     * getMonotonicallyCrescent(x1, ratio1, m, q, minY, maxY);\n     * getMonotonicallyCrescent(x2, ratio2, m, q, minY, maxY);\n     * getMonotonicallyCrescent(x3, ratio3, m, q, minY, maxY);\n     * getMonotonicallyCrescent(x4, ratio4, m, q, minY, maxY);\n     * @endcode\n     * \n     * @param x the number in input to compute a monotonically increase number\n     * @param ratio a number allowing you to determine how fast the function monotonically increment. 1 for normal increment. Values greater than 1 means that the function reaches maxY faster w.r.t of the same @c x. Values smaller than 0 means that the function reaches maxY slower w.r.t the same @c c.\n     * @param m angular coefficient computed previously. \n     * @param q y-value of the point on the line whose x=0.\n     * @param minY the minimum value the function can yield\n     * @param maxY the maximum value the function can yield\n     * @return a monotonically crescent value\n     */\n    template <typename NUM1, typename NUM2, typename NUM3, typename NUM4, typename NUM5, typename NUM6>\n    constexpr double getMonotonicallyCrescentFast(const NUM1& x, const NUM2& ratio, const NUM3& m, const NUM4& q, const NUM5& minY, const NUM6& maxY) {\n        auto newX = linearTransform(x, m, q);\n        debug(\"m=\", m, \"q=\", q, \"x=\", x, \"newX=\", newX);\n        return getMonotonicallyCrescent(ratio * newX, minY, maxY);\n    }\n\n    /**\n     * @brief Get normal distribution\n     * \n     * @code\n     *  (1/sigma sqrt(2*pi))* exp(0.5 * (x- mu/sigma)^2)\n     * @endcode\n     * \n     * @param x \n     * @param mean \n     * @param stddev \n     * @return double \n     */\n    double getNormal(double x, double mean, double stddev);\n\n    /**\n     * @brief Get normal distribution\n     * \n     * @code\n     *  compute a gaussian with mean 0\n     * @endcode\n     * \n     * @param x \n     * @param mean \n     * @param stddev \n     * @return double \n     */\n    double getGaussian(double x, double stddev);\n\n    /**\n     * @brief compute a gaussian whose minimum y and maximum y are given\n     * \n     * @param minY \n     * @param maxY \n     * @param x \n     * @param stddev \n     * @return double \n     */\n    double getGaussian(double minY, double maxY, double x, double stddev);\n\n    /**\n     * @brief compute a gaussian which is \n     * \n     * @note\n     * in the gaussian, \\f$ \\mu + 3 \\sigma \\f$ holds 99.7% of the data\n     * \n     * @param x \n     * @param mean \n     * @param stddevN a number which represents how rapidly the gaussian slows down. It is correlated to the standard deviation. 0 means the \n     * @param minX \n     * @param maxX \n     * @param minY \n     * @param maxY \n     * @return double \n     * @see https://en.wikipedia.org/wiki/Normal_distribution\n     */\n    double getCenteredGaussian(double x, double stddevN, double minX, double maxX, double minY, double maxY);\n\n    double getLeftGaussian(double x, double stddev, double minX, double maxX, double minY, double maxY);\n\n    double getRightGaussian(double x, double stddev, double minX, double maxX, double minY, double maxY);\n\n    /**\n     * @brief parse a number from a string\n     * \n     * @tparam T the type of the number to parse\n     * @param s the string representing a number\n     * @return T the parsed number\n     */\n    template <typename T>\n    T parseFromString(const std::string& s) {\n  \n        // object from the class stringstream \n        std::stringstream converter(s); \n    \n        // The object has the value 12345 and stream \n        // it to the integer x \n        T x; \n        converter >> x; \n        return x; \n    }\n\n    /**\n     * @brief parse a number from a string\n     * \n     * @tparam T the type of the number to parse\n     * @param s the string representing a number\n     * @return T the parsed number\n     */\n    template <typename T>\n    T parseFromString(const char* s) {\n        return parseFromString<T>(std::string{s});\n    }\n\n    /**\n     * @brief check if 2 decimal numbers are more or less equal\n     * \n     * @tparam T either float or double\n     * @param a first number to check\n     * @param b second number to check\n     * @param epsilon threshold of equality. (e.g., 0.001, 0.0001). If the difference between the 2 numbers is less than the threshold, the 2 numbers are equal\n     * @return true if `a` is the same of `b`\n     * @return false otherwise\n     * @see https://stackoverflow.com/a/253874/1887602\n     */\n    template <typename T>\n    constexpr bool isApproximatelyEqual(const T& a, const T& b, const T& epsilon) {\n        //see https://stackoverflow.com/a/41405501/1887602\n        auto_debug(a);\n        auto_debug(b);\n        auto_debug(epsilon);\n        auto diff = std::fabs(a - b);\n        if (diff <= epsilon)\n            return true;\n\n        if (diff < std::fmax(std::fabs(a), std::fabs(b)) * epsilon)\n            return true;\n\n        return false;\n    }\n\n    /**\n     * @brief check if 2 decimal numbers are equal. Use together with ::isApproximatelyEqual\n     * \n     * @tparam T either float or double\n     * @param a first number to check\n     * @param b second number to check\n     * @param epsilon threshold of equality. (e.g., 0.001, 0.0001). If the difference between the 2 numbers is less than the threshold, the 2 numbers are equal\n     * @return true if `a` is the same of `b`\n     * @return false otherwise\n     */\n    template <typename T>\n    bool isEssentiallyEqual(T a, T b, T epsilon) {\n        return std::abs(a - b) <= ( (std::abs(a) > std::abs(b) ? std::abs(b) : std::abs(a)) * epsilon);\n    }\n\n    /**\n     * @brief check if one number is for sure greater than another one.\n     * \n     * @tparam T either float or double\n     * @param a first number to check\n     * @param b second number to check\n     * @param epsilon threshold of equality. (e.g., 0.001, 0.0001).\n     * @return true if `a > b`\n     * @return false otherwise\n     */\n    template <typename T>\n    bool isDefinitelyGreaterThan(T a, T b, T epsilon) {\n        return (a - b) > ( (std::abs(a) < std::abs(b) ? std::abs(b) : std::abs(a)) * epsilon);\n    }\n\n    /**\n     * @brief check if one number is for sure less than another one.\n     * \n     * @tparam T either float or double\n     * @param a first number to check\n     * @param b second number to check\n     * @param epsilon threshold of equality. (e.g., 0.001, 0.0001).\n     * @return true if `a < b`\n     * @return false otherwise\n     */\n    template <typename T>\n    bool isDefinitelyLessThan(T a, T b, T epsilon) {\n        return (b - a) > ( (std::abs(a) < std::abs(b) ? std::abs(b) : std::abs(a)) * epsilon);\n    }\n\n    template <typename T>\n    constexpr T _Pow2GreaterThan(T n, T power) {\n        return (power >= n) ? power : _Pow2GreaterThan(n, 2*power);\n    }\n\n    /**\n     * @brief retrieve the smallest power of 2 which is greater or equal than the given number\n     * \n     * @code\n     *  ceilPow(1) //1\n     *  ceilPow(2) //2\n     *  ceilPow(3) //4\n     *  ceilPow(4) //4\n     *  ceilPow(5) //8\n     * @endcode\n     * \n     * @tparam T type of the number\n     * @param n the number involved\n     * @return constexpr T \n     */\n    template <typename T>\n    constexpr T pow2GreaterThan(T n) {\n        return n == 0 ? 0 : _Pow2GreaterThan(n, 1);\n    }\n\n    /**\n     * @brief converts a decimal number into a pair of numerator and denominator\n     * \n     * The function will generate ratios where the denominator is a power of 10.\n     * \n     * @tparam T the type of the decimale number. Ususally either `double` or `float`\n     * @tparam OUT the type of the numerator and denominator\n     * @param decimal the number to convert\n     * @param numerator the number which  will represents the numerator\n     * @param denominator the number which  will represents the denominator\n     * @param epsilon threshold of accuracy for the decimal value\n     * @param limit tries to perform before giving up the conversion. Ususally the module of the exponent of `epsilon`. Needs to be > 0\n     */\n    template <typename T, typename OUT>\n    void getRatioOf(T decimal, OUT& numerator, OUT& denominator, T epsilon, int limit) {\n        denominator = 1;\n        T denominatorT = 1;\n\n        while (true) {\n            if (limit == 0) {\n                throw cpp_utils::exceptions::InvalidArgumentException{\"cannot convert fraction\", decimal, \"into numerator and denominator\", decimal, \". epsilon=\", epsilon, \"limit\", limit};\n            }\n            limit -= 1;\n\n            numerator = static_cast<OUT>(decimal * static_cast<T>(denominator));\n            T numeratorT = decimal * denominatorT;\n\n            T numeratorTimesDivided10 = (static_cast<T>(10.) * numeratorT)/(static_cast<T>(10.));\n            debug(\"decimal=\", decimal, \"numerator=\", numerator, \"denominator=\", denominator, \"numeratorT=\", numeratorT, \"denominatorT=\", denominatorT, \"numeratorTimesDivided10=\", numeratorTimesDivided10, \"limit=\", limit, \"epsilon=\", epsilon);\n            if (isApproximatelyEqual(numeratorTimesDivided10, static_cast<T>(numerator), epsilon)) {\n                //only an integer number would return the same value\n                return;\n            } else {\n                //increase the numerator and denominator\n                denominator *= 10;\n                denominatorT *= 10;\n            }\n        }\n    }\n\n    namespace internal {\n\n        template<typename T>\n        constexpr int _argmin2(int minimumIndex, int nIndex, const T& minimum) {\n            return minimumIndex;\n        }\n\n        template<typename T, typename... NUMS>\n        constexpr int _argmin2(int minimumIndex, int nIndex, const T& minimum, const T& n, const NUMS&... args) {\n            return (n < minimum)\n                ? _argmin2(nIndex, nIndex + 1, n, args...)\n                : _argmin2(minimumIndex, nIndex + 1, minimum, args...)\n            ;\n        }\n\n        template<typename T, typename... NUMS>\n        constexpr int _argmin1(const T& first, const NUMS&... args) {\n            return _argmin2(0, 1, first, args...);\n        }\n\n        template<typename T>\n        constexpr int _argmax2(int maximumIndex, int nIndex, const T& maximum) {\n            return maximumIndex;\n        }\n\n        template<typename T, typename... NUMS>\n        constexpr int _argmax2(int maximumIndex, int nIndex, const T& maximum, const T& n, const NUMS&... args) {\n            return (n > maximum)\n                ? _argmax2(nIndex, nIndex + 1, n, args...)\n                : _argmax2(maximumIndex, nIndex + 1, maximum, args...)\n                ;\n        }\n\n        template<typename T, typename... NUMS>\n        constexpr int _argmax1(const T& first, const NUMS&... args) {\n            return _argmax2(0, 1, first, args...);\n        }\n\n    }\n\n    /**\n     * @brief computes the argmin of a sequence of values\n     * \n     * the argmin is the index of the element which is the minimum\n     * \n     * @note\n     * if multiple values are the minimum, we will return the index of the first one\n     * \n     * @tparam NUMS \n     * @param args \n     * @return constexpr int \n     */\n    template<typename... NUMS>\n    constexpr int argmin(const NUMS&... args) {\n        return internal::_argmin1(args...);\n    }\n\n    template <typename T>\n    constexpr int argmin(const T& num) {\n        return 0;\n    }\n\n    /**\n     * @brief computes the argmax of a sequence of values\n     * \n     * the argmax is the index of the element which is the maximum\n     * \n     * @note\n     * if multiple values are the maximum, we will return the index of the first one\n     * \n     * @tparam NUMS \n     * @param args \n     * @return constexpr int \n     */\n    template<typename... NUMS>\n    constexpr int argmax(const NUMS&... args) {\n        return internal::_argmax1(args...);\n    }\n\n    template<typename T>\n    constexpr int argmax(const T& num) {\n        return 0;\n    }\n\n    template <typename T>\n    bool isDecimal(const T& n) {\n        return isApproximatelyEqual(std::fmod(n, 1.0), 0.0, 1e-3);\n    }\n\n    template<int>\n    bool isDecimal(const int& n) {\n        return true;\n    }\n\n    template<unsigned int>\n    bool isDecimal(const unsigned int& n) {\n        return true;\n    }\n\n    template<long>\n    bool isDecimal(const long& n) {\n        return true;\n    }\n\n    template<unsigned long>\n    bool isDecimal(const unsigned long& n) {\n        return true;\n    }\n\n\n    /**\n     * @brief compute a value when it is inside a ring bound.\n     * \n     * The ring has as lowerbound 0 and as excluded upperbound @c ub\n     * \n     * @code\n     * ringBound(5, 10) // 5\n     * ringBound(0, 10) // 0\n     * ringBound(10, 10) // 0\n     * ringBound(-1, 10) // 9\n     * ringBound(11, 10) // 1\n     * @endcode\n     * \n     * @tparam T integer type (like int)\n     * @param val the value to ringBound\n     * @param ub the (excluded) upperbound of the interval\n     * @return T value inside the bound\n     */\n    template <typename T>\n    constexpr T ringBound(T val, const T& ub) {\n        return  (val < 0) ? ringBound(ub + val, ub) : \n                (val >= ub) ? val % ub :\n                val\n                ;\n    }\n\n    /**\n     * @brief like ::ringBound but with a lowerbound which is not 0\n     * \n     * \n     * @code\n     * ringBound(5, 2, 10) // 5\n     * ringBound(2, 2, 10) // 2\n     * ringBound(0, 2, 10) // 8\n     * @endcode\n     * \n     * @tparam T integer type (like int)\n     * @param val the value to ringBound\n     * @param ub the (excluded) upperbound of the interval\n     * @return T value inside the bound\n     */\n    template <typename T>\n    constexpr T ringBound(T val, const T& lb, const T& ub) {\n        return lb + ringBound(val - lb, ub - lb);\n    }\n\n    /**\n     * @brief constraint a value within an inclusive interval\n     * \n     * @tparam NUM1 type of @c x\n     * @tparam NUM2 type of @c lb\n     * @tparam NUM3 type of @c ub\n     * @param x the value to test\n     * @param lb lowerbound of the interval\n     * @param ub upperbound of the interval\n     * @return lb if \\f$ x < lb \\f$, ub if \\f$ x > ub \\f$, @c x otherwise\n     */\n    template <typename NUM1, typename NUM2, typename NUM3>\n    constexpr NUM1 bound(const NUM1& x, const NUM2& lb, const NUM3& ub) {\n        if (x < lb) {\n            return static_cast<NUM1>(lb);\n        }\n        if (x > ub) {\n            return static_cast<NUM2>(ub);\n        }\n        return x;\n    }\n\n}\n\n#endif", "meta": {"hexsha": "7df970b0f7f7fe3782f93573df83d7bd9665e69e", "size": 27734, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/main/include/math.hpp", "max_stars_repo_name": "Koldar/cpp-utils", "max_stars_repo_head_hexsha": "eaafe5c1f6da034ce19a612aeb7942fe0378d048", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-11T23:20:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-11T23:20:14.000Z", "max_issues_repo_path": "src/main/include/math.hpp", "max_issues_repo_name": "Koldar/cpp-utils", "max_issues_repo_head_hexsha": "eaafe5c1f6da034ce19a612aeb7942fe0378d048", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2019-09-19T09:18:06.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-15T15:52:59.000Z", "max_forks_repo_path": "src/main/include/math.hpp", "max_forks_repo_name": "Koldar/cpp-utils", "max_forks_repo_head_hexsha": "eaafe5c1f6da034ce19a612aeb7942fe0378d048", "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.7979924718, "max_line_length": 302, "alphanum_fraction": 0.5955505877, "num_tokens": 7770, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.8244619350028204, "lm_q1q2_score": 0.7424525343923508}}
{"text": "#ifndef DET_MODEL_PMCA_HPP_INCLUDED\n#define DET_MODEL_PMCA_HPP_INCLUDED\n#include <vector>\n#include <iostream>\n#include <cmath>\n#include <boost/math/constants/constants.hpp>\n#include \"utility_functions.hpp\"\n\n//DECLATATIONS FOR PMCA_SYSTEM\n//Units: SI\nclass DET_MODEL_PMCA\n{\nprivate:\n  double kf1 = 3E7;   // 1.5E07 M^-1S^-1\n  double kb1 = 20.0;    // S^-1\n  double kf2 = 20.0;    // S^-1\n  double kf3 = 100.0;   // S^-1\n  double kl = 12.5;\t// 12.5 S^-1\n\npublic:\n  std::vector<double> X;      // Inside Calcium concentration in Molars\n  //------------------ CONSTRUCTORS\n  DET_MODEL_PMCA(std::vector<double> X_): X(X_) { };\n  template <class State, class Deriv >\n  void operator() ( const State &x, Deriv &dxdt , const double  t );\n};\n\n//------- PMCA class ODE Function\ntemplate <class State, class Deriv >\nvoid DET_MODEL_PMCA::operator() ( const State &x, Deriv &dxdt, const double t )\n// [Cai] [PMCA0] [PMCA1] [PMCA2]  [Cao]\n// [x0]    [x1]    [x2]    [x3]   [x4] \n{ \n  dxdt[0] = (-x[0]*x[1]*kf1) + (x[1]*kl);\n  dxdt[1] = (-x[0]*x[1]*kf1) + (-x[1]*kl) + (x[2]*kb1) + (x[3]*kf3);\n  dxdt[2] = (-x[2]*kb1) + (x[1]*x[0]*kf1) + (-x[2]*kf2);\n  dxdt[3] = (-x[3]*kf3) + (x[2]*kb1);\n  dxdt[4] = (x[3]*kf3) + (-x[1]*kl);\n}\n#endif // DET_MODEL_PMCA_HPP_INCLUDED\n\n\n\n\n", "meta": {"hexsha": "67a743c51b14e9fc209fa465e3cd78c3f037eb4d", "size": 1255, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/old/src/old/det_model_pmca.hpp", "max_stars_repo_name": "anupgp/astron", "max_stars_repo_head_hexsha": "5ef1b113b5025f5e0477a1fb2b5202fadbc5335c", "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/old/src/old/det_model_pmca.hpp", "max_issues_repo_name": "anupgp/astron", "max_issues_repo_head_hexsha": "5ef1b113b5025f5e0477a1fb2b5202fadbc5335c", "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/old/src/old/det_model_pmca.hpp", "max_forks_repo_name": "anupgp/astron", "max_forks_repo_head_hexsha": "5ef1b113b5025f5e0477a1fb2b5202fadbc5335c", "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.8888888889, "max_line_length": 79, "alphanum_fraction": 0.593625498, "num_tokens": 494, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248242542283, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.7423275889223145}}
{"text": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <cmath>\n#include <boost/bind.hpp>\n#include <iterator>\n\ndouble nextNumber( double number ) {\n   return number + floor( 0.5 + sqrt( number ) ) ;\n}\n\nint main( ) {\n   std::vector<double> non_squares ;\n   typedef std::vector<double>::iterator SVI ;\n   non_squares.reserve( 1000000 ) ;\n   //create a vector with a million sequence numbers\n   for ( double i = 1.0 ; i < 100001.0 ; i += 1 )\n      non_squares.push_back( nextNumber( i ) ) ;\n   //copy the first numbers to standard out\n   std::copy( non_squares.begin( ) , non_squares.begin( ) + 22 ,\n\t std::ostream_iterator<double>(std::cout, \" \" ) ) ;\n   std::cout << '\\n' ;\n   //find if floor of square root equals square root( i. e. it's a square number )\n   SVI found = std::find_if ( non_squares.begin( ) , non_squares.end( ) ,\n\t boost::bind( &floor, boost::bind( &sqrt, _1 ) ) == boost::bind( &sqrt, _1 ) ) ;\n   if ( found != non_squares.end( ) ) {\n      std::cout << \"Found a square number in the sequence!\\n\" ;\n      std::cout << \"It is \" << *found << \" !\\n\" ;\n   }\n   else {\n      std::cout << \"Up to 1000000, found no square number in the sequence!\\n\" ;\n   }\n   return 0 ;\n}\n", "meta": {"hexsha": "353b14209ab91216441f3ca2cdb78780b93d4af7", "size": 1194, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lang/C++/sequence-of-non-squares.cpp", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-01-29T20:08:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T06:16:05.000Z", "max_issues_repo_path": "lang/C++/sequence-of-non-squares.cpp", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "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": "lang/C++/sequence-of-non-squares.cpp", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-13T04:19:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-13T04:19:31.000Z", "avg_line_length": 34.1142857143, "max_line_length": 82, "alphanum_fraction": 0.6130653266, "num_tokens": 360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418283357703, "lm_q2_score": 0.803173801068221, "lm_q1q2_score": 0.742246504990576}}
{"text": "/* \n\n g++ -I/usr/local/include/eigen3 -o diag diag.cpp\n\n*/\n\n\n#include <iostream>\n#include <Eigen/Eigenvalues> \n      \nusing namespace std;\nusing namespace Eigen;\n\n\ndouble V(double x) {\n  return x*x/2.0;\n}\n\ndouble E(int i, int ell) {\n  return  2*i+ell+1.5;\n}\n\nint main() {\n  int N,ell;\n  double xmax;\n  cout << \" enter xmax, ell, N \" << endl;\n  cin >> xmax >> ell >> N;\n  double dx = xmax/N;\n  MatrixXd H = MatrixXd::Zero(N,N); // variable-size double matrix\n  // fill in H\n  for (int i=0;i<N;i++) {\n    double x = i*dx + dx;\n    H(i,i) = 1.0/(dx*dx) + ell*(ell+1.0)/(2.0*x*x) + V(x);\n  }\n  for (int i=0;i<N-1;i++) {\n    double x = i*dx + dx;\n    H(i,i+1) = -1.0/(2.0*dx*dx);\n    H(i+1,i) = -1.0/(2.0*dx*dx);\n  }\n  SelfAdjointEigenSolver<MatrixXd> es(H);   \n  VectorXd ev(N), r2(N);\n  for (int i=0;i<N;i++) {   \n    double x = dx*i + dx;\n    r2(i) = x*x;\n  }\n  MatrixXd R2 = r2.asDiagonal();\n  for (int i=0;i<10;i++) { \n    ev = es.eigenvectors().col(i).normalized();  // ith eigenvector\n    ev /= sqrt(dx);                              // normalize\n    double rsq   = dx * ev.transpose() *  R2 * ev;  // <r^2>\n    cout << E(i,ell) << \" \" << es.eigenvalues()[i] << \" \" << (es.eigenvalues()[i]-E(i,ell))/E(i,ell) << \" Rrms: \" << sqrt(rsq) << endl;\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "a412a3528696a948c7ef40d536eca8bfaabe2822", "size": 1265, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CH21/DIAG/diag.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": "CH21/DIAG/diag.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": "CH21/DIAG/diag.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": 22.5892857143, "max_line_length": 135, "alphanum_fraction": 0.5114624506, "num_tokens": 467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787566, "lm_q2_score": 0.8031738057795402, "lm_q1q2_score": 0.7422465026323687}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include \"fvm_1d_functions.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\n// This function calculates the cell centered grid\nArrayXd makeGrid(int totalNCells, int numGhost, double xLeft, double dx) {\n    // Create a uniform Cartesian mesh for x based on cell centers\n    ArrayXd x(totalNCells);\n    \n    // Iterate through the total number of cells.\n    // Note we are including ghost cells so the actual limits of this grid are larger than\n    // the bounds set by xLeft and xRight \n    for (int i = 0; i < totalNCells; i++) {\n        x(i) = (i - numGhost) * dx + (xLeft + dx / 2.);\n    }\n    return x;\n} // Tested. Works correctly. 2021/11/18\n\n// This function calculates conservative variables based on primitive variables for the 1D Euler equations\nvoid prim2cons(double gasGamma, Array<ArrayXd, 3, 1> &prim, Array<ArrayXd, 3, 1> &cons) {\n    // See documentation for how conversions are derived\n    cons(0) = prim(0);\n    cons(1) = prim(0) * prim(1);\n    cons(2) = prim(2)/(gasGamma-1.0) + 0.5*prim(0)*prim(1)*prim(1);\n} // Tested. Works correctly. 2021/11/21\n\n// This function calculates the primitive variables based on the conservative variables for the 1D Euler equations\nvoid cons2prim(double gasGamma, Array<ArrayXd, 3, 1> &cons, Array<ArrayXd, 3, 1> &prim) {\n    // See documentation for how conversions are derived\n    prim(0) = cons(0);\n    prim(1) = cons(1) / cons(0);\n    prim(2) = (gasGamma - 1.) * (cons(2) - 0.5 * cons(1)*cons(1)/cons(0) );\n} // Tested. Works correctly. 2021/11/22\n\n// Compute the time step based on the max speed in the system\ndouble computeTimeStep(double CFL, double dx, double gasGamma, Array<ArrayXd, 3, 1> &prim) {\n    // This is several calculations done in one go\n    // The denominator is the maximum eigenvalue\n    // For the Euler 1D equations, this is |u|+a \n    // where a=(gasGamma*p/rho)^.5 is the sound speed\n    // The time step is determined by dividing dx by the maximum eigenvalue\n    // This value is multiplied by the CFL number to ensure numerical stability    \n    return CFL * dx / (abs(prim(1)) + pow(gasGamma*prim(2)/prim(0),0.5)).maxCoeff();\n}\n\n\n\n// This is the big function that runs the entire simulation based on all of the other functions\nvoid runSimulation(double gasGamma, int maxIter, int nCells, \\\n    int numGhost, double xLeft, double xRight) {\n\n    \n\n    // Set boundary conditions\n\n    // Initialize other variables important in main time integration loop\n\n    // Start main time loop\n\n    \n\n    // Iterate through time\n    for (int i = 0; i < maxIter; i++) {\n        \n        // Calculate fastest speed\n\n        // Calculate time step\n\n        // Do SSPRK loop (review 4 stage SSPRK3 method). Think about ways to do it nicely in loop\n\n        for (int stage = 0; stage < 4; stage++) {            \n\n            // Do stuff here in the RK loop\n\n\n        }\n\n\n\n    }\n\n    \n}\n\n", "meta": {"hexsha": "6aaef34da3315446f1acc2b8b68c55bea396479a", "size": 2894, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "FVM_1D/main/fvm_1d_functions.cpp", "max_stars_repo_name": "Aquadorf/computational-skolar", "max_stars_repo_head_hexsha": "77ebab70fe22a9e48b7d187b965781fe941e3ae1", "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": "FVM_1D/main/fvm_1d_functions.cpp", "max_issues_repo_name": "Aquadorf/computational-skolar", "max_issues_repo_head_hexsha": "77ebab70fe22a9e48b7d187b965781fe941e3ae1", "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": "FVM_1D/main/fvm_1d_functions.cpp", "max_forks_repo_name": "Aquadorf/computational-skolar", "max_forks_repo_head_hexsha": "77ebab70fe22a9e48b7d187b965781fe941e3ae1", "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.8863636364, "max_line_length": 114, "alphanum_fraction": 0.6589495508, "num_tokens": 802, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.7421937693700807}}
{"text": "#include <cmath>\n#include <iostream>\n#include <vector>\n#include <catch/catch.hpp>\n#include <Eigen/Dense>\n#include \"numeric_utils.h\"\n\nTEST_CASE(\"Test correlation to covariance functionality\", \"[Helpers]\") {\n  SECTION(\"Correlation is diagonal matrix with values of 1.0 along diagonal\") {\n    Eigen::MatrixXd test_corr = Eigen::MatrixXd::Zero(3, 3);\n    test_corr(0, 0) = 1.0;\n    test_corr(1, 1) = 1.0;\n    test_corr(2, 2) = 1.0;\n    Eigen::MatrixXd std_dev = Eigen::VectorXd::Ones(3);\n\n    std_dev << 2.0, 3.0, 4.0;\n\n    auto cov = numeric_utils::corr_to_cov(test_corr, std_dev);\n\n    Eigen::MatrixXd expected_matrix = Eigen::MatrixXd::Zero(3, 3);\n    expected_matrix(0, 0) = 4.0;\n    expected_matrix(1, 1) = 9.0;\n    expected_matrix(2, 2) = 16.0;\n\n    REQUIRE(cov(0, 0) == expected_matrix(0, 0));\n    REQUIRE(cov(1, 1) == expected_matrix(1, 1));\n    REQUIRE(cov(2, 2) == expected_matrix(2, 2));\n    REQUIRE(expected_matrix.lpNorm<2>() == Approx(cov.lpNorm<2>()).epsilon(0.01));\n  }\n}\n\nTEST_CASE(\"Test one dimensional convolution\", \"[Helpers][Convolution]\") { \n  SECTION(\"One dimensional convolution of vectors with length 1\") {\n    std::vector<double> input_x{1.0};\n    std::vector<double> input_y{2.0};\n    std::vector<double> response;\n\n    bool status;\n    try {\n      status = numeric_utils::convolve_1d(input_x, input_y, response);\n    } catch (std::exception &exception) {\n      std::cout << \"Convolution error: \" << exception.what() << std::endl;      \n      FAIL(\"One dimensional convolution function throws exception, check where \"\n           \"exception is being generated interally\");\n    }\n\n    REQUIRE(status);\n    REQUIRE(response.size() == 1);\n    REQUIRE(response[0] == Approx(2.0).epsilon(0.01));\n  }\n\n  SECTION(\"One dimensional convolution of vectors with length 2 and 3\") {\n    std::vector<double> input_x{3.0, 4.0, 5.0};\n    std::vector<double> input_y{2.0, 1.0};\n    std::vector<double> response(1);\n\n    bool status;\n    try {\n      status = numeric_utils::convolve_1d(input_x, input_y, response);\n    } catch (std::exception &exception) {\n      std::cout << \"Convolution error: \" << exception.what() << std::endl;      \n      FAIL(\"One dimensional convolution function throws exception, check where \"\n           \"exception is being generated interally\");\n    }\n\n    REQUIRE(status);\n    REQUIRE(response.size() == input_x.size() + input_y.size() - 1);\n    REQUIRE(response[0] == Approx(6.0).epsilon(0.01));\n    REQUIRE(response[1] == Approx(11.0).epsilon(0.01));\n    REQUIRE(response[2] == Approx(14.0).epsilon(0.01));\n    REQUIRE(response[3] == Approx(5.0).epsilon(0.01));\n  }  \n}\n\nTEST_CASE(\"Test trapazoid rule\", \"[Helpers][Trapazoid]\") {\n\n  SECTION(\"STL vector with unit spacing\") {\n    std::vector<double> input_vector{1, 4, 9, 16, 25};\n\n    auto integral = numeric_utils::trapazoid_rule(input_vector, 1.0);\n    REQUIRE(integral == 42);\n  }\n\n  SECTION(\"STL vector with non-unit spacing\") {\n    std::vector<double> input_vector(101, 0.0);\n\n    double accumulator = 0.0;\n    for (unsigned int i = 1; i < input_vector.size(); ++i) {\n      accumulator += M_PI / 100.0;\n      input_vector[i] = std::sin(accumulator);\n    }\n\n    auto integral = numeric_utils::trapazoid_rule(input_vector, M_PI / 100.0);\n    REQUIRE(integral == Approx(1.9998).epsilon(0.01));\n  }\n\n  SECTION(\"Eigen vector with unit spacing\") {\n    Eigen::VectorXd input_vector(5);\n    input_vector << 1, 4, 9, 16, 25;\n\n    auto integral = numeric_utils::trapazoid_rule(input_vector, 1.0);\n    REQUIRE(integral == 42);\n  }\n\n  SECTION(\"Eigen vector with non-unit spacing\") {\n    Eigen::VectorXd input_vector = Eigen::VectorXd::Zero(101);\n\n    double accumulator = 0.0;\n    for (unsigned int i = 1; i < input_vector.size(); ++i) {\n      accumulator += M_PI / 100.0;\n      input_vector[i] = std::sin(accumulator);\n    }\n\n    auto integral = numeric_utils::trapazoid_rule(input_vector, M_PI / 100.0);\n    REQUIRE(integral == Approx(1.9998).epsilon(0.01));\n  }    \n}\n\nTEST_CASE(\"Test 1-D inverse Fast Fourier Transform\", \"[Helpers][FFT]\") {\n  SECTION(\"Calculate real portion of one-dimesional inverse FFT\") {\n    std::vector<std::complex<double>> input_vector = {\n        {15.0, 0.0},\n        {-2.5, 3.440954801177933},\n        {-2.5, 0.812299240582266},\n        {-2.5, -0.812299240582266},\n        {-2.5, -3.440954801177933}};\n\n    std::vector<double> output_vector(4);\n    auto status = numeric_utils::inverse_fft(input_vector, output_vector);\n\n    REQUIRE(status);\n    REQUIRE(output_vector[0] == Approx(1.0).epsilon(0.01));\n    REQUIRE(output_vector[1] == Approx(2.0).epsilon(0.01));\n    REQUIRE(output_vector[2] == Approx(3.0).epsilon(0.01));\n    REQUIRE(output_vector[3] == Approx(4.0).epsilon(0.01));\n    REQUIRE(output_vector[4] == Approx(5.0).epsilon(0.01));\n  }\n\n  SECTION(\"Calculate real portion of one-dimesional inverse FFT\") {\n    Eigen::VectorXcd input_vector(5);\n    input_vector << std::complex<double>(15.0, 0.0),\n      std::complex<double>(-2.5, 3.440954801177933),\n      std::complex<double>(-2.5, 0.812299240582266),\n      std::complex<double>(-2.5, -0.812299240582266),\n      std::complex<double>(-2.5, -3.440954801177933);\n\n    Eigen::VectorXd output_vector;\n    auto status = numeric_utils::inverse_fft(input_vector, output_vector);\n\n    REQUIRE(status);\n    REQUIRE(output_vector[0] == Approx(1.0).epsilon(0.01));\n    REQUIRE(output_vector[1] == Approx(2.0).epsilon(0.01));\n    REQUIRE(output_vector[2] == Approx(3.0).epsilon(0.01));\n    REQUIRE(output_vector[3] == Approx(4.0).epsilon(0.01));\n    REQUIRE(output_vector[4] == Approx(5.0).epsilon(0.01));\n  }  \n}\n", "meta": {"hexsha": "6b7c95a8a6dd6453dfdc0ee003e0e778b6b7a88e", "size": 5568, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/numeric_utils_tests.cc", "max_stars_repo_name": "charlesxwang/smelt", "max_stars_repo_head_hexsha": "da1f66ec857dd8ff8e9de104fbb3ecbd0ec84367", "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": "test/numeric_utils_tests.cc", "max_issues_repo_name": "charlesxwang/smelt", "max_issues_repo_head_hexsha": "da1f66ec857dd8ff8e9de104fbb3ecbd0ec84367", "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": "test/numeric_utils_tests.cc", "max_forks_repo_name": "charlesxwang/smelt", "max_forks_repo_head_hexsha": "da1f66ec857dd8ff8e9de104fbb3ecbd0ec84367", "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": 35.2405063291, "max_line_length": 82, "alphanum_fraction": 0.6454741379, "num_tokens": 1657, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.8688267813328976, "lm_q1q2_score": 0.7419022751462409}}
{"text": "#pragma once\n\n#include <cmath>\n#include <cstdint>\n#include <functional>\n#include <random>\n\n#include <Eigen/Geometry>\n\nnamespace common_robotics_utilities\n{\nnamespace random_rotation_generator\n{\n/// Generator for uniform random quaternions and Euler angles.\nclass RandomRotationGenerator\n{\nprivate:\n  std::uniform_real_distribution<double> uniform_unit_dist_;\n\npublic:\n  RandomRotationGenerator() : uniform_unit_dist_(0.0, 1.0) {}\n\n  // From: \"Uniform Random Rotations\", Ken Shoemake, Graphics Gems III,\n  // see pages 124-132.\n  static Eigen::Quaterniond GenerateUniformRandomQuaternion(\n      const std::function<double()>& uniform_unit_dist)\n  {\n    const double x0 = uniform_unit_dist();\n    const double r1 = std::sqrt(1.0 - x0);\n    const double r2 = std::sqrt(x0);\n    const double t1 = 2.0 * M_PI * uniform_unit_dist();\n    const double t2 = 2.0 * M_PI * uniform_unit_dist();\n    const double c1 = std::cos(t1);\n    const double s1 = std::sin(t1);\n    const double c2 = std::cos(t2);\n    const double s2 = std::sin(t2);\n    const double x = s1 * r1;\n    const double y = c1 * r1;\n    const double z = s2 * r2;\n    const double w = c2 * r2;\n    return Eigen::Quaterniond(w, x, y, z);\n  }\n\n  // From Effective Sampling and Distance Metrics for 3D Rigid Body Path\n  // Planning, by James Kuffner, ICRA 2004.\n  static Eigen::Vector3d GenerateUniformRandomEulerAngles(\n      const std::function<double()>& uniform_unit_dist)\n  {\n    const double roll = 2.0 * M_PI * uniform_unit_dist() -  M_PI;\n    const double pitch_init\n        = std::acos(1.0 - (2.0 * uniform_unit_dist())) + M_PI_2;\n    const double pitch\n        = (uniform_unit_dist() < 0.5)\n          ? ((pitch_init < M_PI) ? pitch_init + M_PI : pitch_init - M_PI)\n          : pitch_init;\n    const double yaw = 2.0 * M_PI * uniform_unit_dist() -  M_PI;\n    return Eigen::Vector3d(roll, pitch, yaw);\n  }\n\n  template<typename Generator>\n  Eigen::Quaterniond GetQuaternion(Generator& prng)\n  {\n    std::function<double()> uniform_rand_fn\n        = [&] () { return uniform_unit_dist_(prng); };\n    return GenerateUniformRandomQuaternion(uniform_rand_fn);\n  }\n\n  template<typename Generator>\n  std::vector<double> GetRawQuaternion(Generator& prng)\n  {\n    const Eigen::Quaterniond quat = GetQuaternion(prng);\n    return std::vector<double>{quat.x(), quat.y(), quat.z(), quat.w()};\n  }\n\n  template<typename Generator>\n  Eigen::Vector3d GetEulerAngles(Generator& prng)\n  {\n    std::function<double()> uniform_rand_fn\n        = [&] () { return uniform_unit_dist_(prng); };\n    return GenerateUniformRandomEulerAngles(uniform_rand_fn);\n  }\n\n  template<typename Generator>\n  std::vector<double> GetRawEulerAngles(Generator& prng)\n  {\n    const Eigen::Vector3d angles = GetEulerAngles(prng);\n    return std::vector<double>{angles.x(), angles.y(), angles.z()};\n  }\n};\n}  // namespace random_rotation_generator\n}  // namespace common_robotics_utilities\n", "meta": {"hexsha": "c62597ab40a8392ebedcfd7a26eb5de0a5d0b47b", "size": 2901, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/common_robotics_utilities/random_rotation_generator.hpp", "max_stars_repo_name": "hidmic/common_robotics_utilities", "max_stars_repo_head_hexsha": "b3e10e0e0bfa9a968efdaa57e0a4422d9327bb9c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-10-15T19:04:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-23T01:35:16.000Z", "max_issues_repo_path": "include/common_robotics_utilities/random_rotation_generator.hpp", "max_issues_repo_name": "hidmic/common_robotics_utilities", "max_issues_repo_head_hexsha": "b3e10e0e0bfa9a968efdaa57e0a4422d9327bb9c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2018-10-18T19:14:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-21T15:08:21.000Z", "max_forks_repo_path": "include/common_robotics_utilities/random_rotation_generator.hpp", "max_forks_repo_name": "hidmic/common_robotics_utilities", "max_forks_repo_head_hexsha": "b3e10e0e0bfa9a968efdaa57e0a4422d9327bb9c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2018-10-17T21:12:01.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-18T03:53:47.000Z", "avg_line_length": 31.5326086957, "max_line_length": 73, "alphanum_fraction": 0.6845915202, "num_tokens": 773, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.929440403812707, "lm_q2_score": 0.7981867705385762, "lm_q1q2_score": 0.7418670343273348}}
{"text": "#include <catch2/catch.hpp>\n#include <replay/math.hpp>\n#include <replay/matrix2.hpp>\n#include <replay/minimal_sphere.hpp>\n#include <replay/vector_math.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <random>\n\nnamespace\n{\n\n// FIXME: this is somewhat generically useful - lift it to a visible namespace?\nreplay::vector3f polar_to_model(float latitude, float longitude)\n{\n    latitude = replay::math::convert_to_radians(latitude);\n    longitude = replay::math::convert_to_radians(longitude);\n\n    float cw = std::cos(latitude);\n    float sw = std::sin(latitude);\n    float ch = std::cos(longitude);\n    float sh = std::sin(longitude);\n\n    return {cw * ch, sw * ch, sh};\n}\n\ntemplate <class IteratorType>\nfloat distance_to_sphere(const IteratorType point_begin,\n                         const IteratorType point_end,\n                         const replay::vector3f& center,\n                         const float square_radius)\n{\n    float max_sqr_distance = 0.f;\n\n    for (IteratorType i = point_begin; i != point_end; ++i)\n    {\n        const float sqr_distance = (center - (*i)).squared();\n\n        max_sqr_distance = std::max(max_sqr_distance, sqr_distance);\n    }\n\n    float radius = std::sqrt(square_radius);\n    return std::max(0.f, std::sqrt(max_sqr_distance) - radius);\n}\n} // namespace\n\nTEST_CASE(\"matrix2_operations\")\n{\n    using namespace replay;\n    matrix2 Rotation = matrix2::make_rotation(boost::math::constants::pi<float>() * 0.25f); // 45deg rotation\n    matrix2 Inv = Rotation;\n    REQUIRE(Inv.invert());\n\n    using math::fuzzy_equals;\n    using math::fuzzy_zero;\n    matrix2 I = Rotation * Inv;\n    // This should be identity\n    REQUIRE(fuzzy_equals(I[0], 1.f));\n    REQUIRE(fuzzy_zero(I[1]));\n    REQUIRE(fuzzy_zero(I[2]));\n    REQUIRE(fuzzy_equals(I[3], 1.f));\n\n    I = Inv * Rotation;\n    // This should be identity\n    REQUIRE(fuzzy_equals(I[0], 1.f));\n    REQUIRE(fuzzy_zero(I[1]));\n    REQUIRE(fuzzy_zero(I[2]));\n    REQUIRE(fuzzy_equals(I[3], 1.f));\n}\n\n// This test verifies integer arithmetic with a vector3.\n// Hopefully, floating-point math will behave correct if this does.\nTEST_CASE(\"vector3_integer_operations\")\n{\n    using namespace replay;\n    typedef vector3<int> vec3;\n\n    const vec3 a(-1, -67, 32);\n    const vec3 b(7777, 0, -111);\n    const vec3 c(a - b);\n\n    REQUIRE(c - a == -b);\n\n    const vec3 all_one(1, 1, 1);\n\n    REQUIRE(all_one.sum() == 3);\n    REQUIRE(all_one.squared() == 3);\n\n    int checksum = dot(a, all_one);\n    REQUIRE(checksum == a.sum());\n\n    checksum = dot(b, all_one);\n    REQUIRE(checksum == b.sum());\n\n    REQUIRE(a.sum() - b.sum() == c.sum());\n\n    REQUIRE((a * 42).sum()== a.sum() * 42);\n\n    const vec3 all_two(2, 2, 2);\n    REQUIRE(all_one * 2== all_two);\n    REQUIRE(all_one + all_one== all_two);\n}\n\nTEST_CASE(\"quadratic_equation_solver\")\n{\n    using namespace replay;\n    using range_type = std::uniform_real_distribution<float>;\n    // Attempt to solve a few equations of the form (x-b)(x-a)=0 <=> x^2+(-a-b)*x+b*a=0\n\n    std::mt19937 rng;\n    range_type range(-100.f, 300.f);\n    auto die = [&] { return range(rng); };\n\n    for (std::size_t i = 0; i < 32; ++i)\n    {\n        float a = die();\n        float b = die();\n\n        if (replay::math::fuzzy_equals(a, b))\n            continue;\n\n        interval<> r;\n        // FIXME: use a relative epsilon\n        math::solve_quadratic_eq(1.f, -a - b, a * b, r, 0.001f);\n\n        if (a > b)\n            std::swap(a, b);\n\n        REQUIRE(r[0] == Approx(a).margin(0.01f));\n        REQUIRE(r[1] == Approx(b).margin(0.01f));\n    }\n}\n\nTEST_CASE(\"matrix4_determinant_simple\")\n{\n    using namespace replay;\n    matrix4 M(0.f, 0.f, 3.f, 0.f, 4.f, 0.f, 0.f, 0.f, 0.f, 2.f, 0.f, 0.f, 0.f, 0.f, 0.f, 1.f);\n\n    float d = M.determinant();\n\n    REQUIRE(d == Approx(24.f).margin(0.0001f));\n\n    matrix4 N(2.f, 1.f, 0.f, 0.f, 1.f, 2.f, 1.f, 0.f, 0.f, 1.f, 2.f, 1.f, 0.f, 0.f, 1.f, 2.f);\n\n    float e = N.determinant();\n\n    REQUIRE(e == Approx(5.f).margin(0.0001f));\n}\n\nTEST_CASE(\"circumcircle\")\n{\n    using namespace replay;\n\n    // Construct a rotational matrix\n    vector3f x = polar_to_model(177.f, -34.f);\n    vector3f y = normalized(math::construct_perpendicular(x));\n    matrix3 M(x, y, cross(x, y));\n\n    // Construct three points on a circle and rotate them\n    const float radius = 14.f;\n    float angle = math::convert_to_radians(34.f);\n    vector3f a = M * (vector3f(std::cos(angle), std::sin(angle), 0.f) * radius);\n    angle = math::convert_to_radians(134.f);\n    vector3f b = M * (vector3f(std::cos(angle), std::sin(angle), 0.f) * radius);\n    angle = math::convert_to_radians(270.f);\n    vector3f c = M * (vector3f(std::cos(angle), std::sin(angle), 0.f) * radius);\n\n    // Move the circle\n    const vector3f center(45.f, 32.f, -37.f);\n    a += center;\n    b += center;\n    c += center;\n\n    // Reconstruct it\n    equisphere<float, 3> s(1e-16f);\n    REQUIRE(s.push(a.ptr()));\n    REQUIRE(s.push(b.ptr()));\n    REQUIRE(s.push(c.ptr()));\n\n    vector3f equisphere_center(vector3f::cast(s.get_center()));\n    vector3f center_delta = center - equisphere_center;\n    REQUIRE(center_delta.squared() < 0.001f);\n    REQUIRE(std::sqrt(s.get_squared_radius()) == Approx(radius).margin(0.001f));\n}\n\n// Simple test case directly testing the minimal ball solver in 3D\nTEST_CASE(\"minimal_ball\")\n{\n    using namespace replay;\n    typedef vector3f vec3;\n    using range_type = std::uniform_real_distribution<float>;\n\n    // setup random number generators\n    std::mt19937 rng;\n    auto random_latitude = [&] { return range_type(-180.f, 180.f)(rng); };\n    auto random_longitude = [&] { return range_type(-90.f, 90.f)(rng); };\n    auto random_scale = [&] { return range_type(0.f, 1.0f)(rng); };\n\n    // setup a simple point set\n    std::list<vec3> points{ vec3(1.f, 0.f, 0.f), vec3(0.f, 1.f, 0.f), vec3(0.f, 0.f, 1.f), vec3(0.f, -1.f, 0.f) };\n\n    for (std::size_t i = 0; i < 32; ++i)\n    {\n        vector3f t = polar_to_model(random_latitude(), random_longitude());\n        float s = random_scale();\n        points.push_back(t * s);\n    }\n\n    // run the solver\n    replay::minimal_ball<float, replay::vector3f, 3> ball(points, 1e-15f);\n\n    // check correctness\n    REQUIRE(ball.square_radius() == Approx(1.f).margin(0.001f));\n    REQUIRE(ball.center().squared() < 0.001f);\n    REQUIRE(distance_to_sphere(points.begin(), points.end(), ball.center(), ball.square_radius()) < 0.001f);\n}\n\n// Slightly more sophisticated test for the minimal ball routines using\n// the wrapper from vector_math.hpp and an std::vector\nTEST_CASE(\"minimal_sphere\")\n{\n    using namespace replay;\n    using range_type = std::uniform_real_distribution<float>;\n\n    std::mt19937 rng;\n\n    auto random_coord = [&] { return range_type(-100.f, 100.f)(rng); };\n    auto random_radius = [&] { return range_type(1.f, 3.f)(rng); };\n\n    auto random_latitude = [&] { return range_type(-180.f, 180.f)(rng); };\n    auto random_longitude = [&] { return range_type(-90.f, 90.f)(rng); };\n    auto random_scale = [&] { return range_type(0.0f, 1.0f)(rng); };\n\n    std::vector<vector3f> p(64);\n\n    for (std::size_t i = 0; i < 16; ++i)\n    {\n        const vector3f center(random_coord(), random_coord(), random_coord());\n        const float radius = random_radius();\n\n        std::size_t boundary_n = 2 + rng() % 3;\n\n        for (std::size_t j = 0; j < boundary_n; ++j)\n            p[j] = center + polar_to_model(random_latitude(), random_longitude()) * radius;\n\n        for (std::size_t j = boundary_n; j < 64; ++j)\n            p[j] = center + polar_to_model(random_latitude(), random_longitude()) * (random_scale() * radius);\n\n        std::shuffle(p.begin(), p.end(), rng);\n\n        auto const [result_center, result_square_radius] = math::minimal_sphere(p);\n\n        float square_radius = radius * radius;\n\n        // The generated boundary doesn't necessarily define the minimal ball, but it's an upper bound\n        REQUIRE(result_square_radius <= Approx(square_radius).margin(0.0001));\n        REQUIRE(distance_to_sphere(p.begin(), p.end(), result_center, result_square_radius) < 0.001f);\n    }\n}", "meta": {"hexsha": "560df1042a482b6fc705bf40aaae20c8924c6231", "size": 8066, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/math.t.cpp", "max_stars_repo_name": "ltjax/replay", "max_stars_repo_head_hexsha": "33680beae225c9c388f33e3f7ffd7e8bae4643e9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-09-15T19:52:50.000Z", "max_stars_repo_stars_event_max_datetime": "2015-09-15T19:52:50.000Z", "max_issues_repo_path": "test/math.t.cpp", "max_issues_repo_name": "ltjax/replay", "max_issues_repo_head_hexsha": "33680beae225c9c388f33e3f7ffd7e8bae4643e9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-12-03T21:53:09.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-23T02:11:50.000Z", "max_forks_repo_path": "test/math.t.cpp", "max_forks_repo_name": "ltjax/replay", "max_forks_repo_head_hexsha": "33680beae225c9c388f33e3f7ffd7e8bae4643e9", "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.2635658915, "max_line_length": 114, "alphanum_fraction": 0.6219935532, "num_tokens": 2327, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122288794594, "lm_q2_score": 0.8175744784160989, "lm_q1q2_score": 0.7417953222866721}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\nusing namespace std;\nusing namespace Eigen;\nint main()\n{\n   Matrix3f A;\n   A << 1, 2, 1,\n        2, 1, 0,\n        -1, 1, 2;\n   // \u6570\u5b66\u4e0a inverse \u5f88\u597d, \u4f46\u6570\u503c\u7ebf\u6027\u7cfb\u7edf\u4e2d\u7528\u5206\u89e3\u66f4\u5feb. (\u5c0f\u77e9\u9635\u7684\u8bdd, \u5206\u89e3\u4e5f\u6ca1\u6709\u516c\u5f0f\u5feb)\n   cout << \"Here is the matrix A:\\n\" << A << endl;\n   cout << \"The determinant of A is \" << A.determinant() << endl;\n   cout << \"The inverse of A is:\\n\" << A.inverse() << endl;\n}\n", "meta": {"hexsha": "81ca107c79ec93b03709930a9261214d8688effd", "size": 401, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "snippets/eigen-inverse.cpp", "max_stars_repo_name": "district10/snippet-manager", "max_stars_repo_head_hexsha": "bebe45a601368947168e3ee6e6ab8c1fc2ee2055", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2018-08-04T09:28:19.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-19T17:46:34.000Z", "max_issues_repo_path": "snippets/eigen-inverse.cpp", "max_issues_repo_name": "district10/snippet-manager", "max_issues_repo_head_hexsha": "bebe45a601368947168e3ee6e6ab8c1fc2ee2055", "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": "snippets/eigen-inverse.cpp", "max_forks_repo_name": "district10/snippet-manager", "max_forks_repo_head_hexsha": "bebe45a601368947168e3ee6e6ab8c1fc2ee2055", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-07-31T04:14:55.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-02T01:22:39.000Z", "avg_line_length": 25.0625, "max_line_length": 65, "alphanum_fraction": 0.5710723192, "num_tokens": 160, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122188543453, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7417953100574731}}
{"text": "// Copyright Evan Miller 2020\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 <pch_light.hpp>\n#include <boost/math/concepts/real_concept.hpp>\n\n#define BOOST_TEST_MAIN\n#include <boost/test/unit_test.hpp> // for test_main\n#include <boost/test/tools/floating_point_comparison.hpp> // for BOOST_CHECK_CLOSE\n#include <boost/math/distributions/kolmogorov_smirnov.hpp>\n#include <boost/math/quadrature/exp_sinh.hpp>\n\ntemplate <typename RealType> // Any floating-point type RealType.\nvoid test_spots(RealType)\n{\n    using namespace boost::math;\n    // Test quantiles, CDFs, and complements\n    RealType eps = tools::epsilon<RealType>();\n    RealType tol = tools::epsilon<RealType>() * 25;\n    for (int n=10; n<100; n += 10) {\n        kolmogorov_smirnov_distribution<RealType> dist(n);\n        for (int i=0; i<1000; i++) {\n            RealType p = 1.0 * (i+1) / 1001;\n            RealType crit1 = quantile(dist, 1 - p);\n            RealType crit2 = quantile(complement(dist, p));\n            RealType p1 = cdf(dist, crit1);\n            BOOST_CHECK_CLOSE_FRACTION(crit1, crit2, tol);\n            BOOST_CHECK_CLOSE_FRACTION(1 - p, p1, tol);\n        }\n\n        for (int i=0; i<1000; i++) {\n            RealType x = 1.0 * (i+1) / 1001;\n            RealType p = cdf(dist, x);\n            RealType p1 = cdf(complement(dist, x));\n            RealType x1;\n            if (p < 0.5)\n                x1 = quantile(dist, p);\n            else\n                x1 = quantile(complement(dist, p1));\n            if (p > tol && p1 > tol) // skip the extreme tails\n                BOOST_CHECK_CLOSE_FRACTION(x, x1, tol);\n        }\n    }\n\n    kolmogorov_smirnov_distribution<RealType> dist(100);\n\n    // Basics\n    BOOST_CHECK_THROW(pdf(dist, RealType(-1.0)), std::domain_error);\n    BOOST_CHECK_THROW(cdf(dist, RealType(-1.0)), std::domain_error);\n    BOOST_CHECK_THROW(quantile(dist, RealType(-1.0)), std::domain_error);\n    BOOST_CHECK_THROW(quantile(dist, RealType(2.0)), std::domain_error);\n\n    // Confirm mode is at least a local minimum\n    RealType mode = boost::math::mode(dist);\n\n    using std::sqrt;\n    BOOST_TEST_CHECK(pdf(dist, mode) >= pdf(dist, RealType(mode - sqrt(eps))));\n    BOOST_TEST_CHECK(pdf(dist, mode) >= pdf(dist, RealType(mode + sqrt(eps))));\n\n    // Test the moments - each one integrates the entire distribution\n    quadrature::exp_sinh<RealType> integrator;\n\n    auto f_one = [&, dist](RealType t) { return pdf(dist, t); };\n    BOOST_CHECK_CLOSE_FRACTION(integrator.integrate(f_one, eps), RealType(1), tol);\n\n    RealType mean = boost::math::mean(dist);\n    auto f_mean = [&, dist](RealType t) { return pdf(dist, t) * t; };\n    BOOST_CHECK_CLOSE_FRACTION(integrator.integrate(f_mean, eps), mean, tol);\n\n    RealType var = variance(dist);\n    auto f_var = [&, dist, mean](RealType t) { return pdf(dist, t) * (t - mean) * (t - mean); };\n    BOOST_CHECK_CLOSE_FRACTION(integrator.integrate(f_var, eps), var, tol);\n\n    RealType skew = skewness(dist);\n    auto f_skew = [&, dist, mean, var](RealType t) { return pdf(dist, t)\n        * (t - mean) * (t - mean) * (t - mean) / var / sqrt(var); };\n    BOOST_CHECK_CLOSE_FRACTION(integrator.integrate(f_skew, eps), skew, 10*tol);\n\n    RealType kurt = kurtosis(dist);\n    auto f_kurt= [&, dist, mean, var](RealType t) { return pdf(dist, t)\n        * (t - mean) * (t - mean) * (t - mean) * (t - mean) / var / var; };\n    BOOST_CHECK_CLOSE_FRACTION(integrator.integrate(f_kurt, eps), kurt, 5*tol);\n\n    BOOST_CHECK_CLOSE_FRACTION(kurt, kurtosis_excess(dist) + 3, eps);\n}\n\nBOOST_AUTO_TEST_CASE( test_main )\n{\n  BOOST_MATH_CONTROL_FP;\n\n  // (Parameter value, arbitrarily zero, only communicates the floating point type).\n     test_spots(0.0F); // Test float.\n test_spots(0.0); // Test double.\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n  test_spots(0.0L); // Test long double.\n#if !defined(BOOST_MATH_NO_REAL_CONCEPT_TESTS)\n  test_spots(boost::math::concepts::real_concept(0.)); // Test real concept.\n#endif\n#endif\n}\n", "meta": {"hexsha": "58dad8cd5db3dacf8981b5e819d2189c68722ea6", "size": 4116, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_kolmogorov_smirnov.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": "test/test_kolmogorov_smirnov.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": "Libs/boost_1_76_0/libs/math/test/test_kolmogorov_smirnov.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "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": 39.5769230769, "max_line_length": 96, "alphanum_fraction": 0.6486880466, "num_tokens": 1181, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069987088003, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7417857455938603}}
{"text": "#pragma once\n#include \"load_vector.hpp\"\n#include <Eigen/Core>\n\n//----------------AssembleVectorBegin----------------\n//! Assemble the load vector into the full right hand side\n//! for the linear system\n//!\n//! @param[out] F will at the end contain the RHS values for each vertex.\n//! @param[in] vertices a list of triangle vertices\n//! @param[in] dofs a list of the dofs' indices in each triangle\n//! @param[in] f the RHS function f.\nvoid assembleLoadVector(Eigen::VectorXd &      F,\n                        const Eigen::MatrixXd &vertices,\n                        const Eigen::MatrixXi &dofs,\n                        const int &            N,\n                        const std::function<double(double, double)> &f) {\n\tconst int numberOfElements = dofs.rows();\n\n\tF.resize(N);\n\tF.setZero();\n\t// (write your solution here)\n\tfor (int i = 0; i < numberOfElements; ++i) {\n\t\tconst auto &indexSet = dofs.row(i);\n\n\t\tconst auto &a = vertices.row(indexSet(0));\n\t\tconst auto &b = vertices.row(indexSet(1));\n\t\tconst auto &c = vertices.row(indexSet(2));\n\n\t\tEigen::VectorXd elementVector;\n\t\tcomputeLoadVector(elementVector, a, b, c, f);\n\n\t\tfor (int j = 0; j < 6; ++j) {\n\t\t\tF(indexSet(j)) += elementVector(j);\n\t\t}\n\t}\n}\n//----------------AssembleVectorEnd----------------\n", "meta": {"hexsha": "9fd91529732edeb6599261d5717f31750019fad9", "size": 1256, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "series3/2d-poissonqFEM/load_vector_assembly.hpp", "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": "series3/2d-poissonqFEM/load_vector_assembly.hpp", "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": "series3/2d-poissonqFEM/load_vector_assembly.hpp", "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": 32.2051282051, "max_line_length": 73, "alphanum_fraction": 0.5883757962, "num_tokens": 311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789468908171, "lm_q2_score": 0.8289388125473628, "lm_q1q2_score": 0.7417257198366247}}
{"text": "/*\nCopyright (c) 2019, NVIDIA CORPORATION. All rights reserved.\n\nNVIDIA CORPORATION and its licensors retain all intellectual property\nand proprietary rights in and to this software, related documentation\nand any modifications thereto. Any use, reproduction, disclosure or\ndistribution of this software and related documentation without an express\nlicense agreement from NVIDIA CORPORATION is strictly prohibited.\n*/\n\n#include \"packages/pnp/gems/pnp.hpp\"\n\n#include <Eigen/Dense>\n\n#include <cmath>\n#include <deque>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\n#include \"packages/pnp/gems/epnp/epnp_ransac.hpp\"\n\nnamespace isaac {\nnamespace pnp {\n\n// EPnP algorithm: compute the 3D (6-DoF) pose of a calibrated pinhole camera from >=6 2D-3D point\n// correspondences in either 3D or in planar arrangement.\n// Assumes corrected lens distortions.\nStatus ComputeCameraPoseEpnp(const Matrix3Xd& points3, const Matrix2Xd& points2, double focal_u,\n                             double focal_v, double principal_u, double principal_v, Pose3d* pose) {\n  if (pose == nullptr) {\n    return Status::kErrorNullPointer;\n  }\n\n  epnp::Result result;\n  Status status = epnp::ComputeCameraPose(focal_u, focal_v, principal_u, principal_v, points3,\n                                          points2, &result);\n  if (status == Status::kSuccess) {\n    Vector3d angle_axis = AngleAxisFromMatrix(result.rotation);\n    pose->rotation = SO3d::FromAngleAxis(angle_axis.norm(), angle_axis);\n    pose->translation = result.translation;\n  }\n\n  return status;\n}\n\n// RANSAC formula: Calculate the number of RANSAC rounds necessary to sample at least a single\n// uncontaminated sample set with a certain success rate given the expected ratio of outliers.\nunsigned int EvaluateRansacFormula(float success_rate, float outlier_ratio,\n                                   unsigned int sample_size) {\n  constexpr float max_success_rate = 0.9999;\n  constexpr float max_outlier_ratio = 0.9;\n\n  // theor.limits: sample_size > 0, 0 < outlierRate < 1, 0 <= success_rate < 1\n  if (success_rate < 0) {\n    success_rate = 0;\n  } else if (success_rate > max_success_rate) {\n    success_rate = max_success_rate;\n  }\n\n  if (outlier_ratio <= 0) {\n    return 1;\n  } else if (outlier_ratio > max_outlier_ratio) {\n    outlier_ratio = max_outlier_ratio;\n  }\n\n  if (sample_size < 1) {\n    sample_size = 1;\n  }\n\n  // RANSAC formula\n  double good_sample_prob = pow(1 - outlier_ratio, sample_size);\n  return ceil(log(1 - success_rate) / log(1.0 - good_sample_prob));\n}\n\n// RANSAC with 6-point EPnP for robust camera pose estimation.\n// Returns top K different poses in an iterable priority queue.\nstd::vector<PoseHypothesis> ComputeCameraPoseEpnpRansac(const Matrix3Xd& points3,\n                                                        const Matrix2Xd& points2, double focal_u,\n                                                        double focal_v, double principal_u,\n                                                        double principal_v, unsigned num_rounds,\n                                                        double ransac_threshold,\n                                                        unsigned max_top_poses, unsigned seed) {\n  // RANSAC sampler for 6-point pose.\n  pnp::DefaultRansacSampler<6> sampler(points3.cols(), seed);\n\n  // RANSAC adaptor for the EPnP algorithm: pose-, EPnP- and scoring-specific part of RANSAC.\n  epnp::EpnpRansacAdaptor adaptor(points3, points2, focal_u, focal_v, principal_u, principal_v,\n                                  ransac_threshold);\n\n  // Invoke generic RANSAC-TopK algorithm using this core algorithm.\n  auto top_poses = pnp::Ransac(adaptor, num_rounds, max_top_poses, &sampler);\n\n  // Copy the list of top pose hypotheses returned by the algorithm.\n  // This copy allows public and private interfaces to differ.\n  std::vector<PoseHypothesis> result;\n  for (const pnp::RansacHypothesis<Pose3d, 6>& src : top_poses) {\n    PoseHypothesis dst;\n    dst.pose = src.model;\n    dst.score = src.score;\n    dst.inliers = src.inliers;\n    result.push_back(dst);\n  }\n  return result;\n}\n\n}  // namespace pnp\n}  // namespace isaac\n", "meta": {"hexsha": "1b9cc832419fdf12dee691c242c7ea777c532bae", "size": 4123, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sdk/packages/pnp/gems/generic/pnp.cpp", "max_stars_repo_name": "ddr95070/RMIsaac", "max_stars_repo_head_hexsha": "ee3918f685f0a88563248ddea11d089581077973", "max_stars_repo_licenses": ["FSFAP"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sdk/packages/pnp/gems/generic/pnp.cpp", "max_issues_repo_name": "ddr95070/RMIsaac", "max_issues_repo_head_hexsha": "ee3918f685f0a88563248ddea11d089581077973", "max_issues_repo_licenses": ["FSFAP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdk/packages/pnp/gems/generic/pnp.cpp", "max_forks_repo_name": "ddr95070/RMIsaac", "max_forks_repo_head_hexsha": "ee3918f685f0a88563248ddea11d089581077973", "max_forks_repo_licenses": ["FSFAP"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-28T16:37:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-28T16:37:51.000Z", "avg_line_length": 37.8256880734, "max_line_length": 100, "alphanum_fraction": 0.6732961436, "num_tokens": 983, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.8198933381139646, "lm_q1q2_score": 0.7417169512658317}}
{"text": "#include <armadillo>\n#include <iostream>\n#include <catch.hpp>\n#include \"util.hpp\"\n\n\nTEST_CASE( \"Random unitary matrix logarithms\", \"[Util]\"){\n  for (arma::uword N = 2; N < 100; N*=1.5){\n    for (int i = 0; i < 10; i++){\n      arma::mat A(N,N, arma::fill::randu);\n      util::unitarize(A);\n\n      CHECK(arma::norm(util::logmat_unitary(A) -\n                       arma::real(arma::logmat(A)))\n            == Approx(0.0).margin(1e-9));\n    }\n  }\n}\n", "meta": {"hexsha": "a9ff69c6dc6c40b26bd321745cb506265026f8e6", "size": 445, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/util.cpp", "max_stars_repo_name": "INAQS/inaqs", "max_stars_repo_head_hexsha": "f85b39aef0cb67cda4b3cfa61017268fe410c362", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2022-03-04T18:56:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:49:22.000Z", "max_issues_repo_path": "src/tests/util.cpp", "max_issues_repo_name": "INAQS/inaqs", "max_issues_repo_head_hexsha": "f85b39aef0cb67cda4b3cfa61017268fe410c362", "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/tests/util.cpp", "max_forks_repo_name": "INAQS/inaqs", "max_forks_repo_head_hexsha": "f85b39aef0cb67cda4b3cfa61017268fe410c362", "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.4210526316, "max_line_length": 57, "alphanum_fraction": 0.5393258427, "num_tokens": 143, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9263037302939515, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.7416839861552724}}
{"text": "/**\n * @file matode_main.cc\n * @brief NPDE homework MatODE code\n * @copyright Developed at ETH Zurich\n */\n\n#include <Eigen/Dense>\n#include <iomanip>\n#include <iostream>\n\n#include \"matode.h\"\n\nint main(int /*argc*/, char** /*argv*/) {\n  /* SAM_LISTING_BEGIN_6 */\n  double h = 0.01;  // stepsize\n  Eigen::Vector3d norms;\n  // Build M\n  Eigen::Matrix3d M;\n  M << 8, 1, 6, 3, 5, 7, 9, 9, 2;\n  // Build A\n  Eigen::Matrix3d A;\n  A << 0, 1, 1, -1, 0, 1, -1, -1, 0;\n  Eigen::MatrixXd I = Eigen::Matrix3d::Identity();\n#if SOLUTION\n  // Build Q\n  Eigen::HouseholderQR<Eigen::Matrix3d> qr(3, 3);\n  qr.compute(M);\n  Eigen::MatrixXd Q = qr.householderQ();\n  // Set initial conditions\n  Eigen::Matrix3d Meeul = Q, Mieul = Q, Mimp = Q;\n\n  std::vector<int> sep = {5, 15};\n  std::cout << std::setw(sep[0]) << \"step\" << std::setw(sep[1]) << \"exp. Eul\"\n            << std::setw(sep[1]) << \"imp. Eul\" << std::setw(sep[1]) << \"Mid-Pt\"\n            << std::endl;\n  // Norm of Y'Y-I for initial value\n  std::cout << std::setw(sep[0]) << \"0\" << std::setw(sep[1])\n            << (Meeul.transpose() * Meeul - I).norm() << std::setw(sep[1])\n            << (Mieul.transpose() * Mieul - I).norm() << std::setw(sep[1])\n            << (Mimp.transpose() * Mimp - I).norm() << std::endl;\n  // Norm of Y'Y-I for 20 steps\n  for (unsigned int j = 0; j < 20; ++j) {\n    Meeul = MatODE::eeulstep(A, Meeul, h);\n    Mieul = MatODE::ieulstep(A, Mieul, h);\n    Mimp = MatODE::impstep(A, Mimp, h);\n\n    norms[0] = (Meeul.transpose() * Meeul - I).norm();\n    norms[1] = (Mieul.transpose() * Mieul - I).norm();\n    norms[2] = (Mimp.transpose() * Mimp - I).norm();\n\n    std::cout << std::setw(sep[0]) << j + 1 << std::setw(sep[1]) << norms[0]\n              << std::setw(sep[1]) << norms[1] << std::setw(sep[1]) << norms[2]\n              << std::endl;\n  }\n#else\n  //====================\n  // Your code goes here\n  //====================\n#endif\n  /* SAM_LISTING_END_6 */\n  return 0;\n}\n", "meta": {"hexsha": "c86f4a3b8132dbc983ad4160c21f0bafbc1ecf50", "size": 1935, "ext": "cc", "lang": "C++", "max_stars_repo_path": "developers/MatODE/mastersolution/matode_main.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/MatODE/mastersolution/matode_main.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/MatODE/mastersolution/matode_main.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": 30.7142857143, "max_line_length": 79, "alphanum_fraction": 0.5286821705, "num_tokens": 709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.8221891283434877, "lm_q1q2_score": 0.7415493748707912}}
{"text": "// main.cpp\n\n//   Abbreviations:\n// 1) SLE - system of linear equations\n// 2) SOR - successive over-relaxation\n\n//   A main file with code. Here I tesing SLE solvers, count \n// determinants of some matrices, find inverse matrices, determine whether \n// Gaussian elimination is stable and count the speed of convergence rate of\n// iterations\n\n\n#include <iostream>              // cin, cout\n#include <iomanip>               // setprecision\n#include <fstream>               // ofstream\n#include <boost/filesystem.hpp>  // path, create_directory\n\n#include \"matrix.h\"\n#include \"gaussian_method.h\"\n#include \"tester.h\"\n#include \"tests.h\"\n#include \"matrix_functions.h\"\n#include \"SLE_solvers.h\"\n\nusing namespace std;\n\nusing namespace GaussianJordanElimination;\nusing namespace MatrixFunctions;\nusing namespace SLESolvers;\nusing SLESolvers::TesterT;\nusing SLESolvers::TesterA;\n\nusing element_type = double;\nusing matrix_type = Matrix<element_type>;\nusing Me = Matrix<element_type>;\n\n//   Some constants\nenum\n{\n    //   For random generator\n    SEED = 0,\n};\n\ntemplate <class T>\nostream &operator << (ostream &out, const pair<T, T> &a)\n{\n    out << a.first << endl;\n    out << a.second;\n    return out;\n}\n\n//   Create folder (delete it if it exists)\nvoid new_folder(string path)\n{\n    boost::filesystem::path dir(path);\n    boost::filesystem::remove_all(dir);\n    boost::filesystem::create_directory(dir);\n}\n\nstring get_fout_for_test(const string &pref, const string &name, \n        size_t number, size_t max_number, string type = \".txt\")\n{\n    int test_number_digits = to_string(max_number).size();\n    int make_zeros = pow(10, test_number_digits);\n\n    return pref + name + to_string(make_zeros + number).substr(1) + type;\n}\n\n//   Write tests from Tester object to given folder\ntemplate <class T, class A>\nvoid write_tests_to_folder(const Tester<T, A> &tester, \n        string path_to_tests = \"tests/\")\n{\n    //   Create folder for tests\n    new_folder(path_to_tests);\n\n    //   I use these variables to calculate number of digits for \n    // each test number\n    int test_number_digits = to_string(tester.get_num_tests()).size();\n    int make_zeros = pow(10, test_number_digits);\n\n    //   Writing tests\n    for (int i = 0; i < tester.get_num_tests(); ++i) {\n        ofstream fout(path_to_tests + \"/test\" + \n                to_string(make_zeros + i + 1).substr(1) + \".txt\");\n        fout << tester.next_test() << endl;\n        fout.close();\n    }\n}\n\n\nint main()\n{\n    write_tests_to_folder<TesterT<element_type>, TesterA<element_type>>(\n            Tests::create_tester_with_tests<element_type>());\n\n    //   Testing SLEGU\n    cout << \"Testing SLEGU\\n\";\n    test_SLE_solver<element_type>(SLEGU, \"answer_SLEGU/\");\n    cout << endl;\n\n    //   Testing SLEGM\n    cout << \"Testing SLEGM\\n\";\n    test_SLE_solver<element_type>(SLEGM, \"answer_SLEGM/\");\n    cout << endl;\n\n    //   Testing SLE_SOR\n    cout << \"Testing SLE_SOR\\n\";\n    test_SLE_solver<element_type>(SLE_SOR_standard, \"answer_SLE_SOR/\");\n    cout << endl;\n\n    //   Finding determinants\n    cout << \"Finding determinants\" << endl;\n\n    const string determinants = \"determinants/\";\n    new_folder(determinants);\n\n    // Determinants are stored here\n    vector<element_type> dets;\n\n    auto tester = Tests::create_tester_with_tests<element_type>();\n    for (int i = 0; i < tester.get_num_tests(); ++i) {\n        auto det = determinant(tester.next_test().first);\n        dets.push_back(det);\n\n        // Print found determinant\n        ofstream fout(get_fout_for_test(determinants, \"det\", i + 1,\n                tester.get_num_tests()));\n        fout << det << endl;\n        fout.close();\n    }\n\n    //   Finding inverse matrices\n    cout << \"Finding inverse matrices\" << endl;\n\n    const string inverse_matrices = \"inverse_matrices/\";\n    new_folder(inverse_matrices);\n\n    tester = Tests::create_tester_with_tests<element_type>();\n    for (int i = 0; i < tester.get_num_tests(); ++i) {\n        if (check_is_zero(dets[i])) {\n            tester.next_test();\n            continue;\n        }\n\n        // Print found inverse matrix\n        ofstream fout(get_fout_for_test(inverse_matrices, \"inv\", i + 1,\n                tester.get_num_tests()));\n        fout << inverse_matrix(tester.next_test().first) << endl;\n        fout.close();\n    }\n\n    //   Determine whether Gaussian elimination is stable\n    cout << \"Determining Gaussian elimination stability\" << endl;\n\n    const string stability = \"gauss_stability/\";\n    new_folder(stability);\n\n    element_type max_deviation = 0;\n\n    tester = Tests::create_tester_with_tests<element_type>();\n    for (int i = 0; i < tester.get_num_tests(); ++i) {\n        //   Creating generator of random numbers\n        std::mt19937 gen(SEED);\n        const element_type eps1 = 1e-3;\n        std::uniform_real_distribution<> urd(-eps1, eps1);\n\n        auto test = tester.next_test();\n        auto A = test.first;\n        auto f = test.second;\n\n        //   Solving SLE Ax = f\n        Me sol1;\n        try {\n            sol1 = SLEGM(A, f);\n        } catch (domain_error &e) {\n            cerr << e.what() << endl;\n            continue;\n        }\n\n        //   Solving SLE Bx = g, where B and g are slightly modified matrices \n        // A and f\n        auto B = test.first;\n        for (int row = 0; row < A.get_rows(); ++row) {\n            for (int col = 0; col < A.get_cols(); ++col) {\n                B[row][col] += urd(gen);\n            }\n        }\n\n        auto g = test.second;\n        for (int row = 0; row < g.get_rows(); ++row) {\n            g[row][0] += urd(gen);\n        }\n\n        Me sol2;\n        try {\n            sol2 = SLEGM(B, g);\n        } catch (domain_error &e) {\n            cerr << e.what() << endl;\n            continue;\n        }\n\n        //   Counting standard deviation\n        element_type dif = 0;\n        for (int row = 0; row < sol1.get_rows(); ++row) {\n            dif += pow(sol1[row][0] - sol2[row][0], 2);\n        }\n        dif = sqrt(dif / sol1.get_rows());\n\n        max_deviation = max(max_deviation, dif);\n\n        //   Print it out\n        ofstream fout(get_fout_for_test(stability, \"stab\", i + 1,\n                tester.get_num_tests()));\n        fout << dif << endl;\n        fout.close();\n    }\n    cout << \"\\tMaximum standard deviation: \" << max_deviation << endl;\n    \n    \n    //   Counting speed of convergence rate of iterations\n    cout << \"Counting speed of convergence rate of iterations\" << endl;\n\n    const string iter_cov = \"iter_convergance/\";\n    new_folder(iter_cov);\n\n    tester = Tests::create_tester_with_tests<element_type>();\n    for (int i = 0; i < tester.get_num_tests(); ++i) {\n        auto test = tester.next_test();\n        auto A = test.first;\n        auto f = test.second;\n\n        const double eps2 = 1e-3;\n\n        int min_iters = -1;\n        double wmin = -1;\n\n        //   Looking for minimum number of iterations for every w with \n        // step eps2\n        for (double w = eps2; w <= 2 - eps2; w += eps2) {\n            //   Run SOR solver with w and count number of iterations\n            int iters = -1;\n            try {\n                SLE_SOR(A, f, w, &iters);\n            } catch (domain_error &e) {\n                cerr << e.what() << endl;\n                continue;\n            }\n\n            if (iters == -1) {\n                continue;\n            }\n\n            //   Find minimum number of iterations\n            if (min_iters == -1 || min_iters > iters) {\n                min_iters = iters;\n                wmin = w;\n            }\n        }\n\n        // Print minimum number of iterations and coresponding w\n        ofstream fout(get_fout_for_test(iter_cov, \"cov\", i + 1,\n                tester.get_num_tests()));\n        fout << min_iters << \" (\" << wmin << \")\" << endl;\n        fout.close();\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "9b7308366c4666a7282e3d37e4f95c8f42098bdb", "size": 7776, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "C++/big_example01/main.cpp", "max_stars_repo_name": "sasasagagaga/Code-examples", "max_stars_repo_head_hexsha": "084db5bca241b164a670e303f73048fe4e6dad79", "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": "C++/big_example01/main.cpp", "max_issues_repo_name": "sasasagagaga/Code-examples", "max_issues_repo_head_hexsha": "084db5bca241b164a670e303f73048fe4e6dad79", "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": "C++/big_example01/main.cpp", "max_forks_repo_name": "sasasagagaga/Code-examples", "max_forks_repo_head_hexsha": "084db5bca241b164a670e303f73048fe4e6dad79", "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.8, "max_line_length": 78, "alphanum_fraction": 0.5834619342, "num_tokens": 1943, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970873650403, "lm_q2_score": 0.8418256532040708, "lm_q1q2_score": 0.741477583411318}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  MatrixXd A = MatrixXd::Random(6,6);\ncout << \"Here is a random 6x6 matrix, A:\" << endl << A << endl << endl;\n\nRealSchur<MatrixXd> schur(A);\ncout << \"The orthogonal matrix U is:\" << endl << schur.matrixU() << endl;\ncout << \"The quasi-triangular matrix T is:\" << endl << schur.matrixT() << endl << endl;\n\nMatrixXd U = schur.matrixU();\nMatrixXd T = schur.matrixT();\ncout << \"U * T * U^T = \" << endl << U * T * U.transpose() << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "f3a39b4915252be16c4b280c681c1e61a01cd27a", "size": 580, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_RealSchur_RealSchur_MatrixType.cpp", "max_stars_repo_name": "TANHAIYU/Self-calibration-using-Homography-Constraints", "max_stars_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-03-17T16:34:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-17T18:30:13.000Z", "max_issues_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_RealSchur_RealSchur_MatrixType.cpp", "max_issues_repo_name": "TANHAIYU/planecalib", "max_issues_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "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": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_RealSchur_RealSchur_MatrixType.cpp", "max_forks_repo_name": "TANHAIYU/planecalib", "max_forks_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "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.2173913043, "max_line_length": 87, "alphanum_fraction": 0.624137931, "num_tokens": 172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391621868805, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.7413608637309982}}
{"text": "#include <Eigen/LU>\n#include <cmath>\n#include <mathtoolbox/rbf-interpolation.hpp>\n\nusing Eigen::Map;\nusing Eigen::MatrixXd;\nusing Eigen::PartialPivLU;\nusing Eigen::VectorXd;\nusing std::vector;\n\nmathtoolbox::RbfInterpolator::RbfInterpolator(const std::function<double(const double)>& rbf_kernel)\n    : m_rbf_kernel(rbf_kernel)\n{\n}\n\nvoid mathtoolbox::RbfInterpolator::SetData(const Eigen::MatrixXd& X, const Eigen::VectorXd& y)\n{\n    assert(y.rows() == X.cols());\n    this->m_X = X;\n    this->m_y = y;\n}\n\nvoid mathtoolbox::RbfInterpolator::CalcWeights(const bool use_regularization, const double lambda)\n{\n    const int dim = m_y.rows();\n\n    MatrixXd Phi = MatrixXd::Zero(dim, dim);\n    for (int i = 0; i < dim; ++i)\n    {\n        for (int j = i; j < dim; ++j)\n        {\n            const double value = CalcRbfValue(m_X.col(i), m_X.col(j));\n\n            Phi(i, j) = value;\n            Phi(j, i) = value;\n        }\n    }\n\n    const MatrixXd A = use_regularization ? Phi.transpose() * Phi + lambda * MatrixXd::Identity(dim, dim) : Phi;\n    const VectorXd b = use_regularization ? Phi.transpose() * m_y : m_y;\n\n    m_w = PartialPivLU<MatrixXd>(A).solve(b);\n}\n\ndouble mathtoolbox::RbfInterpolator::CalcValue(const VectorXd& x) const\n{\n    const int dim = m_w.rows();\n\n    double result = 0.0;\n    for (int i = 0; i < dim; ++i)\n    {\n        result += m_w(i) * CalcRbfValue(x, m_X.col(i));\n    }\n\n    return result;\n}\n\ndouble mathtoolbox::RbfInterpolator::CalcRbfValue(const VectorXd& xi, const VectorXd& xj) const\n{\n    assert(xi.rows() == xj.rows());\n\n    return m_rbf_kernel((xj - xi).norm());\n}\n", "meta": {"hexsha": "e97e13dca69dbb30cffdafb74d228650601a77ad", "size": 1594, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/rbf-interpolation.cpp", "max_stars_repo_name": "amazing89/mathtoolbox", "max_stars_repo_head_hexsha": "8904bb06ced2ac501594f9574ef1ba3454b8e38e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-02-01T03:39:24.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-01T03:39:24.000Z", "max_issues_repo_path": "src/rbf-interpolation.cpp", "max_issues_repo_name": "amazing89/mathtoolbox", "max_issues_repo_head_hexsha": "8904bb06ced2ac501594f9574ef1ba3454b8e38e", "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/rbf-interpolation.cpp", "max_forks_repo_name": "amazing89/mathtoolbox", "max_forks_repo_head_hexsha": "8904bb06ced2ac501594f9574ef1ba3454b8e38e", "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.90625, "max_line_length": 112, "alphanum_fraction": 0.6329987453, "num_tokens": 465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391643039738, "lm_q2_score": 0.8031737892899222, "lm_q1q2_score": 0.7413608632570258}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n \nusing Eigen::MatrixXd;\nusing namespace Eigen;\nusing namespace std;\n \n\n \nint test()\n{\n  MatrixXd m(2,2);\n  m(0,0) = 3;\n  m(1,0) = 2.5;\n  m(0,1) = -1;\n  m(1,1) = m(1,0) + m(0,1);\n  cout << m << endl;\n}\n\nint main()\n{\n  MatrixXd m = MatrixXd::Random(3,3);\n  m = (m + MatrixXd::Constant(3,3,1.2)) * 50;\n  cout << \"m =\" << endl << m << endl;\n  VectorXd v(3);\n  v << 1, 2, 3;\n  cout << \"m * v =\" << endl << m * v << endl;\n}", "meta": {"hexsha": "f5c08bdb927dcc88c46f1494a7fca0dce2c94951", "size": 461, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ejercicios/semana5/matrix2.cpp", "max_stars_repo_name": "mcvillamil/FISI2028-202120", "max_stars_repo_head_hexsha": "79441bf812ed2b60c02312c956669672d8991bf6", "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": "ejercicios/semana5/matrix2.cpp", "max_issues_repo_name": "mcvillamil/FISI2028-202120", "max_issues_repo_head_hexsha": "79441bf812ed2b60c02312c956669672d8991bf6", "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": "ejercicios/semana5/matrix2.cpp", "max_forks_repo_name": "mcvillamil/FISI2028-202120", "max_forks_repo_head_hexsha": "79441bf812ed2b60c02312c956669672d8991bf6", "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": 16.4642857143, "max_line_length": 45, "alphanum_fraction": 0.5097613883, "num_tokens": 194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109770159683, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.7413138192566133}}
{"text": "#include <iostream>\n#include <cmath>\nusing namespace std;\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\nusing namespace Eigen;\n\nint main(int argc, char **argv) {\n\n    Matrix3d rotation_matrix = Matrix3d::Identity();\n    AngleAxisd rotation_vector(M_PI/4, Vector3d(0,0,1));\n    cout.precision(3);\n    cout << \"rotation matrix =\\n\" << rotation_vector.matrix() << endl;\n\n    rotation_matrix = rotation_vector.toRotationMatrix();\n    Vector3d v(1,0,0);\n    Vector3d v_rotated = rotation_vector * v;\n    cout << \"(1,0,0) after rotation (by angle axis) = \" << v_rotated.transpose() << endl;\n    v_rotated = rotation_matrix * v;\n    cout << \"(1,0,0) after rotation (by matrix) = \" <<v_rotated.transpose() << endl;\n\n    Vector3d euler_angles = rotation_matrix.eulerAngles(2,1,0);  //z,y,x\n    cout << \"yaw pitch roll = \" << euler_angles.transpose() << endl;;\n\n    Isometry3d T = Isometry3d::Identity();\n    T.rotate(rotation_vector);\n    T.pretranslate(Vector3d(1,3,4));\n    cout << \"Transform matrix = \\n\" << T.matrix() << endl;\n\n    Vector3d  v_transformed = T * v;\n    cout << \"v transformed = \" << v_transformed.transpose() << endl;\n\n    Quaterniond q = Quaterniond(rotation_vector);\n    cout << \"quaternion from rotation vector = \" << q.coeffs().transpose() << endl;\n\n    q = Quaterniond(rotation_matrix);\n    cout << \"quaternion from rotation matrix = \" << q.coeffs().transpose() << endl;\n\n    v_rotated = q * v;\n    cout << \"(1,0,0) after rotation = \" << v_rotated.transpose() << endl;\n\n    cout << \"should be equal to \" << (q * Quaterniond(0,1,0,0) * q.inverse()).coeffs().transpose() << endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "36ee9c144030d7bd0366ac3427cdbd5c01d46e7e", "size": 1614, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MySlambook2/ch3/useGeometry/main.cpp", "max_stars_repo_name": "liuyang9609/SLAMProgramming", "max_stars_repo_head_hexsha": "69522f6332e21183e6e0e5c34a9f48c9c580bb43", "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": "MySlambook2/ch3/useGeometry/main.cpp", "max_issues_repo_name": "liuyang9609/SLAMProgramming", "max_issues_repo_head_hexsha": "69522f6332e21183e6e0e5c34a9f48c9c580bb43", "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": "MySlambook2/ch3/useGeometry/main.cpp", "max_forks_repo_name": "liuyang9609/SLAMProgramming", "max_forks_repo_head_hexsha": "69522f6332e21183e6e0e5c34a9f48c9c580bb43", "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.3404255319, "max_line_length": 107, "alphanum_fraction": 0.6400247831, "num_tokens": 450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109728022221, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.7413138062487432}}
{"text": "#include <iostream>\n#include <cmath>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\nusing namespace std;\n\nint main(int argc, char** argv)\n{\n    Eigen::Matrix3d rotation_matrix = Eigen::Matrix3d::Identity();\n    Eigen::AngleAxisd rotation_vector(M_PI/4, Eigen::Vector3d(0,0,1));\n    cout .precision(3);\n    cout << \"rotation matrix =\\n\"<<rotation_vector.matrix()<<endl;\n    rotation_matrix = rotation_vector.toRotationMatrix();\n    // \u7528AngleAxis\u8fdb\u884c\u5750\u6807\u53d8\u6362\n    Eigen::Vector3d v(1,0,0);\n    Eigen::Vector3d v_rotated = rotation_vector * v;\n    cout<<\"(1,0,0) after rotation =\"<<v_rotated.transpose()<<endl;\n    // \u7528\u65cb\u8f6c\u77e9\u9635\u8fdb\u884c\u5750\u6807\u53d8\u6362\n    v_rotated = rotation_matrix * v;\n    cout<<\"(1,0,0) after rotation =\"<<v_rotated.transpose()<<endl;\n    // \u6b27\u62c9\u89d2\n    Eigen::Vector3d euler_angles = rotation_matrix.eulerAngles(2,1,0);\n    cout<<\"yaw pitch roll = \"<<euler_angles.transpose()<<endl;\n\n    Eigen::Isometry3d T = Eigen::Isometry3d::Identity();\n    T.rotate(rotation_vector);\n    T.pretranslate(Eigen::Vector3d(1,3,4));\n    cout<<\"Transform matrix = \\n\"<<T.matrix()<<endl;\n\n    Eigen::Vector3d v_transformed = T * v;\n    cout<<\"v tranformed = \"<<v_transformed.transpose()<<endl;\n\n    // \u56db\u5143\u6570\n    Eigen::Quaterniond q = Eigen::Quaterniond(rotation_vector);\n    cout<<\"auaternion = \\n\"<<q.coeffs()<<endl;\n    q = Eigen::Quaterniond(rotation_matrix);\n    cout<<\"auaternion = \\n\"<<q.coeffs()<<endl;\n    \n    // \u4f7f\u7528\u56db\u5143\u6570\u65cb\u8f6c\u4e00\u4e2a\u5411\u91cf\n    v_rotated = q * v;\n    cout<<\"(1,0,0) after rotation =\"<<v_rotated.transpose()<<endl;\n}\n", "meta": {"hexsha": "ead82993231ca6e826f66205c5cc742c50f73a29", "size": 1494, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch3/useGeometry/useGeometry.cpp", "max_stars_repo_name": "Teeerry/learning-slam", "max_stars_repo_head_hexsha": "064196e03c0fa52e3e7153aabd854922f79ccd8c", "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/useGeometry/useGeometry.cpp", "max_issues_repo_name": "Teeerry/learning-slam", "max_issues_repo_head_hexsha": "064196e03c0fa52e3e7153aabd854922f79ccd8c", "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/useGeometry/useGeometry.cpp", "max_forks_repo_name": "Teeerry/learning-slam", "max_forks_repo_head_hexsha": "064196e03c0fa52e3e7153aabd854922f79ccd8c", "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.9545454545, "max_line_length": 70, "alphanum_fraction": 0.6586345382, "num_tokens": 453, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951552333004, "lm_q2_score": 0.7931059560743423, "lm_q1q2_score": 0.7410743629425403}}
{"text": "//\n// Created by James Koh on 05/02/2021.\n//\n#include <iostream>\n#include <string>\n#include <vector>\n#include <Eigen/Dense>\n\nnamespace LP {\n    using namespace Eigen;\n\n    int findEBV(VectorXd& c, Matrix<bool, Dynamic, 1>& BV) {\n        double max = -1;\n        int ev_id = -1;\n\n        for (int i = 0; i < c.size(); i++) {\n            if (!BV(i) && max < c(i)) {\n                max = c(i);\n                ev_id = i;\n            }\n        }\n\n        return ev_id;\n    }\n\n    int findPivotRowID(VectorXd& ev_col, VectorXd& b) {\n        VectorXd r(b.size());\n\n        for (int i = 0; i < ev_col.size(); i++) {\n            if (ev_col(i) < 0)\n                r(i) = -1;\n            else\n                r(i) = b(i) / ev_col(i);\n        }\n\n        bool init = false;\n        int row = -1;\n        double r_val = -1;\n\n        for (int i = 0; i < r.size(); i++) {\n            if (r(i) != -1) {\n                if (!init) {\n                    init = true;\n                    row = i;\n                    r_val = r(i);\n                } else if (r(i) < r_val) {\n                    row = i;\n                    r_val = r(i);\n                }\n            }\n        }\n\n        return row;\n    }\n\n    int findLBV(RowVectorXd& lv_row, Matrix<bool, Dynamic, 1>& BV, double& epsilon) {\n        for (int i = 0; i < lv_row.size(); i++) {\n            if (BV(i) && lv_row(i) > (1 - epsilon) && lv_row(i) < (1 + epsilon)) {\n                return i;\n            }\n        }\n\n        throw std::logic_error(\"Leaving pivot is not 1 despite finding pivot row.\");\n    }\n\n    void pivotBV(int& ev_id, int& lv_id, Matrix<bool, Dynamic, 1>& BV) {\n        BV(ev_id) = true;\n        BV(lv_id) = false;\n    }\n\n    void gaussElimination(VectorXd& c, MatrixXd& A, VectorXd& b, double& obj, int& pivot_col_id, int& pivot_row_id) {\n        // updating A and b\n        // pivot scaling transformation matrix E1\n        MatrixXd E1 = MatrixXd::Identity(A.rows(),A.rows());\n        E1(pivot_row_id, pivot_row_id) = 1 / A(pivot_row_id, pivot_col_id);\n\n        // gaussian elimination transformation matrix E2\n        MatrixXd E2 = MatrixXd::Identity(A.rows(),A.rows());\n        for (int i = 0; i < E2.cols(); i++) {\n            if (i != pivot_row_id)\n                E2(i, pivot_row_id) = -A(i, pivot_col_id);\n        }\n\n        A = E2 * E1 * A;\n        b = E2 * E1 * b;\n\n        // updating c and obj\n        double m = c(pivot_col_id);\n        c = c - m * (A.row(pivot_row_id).transpose());\n        obj = obj + m * b(pivot_row_id);\n    }\n\n    void displayTableau (VectorXd& c, double& obj, MatrixXd& A, VectorXd& b, int precision,\n                         std::vector<std::string> variable_name) {\n        std::cout << std::fixed;\n        std::cout.precision(precision);\n        std::string blank = \"  \";\n\n        for (auto it = variable_name.begin(); it < variable_name.end(); ++it) {\n            std::cout << \"|\" << blank << *it << blank;\n        }\n        std::cout << \"|\" << blank << \"obj\" << std::endl;\n        std::cout << \"------------------------------------------------------\" << std::endl;\n        std::cout << c.transpose() << blank << obj << std::endl;\n\n        for (auto it = variable_name.begin(); it < variable_name.end(); ++it) {\n            std::cout << \"|\" << blank << *it << blank;\n        }\n        std::cout << \"|\" << blank << \"b\" << std::endl;\n        std::cout << \"------------------------------------------------------\" << std::endl;\n        MatrixXd Ab(A.rows(), A.cols() + 1);\n        Ab << A, b;\n        std::cout << Ab << std::endl;\n    }\n\n    std::tuple<VectorXd, double, MatrixXd, VectorXd>\n    Simplex(VectorXd c, MatrixXd A, VectorXd b, Matrix<bool, Dynamic, 1> BV,\n            std::vector<std::string> variable_name, double epsilon = 0.00001, double obj = 0) {\n        int i = 1;\n\n        while (true) {\n            int ev_id = findEBV(c, BV);\n\n            if (ev_id == -1) {\n                std::cout << \"########\" << std::endl;\n                std::cout << \"Optimal solution found.\" << std::endl;\n                std::cout << \"Terminating ...\" << std::endl;\n                std::cout << \"########\" << std::endl;\n\n                return {c, obj, A, b};\n            }\n\n            std::cout << \"########\" << std::endl;\n            std::cout << \"Iteration \" << i << \":\" << std::endl;\n            std::cout << \"########\" << std::endl;\n\n            VectorXd ev_column = A.col(ev_id);\n            int pivot_row_id = findPivotRowID(ev_column, b);\n\n            if (pivot_row_id == -1) {\n                throw std::runtime_error(\"The linear program is unbounded.\");\n            }\n\n            RowVectorXd lv_row = A.row(pivot_row_id);\n            int lv_id = findLBV(lv_row, BV, epsilon);\n            pivotBV(ev_id, lv_id, BV);\n\n            gaussElimination(c, A, b, obj, ev_id, pivot_row_id);\n            displayTableau(c, obj, A, b, 3, variable_name);\n\n            i++;\n        }\n    }\n\n}", "meta": {"hexsha": "324fbc5d582bfa05bf36a306f3d524ff4cd34da6", "size": 4885, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "linear_program.cpp", "max_stars_repo_name": "jameshskoh/SimplexAlgorithm", "max_stars_repo_head_hexsha": "aa2b2f7a72490b5170f2b40950a688b932920970", "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": "linear_program.cpp", "max_issues_repo_name": "jameshskoh/SimplexAlgorithm", "max_issues_repo_head_hexsha": "aa2b2f7a72490b5170f2b40950a688b932920970", "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": "linear_program.cpp", "max_forks_repo_name": "jameshskoh/SimplexAlgorithm", "max_forks_repo_head_hexsha": "aa2b2f7a72490b5170f2b40950a688b932920970", "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.5161290323, "max_line_length": 117, "alphanum_fraction": 0.4481064483, "num_tokens": 1309, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087926320944, "lm_q2_score": 0.7981867873410141, "lm_q1q2_score": 0.7410436315301612}}
{"text": "\n#include <iostream> \n\n#include \"matplotlibcpp.h\"\n\n#include <Eigen/Dense>\n#include \"../src/rk_implementer.hpp\"\n#include \"../src/rk_solvers.hpp\"\n\nnamespace plt = matplotlibcpp;\n\n\nvoid lotkaVolterra(){\n\n  /**\n   *  Setting global variables, the time we are integrating over\n   *  and the number of integration steps we take in this time.\n   * \n   *  We also define the function f representing our ODE\n   *  and the initial conditiond y0.\n   */\n\n  unsigned int steps = 1000;\n  unsigned int time = 13;\n\n  auto f = [] (Eigen::VectorXd y) {\n    Eigen::VectorXd df(2);\n    df << y(0)*(4-4.0/3*y(1)) , -y(1)*(0.8-0.4*y(0));\n\n    return df;\n  };\n\n  Eigen::VectorXd y0(2);\n  y0 << 6,3;\n\n  /**\n   * Solve using built in solver:\n   */\n\n  std::vector<Eigen::VectorXd> result = ExplicitRKSolvers::classical4thOrderRuleIntegrator(f, time,y0, steps);\n\n  std::vector<double> t(steps);\n  std::vector<double> prey(steps);\n  std::vector<double> predator(steps);\n\n    for(size_t i = 0; i < t.size(); i++) {\n        t[i] = i*(time / (double) steps);\n        prey[i] = result[i](0);\n        predator[i] = result[i](1);\n    }\n    plt::title(\"Lotka-Volterra Integration Example\");\n\n    plt::named_plot(\"Prey Population\",t, prey);\n    plt::named_plot(\"Predator Population\",t,predator);\n    \n    plt::xlabel(\"Time\");\n    plt::ylabel(\"Population\");\n    plt::legend();\n\n    plt::save(\"lotkaVolterraSolved.png\");\n  \n}\n\n    \n\n\n\nvoid lorenzAttractor(){\n\n  /**\n   *  Setting global variables, the time we are integrating over\n   *  and the number of integration steps we take in this time.\n   * \n   *  We also define the function f representing our ODE\n   *  and the initial conditiond y0.\n   */\n\n  unsigned int steps = 10000;\n  unsigned int time = 50;\n  double sigma = 10;\n  double rho = 28;\n  double beta = 8.0/3;\n\n  auto f = [beta,sigma,rho] (Eigen::VectorXd y) {\n    Eigen::VectorXd df(3);\n    df << sigma*(y(1) - y(0)), \n          y(0)*(rho-y(2)) - y(1),\n          y(0)*y(1) - beta*y(2);\n\n    return df;\n  };\n\n\n\n  Eigen::VectorXd y0(3);\n  y0 << 1,1,1;\n\n  /**\n   * Solve using built in solver:\n   */\n\n  std::vector<Eigen::VectorXd> result = ExplicitRKSolvers::classical4thOrderRuleIntegrator(f, time,y0, steps);\n\n  std::vector<double> x(steps);\n  std::vector<double> y(steps);\n  std::vector<double> z(steps);\n\n    for(size_t i = 0; i < x.size(); i++) {\n        x[i] = result[i](0);\n        y[i] = result[i](1);\n        z[i] = result[i](2);\n    }\n    plt::plot3(x, y, z);\n\n    plt::xlabel(\"x\");\n    plt::ylabel(\"y\");\n    plt::set_zlabel(\"z\"); // set_zlabel rather than just zlabel, in accordance with the Axes3D method\n    \n    // plt::title needs to be called after plot3(), otherwise title won't show up\n    plt::title(\"Lorenz Attractor Integration Example\");\n    plt::save(\"lorenzAttractorSolved.png\");\n  \n}\n\n\n\n\nint main(void) {\n  lotkaVolterra();\n  lorenzAttractor();\n  plt::show();\n}", "meta": {"hexsha": "e6dbbdde526c8cd8d8ff45a21a1f9858e8242e61", "size": 2858, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "demo/demo.cpp", "max_stars_repo_name": "davidrzs/Runge-Kutta-ODE-Solver", "max_stars_repo_head_hexsha": "d6295007e78ae390ff95e2c25e4bcc906ce9624e", "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": "demo/demo.cpp", "max_issues_repo_name": "davidrzs/Runge-Kutta-ODE-Solver", "max_issues_repo_head_hexsha": "d6295007e78ae390ff95e2c25e4bcc906ce9624e", "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": "demo/demo.cpp", "max_forks_repo_name": "davidrzs/Runge-Kutta-ODE-Solver", "max_forks_repo_head_hexsha": "d6295007e78ae390ff95e2c25e4bcc906ce9624e", "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.6515151515, "max_line_length": 110, "alphanum_fraction": 0.6021693492, "num_tokens": 863, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107896491797, "lm_q2_score": 0.7905303162021596, "lm_q1q2_score": 0.7408935418894418}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\nCopyright (C) 2005 StatPro Italia srl\nCopyright (C) 2015 CompatibL\n\nThis file is part of QuantLib, a free-software/open-source library\nfor financial quantitative analysts and developers - http://quantlib.org/\n\nQuantLib is free software: you can redistribute it and/or modify it\nunder the terms of the QuantLib license.  You should have received a\ncopy of the license along with this program; if not, please email\n<quantlib-dev@lists.sf.net>. The license is also available online at\n<http://quantlib.org/license.shtml>.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT\nANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\nFOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n#include <ql/quantlib.hpp>\n#include <boost/timer.hpp>\n#include \"utilities.hpp\"\n#include \"adjointcurvefittingtest.hpp\"\n#include \"adjointtestutilities.hpp\"\n\nusing namespace QuantLib;\nusing namespace boost::unit_test_framework;\n\nnamespace\n{\n\tclass BraceVolatilityFunction\n\t{\n\t\tReal a_, b_, c_, d_;\n\tpublic:\n\t\tinline BraceVolatilityFunction(Real a, Real b, Real c, Real d)\n\t\t\t: a_(a), b_(b), c_(c), d_(d)\n\t\t{\n\t\t}\n\t\tinline ~BraceVolatilityFunction() {}\n\n\t\tinline Real operator() (Real t)\n\t\t{\n\t\t\treturn (a_ + b_*t)*std::exp(-c_*t) + d_;\n\t\t}\n\t};\n\n\n\tstruct LSCurvesValue\n\t{\n\t\tstatic std::deque<std::string > get_columns()\n\t\t{\n\t\t\tstatic std::deque<std::string > columns =\n\t\t\t{\n\t\t\t\t\"x\", \"Observed\", \"Estimated\", \"True\"\n\t\t\t};\n\n\t\t\treturn columns;\n\t\t}\n\n\t\ttemplate <typename stream_type>\n\t\tfriend inline stream_type&\n\t\t\toperator << (stream_type& stm, LSCurvesValue& v)\n\t\t{\n\t\t\t\tstm << v.xvalue_\n\t\t\t\t\t<< \";\" << v.observed_\n\t\t\t\t\t<< \";\" << v.estimated_\n\t\t\t\t\t<< \";\" << v.true_ << std::endl;\n\n\t\t\t\treturn stm;\n\t\t\t}\n\n\t\tReal observed_;\n\t\tReal estimated_;\n\t\tReal true_;\n\t\tReal xvalue_;\n\t};\n\n\t/*!\n\tCurve Fitting Problem\n\t*/\n\tclass CurveFittingProblem : public LeastSquareProblem\n\t{\n\t\tconst Array &ttm_;\n\t\tconst Array &target_;\n\n\tpublic:\n\t\t/*!\n\t\tDefault constructor : set time to maturity vector\n\t\tand target value\n\t\t*/\n\n\t\tstatic Size counter;\n\n\t\tCurveFittingProblem(const Array &ttm, const Array &target) : ttm_(ttm), target_(target)\n\t\t{\n\t\t}\n\n\t\t//! Destructor\n\t\tvirtual ~CurveFittingProblem() {}\n\n\t\t//! Size of the least square problem\n\t\tvirtual size_t size()\n\t\t{\n\t\t\treturn ttm_.size();\n\t\t}\n\n\t\t//! return function and target values\n\t\tvirtual void targetAndValue(const Array& coefficients, Array& target, Array& fct2fit)\n\t\t{\n\t\t\tBraceVolatilityFunction bvf(coefficients[0], coefficients[1], coefficients[2], coefficients[3]);\n\n\t\t\ttarget = target_;// target values\n\t\t\tfor (Size i = 0; i < ttm_.size(); ++i)\n\t\t\t\tfct2fit[i] = bvf(ttm_[i]);\n\t\t}\n\n\t\t//! return function, target and first derivatives values\n\t\tvirtual void targetValueAndGradient(const Array& coefficients, Matrix& grad_fct2fit, Array& target, Array& fct2fit)\n\t\t{\n\t\t\tSize n = coefficients.size();\n\t\t\tstd::vector<cl::TapeDouble> coef(n);\n\t\t\tstd::vector<double> coefD(n);\n\t\t\tSize m = ttm_.size();\n\t\t\tfor (size_t i = 0; i < n; i++)\n\t\t\t{\n\t\t\t\tcoef[i] = coefficients[i].value();\n\t\t\t\tcoefD[i] = (double)coefficients[i];\n\t\t\t}\n\n\t\t\tcl::Independent(coef);\n\n\t\t\tBraceVolatilityFunction bvf(coef[0], coef[1], coef[2], coef[3]);\n\n\t\t\tstd::vector<cl::TapeDouble> y(m);\n\t\t\tfor (Size i = 0; i < m; ++i)\n\t\t\t{\n\t\t\t\ty[i] = bvf(ttm_[i]).value();\n\t\t\t}\n\t\t\tcl::TapeFunction<double> f(coef, y);\n\t\t\t//Compute derivatives using Jacobian\n\t\t\tstd::vector<double> Jacobian(m*n);\n\t\t\tJacobian = f.Jacobian(coefD);\n\n\t\t\ttarget = target_;// target values\n\t\t\tfor (Size i = 0; i < ttm_.size(); ++i)\n\t\t\t{\n\t\t\t\t// function value at current point coefficients\n\t\t\t\tfct2fit[i] = bvf(ttm_[i]);\n\t\t\t}\n\n\t\t\t/*\n\t\t\tmatrix of first derivatives :\n\t\t\tthe derivatives with respect to the parameter a,b,c,d\n\t\t\tare stored by row.\n\t\t\t*/\n\t\t\tcounter++;\n\t\t\tfor (size_t i = 0; i < m; i++)\n\t\t\tfor (size_t j = 0; j < n; j++)\n\t\t\t\tgrad_fct2fit[i][j] = Jacobian[i*n + j];\n\n\t\t}\n\t};\n\n\tSize CurveFittingProblem::counter = 0;\n}\n\n/*\nWe define here an inverse problem to show how to fit\nparametric function to data.\n*/\nbool AdjointCurveFittingTest::testCurveFitting()\n{\n\tBOOST_TEST_MESSAGE(\"Testing curve fitting with AAD...\\n\");\n\tbool result = false;\n#ifdef CL_TAPE_CPPAD\n\tboost::mt19937 rng;\n\tboost::normal_distribution<> nd(0.0, 0.01);\n\tboost::variate_generator<boost::mt19937&, boost::normal_distribution<>> noise(rng, nd);\n\n\t/*\n\tParameter values that produce the volatility hump.\n\tConsider it as optimal values of the curve fitting\n\tproblem.\n\t*/\n\tstd::vector<Real> coefficients_ =\n\t{\n\t\t0.147014,\n\t\t0.057302,\n\t\t0.249964,\n\t\t0.148556\n\t};\n\n\n\tArray coefficients(coefficients_.begin(), coefficients_.end());\n\n\t// Define the target volatility function\n\tBraceVolatilityFunction bvf(coefficients[0], coefficients[1], coefficients[2], coefficients[3]);\n\n\t// start date of volatilty\n\tconst Real startDate = 0.0;\n\t// end date of volatility\n\tconst Real endDate = 20.;\n\t// period length between values (in year fraction : quarterly)\n\tconst Real period = 0.1;\n\n\t// number of period\n\tsize_t periodNumber = (size_t)(endDate / period);\n\n\tArray targetValue(periodNumber);\n\tArray timeToMaturity(periodNumber);\n\n\n\n\t// Fill target and time to maturity arrays\n\tfor (size_t i = 0; i < periodNumber; ++i)\n\t{\n\t\tconst Real t = startDate + i * period;\n\t\ttimeToMaturity[i] = t;\n\t\ttargetValue[i] = bvf(t) + noise();\n\t}\n\n\t// Accuracy of the optimization method\n\tconst Real accuracy = 1e-5;// It is the square of the accuracy\n\t// Maximum number of iterations\n\tSize maxiter = 10000;\n\n\tArray initialValue(4, 0.1);\n\n\t// Least square optimizer\n\tNoConstraint nc;\n\tNonLinearLeastSquare lsqnonlin(nc, accuracy, maxiter, boost::shared_ptr<OptimizationMethod>(new ConjugateGradient()));\n\n\t// Define the least square problem\n\tCurveFittingProblem cfp(timeToMaturity, targetValue);\n\n\t// Set initial values\n\tlsqnonlin.setInitialValue(initialValue);\n\t// perform fitting\n\tArray solution = lsqnonlin.perform(cfp);\n\tBraceVolatilityFunction bvf_est(solution[0], solution[1], solution[2], solution[3]);\n\n\t// Plot stream\n\tcl::AdjointTestOutput out(\"AdjointCurveFitting\"\n\t\t\t\t\t\t\t  , { { \"filename\", \"CurveFitting\" }\n\t, { \"ylabel\", \"F(x)\" }\n\t, { \"not_clear\", \"Not\" }\n\t, { \"title\", \"Least-squares curve fitting\" }\n\t, { \"cleanlog\", \"false\" }\n\t, { \"xlabel\", \"x\" } });\n\n\tcl::AdjointTestOutput outPerform(\"AdjointCurveFitting/\"\n\t\t\t\t\t\t\t\t\t , { { \"filename\", \"LSCurves\" }\n\t, { \"not_clear\", \"Not\" }\n\t, { \"line_box_width\", \"-5\" }\n\t, { \"title\", \"Swaption NPV differentiation performance with respect to volatility\" }\n\t, { \"ylabel\", \"Time (s)\" }\n\t, { \"xlabel\", \"Number of volatilities\" } });\n\n#if defined CL_GRAPH_GEN\n\n\t// The observed volatility function \n\tstd::vector<LSCurvesValue> Volatility;\n\n\tLSCurvesValue temp;\n\t// Fill target and time to maturity arrays\n\tfor (size_t i = 0; i < periodNumber; ++i)\n\t{\n\t\tconst Real t = startDate + i * period;\n\t\ttemp.xvalue_ = t;\n\t\ttimeToMaturity[i] = t;\n\t\ttemp.observed_ = targetValue[i];\n\t\ttemp.estimated_ = bvf_est(t);\n\t\ttemp.true_ = bvf(t);\n\t\tVolatility.push_back(temp);\n\t}\n\tstd::cout << Volatility.size() << std::endl;\n\toutPerform << Volatility;\n#endif\n\t\n\n\t// check the result with defined tolerance\n\tconst Real tollerance = 1e-2;\n\tresult = true;\n\tfor (Size i = 0; i < solution.size(); i++)\n\t{\n\t\tif (solution[i] - coefficients[i] > tollerance)\n\t\t{\n\t\t\tresult = false;\n\t\t\tBOOST_ERROR(\"Optimal and solution values [\" << i << \"] mismatch.\"\n\t\t\t\t\t\t<< \"\\nOptimal values  : \" << coefficients[i]\n\t\t\t\t\t\t<< \"\\nSolution values : \" << solution[i]\n\t\t\t\t\t\t<< \"\\nError  : \" << (solution[i] - coefficients[i])\n\t\t\t\t\t\t<< \"\\nTolerance:  \" << tollerance);\n\t\t}\n\t}\n\n#endif\n\treturn result;\n}\n\ntest_suite* AdjointCurveFittingTest::suite()\n{\n\ttest_suite* suite = BOOST_TEST_SUITE(\"AAD curve fitting test\");\n\tsuite->add(QUANTLIB_TEST_CASE(&AdjointCurveFittingTest::testCurveFitting));\n\treturn suite;\n}\n\n#ifdef CL_ENABLE_BOOST_TEST_ADAPTER\n\nBOOST_AUTO_TEST_SUITE(ad_curve_fitting)\n\nBOOST_AUTO_TEST_CASE(testCurveFitting)\n{\n\tBOOST_CHECK(AdjointCurveFittingTest::testCurveFitting());\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n#endif\n", "meta": {"hexsha": "c083826f2cc52a083088bd12fbd27dc9e6d1edb7", "size": 8054, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test-suite-adjoint/adjointcurvefittingtest.cpp", "max_stars_repo_name": "fduffy/QuantLibAdjoint", "max_stars_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 41.0, "max_stars_repo_stars_event_min_datetime": "2016-03-19T02:31:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T13:23:20.000Z", "max_issues_repo_path": "test-suite-adjoint/adjointcurvefittingtest.cpp", "max_issues_repo_name": "fduffy/QuantLibAdjoint", "max_issues_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "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": "test-suite-adjoint/adjointcurvefittingtest.cpp", "max_forks_repo_name": "fduffy/QuantLibAdjoint", "max_forks_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2016-03-17T14:14:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T10:33:19.000Z", "avg_line_length": 25.0903426791, "max_line_length": 119, "alphanum_fraction": 0.6789173082, "num_tokens": 2336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.74086538776288}}
{"text": "//\n// Created by Amir Masoud Abdol on 2020-04-11\n//\n\n#include \"TestStrategy.h\"\n\n#include <boost/math/distributions/students_t.hpp>\n\nusing namespace sam;\nusing boost::math::students_t;\n\nvoid YuenTest::run(Experiment *experiment) {\n\n  // The first group is always the control group\n\n  static YuenTest::ResultType res;\n\n  for (int i{experiment->setup.nd()}, d{0}; i < experiment->setup.ng();\n       ++i, ++d %= experiment->setup.nd()) {\n\n    if (params.paired) {\n      res = yuen_t_test_paired((*experiment)[d].measurements(),\n                               (*experiment)[i].measurements(),\n                               params.alpha,\n                               params.alternative,\n                               params.trim,\n                               0);\n    }else{\n      res = yuen_t_test_two_samples((*experiment)[d].measurements(),\n                                    (*experiment)[i].measurements(),\n                                    params.alpha,\n                                    params.alternative, params.trim, 0);\n    }\n\n    (*experiment)[i].stats_ = res.tstat;\n    (*experiment)[i].pvalue_ = res.pvalue;\n    (*experiment)[i].sig_ = res.sig;\n    (*experiment)[i].eff_side_ = res.side;\n  }\n}\n\nYuenTest::ResultType YuenTest::yuen_t_test_one_sample(\n    const arma::Row<float> &x, float alpha,\n    const TestStrategy::TestAlternative alternative, float trim = 0.2,\n    float mu = 0.0) {\n\n  float M{0};\n\n  bool sig{false};\n  float Sm1 = arma::mean(x);\n\n  auto n = x.n_elem;\n\n  int g = static_cast<int>(floor(trim * n));\n\n  float df = n - 2 * g - 1;\n\n  float sw = sqrt(win_var(x, trim));\n\n  float se = sw / ((1. - 2. * trim) * sqrt(n));\n\n  float dif = trim_mean(x, trim);\n\n  float t_stat = (dif - mu) / se;\n\n  students_t dist(df);\n  float p = 0;\n\n  if (alternative == TestStrategy::TestAlternative::TwoSided) {\n    // Mean != M\n    p = 2 * cdf(complement(dist, fabs(t_stat)));\n    if (p < alpha) // Alternative \"NOT REJECTED\"\n      sig = true;\n    else // Alternative \"REJECTED\"\n      sig = false;\n  }\n\n  if (alternative == TestStrategy::TestAlternative::Greater) {\n    // Mean  > M\n    p = cdf(complement(dist, t_stat));\n    if (p > alpha) // Alternative \"NOT REJECTED\"\n      sig = true;\n    else // Alternative \"REJECTED\"\n      sig = false;\n  }\n\n  if (alternative == TestStrategy::TestAlternative::Less) {\n    // Mean  < M\n    p = cdf(dist, t_stat);\n    if (p > alpha) // Alternative \"NOT REJECTED\"\n      sig = true;\n    else // Alternative \"REJECTED\"\n      sig = false;\n  }\n\n  int eff_side = std::copysign(1.0, Sm1 - M);\n\n  return {.tstat = t_stat, .df = df, .pvalue = p, .side = eff_side, .sig = sig};\n}\n\nYuenTest::ResultType\nYuenTest::yuen_t_test_paired(const arma::Row<float> &x,\n                             const arma::Row<float> &y, float alpha,\n                             const TestStrategy::TestAlternative alternative,\n                             float trim = 0.2, float mu = 0) {\n  // Do some check whether it's possible to run the test\n\n  float Sm1 = arma::mean(x);\n  float Sm2 = arma::mean(y);\n\n  bool sig{false};\n\n  auto h1 = x.n_elem - 2 * static_cast<int>(floor(trim * x.n_elem));\n\n  float q1 = (x.n_elem - 1) * win_var(x, trim);\n\n  float q2 = (y.n_elem - 1) * win_var(y, trim);\n\n  float q3 = (x.n_elem - 1) * std::get<1>(win_cor_cov(x, y, trim));\n\n  float df = h1 - 1;\n\n  float se = sqrt((q1 + q2 - 2 * q3) / (h1 * (h1 - 1)));\n\n  float dif = trim_mean(x, trim) - trim_mean(y, trim);\n\n  float t_stat = (dif - mu) / se;\n\n  students_t dist(df);\n  float p = 0;\n\n  if (alternative == TestStrategy::TestAlternative::TwoSided) {\n    // Mean != M\n    p = 2 * cdf(complement(dist, fabs(t_stat)));\n    if (p < alpha) // Alternative \"NOT REJECTED\"\n      sig = true;\n    else // Alternative \"REJECTED\"\n      sig = false;\n  }\n\n  if (alternative == TestStrategy::TestAlternative::Greater) {\n    // Mean  > M\n    p = cdf(complement(dist, t_stat));\n    if (p > alpha) // Alternative \"NOT REJECTED\"\n      sig = true;\n    else // Alternative \"REJECTED\"\n      sig = false;\n  }\n\n  if (alternative == TestStrategy::TestAlternative::Less) {\n    // Mean  < M\n    p = cdf(dist, t_stat);\n    if (p > alpha) // Alternative \"NOT REJECTED\"\n      sig = true;\n    else // Alternative \"REJECTED\"\n      sig = false;\n  }\n\n  int eff_side = std::copysign(1.0, Sm2 - Sm1);\n\n  return {.tstat = t_stat, .df = df, .pvalue = p, .side = eff_side, .sig = sig};\n}\n\nYuenTest::ResultType YuenTest::yuen_t_test_two_samples(\n    const arma::Row<float> &x, const arma::Row<float> &y, float alpha,\n    const TestStrategy::TestAlternative alternative, float trim, float mu) {\n\n  float Sm1 = arma::mean(x);\n  float Sm2 = arma::mean(y);\n\n  bool sig{false};\n\n  int h1 = x.n_elem - 2 * floor(trim * x.n_elem);\n  int h2 = y.n_elem - 2 * floor(trim * y.n_elem);\n\n  float d1 = (x.n_elem - 1.) * win_var(x, trim) / (h1 * (h1 - 1.));\n  float d2 = (y.n_elem - 1.) * win_var(y, trim) / (h2 * (h2 - 1.));\n\n  if (!(isgreater(d1, 0) or isless(d1, 0))) {\n    // Samples are almost equal and elements are constant\n    d1 += std::numeric_limits<float>::epsilon();\n  }\n\n  if (!(isgreater(d2, 0) or isless(d2, 0))) {\n    // Samples are almost equal and elements are constant\n    d2 += std::numeric_limits<float>::epsilon();\n  }\n\n  float df =\n      pow(d1 + d2, 2) / (pow(d1, 2) / (h1 - 1.) + pow(d2, 2) / (h2 - 1.));\n\n  float se = sqrt(d1 + d2);\n\n  float dif = trim_mean(x, trim) - trim_mean(y, trim);\n\n  float t_stat = (dif - mu) / se;\n\n  students_t dist(df);\n  float p;\n\n  if (alternative == TestStrategy::TestAlternative::TwoSided) {\n    // Sample 1 Mean != Sample 2 Mean\n    p = 2 * cdf(complement(dist, fabs(t_stat)));\n    if (p < alpha) // Alternative \"NOT REJECTED\"\n      sig = true;\n    else // Alternative \"REJECTED\"\n      sig = false;\n  }\n\n  if (alternative == TestStrategy::TestAlternative::Greater) {\n    // Sample 1 Mean <  Sample 2 Mean\n    p = cdf(dist, t_stat);\n    if (p < alpha) // Alternative \"NOT REJECTED\"\n      sig = true;\n    else // Alternative \"REJECTED\"\n      sig = false;\n  }\n\n  if (alternative == TestStrategy::TestAlternative::Less) {\n    // Sample 1 Mean >  Sample 2 Mean\n    p = cdf(complement(dist, t_stat));\n    if (p < alpha) // Alternative \"NOT REJECTED\"\n      sig = true;\n    else // Alternative \"REJECTED\"\n      sig = false;\n  }\n\n  int eff_side = std::copysign(1.0, Sm2 - Sm1);\n\n  return {.tstat = t_stat, .df = df, .pvalue = p, .side = eff_side, .sig = sig};\n}\n", "meta": {"hexsha": "20a97b0cdccf39e7d255492baf293c5d4af1b9fa", "size": 6368, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sam-project/bakker-et-al-2012/SAM/SAM/src/TSYuenTest.cpp", "max_stars_repo_name": "amirmasoudabdol/bakker-et-al-2012-reproduction-using-sam", "max_stars_repo_head_hexsha": "518ab1cebaa80c19a12e92db8ae87386512ae053", "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": "sam-project/bakker-et-al-2012/SAM/SAM/src/TSYuenTest.cpp", "max_issues_repo_name": "amirmasoudabdol/bakker-et-al-2012-reproduction-using-sam", "max_issues_repo_head_hexsha": "518ab1cebaa80c19a12e92db8ae87386512ae053", "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": "sam-project/bakker-et-al-2012/SAM/SAM/src/TSYuenTest.cpp", "max_forks_repo_name": "amirmasoudabdol/bakker-et-al-2012-reproduction-using-sam", "max_forks_repo_head_hexsha": "518ab1cebaa80c19a12e92db8ae87386512ae053", "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.4482758621, "max_line_length": 80, "alphanum_fraction": 0.5727072864, "num_tokens": 1896, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475810629193, "lm_q2_score": 0.7853085808877581, "lm_q1q2_score": 0.7408189501684205}}
{"text": "\n// solving A * X = B\n// using driver function gesv()\n\n#include <cstddef>\n#include <iostream>\n#include <complex>\n#include <boost/numeric/bindings/lapack/gesv.hpp>\n#include <boost/numeric/bindings/traits/ublas_matrix.hpp>\n#include <boost/numeric/bindings/traits/std_vector.hpp>\n#include \"utils.h\"\n\nnamespace ublas = boost::numeric::ublas;\nnamespace lapack = boost::numeric::bindings::lapack;\n\nusing std::size_t; \nusing std::cout;\nusing std::endl; \n\ntypedef std::complex<double> cmpx_t; \n\ntypedef ublas::matrix<double, ublas::column_major> m_t;\ntypedef ublas::matrix<cmpx_t, ublas::column_major> cm_t;\n\nint main() {\n\n  cout << endl; \n  cout << \"real system:\" << endl << endl; \n\n  size_t n = 5;   \n  m_t a (n, n);   // system matrix \n\n  size_t nrhs = 2; \n  m_t x (n, nrhs), b (n, nrhs);  // b -- right-hand side matrix\n\n  std::vector<int> ipiv (n);  // pivot vector\n\n  init_symm (a); \n  //     [n   n-1 n-2  ... 1]\n  //     [n-1 n   n-1  ... 2]\n  // a = [n-2 n-1 n    ... 3]\n  //     [        ...       ]\n  //     [1   2   ...  n-1 n]\n\n  m_t aa (a);  // copy of a, because a is `lost' after gesv()\n\n  for (int i = 0; i < x.size1(); ++i) {\n    x (i, 0) = 1.;\n    x (i, 1) = 2.; \n  }\n  b = prod (a, x); \n\n  print_m (a, \"A\"); \n  cout << endl; \n  print_m (b, \"B\"); \n  cout << endl; \n\n  lapack::gesv (a, ipiv, b);   // solving the system, b contains x \n  print_m (b, \"X\"); \n  cout << endl; \n\n  x = prod (aa, b); \n  print_m (x, \"B = A X\"); \n  cout << endl; \n\n  ////////////////////////////////////////////////////////\n\n  cout << endl; \n  cout << \"complex system:\" << endl << endl; \n  cm_t ca (3, 3), cb (3, 1), cx (3, 1);\n  std::vector<int> ipiv2 (3); \n\n  ca (0, 0) = cmpx_t (3, 0);\n  ca (0, 1) = cmpx_t (4, 2);\n  ca (0, 2) = cmpx_t (-7, 5);\n  ca (1, 0) = cmpx_t (4, -2);\n  ca (1, 1) = cmpx_t (-5, 0);\n  ca (1, 2) = cmpx_t (0, -3);\n  ca (2, 0) = cmpx_t (-7, -5);\n  ca (2, 1) = cmpx_t (0, 3);\n  ca (2, 2) = cmpx_t (2, 0);\n  print_m (ca, \"CA\"); \n  cout << endl; \n\n  for (int i = 0; i < cx.size1(); ++i) \n    cx (i, 0) = cmpx_t (1, -1); \n  cb = prod (ca, cx); \n  print_m (cb, \"CB\"); \n  cout << endl; \n  \n  int ierr = lapack::gesv (ca, ipiv2, cb); \n  if (ierr == 0) \n    print_m (cb, \"CX\");\n  else\n    cout << \"matrix is singular\" << endl; \n\n  cout << endl; \n\n}\n\n", "meta": {"hexsha": "b4d2d41a91ef04a6c22f36a5d1a4454a9662faf1", "size": 2250, "ext": "cc", "lang": "C++", "max_stars_repo_path": "libs/numeric/bindings/lapack/test/ublas_gesv.cc", "max_stars_repo_name": "inducer/boost-numeric-bindings", "max_stars_repo_head_hexsha": "1f994e8a2e161cddb6577eacc76b7bc358701cbe", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-14T19:18:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-14T19:18:21.000Z", "max_issues_repo_path": "libs/numeric/bindings/lapack/test/ublas_gesv.cc", "max_issues_repo_name": "inducer/boost-numeric-bindings", "max_issues_repo_head_hexsha": "1f994e8a2e161cddb6577eacc76b7bc358701cbe", "max_issues_repo_licenses": ["BSL-1.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/numeric/bindings/lapack/test/ublas_gesv.cc", "max_forks_repo_name": "inducer/boost-numeric-bindings", "max_forks_repo_head_hexsha": "1f994e8a2e161cddb6577eacc76b7bc358701cbe", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-23T09:56:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-23T09:56:06.000Z", "avg_line_length": 22.2772277228, "max_line_length": 67, "alphanum_fraction": 0.5071111111, "num_tokens": 888, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797172476385, "lm_q2_score": 0.8128673087708698, "lm_q1q2_score": 0.7406682045656899}}
{"text": "#include <Eigen/Cholesky>\n#include <Eigen/Core>\n#include <Eigen/LU>\n#include <cmath>\n#include <iostream>\n#include <mathtoolbox/log-determinant.hpp>\n\ndouble CalcCovariance(const Eigen::VectorXd& x_1, const Eigen::VectorXd& x_2)\n{\n    return std::exp(-(x_1 - x_2).squaredNorm());\n}\n\nint main(int argc, char** argv)\n{\n    constexpr int num_points = 150;\n    constexpr int num_dims   = 3;\n\n    const Eigen::MatrixXd points = Eigen::MatrixXd::Random(num_dims, num_points);\n\n    Eigen::MatrixXd covariance_matrix(num_points, num_points);\n    for (int i = 0; i < num_points; ++i)\n    {\n        for (int j = i; j < num_points; ++j)\n        {\n            const double covariance = CalcCovariance(points.col(i), points.col(j));\n\n            covariance_matrix(i, j) = covariance;\n            covariance_matrix(j, i) = covariance;\n        }\n    }\n\n    const double log_det       = mathtoolbox::CalcLogDetOfSymmetricPositiveDefiniteMatrix(covariance_matrix);\n    const double log_det_naive = std::log(covariance_matrix.determinant());\n\n    assert(!std::isnan(log_det));\n\n    std::cout << \"log(det(K)) = \" << log_det << std::endl;\n    std::cout << \"log(det(K)) = \" << log_det_naive\n              << \" (calculated by a naive approach, which may suffer from numerical instability)\" << std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "33f083612f4c934bb17ca95a7873f13531995062", "size": 1297, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/log-determinant/main.cpp", "max_stars_repo_name": "yuki-koyama/mathtoolbox", "max_stars_repo_head_hexsha": "eb7449c3c489f465849a74405e72aff016a296f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 195.0, "max_stars_repo_stars_event_min_datetime": "2018-04-28T16:12:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:52:56.000Z", "max_issues_repo_path": "examples/log-determinant/main.cpp", "max_issues_repo_name": "amazing89/mathtoolbox", "max_issues_repo_head_hexsha": "8904bb06ced2ac501594f9574ef1ba3454b8e38e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 52.0, "max_issues_repo_issues_event_min_datetime": "2018-04-15T01:24:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-02T09:14:23.000Z", "max_forks_repo_path": "examples/log-determinant/main.cpp", "max_forks_repo_name": "amazing89/mathtoolbox", "max_forks_repo_head_hexsha": "8904bb06ced2ac501594f9574ef1ba3454b8e38e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 21.0, "max_forks_repo_forks_event_min_datetime": "2018-06-05T04:11:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T13:28:12.000Z", "avg_line_length": 30.1627906977, "max_line_length": 111, "alphanum_fraction": 0.6445643793, "num_tokens": 341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760039, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.7406682031289167}}
{"text": "\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n//#include <s\n\nnamespace gd {\nusing namespace Eigen;\n//using namespace std;\ntypedef Matrix<double, 3, 1> Vector3;\ntypedef Matrix<double, 3, 3> Matrix3;\n\n\n/*\n\n System3(System2(System1(..)))\n\n*/\nclass CoordinateSystem {\npublic:\n\tCoordinateSystem() {\n\t}/*\n\tvirtual Matrix3 matrix(double x, double y, double z) {\n\t\treturn this->matrix_local(x, y, z) * parent->matrix(x, y, z);\n\t}*/\n\tvirtual Vector3 ex(double x, double y, double z) = 0;\n\tvirtual Vector3 ey(double x, double y, double z) = 0;\n\tvirtual Vector3 ez(double x, double y, double z) = 0;\n\t//virtual Vector3 get_origin_cartesian() { return Vector3(0,0,0); }\n\tvirtual Vector3 to_cartesian(Vector3d v) = 0;\n\tvirtual Vector3 from_cartesian(Vector3d v) = 0;\n\n\tMatrix3 basis_matrix(double x, double y, double z) {\n\t\tMatrix3 m;\n\t\tm.block<3,1>(0,0) = ex(x, y, z);\n\t\tm.block<3,1>(0,1) = ey(x, y, z);\n\t\tm.block<3,1>(0,2) = ez(x, y, z);\n\t\treturn m;\n\t}\n\t/*Matrix3 matrix_local(double x, double y, double z) {\n\t\tMatrix3 m;\n\t\tm.block<3,1>(0,0) = ex(x, y, z);\n\t\tm.block<3,1>(0,1) = ey(x, y, z);\n\t\tm.block<3,1>(0,2) = ez(x, y, z);\n\t\treturn m;\n\t}\n\tMatrix3 matrix(Vector3 v) {\n\t\treturn this->matrix(v(0),v(1),v(2));\n\t}\n\n\tMatrix3 transformation_matrix(double x, double y, double z, CoordinateSystem* prime_system) {\n\t\tMatrix3 m1 = this->matrix(x, y, z);\n\t\tMatrix3 m2 = prime_system->matrix(x, y, z);\n\t\treturn m1*m2.transpose();\n\t}*/\n};\n\nclass Cartesian : public CoordinateSystem {\npublic:\n\tVector3 ex(double x, double y, double z) {\n\t\treturn Vector3(1, 0, 0);\n\t}\n\tVector3 ey(double x, double y, double z) {\n\t\treturn Vector3(0, 1, 0);\n\t}\n\tVector3 ez(double x, double y, double z) {\n\t\treturn Vector3(0, 0, 1);\n\t}\n\tVector3 to_cartesian(Vector3d v) {\n\t\treturn v;\n\t}\n\tVector3 from_cartesian(Vector3d v) {\n\t\treturn v;\n\t}\n};\n\nclass Cylindrical : public CoordinateSystem {\npublic:\n\tVector3 ex(double x, double y, double z) {\n\t\tdouble rho = sqrt(x*x+y*y);\n\t\treturn Vector3(x/rho, y/rho, 0);\n\t}\n\tVector3 ey(double x, double y, double z) {\n\t\tdouble rho = sqrt(x*x+y*y);\n\t\treturn Vector3(y/rho, -x/rho, 0);\n\t}\n\tVector3 ez(double x, double y, double z) {\n\t\treturn Vector3(0, 0, 1);\n\t}\n\tVector3 to_cartesian(Vector3d v) {\n\t\tdouble rho = v(0);\n\t\tdouble theta = v(1);\n\t\tdouble z = v(2);\n\t\tdouble x = rho * cos(theta);\n\t\tdouble y = rho * sin(theta);\n\t\tVector3 cartesian(x,y,z);\n\t\treturn cartesian;\n\t}\n\tVector3 from_cartesian(Vector3d v) {\n\t\tdouble x = v(0);\n\t\tdouble y = v(1);\n\t\tdouble z = v(2);\n\t\tdouble rho = sqrt(x*x+y*y);\n\t\tdouble theta = atan2(y,x);\n\t\tVector3 cylindrical(rho,theta,z);\n\t\treturn cylindrical;\n\t}\n};\n\n\nclass SphericalGalactic : public CoordinateSystem {\npublic:\n\tSphericalGalactic() {\n\t\t//rotation = AngleAxisd(M_PI, Vector3::UnitZ());\n\t\t//std::cout << \"rot[\" << rotation << \"]\" << std::endl; \n\t}\n\tVector3 ex(double x, double y, double z) {\n\t\tdouble r = sqrt(x*x+y*y+z*z);\n\t\treturn Vector3(x/r, y/r, z/r);\n\t}\n\tVector3 ey(double x, double y, double z) {\n\t\tdouble rho = sqrt(x*x+y*y);\n\t\treturn Vector3(-y/rho, x/rho, 0);\n\t}\n\tVector3 ez(double x, double y, double z) {\n\t\tdouble r = sqrt(x*x+y*y+z*z);\n\t\tdouble rho = sqrt(x*x+y*y);\n\t\tVector3 v = Vector3(z*x/rho/r, z*y/rho/r, -rho/r);\n\t\treturn v;\n\t}\n\tVector3 to_cartesian(Vector3d v) {\n\t\tdouble r = v(0);\n\t\tdouble phi = v(1);\n\t\tdouble theta = v(2);\n\t\tdouble x = r * sin(theta) * cos(phi);\n\t\tdouble y = r * sin(theta) * sin(phi);\n\t\tdouble z = r * cos(theta); \n\t\tVector3 cartesian(x,y,z);\n\t\treturn cartesian;\n\t}\n\tVector3 from_cartesian(Vector3d cartesian) {\n\t\tdouble x = cartesian(0);\n\t\tdouble y = cartesian(1);\n\t\tdouble z = cartesian(2);\n\t\tdouble r = sqrt(x*x+y*y+z*z);\n\t\tdouble phi = atan2(y,x); \n\t\tdouble theta = acos(z/r);\n\t\tVector3 spherical(r,phi,theta);\n\t\treturn spherical;\n\t}\n};\n\n\n\nclass Coordinate {\npublic:\n\tCoordinateSystem* coordinate_system;\n\tVector3 x;\n\tCoordinate(double x1, double x2, double x3, CoordinateSystem* coordinate_system) : coordinate_system(coordinate_system), x(x1, x2, x3) {\n\t}\n\t/*virtual Matrix3 matrix(double x, double y, double z) {\n\t\treturn this->matrix_local(x, y, z) * parent->matrix(x, y, z);\n\t}\n\tvirtual Vector3 ex(double x, double y, double z) = 0;\n\tvirtual Vector3 ey(double x, double y, double z) = 0;\n\tvirtual Vector3 ez(double x, double y, double z) = 0;\n\t//virtual Vector3 get_origin_cartesian() { return Vector3(0,0,0); }\n\tvirtual Vector3 cartesian_transformation(Vector3 v) { return v;}*/\n\tvirtual Vector3 to_cartesian() {\n\t\treturn coordinate_system->to_cartesian(x);\n\t}\n\t//virtual Vector3 to_cartesian_local(Vector3d v) = 0;\n\t//virtual Vector3 from_cartesian_local(Vector3d v) = 0;\n\t/*Matrix3 matrix_local(double x, double y, double z) {\n\t\tMatrix3 m;\n\t\tm.block<3,1>(0,0) = ex(x, y, z);\n\t\tm.block<3,1>(0,1) = ey(x, y, z);\n\t\tm.block<3,1>(0,2) = ez(x, y, z);\n\t\treturn m;\n\t}\n\tMatrix3 matrix(Vector3 v) {\n\t\treturn this->matrix(v(0),v(1),v(2));\n\t}\n\t\n\tMatrix3 transformation_matrix(double x, double y, double z, CoordinateSystem* prime_system) {\n\t\tMatrix3 m1 = this->matrix(x, y, z);\n\t\tMatrix3 m2 = prime_system->matrix(x, y, z);\n\t\treturn m1*m2.transpose();\n\t}*/\n};\n\nclass VelocityCoordinate {\npublic:\n\tCoordinateSystem* coordinate_system;\n\tVector3 v;\n\tVelocityCoordinate(double v1, double v2, double v3, CoordinateSystem* coordinate_system) : coordinate_system(coordinate_system), v(v1, v2, v3) {\n\t}\n\t/*virtual Matrix3 matrix(double x, double y, double z) {\n\t\treturn this->matrix_local(x, y, z) * parent->matrix(x, y, z);\n\t}\n\tvirtual Vector3 ex(double x, double y, double z) = 0;\n\tvirtual Vector3 ey(double x, double y, double z) = 0;\n\tvirtual Vector3 ez(double x, double y, double z) = 0;\n\t//virtual Vector3 get_origin_cartesian() { return Vector3(0,0,0); }\n\tvirtual Vector3 cartesian_transformation(Vector3 v) { return v;}*/\n\tvirtual Vector3 to_cartesian(double x, double y, double z) {\n\t\treturn \\\n\t\t\tv(0) * coordinate_system->ex(x, y, z) +\\\n\t\t\tv(1) * coordinate_system->ey(x, y, z) +\\\n\t\t\tv(2) * coordinate_system->ez(x, y, z);\n\t}\n\tvirtual Vector3 to_cartesian_vec(Vector3 p) {\n\t\treturn to_cartesian(p(0), p(1), p(2));\n\t}\n\n};\n\nclass ReferenceFrameBase {\npublic:\n\tMatrix3 basis_matrix(double x, double y, double z) {\n\t\tMatrix3 m;\n\t\tm.block<3,1>(0,0) = ex(x, y, z);\n\t\tm.block<3,1>(0,1) = ey(x, y, z);\n\t\tm.block<3,1>(0,2) = ez(x, y, z);\n\t\treturn m;\n\t}\n\tvirtual Vector3 ex(double x, double y, double z) = 0;\n\tvirtual Vector3 ey(double x, double y, double z) = 0;\n\tvirtual Vector3 ez(double x, double y, double z) = 0;\n\tvirtual Vector3 to_global(Vector3 local) = 0;\n\tvirtual Vector3 to_local(Vector3 global) = 0;\n\tvirtual Vector3 to_global_velocity(Vector3 v_local) { return v_local; }\n\tvirtual Vector3 to_local_velocity(Vector3 v_global) { return v_global; }\n};\n\n\nclass Position {\npublic:\n\tCoordinate* c;\n\tReferenceFrameBase* f;\n\tPosition(Coordinate* c, ReferenceFrameBase* f) : c(c), f(f) {\n\t}\n\tVector3 to(ReferenceFrameBase* target_frame) {\n\t\treturn target_frame->to_local( f->to_global(c->to_cartesian()) );;\n\t}\n\tVector3 to_global() {\n\t\treturn f->to_global(c->to_cartesian());\n\t}\n\tVector3 to_coordinate_system(ReferenceFrameBase* target_frame, CoordinateSystem* target_coordinate_system) {\n\t\tVector3 v = to(target_frame);\n\t\treturn target_coordinate_system->from_cartesian(v);\n\t}\n};\n\nclass Velocity {\npublic:\n\tVelocityCoordinate* vc;\n\tReferenceFrameBase* f;\n\tPosition* p;\n\tReferenceFrameBase* pos_frame;\n\tVelocity(VelocityCoordinate* vc, ReferenceFrameBase* f, Position* p, ReferenceFrameBase* pos_frame) : vc(vc), f(f), p(p), pos_frame(pos_frame) {\n\t}\n\tVector3 to_coordinate_system(ReferenceFrameBase* target_frame, CoordinateSystem* target_coordinate_system) {\n\t\tVector3 v = to(target_frame);\n\t\tVector3 local_coordinate = p->to(target_frame); //f->to_global(Vector3(0, 0, 0));\n\t\tdouble x = local_coordinate(0);\n\t\tdouble y = local_coordinate(1);\n\t\tdouble z = local_coordinate(2);\n\t\t//std::cout << \"[x,y,z = ( \" << x << \", \" << y << \", \" << z <<\")]\" << std::endl;\n\t\tMatrix3 m = target_coordinate_system->basis_matrix(x, y, z);\n\t\treturn m.inverse() * v; \n\t}\n\tVector3 to(ReferenceFrameBase* target_frame) {\n\t\tVector3 global_velocity = to_global();\n\t\treturn target_frame->to_local_velocity(global_velocity);\n\t}\n\tVector3 to_global() {\n\t\tVector3 local_coordinate = p->to(pos_frame); //f->to_global(Vector3(0, 0, 0));\n\t\tVector3 local_velocity = vc->to_cartesian_vec(local_coordinate);\n\t\tVector3 global_velocity = f->to_global_velocity(local_velocity);\n\t\treturn global_velocity;\n\t}\t\n};\n\nclass ZeroReferenceFrame : public ReferenceFrameBase {\npublic:\n\tZeroReferenceFrame()  {\n\t}\n\tVector3 ex(double x, double y, double z) {\n\t\treturn Vector3(1, 0, 0);\n\t}\n\tVector3 ey(double x, double y, double z) {\n\t\treturn Vector3(0, 1, 0);\n\t}\n\tVector3 ez(double x, double y, double z) {\n\t\treturn Vector3(0, 0, 1);\n\t}\n\tvirtual Vector3 to_global(Vector3 local) { return local; }\n\tvirtual Vector3 to_local(Vector3 global) { return global; }\n};\n\nclass ReferenceFrame : public ReferenceFrameBase {\npublic:\n\tVector3 x0;\n\tReferenceFrameBase* parent;\n\tReferenceFrame(Position* origin, ReferenceFrameBase* parent) : x0(origin->to(parent)), parent(parent) {\n\t}\n\tvirtual Vector3 to_global(Vector3 local) { return parent->to_global(local + x0); }\n\tvirtual Vector3 to_local(Vector3 global) { return parent->to_local(global) - x0; }\n\tVector3 ex(double x, double y, double z) {\n\t\treturn Vector3(1, 0, 0);\n\t}\n\tVector3 ey(double x, double y, double z) {\n\t\treturn Vector3(0, 1, 0);\n\t}\n\tVector3 ez(double x, double y, double z) {\n\t\treturn Vector3(0, 0, 1);\n\t}\n};\n\nclass RotatedReferenceFrame : public ReferenceFrameBase {\npublic:\n\tMatrix3 rotation;\n\tMatrix3 rotation_inverse;\n\tReferenceFrameBase *parent;\n\tRotatedReferenceFrame(double angle, ReferenceFrameBase* parent) : parent(parent) {\n\t\trotation = AngleAxisd(angle, Vector3::UnitZ());\n\t\trotation_inverse = rotation.inverse();\n\t}\n\tvirtual Vector3 to_global_velocity(Vector3 v_local) { return parent->to_global_velocity(rotation*v_local); }\n\tvirtual Vector3 to_local_velocity(Vector3 v_global) { return rotation_inverse*parent->to_local_velocity(v_global); }\n\tvirtual Vector3 to_global(Vector3 local) { return parent->to_global(rotation*local); }\n\tvirtual Vector3 to_local(Vector3 global) { return rotation_inverse*parent->to_local(global); }\n\t//Vector3 get_origin_cartesian() { return origin->to_cartesian(); }\n\tVector3 ex(double x, double y, double z) {\n\t\treturn rotation * Vector3::UnitX();\n\t}\n\tVector3 ey(double x, double y, double z) {\n\t\treturn rotation * Vector3::UnitY();\n\t}\n\tVector3 ez(double x, double y, double z) {\n\t\treturn rotation * Vector3::UnitZ();\n\t}\n};\n\nclass EqReferenceFrame : public ReferenceFrameBase {\npublic:\n\tMatrix3 rotation;\n\tMatrix3 rotation_inverse;\n\tReferenceFrameBase *parent;\n\tEqReferenceFrame(double theta0, double a_NGP, double d_NGP, ReferenceFrameBase* parent) : parent(parent) {\n\t\tMatrix3 a,b,c;\n\t\tc << \tcos(a_NGP),  sin(a_NGP), 0,\n\t\t\t\tsin(a_NGP), -cos(a_NGP), 0,\n\t\t\t\t0, 0, 1;\n\t\tb << \t-sin(d_NGP), 0, cos(d_NGP),\n\t\t\t\t0, -1, 0,\n\t\t\t\tcos(d_NGP), 0, sin(d_NGP);\n\t\ta << \tcos(theta0),  sin(theta0), 0,\n\t\t\t\tsin(theta0), -cos(theta0), 0,\n\t\t\t\t0, 0, 1;\n\t\trotation = a*b*c;\n\t\trotation_inverse = rotation.inverse();\n\t\t//std::cout << \"[\" << rotation << \"]\" << std::endl;\n\t\t//std::cout << rotation_inverse << std::endl;\n\t}\n\tvirtual Vector3 to_global_velocity(Vector3 v_local) { return parent->to_global_velocity(rotation*v_local); }\n\tvirtual Vector3 to_local_velocity(Vector3 v_global) { return rotation_inverse*parent->to_local_velocity(v_global); }\n\tvirtual Vector3 to_global(Vector3 local) { return parent->to_global(rotation*local); }\n\tvirtual Vector3 to_local(Vector3 global) { return rotation_inverse*parent->to_local(global); }\n\t//Vector3 get_origin_cartesian() { return origin->to_cartesian(); }\n\tVector3 ex(double x, double y, double z) {\n\t\treturn rotation * Vector3::UnitX();\n\t}\n\tVector3 ey(double x, double y, double z) {\n\t\treturn rotation * Vector3::UnitY();\n\t}\n\tVector3 ez(double x, double y, double z) {\n\t\treturn rotation * Vector3::UnitZ();\n\t}\n};\n\nclass MovingReferenceFrame : public ReferenceFrameBase {\npublic:\n\tReferenceFrameBase* parent;\n\tVector3 velocity_frame;\n\tMovingReferenceFrame(Velocity* velocity , ReferenceFrameBase* parent) : parent(parent) {\n\t\tvelocity_frame = velocity->to(parent);\n\t}\n\tvirtual Vector3 to_global_velocity(Vector3 v_local) { return parent->to_global_velocity(v_local+velocity_frame); }\n\tvirtual Vector3 to_local_velocity(Vector3 v_global) { return parent->to_local_velocity(v_global)-velocity_frame; }\n\tvirtual Vector3 to_global(Vector3 local) { return parent->to_global(local); }\n\tvirtual Vector3 to_local(Vector3 global) { return parent->to_local(global); }\n\tVector3 ex(double x, double y, double z) {\n\t\treturn Vector3::UnitX();\n\t}\n\tVector3 ey(double x, double y, double z) {\n\t\treturn Vector3::UnitY();\n\t}\n\tVector3 ez(double x, double y, double z) {\n\t\treturn Vector3::UnitZ();\n\t}\n};\n\n\n\n/*\nclass TranslatedReferenceFrame : public CoordinateSystem {\npublic:\n\tVector3 translation;\n\tTranslatedReferenceFrame(double x, double y, double z, CoordinateSystem* parent) : CoordinateSystem(parent), translation(x, y, z) {\n\t}\n\tVector3 ex(double x, double y, double z) {\n\t\treturn Vector3(1, 0, 0);\n\t}\n\tVector3 ey(double x, double y, double z) {\n\t\treturn Vector3(0, 1, 0);\n\t}\n\tVector3 ez(double x, double y, double z) {\n\t\treturn Vector3(0, 0, 1);\n\t}\n\tVector3 to_cartesian_local(Vector3d v) {\n\t\treturn v+translation;\n\t}\n\tVector3 from_cartesian_local(Vector3d cartesian) {\n\t\treturn cartesian-translation;\n\t}\n};*/\n/*\nclass Cylindrical : public CoordinateSystem {\npublic:\n\tPosition* origin;\n\tCylindrical(Position* origin) : origin(origin) {\n\t}\n\tVector3 get_origin_cartesian() { return origin->to_cartesian(); }\n\tVector3 ex(double x, double y, double z) {\n\t\tdouble rho = sqrt(x*x+y*y);\n\t\treturn Vector3(x/rho, y/rho, 0);\n\t}\n\tVector3 ey(double x, double y, double z) {\n\t\tdouble rho = sqrt(x*x+y*y);\n\t\treturn Vector3(y/rho, -x/rho, 0);\n\t}\n\tVector3 ez(double x, double y, double z) {\n\t\treturn Vector3(0, 0, 1);\n\t}\n\tVector3 to_cartesian_local(Vector3d v) {\n\t\tdouble rho = v(0);\n\t\tdouble theta = v(1);\n\t\tdouble z = v(2);\n\t\tdouble x = rho * cos(theta);\n\t\tdouble y = rho * sin(theta);\n\t\tVector3 cartesian(x,y,z);\n\t\treturn cartesian;\n\t}\n\tVector3 from_cartesian_local(Vector3d v) {\n\t\tdouble x = v(0);\n\t\tdouble y = v(1);\n\t\tdouble z = v(2);\n\t\tdouble rho = sqrt(x*x+y*y);\n\t\tdouble theta = atan2(y,x);\n\t\tVector3 cylindrical(rho,theta,z);\n\t\treturn cylindrical;\n\t}\n};\n*/\n/*\nclass RotatedCoordinateSystem : public CoordinateSystem {\npublic:\n\tMatrix3 rotation;\n\tMatrix3 rotation_inverse;\n\tRotatedCoordinateSystem(CoordinateSystem* parent) : CoordinateSystem(parent) {\n\t\trotation = AngleAxisd(M_PI, Vector3::UnitZ());\n\t\trotation_inverse = rotation.inverse();\n\t}\n\t//Vector3 get_origin_cartesian() { return origin->to_cartesian(); }\n\tVector3 ex(double x, double y, double z) {\n\t\treturn rotation * parent->ex(x, y, z);\n\t}\n\tVector3 ey(double x, double y, double z) {\n\t\treturn rotation * parent->ey(x, y, z);\n\t}\n\tVector3 ez(double x, double y, double z) {\n\t\treturn rotation * parent->ez(x, y, z);\n\t}\n\tVector3 to_cartesian_local(Vector3d v) {\n\t\t//return rotation*parent->to_cartesian(v);\n\t\treturn rotation*v;\n\t}\n\tVector3 from_cartesian_local(Vector3d cartesian) {\n\t\t//return parent->from_cartesian(rotation_inverse * cartesian);\n\t\treturn rotation_inverse*cartesian;\n\t}\n};\n\n*/\n\n\n/*\nclass Spherical {\n\t\n\tVector3 ex(double x, double y, double z) {\n\t\t\n\t}\n\tVector3 ey(double x, double y, double z) {\n\t}\n\tVector3 ez(double x, double y, double z) {\n\t}\n};*/\n\n}", "meta": {"hexsha": "23743c799277ae99e89069f0ad6afd9fb1c1075c", "size": 15361, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "gdfast/src/coordinate_systems.hpp", "max_stars_repo_name": "maartenbreddels/mab", "max_stars_repo_head_hexsha": "112dcfbc4a74b07aff13d489b3776bca58fe9bdf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-01T04:10:34.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-01T04:10:34.000Z", "max_issues_repo_path": "gdfast/src/coordinate_systems.hpp", "max_issues_repo_name": "maartenbreddels/mab", "max_issues_repo_head_hexsha": "112dcfbc4a74b07aff13d489b3776bca58fe9bdf", "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": "gdfast/src/coordinate_systems.hpp", "max_forks_repo_name": "maartenbreddels/mab", "max_forks_repo_head_hexsha": "112dcfbc4a74b07aff13d489b3776bca58fe9bdf", "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.1196078431, "max_line_length": 145, "alphanum_fraction": 0.6897988412, "num_tokens": 4592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797051879431, "lm_q2_score": 0.8128673087708699, "lm_q1q2_score": 0.7406681947627579}}
{"text": "#include <kortex/eigen_conversion.h>\n\n#include <Eigen/Eigenvalues>\n\n#include <iostream>\n\nnamespace kortex {\n\n    int matrix_invert_g_lu( const double* A, int ar, double* iA ) {\n        passert_pointer( A && iA );\n        assert_pointer_size( ar );\n        Eigen::MatrixXd m;\n        convert_mat( A, ar, ar, ar, m );\n        int asz = ar*ar;\n        convert_mat( m.inverse(), iA, asz );\n        return !is_valid_array(iA,asz);\n    }\n\n    //\n    // Least Square Solvers\n    //\n    void lsq_solver_svd( const double* A, int ar, int ac, int lda,\n                         const double* B, int bc, int ldb,\n                         double* x, int xsz ) {\n        Eigen::MatrixXd eA; convert_mat( A, ar, ac, lda, eA );\n        Eigen::MatrixXd eB; convert_mat( B, ar, bc, ldb, eB );\n        Eigen::MatrixXd eX = eA.jacobiSvd( Eigen::ComputeThinU | Eigen::ComputeThinV ).solve(eB);\n        convert_mat( eX, x, xsz );\n        assert_array( \"EIGEN - SVD LSQ\", x, xsz );\n    }\n\n    void lsq_solver_cholesky( const double* A, int ar, int lda,\n                              const double* B, int bc, int ldb,\n                              double* x, int xsz ) {\n        assert_statement( is_symmetric( A, ar, ar ), \"A is not symmetric - call lsq_solver_svd\" );\n        Eigen::MatrixXd eA; convert_mat( A, ar, ar, lda, eA );\n        Eigen::MatrixXd eB; convert_mat( B, ar, bc, ldb, eB );\n        Eigen::MatrixXd eX = eA.ldlt().solve(eB);\n        convert_mat( eX, x, xsz );\n        assert_array( \"EIGEN - CHOLESKY LSQ\", x, xsz );\n    }\n\n    void lsq_solver_svd( const KMatrix& A, const KMatrix& B, KMatrix& x ) {\n        x.resize( A.w(), B.w() );\n        lsq_solver_svd( A(), A.h(), A.w(), A.w(), B(), B.w(), B.w(), x.get_pointer(), x.size() );\n    }\n\n\n    void lsq_solver_cholesky( const KMatrix& A, const KMatrix& B, KMatrix& x ) {\n        x.resize( A.w(), B.w() );\n        lsq_solver_cholesky( A(), A.h(), A.w(), B(), B.w(), B.w(), x.get_pointer(), x.size() );\n    }\n\n    //\n    //\n    //\n    bool find_eigenvalues( const KMatrix& m, vector<double>& eig_real, vector<double>& eig_imag ) {\n        eig_real.clear();\n        eig_imag.clear();\n\n        passert_statement( m.is_square(), \"matrix needs to be square\" );\n        Eigen::MatrixXd em;\n        convert_mat( m, em );\n        Eigen::EigenSolver<Eigen::MatrixXd> esolver(em);\n\n        auto eigs = esolver.eigenvalues();\n\n        int n_eigs = eigs.rows();\n        for( int i=0; i<n_eigs; i++ ) {\n            std::complex<double> r = eigs.col(0)[i];\n            eig_real.push_back( r.real() );\n            eig_imag.push_back( r.imag() );\n        }\n\n        return true;\n    }\n\n\n\n}\n", "meta": {"hexsha": "d2c79bb759d052426a12ac06b547c4dac2bf550e", "size": 2619, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/linear_algebra_eigen.cc", "max_stars_repo_name": "etola/kortex", "max_stars_repo_head_hexsha": "172877fde712dce2e5ecf9bc9b5ec3b86d8e085f", "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/linear_algebra_eigen.cc", "max_issues_repo_name": "etola/kortex", "max_issues_repo_head_hexsha": "172877fde712dce2e5ecf9bc9b5ec3b86d8e085f", "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/linear_algebra_eigen.cc", "max_forks_repo_name": "etola/kortex", "max_forks_repo_head_hexsha": "172877fde712dce2e5ecf9bc9b5ec3b86d8e085f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-11-29T12:50:25.000Z", "max_forks_repo_forks_event_max_datetime": "2017-09-13T21:29:01.000Z", "avg_line_length": 32.3333333333, "max_line_length": 99, "alphanum_fraction": 0.5395189003, "num_tokens": 760, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.888758793492457, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7406245655960187}}
{"text": "#include <Eigen/Dense>\n#include <Eigen/SparseLU>\n#include <iostream>\n\nint main() {\n    Eigen::MatrixXd A(2, 2);\n    A << 3.0, -1.5,\n         2.5,   0.5; \n    std::cout << \"A =\" << std::endl << A << std::endl;\n    Eigen::VectorXd b(2);\n    b << 3.5, -2.5;\n    std::cout << \"b =\" << std::endl << b << std::endl;\n    auto decomposition = A.partialPivLu();\n    Eigen::VectorXd x = decomposition.solve(b);\n    std::cout << \"x =\" << std::endl << x << std::endl;\n    std::cout << \"A*x - b =\" << std::endl << A*x - b << std::endl;\n    return 0;\n}\n\n", "meta": {"hexsha": "e257c02d12577c5eeffd59e424b65059909c2dc9", "size": 540, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source-code/Eigen/solve_eqns.cpp", "max_stars_repo_name": "gjbex/Scientific-C-", "max_stars_repo_head_hexsha": "d7aeb88743ffa2a43b1df1569a9200b2447f401c", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 115.0, "max_stars_repo_stars_event_min_datetime": "2015-03-23T13:34:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T00:27:21.000Z", "max_issues_repo_path": "source-code/Eigen/solve_eqns.cpp", "max_issues_repo_name": "gjbex/Scientific-C-", "max_issues_repo_head_hexsha": "d7aeb88743ffa2a43b1df1569a9200b2447f401c", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 56.0, "max_issues_repo_issues_event_min_datetime": "2015-02-25T15:04:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T07:42:48.000Z", "max_forks_repo_path": "source-code/Eigen/solve_eqns.cpp", "max_forks_repo_name": "gjbex/Scientific-C-", "max_forks_repo_head_hexsha": "d7aeb88743ffa2a43b1df1569a9200b2447f401c", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 59.0, "max_forks_repo_forks_event_min_datetime": "2015-11-26T11:44:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T00:27:22.000Z", "avg_line_length": 27.0, "max_line_length": 66, "alphanum_fraction": 0.5, "num_tokens": 187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765257642906, "lm_q2_score": 0.8104789155369047, "lm_q1q2_score": 0.740515559752969}}
{"text": "#ifndef KALMAN_FILTER_HPP_\n\n#define KALMAN_FILTER_HPP_\n#include <Eigen/Dense>\n\nnamespace mineral_deposit_tracking\n{\n\ntemplate<int StateSize>\nclass KalmanFilter\n{\npublic:\n\tusing VectorType = Eigen::Matrix<double, StateSize, 1>;\n\tusing MatrixType = Eigen::Matrix<double, StateSize, StateSize>;\n\n\tKalmanFilter(\n\t\tconst MatrixType & transition_matrix,\n\t\tconst MatrixType & process_covariance,\n\t\tconst MatrixType & observation_matrix)\n\t:\ttransition_matrix_(transition_matrix),\n\t\tprocess_covariance_(process_covariance),\n\t\tobservation_matrix_(observation_matrix),\n\t\testimate_(VectorType::Zero()),\n\t\testimate_covariance_(MatrixType::Identity() * 500)\n\t{\n\t}\n\n\tvoid Reset(const VectorType & initial_state, const MatrixType & initial_covariance)\n\t{\n\t\testimate_ = initial_state;\n\t\testimate_covariance_ = initial_covariance;\n\t}\n\n\tvoid TimeUpdate()\n\t{\n\t\testimate_ = transition_matrix_ * estimate_;\n\t\testimate_covariance_ = (transition_matrix_ * estimate_covariance_ * transition_matrix_.transpose()) + process_covariance_;\n\t}\n\n\tvoid MeasurementUpdate(const VectorType & measurement, const MatrixType & measurement_covariance)\n\t{\n\t\tconst MatrixType innovation_covariance = (observation_matrix_ * estimate_covariance_ * observation_matrix_.transpose()) + measurement_covariance;\n\n\t\tconst MatrixType kalman_gain = estimate_covariance_ * observation_matrix_.transpose() * innovation_covariance.inverse();\n\n\t\testimate_ = estimate_ + (kalman_gain * (measurement - (observation_matrix_ * estimate_)) );\n\n\t\tconst MatrixType tmp = MatrixType::Identity() - (kalman_gain * observation_matrix_);\n\n\t\testimate_covariance_ = ( tmp * estimate_covariance_ * tmp.transpose() ) + ( kalman_gain * measurement_covariance * kalman_gain.transpose() );\n\n\t}\n\n\tconst VectorType & GetEstimate() const\n\t{\n\t\treturn estimate_;\n\t}\n\n\tconst MatrixType & GetEstimateCovariance() const\n\t{\n\t\treturn estimate_covariance_;\n\t}\n\nprivate:\n\tconst MatrixType transition_matrix_;\n\tconst MatrixType process_covariance_;\n\tconst MatrixType observation_matrix_;\n\tVectorType estimate_;\n\tMatrixType estimate_covariance_;\n};\n\n\n}\n\n#endif", "meta": {"hexsha": "7aac4be80d94b123971a5bb0b9d56203c4d17967", "size": 2072, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mineral_deposit_tracking/src/kalman_filter.hpp", "max_stars_repo_name": "JesseDill/software-training", "max_stars_repo_head_hexsha": "016bbcd76a923dab5b852ff221293f5e2d0bee49", "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": "mineral_deposit_tracking/src/kalman_filter.hpp", "max_issues_repo_name": "JesseDill/software-training", "max_issues_repo_head_hexsha": "016bbcd76a923dab5b852ff221293f5e2d0bee49", "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": "mineral_deposit_tracking/src/kalman_filter.hpp", "max_forks_repo_name": "JesseDill/software-training", "max_forks_repo_head_hexsha": "016bbcd76a923dab5b852ff221293f5e2d0bee49", "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.6266666667, "max_line_length": 147, "alphanum_fraction": 0.7857142857, "num_tokens": 467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741268224331, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.7404357463661961}}
{"text": "/**\r\n *  @file    Mesh.hpp\r\n *  @brief   Definition of the finite difference mesh.\r\n *  @author  Francois Roy\r\n *  @date    12/04/2019\r\n */\r\n#ifndef MESH_H\r\n#define MESH_H\r\n\r\n#include <stdexcept>\r\n#include <vector>\r\n#include <unordered_set>\r\n#include <Eigen/Core>\r\n#include \"spdlog/spdlog.h\"\r\n#include \"utils/Utils.hpp\"\r\n\r\nnamespace numerical {\r\n\r\nnamespace fdm {\r\n\r\n/*!\r\n* Holds data structures for a uniform mesh on a hypercube in\r\n* space, plus a uniform mesh in time.\r\n*\r\n*  \\anchor fig_mesh\r\n*  \\image html bloc.png <\"Figure 1: A typical mesh for a bloc. The scene shows \r\n*  the bottom (orange), left (magenta) and front (blue) boundaries.\">\r\n*  \\image latex bloc.eps \"bloc\" width=10cm\r\n*\r\n* @param lengths List of 2-lists of min and max coordinates in each spatial \r\n* direction.\r\n* @param t0 The initial time in time mesh.\r\n* @param tend The final time in time mesh.\r\n* @param nt Number of cells in time mesh.\r\n* @param n List of number of cells in the spatial directions.\r\n*/\r\ntemplate <typename T>\r\nclass Mesh {\r\ntypedef Eigen::Matrix<T, Eigen::Dynamic, 1> Vec;\r\nprivate:\r\n\tconst std::vector<std::vector<T>> m_lengths;\r\n\tconst T m_t0, m_tend;\r\n\tT m_dt;\r\n\tconst std::vector<int> m_nx;\r\n\tstd::vector<T> m_dx;\r\n\tconst int m_nt;\r\n\tstd::vector<Vec> m_x;\r\n\tVec m_t;\r\n\tstd::size_t m_dim; \r\npublic:\r\n\tMesh(const std::vector<std::vector<T>>& lengths, T t0, T tend, \r\n\t\tconst std::vector<int>& nx, int nt) \r\n\t  : m_lengths(lengths),\r\n\t  m_t0(t0),\r\n      m_tend(tend),\r\n      m_nx(nx),\r\n      m_nt(nt)\r\n\t{\r\n        m_dim = m_lengths.size(); \r\n        if (m_dim < 1){\r\n        \tthrow std::invalid_argument(\r\n        \t\t\"At least one 2-lists of min and max coords must be given.\"\r\n        \t\t);\r\n        }\r\n        if (m_nx.size() != m_lengths.size()){\r\n        \tthrow std::invalid_argument(\"n and lengths have different size.\");\r\n        }\r\n        for(int i=0; i<m_dim; ++i){\r\n        \tif(m_lengths[i].size() != 2){\r\n        \t\tthrow std::invalid_argument(\"length item is not a 2-list.\");\r\n        \t}\r\n        \tm_dx.push_back(T (m_lengths[i][1] - m_lengths[i][0])/m_nx[i]);\r\n        }\r\n        m_dt = m_tend / T(nt);\r\n        for(int i=0; i<m_dim; ++i){\r\n        \tVec temp(m_nx[i] + 1);\r\n        \tfor(int j=0; j<m_nx[i] + 1; ++j){\r\n        \t\ttemp[j] = j * m_dx[i];\r\n        \t}\r\n            m_x.push_back(temp);\r\n        }\r\n        m_t = Vec(m_nt + 1);\r\n        for(int i=0; i<m_nt; ++i){\r\n        \tm_t[i] = i * m_nt;\r\n        }\r\n\t}\r\n\r\n    /*!\r\n    * If 1D, \\c ny\\c and \\c nz\\c = 0, if 2D \\c nz\\c = 0, else all are > 1. See \r\n    * \\ref fig_mesh\r\n    *\r\n    * @return The number of divisions per axis.\r\n    */\r\n    std::vector<int> division_per_axis(){\r\n        int n_x = m_nx[0];\r\n        int n_y = 0;\r\n        int n_z = 0;\r\n        if (m_dim >= 2){\r\n            n_y = m_nx[1];\r\n        }\r\n        if (m_dim == 3) {\r\n            n_z = m_nx[2];\r\n        }\r\n        return {n_x, n_y, n_z};\r\n    }\r\n    \r\n    /*!\r\n    *  The indices of the nodes on the left boundary, \r\n    *  i.e. at x = lengths[0][0].\r\n    */\r\n    std::vector<int> left(){\r\n        std::vector<int> nx = division_per_axis();\r\n        std::unordered_set<int> temp1;\r\n        std::vector<int> temp;\r\n        if (m_dim == 1){\r\n            temp = {0};\r\n        }\r\n        else if (m_dim == 2){\r\n            for (int j=0; j<nx[1] + 1; ++j){\r\n                temp.push_back(j * (nx[0] + 1));\r\n            }\r\n        }\r\n        else {  // m_dim = 3\r\n            for (int j=0; j<nx[1] + 1; ++j){\r\n                for (int k=0; k<nx[2] + 1; ++k){\r\n                    temp.push_back(j * (nx[0] + 1) + \r\n                        k * ((nx[0] + 1)*(nx[1] + 1)));\r\n                }\r\n            }\r\n        }\r\n        return temp;\r\n    }\r\n\r\n    /*!\r\n    *  The indices of the nodes on the right boundary, i.e. at \r\n    *  x = lengths[0][1]. It is just left + n_x.\r\n    */\r\n    std::vector<int> right(){\r\n        std::vector<int> nx = division_per_axis();\r\n        std::vector<int> out = left();\r\n        for(int& i : out){\r\n            i += nx[0];\r\n        }\r\n    \treturn out;\r\n    }\r\n\r\n    /*!\r\n    *  The indices of the nodes on the bottom boundary, i.e. at \r\n    *  y = lengths[1][0]. Only for 2D and 3D models.\r\n    */\r\n    std::vector<int> bottom(){\r\n        std::vector<int> nx = division_per_axis();\r\n        std::vector<int> temp;\r\n        if (m_dim == 2){\r\n            for (int i=0; i<nx[0] + 1; ++i){\r\n                temp.push_back(i);\r\n            }\r\n        }\r\n        else {  // m_dim = 3\r\n            for (int i=0; i<nx[0] + 1; ++i){\r\n                for (int k=0; k<nx[2] + 1; ++k){\r\n                    temp.push_back(i + k * (nx[0] + 1) * (nx[1] + 1));\r\n                }\r\n            }\r\n        }\r\n        return temp;\r\n    }\r\n\r\n    /*!\r\n    *  The indices of the nodes on the top boundary i.e. at \r\n    *  y = lengths[1][1]. Only for 2D and 3D models.\r\n    */\r\n    std::vector<int> top(){\r\n    \tstd::vector<int> nx = division_per_axis();\r\n        std::vector<int> out = bottom();\r\n        if (m_dim == 2){\r\n            for(int& i : out){\r\n                i += nx[1] * (nx[0] + 1);\r\n            }\r\n        }\r\n        else { // 3D\r\n            for(int& i : out){\r\n                i += (nx[0] + 1) * (nx[0] + 1);\r\n            }\r\n        }\r\n        return out;\r\n    }\r\n\r\n    /*!\r\n    *  The indices of the nodes on the front, i.e. at \r\n    *  z = length[2][0]. Only for 3D models.\r\n    */\r\n    std::vector<int> front(){\r\n        std::vector<int> nx = division_per_axis();\r\n        std::vector<int> out = back();\r\n        for(int& i : out){\r\n            i += nx[2] * (nx[0] + 1) * (nx[1] + 1);\r\n        }\r\n        return out;\r\n    }\r\n\r\n    /*!\r\n    *  The indices of the nodes on the back boundary, i.e. at \r\n    *  z = length[2][1]. Only for 3D models.\r\n    */\r\n    std::vector<int> back(){\r\n        std::vector<int> nx = division_per_axis();\r\n        std::vector<int> temp;\r\n        for (int i=0; i<nx[0] + 1; ++i){\r\n                for (int j=0; j<nx[1] + 1; ++j){\r\n                    temp.push_back(i + j * (nx[0] + 1));\r\n                }\r\n            }\r\n        return temp;\r\n    }\r\n\r\n    /*!\r\n    * @return The indices of the external boundaries.\r\n    */\r\n    std::vector<int> boundaries(){\r\n        // points in 1D\r\n        // lines in 2D\r\n        // surfaces in 3D\r\n        std::vector<int> nx = division_per_axis();\r\n        std::vector<int> temp;\r\n        if (m_dim == 1){\r\n            temp = {0, nx[0]};\r\n        }\r\n        else if (m_dim == 2){\r\n            for (int j=0; j<nx[1] + 1; ++j){\r\n                temp.push_back(j * (nx[0] + 1)); // left\r\n                temp.push_back(j * (nx[0] + 1) + nx[0]); // right\r\n            }\r\n            for (int i=0; i<nx[0] + 1; ++i){\r\n                temp.push_back(i);  // bottom \r\n                temp.push_back(i + nx[1] * (nx[0] + 1));  // top \r\n            }\r\n            // make unique\r\n            std::sort(temp.begin(), temp.end());\r\n            auto last = std::unique(temp.begin(), temp.end());\r\n            temp.erase(last, temp.end()); \r\n        }\r\n        else {  // m_dim = 3\r\n            for (int j=0; j<nx[1] + 1; ++j){\r\n                for (int k=0; k<nx[2] + 1; ++k){\r\n                    temp.push_back(j * (nx[0] + 1) + \r\n                        k * ((nx[0] + 1)*(nx[1] + 1)));  // left\r\n                    temp.push_back(j * (nx[0] + 1) + \r\n                        k * ((nx[0] + 1)*(nx[1] + 1)) + nx[0]); // right\r\n                }\r\n            }\r\n            for (int i=0; i<nx[0] + 1; ++i){\r\n                for (int k=0; k<nx[2] + 1; ++k){\r\n                    temp.push_back(i + k * (nx[0] + 1) * \r\n                        (nx[1] + 1));  // bottom\r\n                    temp.push_back(i + k * (nx[0] + 1) * \r\n                        (nx[1] + 1) + (nx[0] + 1) * (nx[0] + 1));  // top\r\n                }\r\n            }\r\n            for (int i=0; i<nx[0] + 1; ++i){\r\n                for (int j=0; j<nx[1] + 1; ++j){\r\n                    temp.push_back(i + j * (nx[0] + 1));  // back\r\n                    temp.push_back(i + j * (nx[0] + 1) + \r\n                        nx[2] * (nx[0] + 1) * (nx[1] + 1));   // front\r\n                }\r\n            }\r\n            // make unique\r\n            std::sort(temp.begin(), temp.end());\r\n            auto last = std::unique(temp.begin(), temp.end());\r\n            temp.erase(last, temp.end()); \r\n        }\r\n        return temp;\r\n    }\r\n\r\n    /*!\r\n    *  \r\n    */\r\n    std::vector<int> domain(){\r\n        std::vector<int> nx = division_per_axis();\r\n        std::vector<int> all;\r\n        if (m_dim == 1){\r\n            all == utils::linear_spaced<int>(0, nx[0], nx[0] + 1);\r\n        }\r\n        else if (m_dim ==2){\r\n            all == utils::linear_spaced<int>(0, (nx[0] + 1) * (nx[1] + 1) - 1, \r\n                (nx[0] + 1) * (nx[1] + 1));\r\n        } else {\r\n            all == utils::linear_spaced<int>(0, \r\n                (nx[0] + 1) * (nx[1] + 1) * (nx[2] + 1) - 1, \r\n                (nx[0] + 1) * (nx[1] + 1) * (nx[2] + 1));\r\n        }\r\n        return all;\r\n    }\r\n\r\n    /*!\r\n    *  @return The interior nodes.\r\n    */\r\n    std::vector<int> interior(){\r\n        return {0};\r\n    }\r\n\r\n    /*!\r\n    *  Returns the boundary nodes in 3D.\r\n    *  @return The surfaces. \r\n    */\r\n    std::vector<int> surfaces(){\r\n        std::vector<int> out;\r\n        if (m_dim == 3){\r\n            out = boundaries();\r\n        }\r\n        return out;\r\n    }\r\n\r\n    /*!\r\n    *  2D, 3D \r\n    */\r\n    std::vector<int> edges(){\r\n        // TODO define in 3D\r\n        // boundaries in 2D\r\n        return {0};\r\n    }\r\n\r\n    /*!\r\n    *  1D, 2D, 3D \r\n    */\r\n    std::vector<int> corners(){\r\n        // TODO define in 3D\r\n        // 2D: 0, nx, ny * (nx+1), (ny+1) * (nx+1) -1\r\n        // boundaries in 1D\r\n        return {0};\r\n    }\r\n\r\n\t/*!\r\n\t* @return the space dimension.\r\n\t*/\r\n\tstd::size_t dim(){\r\n\t\treturn m_dim;\r\n\t}\r\n\t/*!\r\n\t* @return the space increment for each dimension.\r\n\t*/\r\n\tstd::vector<T> dx() {\r\n\t\treturn m_dx;\r\n\t}\r\n\r\n    /*!\r\n    * Defines a mapping \\f$m(i, j, k)\\f$ from a mesh point with indices \r\n    * \\f$(i, j, k)\\f$ to the corresponding unknown index \\f$p\\f$ in the \r\n    * equation system:\r\n    *\r\n    * \\f[\r\n    *  p = m(i, j, k) = i+ j(n_x + 1) + k((n_x + 1)(n_y+1)))\r\n    * \\f]\r\n    *\r\n    * where \\f$n_x\\f$  and \\f$n_y\\f$ are the number of division along the \r\n    * \\f$x\\f$- and \\f$y\\f$-directions.\r\n    *\r\n    * We number the points along the x axis, starting with y = y_0, and \r\n    * z = z_0. We then progress one mesh line at a time \r\n    * (from y = y_0 to y = y_end) until the slice \r\n    * located at z = z_0 has been processed. We then continue on the next \r\n    * slice until the entire meshed cube has been mapped.\r\n    *\r\n    * The coordinates are returned in a 3D vector.\r\n    * @return The mesh node coordinates.\r\n    */\r\n    Eigen::Matrix<Eigen::Matrix<T, 3, 1>, Eigen::Dynamic, 1> coordinates() {\r\n        // get the number of divisions per axis\r\n        int n_x = m_nx[0];\r\n        int n_y = 0;\r\n        int n_z = 0;\r\n        Vec y = Vec::Zero(n_x + 1);\r\n        Vec z = Vec::Zero(n_x + 1); \r\n        if (m_dim >= 2){\r\n            n_y = m_nx[1];\r\n            y = m_x[1];\r\n            z = Vec::Zero((n_x + 1)*(n_y + 1)); \r\n        } \r\n        if (m_dim == 3) {\r\n            n_z = m_nx[2];\r\n            z = m_x[2];\r\n        }\r\n        // generate the vector of coordinates\r\n        Eigen::Matrix<T, 3, 1> node;\r\n        Eigen::Matrix<Eigen::Matrix<T, 3, 1>, Eigen::Dynamic, 1> coords;\r\n        for (int k=0; k<n_z + 1; ++k){\r\n            for (int j=0; j<n_y + 1; ++j) {\r\n                for (int i=0; i<n_x + 1; ++i){\r\n                    // spdlog::debug(\"{}\",i + j*(n_x + 1) + k*((n_x + 1) * (n_y+1)));\r\n                    node = {m_x[0][i], y[j], z[k]};\r\n                    // spdlog::debug(\"x: {} y: {} z: {}\", m_x[0][i], y[j], z[k]);\r\n                }\r\n            }\r\n        }\r\n        return coords;\r\n    }\r\n\r\n\t/*!\r\n\t* @return the time increment.\r\n\t*/\r\n\tT dt() {\r\n\t\treturn m_dt;\r\n\t}\r\n\t/*!\r\n\t* @return the list of coordinates in each dimensions.\r\n\t*/\r\n\tstd::vector<Vec> x() {\r\n\t\treturn m_x;\r\n\t}\r\n\t/*!\r\n\t* @return the time list.\r\n\t*/\r\n\tVec t() {\r\n\t\treturn m_t;\r\n\t}\r\n};\r\n\r\n\r\n}  // namespace fdm\r\n\r\n} // namespace numerical\r\n\r\n#endif  // MESH_H\r\n", "meta": {"hexsha": "bfdf5d10efba59d0bf5990cbd96b733c44f260f4", "size": 12149, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "numerical/fdm/Mesh.hpp", "max_stars_repo_name": "dbeat/numerical", "max_stars_repo_head_hexsha": "bce26eb7d537eb8e32105f2887ea11940ce4fc96", "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": "numerical/fdm/Mesh.hpp", "max_issues_repo_name": "dbeat/numerical", "max_issues_repo_head_hexsha": "bce26eb7d537eb8e32105f2887ea11940ce4fc96", "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": "numerical/fdm/Mesh.hpp", "max_forks_repo_name": "dbeat/numerical", "max_forks_repo_head_hexsha": "bce26eb7d537eb8e32105f2887ea11940ce4fc96", "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.6533018868, "max_line_length": 86, "alphanum_fraction": 0.4273602766, "num_tokens": 3749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.8221891392358014, "lm_q1q2_score": 0.7404058097044707}}
{"text": "#include <Eigen/Dense>\n\n/*\n   A collection of metrics to use for determining the\n   error between the predicted and actual Y values.\n*/\n\ndouble mse(Eigen::MatrixXd X, Eigen::VectorXd W, Eigen::VectorXd Y) {\n\t/*\n\t  Computes the mean squared error for a XW and Y.\n\t*/\n\treturn 0.5 * (Y - X * W).transpose() * (Y - X * W);\n}\n", "meta": {"hexsha": "4f3519c50c84f21938ae60f6ea3c7d75f7028480", "size": 321, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/metrics.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/metrics.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/metrics.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": 22.9285714286, "max_line_length": 69, "alphanum_fraction": 0.6542056075, "num_tokens": 89, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.933430812881347, "lm_q2_score": 0.7931059487389968, "lm_q1q2_score": 0.7403095304324737}}
{"text": "// Test101.cpp\n//\n// First program test the boost statistics library.\n//\n// 2008-6-27 DD initial code\n// 2008-10-10 DD Bernoulli distribution\n// 2011-11-8 DD for QN students\n//\n// (C) Datasim Education BV 2009-2011\n//\n\n#include <boost/math/distributions/uniform.hpp>\n#include <boost/math/distributions/bernoulli.hpp>\n#include <boost/math/distributions/gamma.hpp>\n#include <boost/math/distributions/students_t.hpp>\n#include <boost/math/distributions.hpp> // For non-member functions of distributions\n\n#include <iostream>\nusing namespace std;\n\nint main()\n{\n\t// Don't forget to tell compiler which namespace\n\tusing namespace boost::math;\n\n\tuniform_distribution<> myUniform(0.0, 1.0); // Default type ie 'double'\n\tcout << \"Lower value: \" << myUniform.lower() << \", upper value: \" << myUniform.upper() << endl;\n\n\t// Choose another data type\n\tuniform_distribution<float> myUniform2(0.0, 1.0); \n\tcout << \"Lower value: \" << myUniform2.lower() << \", upper value: \" << myUniform2.upper() << endl;\n\n\t// Distributional properties\n\tdouble x = 0.25;\n\n\tcout << \"pdf of Uniform: \" << pdf(myUniform, x) << endl;\n\tcout << \"cdf of Uniform: \" << cdf(myUniform, x) << endl;\n\t\n\t// Bernoulli distributions\n\tbernoulli_distribution<> myBernoulli(0.4);\n\tcout << \"Probability of success: \" << myBernoulli.success_fraction() << endl;\n\n\tint k = 0;\n\tcout << \"pdf of Bernoulli: \" << pdf(myBernoulli, k) << endl;\n\tcout << \"cdf of Bernoulli : \" << cdf(myBernoulli, k) << endl << endl;\n\n\t\n\t// Choose precision\n\tcout.precision(8); // Number of values behind the comma\n\n\t// Other properties\n\tcout << \"\\n***Uniform distribution: \\n\";\n\tcout << \"mean: \" << mean(myUniform) << endl;\n\t\n\t// ... more\n\n\tcout << \"hazard: \" << hazard(myUniform, x) << endl;\n\n\t// STUDENT\n\tstudents_t_distribution<float> myStudent(30);\n\n\t// Quantiles and conversions between significance levels (fractions, 0.05) \n\t// and cofidence levels (in percentages, e.g. 95%)\n\tdouble Alpha = 0.25;\n\tcout << \"Confidence 1: \" << quantile(myStudent, Alpha / 2) << endl;\n\tcout << \"Confidence, in %: \" << quantile(complement(myStudent, Alpha / 2)) << endl;\n\n\t// Required sample sizes for Students t-distribution\n\tdouble M = 1.2;\t\t// True mean\n\tdouble Sm = 1.8;\t// Sample mean\n\tdouble Sd = 2.4;\t// Sample standard deviation\n\n\ttry\n\t{\n\t\tdouble df = students_t::find_degrees_of_freedom (fabs(M-Sm), Alpha, Alpha, Sd);\n\t\tint dof = ceil(df) + 1; // ceil(x) == smallest integer not less than x\n\t\tcout << \"One-sided degrees of freedom: \" << dof << endl;\n\t}\n\tcatch(const std::exception& e)\n\t{\n      cout << e.what() << endl;\n\t}\n\n\treturn 0;\n}", "meta": {"hexsha": "93382a4eb84ec6b893ca794d7756b3f1f059c6d7", "size": 2553, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Level_8/V. An Introduction to the Boost C++ Libraries/05a - Statistical Functions/TestStatistics101.cpp", "max_stars_repo_name": "ZhehaoLi9705/QuantNet_CPP", "max_stars_repo_head_hexsha": "a889f4656e757842f4163b0cda7e098cc6ad1193", "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": "Level_8/V. An Introduction to the Boost C++ Libraries/05a - Statistical Functions/TestStatistics101.cpp", "max_issues_repo_name": "ZhehaoLi9705/QuantNet_CPP", "max_issues_repo_head_hexsha": "a889f4656e757842f4163b0cda7e098cc6ad1193", "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": "Level_8/V. An Introduction to the Boost C++ Libraries/05a - Statistical Functions/TestStatistics101.cpp", "max_forks_repo_name": "ZhehaoLi9705/QuantNet_CPP", "max_forks_repo_head_hexsha": "a889f4656e757842f4163b0cda7e098cc6ad1193", "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.0352941176, "max_line_length": 98, "alphanum_fraction": 0.6674500588, "num_tokens": 742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086367, "lm_q2_score": 0.8080672066194945, "lm_q1q2_score": 0.7402781327088863}}
{"text": "#include \"Kinematics.h\"\r\n#include <Eigen/SVD>\r\n\r\nusing namespace MotionControl;\r\n\r\nMatrix<double,3,3> Kinematics::Rodrigues(Matrix<double,3,1> a, double q)\r\n{\r\n\treturn AngleAxisd(q,a).toRotationMatrix();\r\n}\r\n\r\nMatrix<double,3,1> Kinematics::rot2omega(Matrix<double,3,3> R)\r\n{\r\n\tdouble alpha = (R(0,0)+R(1,1)+R(2,2)-1)/2;\r\n\tdouble th;\r\n\tMatrix<double,3,1> vector_R(Matrix<double,3,1>::Zero());\r\n\r\n\tif(fabs(alpha-1) < eps)\r\n\t\treturn Matrix<double,3,1>::Zero();\r\n\r\n\tth = acos(alpha);\r\n\tvector_R << R(2,1)-R(1,2), R(0,2)-R(2,0), R(1,0)-R(0,1);\r\n\treturn 0.5*th/sin(th)*vector_R;\r\n}\r\n\r\nvector<int> Kinematics::FindRoute(int to)\r\n{\r\n\tvector<int> idx;\r\n\tint link_num = to;\r\n\r\n\twhile(link_num != 0)\r\n\t{\r\n\t\tidx.push_back(link_num);\r\n\t\tlink_num = ulink[link_num].parent;\r\n\t}\r\n\treverse(idx.begin(), idx.end());\r\n\treturn idx;\r\n}\r\n\r\nMatrix<double,6,1> Kinematics::calcVWerr(Link Cref, Link Cnow)\r\n{\r\n\tMatrix<double,3,1> perr = Cref.p - Cnow.p;\r\n\tMatrix<double,3,3> Rerr = Cref.R - Cnow.R;\r\n\tMatrix<double,3,1> werr = Cnow.R * rot2omega(Rerr);\r\n\tMatrix<double,6,1> err;\r\n\r\n\terr << perr,werr;\r\n\treturn err;\r\n}\r\n\r\nvoid Kinematics::calcForwardKinematics(int rootlink)\r\n{\r\n\tif(rootlink == -1)\r\n\t\treturn ;\r\n\tif(rootlink != 0)\r\n\t{\r\n\t\tint parent = ulink[rootlink].parent;\r\n\t\tulink[rootlink].p = ulink[parent].R * ulink[rootlink].b + ulink[parent].p;\r\n\t\tulink[rootlink].R = ulink[parent].R * Rodrigues(ulink[rootlink].a, ulink[rootlink].q);\r\n\t}\r\n\tcalcForwardKinematics(ulink[rootlink].sister);\r\n\tcalcForwardKinematics(ulink[rootlink].child);\r\n}\r\n\r\nMatrixXd Kinematics::calcJacobian(vector<int> idx)\r\n{\r\n\tsize_t jsize = idx.size();\r\n\tMatrix<double,3,1> target = ulink[idx.back()].p;\r\n\tMatrix<double,6,11> J = MatrixXd::Zero(6,11);\r\n\r\n\tfor(size_t i=0;i<jsize;i++)\r\n\t{\r\n\t\tint j = idx[i];\r\n\t\tMatrix<double,3,1> a = ulink[j].R * ulink[j].a;\r\n\t\tMatrix<double,3,1> b = a.cross(target - ulink[j].p);\r\n\t\tJ(0,i) = b(0); J(1,i) = b(1); J(2,i) = b(2);\r\n\t\tJ(3,i) = a(0); J(4,i) = a(1); J(5,i) = a(2);\r\n\t}\r\n\r\n\treturn J;\r\n}\r\n\r\ntemplate <typename t_matrix>\r\nt_matrix Kinematics::PseudoInverse(const t_matrix& m, const double &tolerance)\r\n{\r\n\ttypedef JacobiSVD<t_matrix> TSVD;\r\n\tunsigned int svd_opt(ComputeThinU | ComputeThinV);\r\n\tif(m.RowsAtCompileTime!=Dynamic || m.ColsAtCompileTime!=Dynamic)\r\n\t\tsvd_opt= ComputeFullU | ComputeFullV;\r\n\tTSVD svd(m, svd_opt);\r\n\tconst typename TSVD::SingularValuesType &sigma(svd.singularValues());\r\n\ttypename TSVD::SingularValuesType sigma_inv(sigma.size());\r\n\tfor(long i=0; i<sigma.size(); ++i)\r\n\t{\r\n\t\tif(sigma(i) > tolerance)\r\n\t\t\tsigma_inv(i)= 1.0/sigma(i);\r\n\t\telse\r\n\t\t\tsigma_inv(i)= 0.0;\r\n\t}\r\n\treturn svd.matrixV()*sigma_inv.asDiagonal()*svd.matrixU().transpose();\r\n}\r\n\r\nbool Kinematics::calcInverseKinematics(int to, Link target)\r\n{\r\n\tMatrixXd J, dq;\r\n\tMatrix<double,6,1> err;\r\n\r\n\tColPivHouseholderQR<MatrixXd> QR; //QR\u5206\u89e3?\r\n\tconst double dampingConstantSqr = 1.0e-12;\r\n\tconst double lambda = 0.5;\r\n\tconst int iteration = 100;\r\n\t\r\n\tcalcForwardKinematics(WAIST);\r\n\t\r\n\tvector<int> idx = FindRoute(to);\r\n\tconst int jsize = idx.size();\r\n\t\r\n\tJ.resize(6,jsize); dq.resize(jsize,1);\r\n\r\n\tfor(int n=0;n<iteration;n++){\r\n\t\tJ = calcJacobian(idx);\r\n\t\terr = calcVWerr(target, ulink[to]);\r\n\t\tif(err.norm() < eps) return true;\r\n\r\n\t\tMatrixXd JJ = J*J.transpose()+dampingConstantSqr*MatrixXd::Identity(J.rows(),J.rows());\r\n\t\tdq = J.transpose() * QR.compute(JJ).solve(err) * lambda;\r\n\t\t\r\n\t\tfor(size_t nn=0;nn<jsize;nn++){\r\n\t\t\tint j = idx[nn];\r\n\t\t\tulink[j].q += dq(nn);\r\n\t\t}\r\n\t\tcalcForwardKinematics(WAIST);\r\n\t}\r\n\treturn false;\r\n}\r\n", "meta": {"hexsha": "a0316774179bd788cae212898ce12ebc35c04061", "size": 3512, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "choreonoid/rtc/ArmInverseKinematicsTest/Kinematics.cpp", "max_stars_repo_name": "takayan660/HumanoidRobotLibrary", "max_stars_repo_head_hexsha": "302c95f8660056b42d1bed836253f2169d71769f", "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": "choreonoid/rtc/ArmInverseKinematicsTest/Kinematics.cpp", "max_issues_repo_name": "takayan660/HumanoidRobotLibrary", "max_issues_repo_head_hexsha": "302c95f8660056b42d1bed836253f2169d71769f", "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": "choreonoid/rtc/ArmInverseKinematicsTest/Kinematics.cpp", "max_forks_repo_name": "takayan660/HumanoidRobotLibrary", "max_forks_repo_head_hexsha": "302c95f8660056b42d1bed836253f2169d71769f", "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": 26.0148148148, "max_line_length": 90, "alphanum_fraction": 0.645785877, "num_tokens": 1146, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012701768145, "lm_q2_score": 0.782662489091802, "lm_q1q2_score": 0.7402431763027736}}
{"text": "#include \"tools.hpp\"\n\n#include <Eigen/Geometry>\n\nusing namespace std ;\nusing namespace Eigen ;\nusing namespace vsim ;\n\nstatic float polygon_area(const vector<Vector2f> &contour)\n{\n    uint n = contour.size();\n\n    float A = 0.0f;\n\n    for( uint p=n-1, q=0; q<n; p=q++ )\n    {\n        A+= contour[p].x()*contour[q].y() - contour[q].x()*contour[p].y();\n    }\n\n    return A*0.5f;\n}\n\n/*\n     InsideTriangle decides if a point P is Inside of the triangle\n     defined by A, B, C.\n   */\nbool inside_triangle(float Ax, float Ay,\n                                 float Bx, float By,\n                                 float Cx, float Cy,\n                                 float Px, float Py)\n\n{\n    float ax, ay, bx, by, cx, cy, apx, apy, bpx, bpy, cpx, cpy;\n    float cCROSSap, bCROSScp, aCROSSbp;\n\n    ax = Cx - Bx;  ay = Cy - By;\n    bx = Ax - Cx;  by = Ay - Cy;\n    cx = Bx - Ax;  cy = By - Ay;\n    apx= Px - Ax;  apy= Py - Ay;\n    bpx= Px - Bx;  bpy= Py - By;\n    cpx= Px - Cx;  cpy= Py - Cy;\n\n    aCROSSbp = ax*bpy - ay*bpx;\n    cCROSSap = cx*apy - cy*apx;\n    bCROSScp = bx*cpy - by*cpx;\n\n    return ((aCROSSbp >= 0.0f) && (bCROSScp >= 0.0f) && (cCROSSap >= 0.0f));\n}\n\nbool snip(const vector<Vector2f> &contour, int u,int v,int w,int n, vector<uint> &V)\n{\n    static const float EPSILON = 1.0e-10f;\n\n    uint p;\n    float Ax, Ay, Bx, By, Cx, Cy, Px, Py;\n\n    Ax = contour[V[u]].x();\n    Ay = contour[V[u]].y();\n\n    Bx = contour[V[v]].x();\n    By = contour[V[v]].y();\n\n    Cx = contour[V[w]].x();\n    Cy = contour[V[w]].y();\n\n    if ( EPSILON > (((Bx-Ax)*(Cy-Ay)) - ((By-Ay)*(Cx-Ax))) ) return false;\n\n    for ( p=0 ; p<n ; p++ )\n    {\n        if ( (p == u) || (p == v) || (p == w) ) continue;\n        Px = contour[V[p]].x();\n        Py = contour[V[p]].y();\n        if ( inside_triangle(Ax,Ay,Bx,By,Cx,Cy,Px,Py) ) return false;\n    }\n\n    return true;\n}\n\nstatic float triangle_area(const Vector3f &v1, const Vector3f &v2, const Vector3f &v3) {\n    Vector3f n1, n2 ;\n\n    n1 = v1 - v2 ;\n    n2 = v1 - v3 ;\n    return  n1.cross(n2).norm() ;\n}\n\nEigen::Hyperplane<float, 3> fitPlaneToPoints(const vector<Vector3f> &pts) {\n    uint n_pts = pts.size() ;\n    assert(n_pts >= 3) ;\n\n    if ( n_pts == 3 )\n        return Eigen::Hyperplane<float, 3>::Through(pts[0], pts[1], pts[2]) ;\n    else {\n        Eigen::Map<Matrix<float,Dynamic,3,RowMajor> > mat((float *)pts.data(), pts.size(), 3);\n        VectorXf centroid = mat.colwise().mean();\n        MatrixXf centered = mat.rowwise() - centroid.adjoint() ;\n        MatrixXf cov = (centered.adjoint() * centered) / double(mat.rows() - 1);\n        JacobiSVD<Matrix3f> svd(cov, ComputeFullU);\n        Vector3f normal = svd.matrixU().col(2);\n        return Eigen::Hyperplane<float, 3>(normal, centroid) ;\n    }\n}\n\n\nbool triangulate(const vector<Vector3f> &pts, vector<uint32_t> &result)\n{\n    if ( pts.size() < 3 ) return false ;\n\n    if ( pts.size() == 3 ) {\n\n        result.push_back(0) ; result.push_back(1) ; result.push_back(2) ;\n        return true ;\n    }\n\n    // fit plane to points\n\n    Eigen::Hyperplane<float, 3> plane = fitPlaneToPoints(pts) ;\n\n    Vector3f na, nb, nz = plane.normal() ;\n    double q = sqrt(nz.x() * nz.x() + nz.y() * nz.y()) ;\n    if ( q < 1.0e-4 )\n    {\n        na = Vector3f(1, 0, 0) ;\n        nb = nz.cross(na) ;\n    }\n    else {\n        na = Vector3f(nz.y()/q, -nz.x()/q, 0) ;\n        nb = Vector3f(nz.x() * nz.z()/q, nz.y() * nz.z()/q, -q) ;\n    }\n\n    // project points to plane\n\n    vector<Vector2f> contour ;\n    for(uint i=0 ; i<pts.size() ; i++ ) {\n        const Vector3f &pt = pts[i] ;\n        contour.push_back(Vector2f(na.dot(pt), nb.dot(pt))) ;\n    }\n\n    /* allocate and initialize list of Vertices in polygon */\n\n    uint n = contour.size();\n\n    vector<uint> V(n) ;\n\n    /* we want a counter-clockwise polygon in V */\n\n    if (  polygon_area(contour) > 0 )\n        for ( uint v=0; v<n; v++) V[v] = v;\n    else\n        for(int v=0; v<n; v++) V[v] = (n-1)-v;\n\n    uint nv = n;\n\n    /*  remove nv-2 Vertices, creating 1 triangle every time */\n    uint count = 2*nv;   /* error detection */\n\n    for(int m=0, v=nv-1; nv>2; )\n    {\n        /* if we loop, it is probably a non-simple polygon */\n        if (0 >= (count--))\n        {\n            //** Triangulate: ERROR - probable bad polygon!\n            return false;\n        }\n\n        /* three consecutive vertices in current polygon, <u,v,w> */\n        uint u = v  ; if (nv <= u) u = 0;     /* previous */\n        v = u+1; if (nv <= v) v = 0;     /* new v    */\n        uint w = v+1; if (nv <= w) w = 0;     /* next     */\n\n        if ( snip(contour,u,v,w,nv,V) )\n        {\n            uint a,b,c,s,t;\n\n            /* true names of the vertices */\n            a = V[u]; b = V[v]; c = V[w];\n\n            /* output Triangle */\n            result.push_back( a );\n            result.push_back( b );\n            result.push_back( c );\n\n            m++;\n\n            /* remove v from remaining polygon */\n            for(s=v,t=v+1;t<nv;s++,t++) V[s] = V[t]; nv--;\n\n            /* resest error detection counter */\n            count = 2*nv;\n        }\n    }\n\n\n    return true;\n}\n\n\nvoid flatten_mesh(const Mesh &mesh, std::vector<Vector3f> &vertices, std::vector<Vector3f> &normals, std::vector<Vector3f> &colors,\n                  std::vector<Vector2f> tex_coords[])\n{\n    vector<Vector3f> cnormals ;\n\n    if ( mesh.normals_.empty() && mesh.ptype_ == Mesh::Triangles )\n        compute_normals(mesh.vertices_, mesh.vertex_indices_, cnormals );\n\n    for( uint v=0 ; v<mesh.vertex_indices_.size() ; v++) {\n\n        uint32_t vidx = mesh.vertex_indices_[v] ;\n        const Vector3f &pos = mesh.vertices_[vidx] ;\n        vertices.push_back(pos) ;\n\n        if ( !cnormals.empty() ) {\n            const Vector3f &normal = cnormals[vidx] ;\n            normals.push_back(normal) ;\n        }\n        else if ( !mesh.normal_indices_.empty() ) {\n            uint32_t nidx = mesh.normal_indices_[v] ;\n            const Vector3f &normal = mesh.normals_[nidx] ;\n            normals.push_back(normal) ;\n        } else if ( !mesh.normals_.empty() ){\n            const Vector3f &norm = mesh.normals_[vidx] ;\n            normals.push_back(norm) ;\n        }\n\n        if ( !mesh.colors_.empty() ) {\n            if ( !mesh.color_indices_.empty() ) {\n                uint32_t cidx = mesh.color_indices_[v] ;\n                const Vector3f &color = mesh.colors_[cidx] ;\n                colors.push_back(color) ;\n            }\n            else {\n                const Vector3f &color = mesh.colors_[vidx] ;\n                colors.push_back(color) ;\n            }\n        }\n\n        for( uint t=0 ; t<MAX_MESH_TEXTURES ; t++ ) {\n            if ( !mesh.tex_coords_[t].empty() ) {\n                if ( !mesh.tex_coord_indices_[t].empty() ) {\n                    uint32_t tidx = mesh.tex_coord_indices_[t][v] ;\n                    const Vector2f &uv = mesh.tex_coords_[t][tidx] ;\n                    tex_coords[t].push_back(uv) ;\n                }\n                else {\n                    const Vector2f &uv = mesh.tex_coords_[t][vidx] ;\n                    tex_coords[t].push_back(uv) ;\n                }\n            }\n        }\n    }\n}\n\n\nstatic Vector3f normal_triangle(const Vector3f &v1, const Vector3f &v2, const Vector3f &v3)\n{\n    Vector3f n1, n2 ;\n\n    n1 = v1 - v2 ;\n    n2 = v1 - v3 ;\n    return  n1.cross(n2).normalized() ;\n\n}\nvoid compute_normals(const vector<Vector3f> &vertices, const vector<uint> &indices, vector<Vector3f> &vtx_normals)\n{\n    vtx_normals.resize(vertices.size()) ;\n    for( int i=0 ; i<vertices.size() ; i++ ) vtx_normals[i] = Vector3f::Zero() ;\n\n    for( int i=0 ; i<indices.size() ; i+=3 )\n    {\n        uint idx0 = indices[i] ;\n        uint idx1 = indices[i+1] ;\n        uint idx2 = indices[i+2] ;\n        Vector3f n = normal_triangle(vertices[idx0], vertices[idx1], vertices[idx2]) ;\n\n        vtx_normals[idx0] += n ;\n        vtx_normals[idx1] += n ;\n        vtx_normals[idx2] += n ;\n    }\n\n    for( int i=0 ; i<vertices.size() ; i++ ) vtx_normals[i].normalize() ;\n\n}\n", "meta": {"hexsha": "6cc11eb6cf73f9228ea859bdb852656e6b403e6f", "size": 7993, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/renderer/tools.cpp", "max_stars_repo_name": "malasiot/vsim", "max_stars_repo_head_hexsha": "2a69e27364bab29194328af3d050e34f907e226b", "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/renderer/tools.cpp", "max_issues_repo_name": "malasiot/vsim", "max_issues_repo_head_hexsha": "2a69e27364bab29194328af3d050e34f907e226b", "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/renderer/tools.cpp", "max_forks_repo_name": "malasiot/vsim", "max_forks_repo_head_hexsha": "2a69e27364bab29194328af3d050e34f907e226b", "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.2438162544, "max_line_length": 131, "alphanum_fraction": 0.5163267859, "num_tokens": 2413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632896242073, "lm_q2_score": 0.7981867777396211, "lm_q1q2_score": 0.740209115939161}}
{"text": "/**\n * \\file inc/dcs/math/function/bell.hpp\n *\n * \\brief Compute the n-th Bell number.\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n *\n * <hr/>\n *\n * Copyright 2014 Marco Guazzone (marco.guazzone@gmail.com)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#ifndef DCS_MATH_FUNCTION_BELL_HPP\n#define DCS_MATH_FUNCTION_BELL_HPP\n\n\n#include <dcs/debug.hpp>\n#include <boost/math/special_functions/binomial.hpp>\n#include <vector>\n\n\nnamespace dcs { namespace math {\n\nnamespace detail { namespace /*<unnamed>*/ {\n\n/**\n * \\brief Compute the n-th Bell's number with the recursive formula.\n *\n * \\tparam RealT The real type of the return value\n * \\param n The order of the Bell's number\n * \\return the n-th Bell's number\n *\n * The n-th Bell number \\f$B_n\\f$ can be computed as:\n * \\f{equation}\n *  B_n=sum_(k=0)^(n-1){\\binom{n-1}{k} B_k}\n * \\f}\n *\n * \\note This is a naive implementation that should not be used in practice.\n */\ntemplate <typename RealT>\nRealT bell_rec(unsigned int n)\n{\n\tif (n <= 1)\n\t{\n\t\treturn 1;\n\t}\n\n\tRealT Bn = 0;\n\tfor (unsigned int k = 0; k < n; ++k)\n\t{\n\t\tBn += ::boost::math::binomial_coefficient<RealT>(n-1, k)*bell_rec<RealT>(k);\n\t}\n\n\treturn Bn;\n}\n\n/**\n * \\brief Compute the n-th Bell's number with the triangle method.\n *\n * \\tparam RealT The real type of the return value\n * \\param n The order of the Bell's number\n * \\return the n-th Bell's number\n *\n * For details about the triangle method see [1].\n *\n * References:\n * -# J. Shallit\n *    \"A triangle for the Bell numbers\",\n *    In: A collection of manuscripts related to the Fibonacci sequence (eds. V.E. Hoggatt, Jr. and M. Bicknell-Johnson), pp. 69-71, Fibonacci Association, 1980\n *    [http://www.fq.math.ca/Books/Collection/shallit.pdf]\n * .\n */\ntemplate <typename RealT>\nRealT bell_triangle(unsigned int n)\n{\n\tif (n <= 1)\n\t{\n\t\treturn 1;\n\t}\n\n\t::std::vector<RealT> Tup(n); // The upper row of Bell triangle\n\t::std::vector<RealT> Tlo(n); // The lower row of Bell triangle\n\n    Tup[0] = 1;\n\tfor (unsigned int i = 1; i < n; ++i)\n\t{\n\t\tTlo[0] = Tup[i-1];\n\t\tfor (unsigned int k = 1; k <= i; ++k)\n\t\t{\n\t\t\tTlo[k] = Tlo[k-1]+Tup[k-1];\n\t\t\tTup[k-1] = Tlo[k-1];\n\t\t}\n\t\tTup[i] = Tlo[i];\n\t}\n\nDCS_DEBUG_TRACE(\"B(\"<<n<<\")=\"<<Tlo.back());\n\treturn Tlo.back();\n}\n\n}} // Namespace detail::<unnamed>\n\n#if 0 // Naive implementation, only used for testing/debugging purpose\n/**\n * \\brief Compute the n-th Bell number\n *\n * \\tparam RealT The real type of the return value\n * \\param n The order of the Bell's number\n * \\return the n-th Bell's number\n *\n * The n-th Bell number \\f$B_n\\f$ is the number of ways a set of n elements can\n * be partitioned into nonempty subsets.\n * \\f$B_n\\f$ can be computed as:\n * \\f{equation}\n *  B_n=sum_(k=0)^(n-1){\\binom{n-1}{k} B_k}\n * \\f}\n */\ntemplate <typename RealT>\nRealT bell_naive(unsigned int n)\n{\n\treturn detail::bell_rec<RealT>(n);\n}\n#endif // if 0\n\n/**\n * \\brief Compute the n-th Bell number\n *\n * \\tparam RealT The real type of the return value\n * \\param n The order of the Bell's number\n * \\return the n-th Bell's number\n *\n * The n-th <em>Bell number</em> \\f$B_n\\f$ (also called the <em>exponential\n * number</em>) is the number of ways a set of n elements can be partitioned\n * into nonempty subsets.\n * \\f$B_n\\f$ can be computed as:\n * \\f{equation}\n *  B_n=sum_(k=0)^(n-1){\\binom{n-1}{k} B_k}\n * \\f}\n */\ntemplate <typename RealT>\nRealT bell(unsigned int n)\n{\n\treturn detail::bell_triangle<RealT>(n);\n}\n\n}} // Namespace dcs::math\n\n#endif // DCS_MATH_FUNCTION_BELL_HPP\n", "meta": {"hexsha": "dc6c799c9275f8fc83df88d23d62b8d2f2a89eb8", "size": 3990, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "inc/dcs/math/function/bell.hpp", "max_stars_repo_name": "sguazt/dcsxx-commons", "max_stars_repo_head_hexsha": "0fc1fd8a38b7c412941b401c00a9293bc5df8b21", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T19:03:40.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-26T19:03:40.000Z", "max_issues_repo_path": "include/dcs/math/function/bell.hpp", "max_issues_repo_name": "sguazt/fog-gt", "max_issues_repo_head_hexsha": "92a01de4f3d71bf89741c7e4af1bebb965c64d28", "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": "include/dcs/math/function/bell.hpp", "max_forks_repo_name": "sguazt/fog-gt", "max_forks_repo_head_hexsha": "92a01de4f3d71bf89741c7e4af1bebb965c64d28", "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": 24.9375, "max_line_length": 160, "alphanum_fraction": 0.6656641604, "num_tokens": 1211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267796346599, "lm_q2_score": 0.8519528076067262, "lm_q1q2_score": 0.740199414233659}}
{"text": "#ifndef INVERT_MATRIX_GJ_HPP\n#define INVERT_MATRIX_GJ_HPP\n\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/triangular.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n#define abs(x) ((x) < 0 ? -x : x)\n\nnamespace ublas = boost::numeric::ublas;\n\ntemplate<class T>\nbool invert_matrix_gj(const ublas::matrix<T>& input, ublas::matrix<T>& inverse) {\n    typedef ublas::matrix<T> tmatrix;\n    typedef ublas::vector<T> tvector;\n    typedef ublas::identity_matrix<T> imatrix;\n\n    T eps = 1e-10;\n\n    int h = input.size1();\n    int w = input.size2();\n\n    // get a working copy of the input and augment it by the identity matrix\n    tmatrix A(h, w + h);\n    imatrix I(h, h);\n    for (int i = 0; i < A.size1(); i++) {\n\tfor (int j = 0; j < A.size2(); j++) {\n\t    if (j < input.size2()) {\n\t\tA(i, j) = input(i, j);\n\t    } else {\n\t\tA(i, j) = I(i, j - input.size2());\n\t    }\n\t}\n    }\n\n    // do gauss-jordan\n    for (int y = 0; y < h; y++) {\n\t// find max pivot\n\tint maxrow = y;\n\tfor (int y2 = y+1; y2 < h; y2++) {\n\t    if (abs(A(y2, y)) > abs(A(maxrow,y))) {\n\t\tmaxrow = y2;\n\t    }\n\t}\n\t// swap row y with maxrow\n\tublas::matrix_row<tmatrix> current(A, y);\n\tublas::matrix_row<tmatrix> toswap (A, maxrow);\n\tcurrent.swap(toswap);\n\t// check for singularity\n\tif (abs(A(y, y)) <= eps) {\n\t    return false;\n\t}\n\t// eliminate row y\n\tfor (int y2 = y+1; y2 < h; y2++) {\n\t    T c = A(y2, y) / A(y, y);\n\t    for (int x = y; x < w+h; x++) {\n\t\tA(y2, x) -= A(y, x) * c;\n\t    }\n\t}\n    }\n    // backsubstitution\n    for (int y = h - 1; y >= 0; y--) {\n\tT c = A(y, y);\n\tfor (int y2 = 0; y2 < y; y2++) {\n\t    for (int x = w+h - 1; x >= 0; x--) {\n\t\tA(y2, x) -= A(y, x) * A(y2, y) / c;\n\t    }\n\t}\n\tA(y, y) /= c;\n\tfor (int x = h; x < w+h; x++) {\n\t    A(y, x) /= c;\n\t}\n    }\n    // get out the inverted part\n    ublas::matrix_range<tmatrix> orig_range(A, ublas::range(0, h), ublas::range(h, w+h));\n    inverse = orig_range;\n    return true;\n}\n\n#endif/*INVERT_MATRIX_GJ_HPP*/\n", "meta": {"hexsha": "160d865bac350be6ebdc038bb1264952788202de", "size": 2127, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "invert_matrix_gj.hpp", "max_stars_repo_name": "tjanu/cfdlp", "max_stars_repo_head_hexsha": "8c9ba7738f0b1dd41142d084352e74202777fe16", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-08T16:05:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-08T16:05:42.000Z", "max_issues_repo_path": "invert_matrix_gj.hpp", "max_issues_repo_name": "tjanu/cfdlp", "max_issues_repo_head_hexsha": "8c9ba7738f0b1dd41142d084352e74202777fe16", "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": "invert_matrix_gj.hpp", "max_forks_repo_name": "tjanu/cfdlp", "max_forks_repo_head_hexsha": "8c9ba7738f0b1dd41142d084352e74202777fe16", "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.0235294118, "max_line_length": 89, "alphanum_fraction": 0.5637047485, "num_tokens": 761, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.8418256532040707, "lm_q1q2_score": 0.7400883018209568}}
{"text": "// vim: set fileencoding=utf-8\n// File:     problem7.cpp\n// Author:   Yusuke Sasaki <y_sasaki@nuem.nagoya-u.ac.jp>\n// URL:      http://y-sasaki-nuem.github.io/\n// License:  MIT License\n// Created:  2015-03-13T01:40:14\n\n// output:\n// nth_prime(6) = 13\t(in 0 secs)\n// nth_prime(10001) = 104743\t(in 1.048 secs)\n\n#include <iostream>\n#include <algorithm>\n#include <stdexcept>\n#include <boost/timer.hpp>\nusing namespace std;\n\ntemplate <size_t N>\nvoid next_prime(long long (&primes)[N], int& i)\n{\n    for (int v = primes[i] + 1; v <= numeric_limits<long long>::max(); ++v)\n    {\n        if (all_of(primes, primes+i+1, [=](long long p){ return v%p != 0; })) {\n            primes[++i] = v;\n            return;\n        }\n    }\n    throw std::logic_error(\"next prime is not found.\");\n}\n\ntemplate <size_t N>\nlong long nth_prime()\n{\n    boost::timer t;\n\n    long long primes[N] = {0};\n    primes[0] = 2L;\n    \n    for (int i = 0; i < N - 1; next_prime(primes, i));\n    \n    cout << \"nth_prime(\"<<N<<\") = \"<<primes[N-1]<<\"\\t(in \"<<t.elapsed()<<\" secs)\\n\";\n}\n\n\nint main(int argc, char** argv)\n{\n    nth_prime<6>();\n    nth_prime<10001>();\n}\n\n", "meta": {"hexsha": "dab5381a4f0e72e0bcb9e3207d6aff9895946e66", "size": 1127, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "007/problem7.cpp", "max_stars_repo_name": "ys-nuem/project-euler", "max_stars_repo_head_hexsha": "bcdb98fa01bea93606227e74cc15930a38a4c8d5", "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": "007/problem7.cpp", "max_issues_repo_name": "ys-nuem/project-euler", "max_issues_repo_head_hexsha": "bcdb98fa01bea93606227e74cc15930a38a4c8d5", "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": "007/problem7.cpp", "max_forks_repo_name": "ys-nuem/project-euler", "max_forks_repo_head_hexsha": "bcdb98fa01bea93606227e74cc15930a38a4c8d5", "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.0980392157, "max_line_length": 84, "alphanum_fraction": 0.5714285714, "num_tokens": 363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095292, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.7400882930990846}}
{"text": "\ufeff/*\r\n * Copyright (c) 2007-2010 Tao Wang <dancefire@gmail.org>\r\n * See the file \"LICENSE.txt\" for usage and redistribution license requirements\r\n *\r\n *\t$Id$\r\n */\r\n\r\n#pragma once\r\n#ifndef _OPENCLAS_UNIT_TEST_VITERBI_HPP_\r\n#define _OPENCLAS_UNIT_TEST_VITERBI_HPP_\r\n\r\n#include <openclas/viterbi.hpp>\r\n#include <boost/test/floating_point_comparison.hpp>\r\n\r\nBOOST_AUTO_TEST_SUITE( viterbi )\r\n\r\nusing namespace openclas;\r\n\r\nenum State { Rainy, Sunny };\r\nenum Observation { Walk, Shop, Clean };\r\nconst char* StateName[] = { \"Rainy\", \"Sunny\" };\r\nconst char* ObservationName[] = { \"walk\", \"shop\", \"clean\" };\r\n\r\nconst int number_of_states = 2;\r\nconst int number_of_observations = 3;\t//not for sequence, it's number of total obs\r\n\r\nconst int observation_sequence[] = { Walk, Shop, Clean };\r\nconst int number_of_observation_sequence = 3;\r\n\r\ndouble start_probability[] = {/*Rainy*/ 0.6, /*Sunny*/ 0.4};\r\ndouble transition_probability[] = {\r\n\t/*Rainy : */ /*Rainy*/ 0.7, /*Sunny*/ 0.3, \r\n\t/*Sunny : */ /*Rainy*/ 0.4, /*Sunny*/ 0.6\r\n};\r\ndouble emission_probability[] = {\r\n\t/*Rainy : */ /*walk*/ 0.1, /*shop*/ 0.4, /*clean*/ 0.5,\r\n\t/*Sunny : */ /*walk*/ 0.6, /*shop*/ 0.3, /*clean*/ 0.1\r\n};\r\n\r\nBOOST_AUTO_TEST_CASE( test_viterbi_array )\r\n{\r\n\r\n\tstd::vector<size_t> obs(observation_sequence, observation_sequence + number_of_observation_sequence);\r\n\tviterbi_info<double> result;\r\n\tforward_viterbi(number_of_states,\r\n\t\tnumber_of_observations,\r\n\t\tobs,\r\n\t\tstart_probability,\r\n\t\ttransition_probability,\r\n\t\temission_probability,\r\n\t\tresult);\r\n\r\n\tBOOST_CHECK_CLOSE( result.prob, 0.033612, 0.00001 );\r\n\tBOOST_CHECK_CLOSE( result.v_prob, 0.009408, 0.00001 );\r\n\tBOOST_CHECK_EQUAL( result.v_path.size(), 4 );\r\n\tBOOST_CHECK_EQUAL( result.v_path[0], Sunny );\r\n\tBOOST_CHECK_EQUAL( result.v_path[1], Rainy );\r\n\tBOOST_CHECK_EQUAL( result.v_path[2], Rainy );\r\n\tBOOST_CHECK_EQUAL( result.v_path[3], Rainy );\r\n\r\n\t//print(result, StateName);\r\n\t/*\r\n\tExample output:\r\n\r\n\tTotal probability is 0.033612\r\n\tThe Viterbi path is ['Sunny', 'Rainy', 'Rainy', 'Rainy']\r\n\twith probability 0.009408\r\n\t*/\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE( test_viterbi_vector )\r\n{\r\n\r\n\tstd::vector<size_t> obs(observation_sequence, observation_sequence + number_of_observation_sequence);\r\n\tviterbi_info<double> result;\r\n\t//\tExample of using STL container for start_p, tran_p and emit_p\r\n\tstd::vector<double> start_p(start_probability, start_probability + number_of_states);\r\n\tstd::vector<double> tran_p(transition_probability, transition_probability + (number_of_states * number_of_states));\r\n\tstd::vector<double> emit_p(emission_probability, emission_probability + (number_of_states * number_of_observations));\r\n\tforward_viterbi(number_of_states,\r\n\t\tnumber_of_observations,\r\n\t\tobs,\r\n\t\tstart_p, tran_p, emit_p, result);\r\n\tBOOST_CHECK_CLOSE( result.prob, 0.033612, 0.00001 );\r\n\tBOOST_CHECK_CLOSE( result.v_prob, 0.009408, 0.00001 );\r\n\tBOOST_CHECK_EQUAL( result.v_path.size(), 4 );\r\n\tBOOST_CHECK_EQUAL( result.v_path[0], Sunny );\r\n\tBOOST_CHECK_EQUAL( result.v_path[1], Rainy );\r\n\tBOOST_CHECK_EQUAL( result.v_path[2], Rainy );\r\n\tBOOST_CHECK_EQUAL( result.v_path[3], Rainy );\r\n\r\n\t//print(result, StateName);\r\n\t/*\r\n\tExample output:\r\n\r\n\tTotal probability is 0.033612\r\n\tThe Viterbi path is ['Sunny', 'Rainy', 'Rainy', 'Rainy']\r\n\twith probability 0.009408\r\n\t*/\r\n}\r\n\r\n\r\nBOOST_AUTO_TEST_SUITE_END()\r\n\r\n//\t_OPENCLAS_UNIT_TEST_VITERBI_HPP_\r\n#endif\r\n", "meta": {"hexsha": "9013c15d25a4df8ccd87075563c87cbe4364d7b0", "size": 3361, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cpp/src/unit_test/unit_test_viterbi.hpp", "max_stars_repo_name": "dancefire/openclas", "max_stars_repo_head_hexsha": "af15aad1891cb7e597dfe9dbc92dbd91093d613e", "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": "cpp/src/unit_test/unit_test_viterbi.hpp", "max_issues_repo_name": "dancefire/openclas", "max_issues_repo_head_hexsha": "af15aad1891cb7e597dfe9dbc92dbd91093d613e", "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": "cpp/src/unit_test/unit_test_viterbi.hpp", "max_forks_repo_name": "dancefire/openclas", "max_forks_repo_head_hexsha": "af15aad1891cb7e597dfe9dbc92dbd91093d613e", "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": 31.4112149533, "max_line_length": 119, "alphanum_fraction": 0.713775662, "num_tokens": 924, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972583359806, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.7399825785007104}}
{"text": "#include <algorithm>\n#include <cmath>\n#include <stdexcept>\n\n#include <Eigen/QR>\n#include <Euclid/Geometry/Spectral.h>\n\nnamespace Euclid\n{\n\ntemplate<typename Mesh>\nvoid WKS<Mesh>::build(const Mesh& mesh, unsigned k)\n{\n    _mesh = &mesh;\n    auto n = spectrum(mesh, k, _loglambda, _phi2);\n    // abs fix numerical error\n    _lambda_max = std::abs(_loglambda(n - 1));\n    _lambda_min = std::abs(_loglambda(1));\n    _loglambda = _loglambda.array().abs().log().matrix().eval();\n    _phi2 = _phi2.array().square().matrix().eval();\n}\n\ntemplate<typename Mesh>\nvoid WKS<Mesh>::build(const Mesh& mesh,\n                      const Vec* eigenvalues,\n                      const Mat* eigenfunctions)\n{\n    _mesh = &mesh;\n    // abs fix numerical error\n    _lambda_max = std::abs(eigenvalues->coeff(eigenvalues->size() - 1));\n    _lambda_min = std::abs(eigenvalues->coeff(1));\n    _loglambda = (*eigenvalues).array().abs().log().matrix().eval();\n    _phi2 = (*eigenfunctions).array().square().matrix().eval();\n}\n\ntemplate<typename Mesh>\ntemplate<typename Derived>\nvoid WKS<Mesh>::compute(Eigen::ArrayBase<Derived>& wks,\n                        unsigned escales,\n                        float emin,\n                        float emax,\n                        float sigma)\n{\n    if (emin >= emax || sigma <= 0) {\n        // the parameters described in paper form a linear system\n        Eigen::Matrix3f A;\n        Eigen::Vector3f B;\n        A << 1.0f, 0.0f, -2.0f, 0.0f, 1.0f, 2.0f, 7.0f, -7.0f, escales + 0.0f;\n        B << std::log(_lambda_min), std::log(_lambda_max), 0.0f;\n        Eigen::Vector3f x = A.colPivHouseholderQr().solve(B);\n        emin = x(0);\n        emax = x(1);\n        sigma = x(2);\n        EASSERT(emin < 0);\n        EASSERT(emax > emin);\n        EASSERT(sigma > 0);\n    }\n    auto estep = (emax - emin) / escales;\n    auto edenom = 0.5f / (sigma * sigma);\n    auto vimap = get(boost::vertex_index, *_mesh);\n    auto nv = num_vertices(*_mesh);\n    wks.derived().resize(escales, nv);\n\n    for (auto v : vertices(*_mesh)) {\n        auto idx = get(vimap, v);\n        for (size_t i = 0; i < escales; ++i) {\n            auto e = emin + estep * i;\n            auto wks_e = static_cast<FT>(0);\n            auto ce = static_cast<FT>(0);\n            for (int j = 1; j < _loglambda.size(); ++j) {\n                auto exp = std::exp(-std::pow(e - _loglambda(j), 2) * edenom);\n                ce += exp;\n                wks_e += exp * _phi2(idx, j);\n            }\n            wks(i, idx) = wks_e / ce;\n        }\n    }\n}\n\n} // namespace Euclid\n", "meta": {"hexsha": "44cc944a067bbdd88c17d874357059926df34ab9", "size": 2537, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/Euclid/Descriptor/src/WKS.cpp", "max_stars_repo_name": "unclejimbo/euclid", "max_stars_repo_head_hexsha": "e118abdcdf51b6bc05cf5aa056bf228e052cf501", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2017-05-02T07:04:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T10:00:01.000Z", "max_issues_repo_path": "include/Euclid/Descriptor/src/WKS.cpp", "max_issues_repo_name": "unclejimbo/euclid", "max_issues_repo_head_hexsha": "e118abdcdf51b6bc05cf5aa056bf228e052cf501", "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": "include/Euclid/Descriptor/src/WKS.cpp", "max_forks_repo_name": "unclejimbo/euclid", "max_forks_repo_head_hexsha": "e118abdcdf51b6bc05cf5aa056bf228e052cf501", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-07-02T17:59:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-18T07:01:17.000Z", "avg_line_length": 31.3209876543, "max_line_length": 78, "alphanum_fraction": 0.5451320457, "num_tokens": 748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480237330998, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.7399572441369948}}
{"text": "/*******************************************************************\r\nAuthor: David Ge (dge893@gmail.com, aka Wei Ge)\r\nLast modified: 11/02/2020\r\nAllrights reserved by David Ge\r\n\r\nModifications\r\nDate            Author      Description\r\n---------------------------------------------\r\n\r\n********************************************************************/\r\n#include <malloc.h>\r\n\r\n#include <math.h>\r\n#define _USE_MATH_DEFINES // for C++  \r\n#include <cmath>  \r\n\r\n#include \"HiMatrix.h\"\r\n\r\n#include <boost/multiprecision/cpp_dec_float.hpp>\r\nusing namespace boost::multiprecision;\r\nHiMatrixTools::HiMatrixTools()\r\n{\r\n\r\n}\r\n\r\n// Function to get cofactor of A[p][q] in temp[][]. n is current\r\n// dimension of A[][]\r\nvoid HiMatrixTools::HIgetCofactor(void *inA, void *intemp, int p, int q, int n)\r\n{\r\n\tint i = 0, j = 0;\r\n\tint rowx = 0, ix = 0;\r\n\tcpp_dec_float_100 *A = (cpp_dec_float_100 *)inA;\r\n\tcpp_dec_float_100 *temp = (cpp_dec_float_100*)intemp;\r\n\t// Looping for each element of the matrix\r\n\tfor (int row = 0; row < n; row++)\r\n\t{\r\n\t\tif (row != p)\r\n\t\t{\r\n\t\t\tfor (int col = 0; col < n; col++)\r\n\t\t\t{\r\n\t\t\t\t//  Copying into temporary matrix only those element\r\n\t\t\t\t//  which are not in given row and column\r\n\t\t\t\tif (col != q)\r\n\t\t\t\t{\r\n\t\t\t\t\ttemp[ix + j] = A[rowx + col];//A[row][col];\r\n\r\n\t\t\t\t\tj++;\r\n\t\t\t\t\t// Row is filled, so increase row index and\r\n\t\t\t\t\t// reset col index\r\n\t\t\t\t\tif (j == n - 1)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tj = 0;\r\n\t\t\t\t\t\ti++;\r\n\t\t\t\t\t\tix += (n - 1);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\trowx += n;\r\n\t}\r\n}\r\n\r\n/* Recursive function for finding determinant of matrix.\r\nn is current dimension of A[][]. */\r\nvoid HiMatrixTools::HIdeterminant(void *inA,void *outret, int n)\r\n{\r\n\tcpp_dec_float_100 D = 0; // Initialize result\r\n\tcpp_dec_float_100 *A = (cpp_dec_float_100 *)inA;\r\n\tcpp_dec_float_100 *ret = (cpp_dec_float_100 *)outret;\r\n\t//  Base case : if matrix contains single element\r\n\tif (n == 1)\r\n\t{\r\n\t\tret[0] = A[0];\r\n\t\treturn;\r\n\t}\r\n\tcpp_dec_float_100 det;\r\n\tcpp_dec_float_100 *temp = (cpp_dec_float_100 *)malloc((n - 1)*(n - 1)*sizeof(cpp_dec_float_100));// [N][N]; // To store cofactors\r\n\tif (temp == NULL)\r\n\t{\r\n\t\tthrow;\r\n\t}\r\n\tint sign = 1;  // To store sign multiplier\r\n\r\n\t// Iterate for each element of first row\r\n\tfor (int f = 0; f < n; f++)\r\n\t{\r\n\t\t// Getting Cofactor of A[0][f]\r\n\t\tHIgetCofactor(A, temp, 0, f, n);\r\n\t\t//D += sign * A[0][f] * determinant(temp, n - 1);\r\n\t\tif (sign > 0)\r\n\t\t{\r\n\t\t\tHIdeterminant(temp, &det, n - 1);\r\n\t\t\tD += A[f] * det;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tHIdeterminant(temp, &det, n - 1);\r\n\t\t\tD -= A[f] * det;\r\n\t\t}\r\n\t\t// terms are to be added with alternate sign\r\n\t\tsign = -sign;\r\n\t}\r\n\tfree(temp);\r\n\tret[0] = D;\r\n\treturn;\r\n}\r\n\r\n// Function to get adjoint of A[N][N] in adj[N][N].\r\nvoid HiMatrixTools::HIadjoint(void *inA, void *inadj, int N)\r\n{\r\n\tcpp_dec_float_100 *A = (cpp_dec_float_100 *)inA;\r\n\tcpp_dec_float_100 *adj = (cpp_dec_float_100 *)inadj;\r\n\tif (N == 1)\r\n\t{\r\n\t\tadj[0] = 1;\r\n\t\treturn;\r\n\t}\r\n\r\n\t// temp is used to store cofactors of A[][]\r\n\tint sign = 1;\r\n\tint ix;\r\n\tcpp_dec_float_100 det;\r\n\tcpp_dec_float_100 *temp = (cpp_dec_float_100 *)malloc((N - 1)*(N - 1)*sizeof(cpp_dec_float_100));\r\n\r\n\tfor (int i = 0; i<N; i++)\r\n\t{\r\n\t\tix = 0;\r\n\t\tfor (int j = 0; j<N; j++)\r\n\t\t{\r\n\t\t\t// Get cofactor of A[i][j]\r\n\t\t\tHIgetCofactor(A, temp, i, j, N);\r\n\r\n\t\t\t// sign of adj[j][i] positive if sum of row\r\n\t\t\t// and column indexes is even.\r\n\t\t\tsign = ((i + j) % 2 == 0) ? 1 : -1;\r\n\r\n\t\t\t// Interchanging rows and columns to get the\r\n\t\t\t// transpose of the cofactor matrix\r\n\t\t\t//adj[j+ix] = (sign)*(determinant(temp, N-1));\r\n\t\t\tif (sign > 0)\r\n\t\t\t{\r\n\t\t\t\tHIdeterminant(temp, &det, N - 1);\r\n\t\t\t\tadj[i + ix] = det;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tHIdeterminant(temp, &det, N - 1);\r\n\t\t\t\tadj[i + ix] = -det;\r\n\t\t\t}\r\n\t\t\tix += N;\r\n\t\t}\r\n\r\n\t}\r\n\tfree(temp);\r\n}\r\n\r\n// Function to calculate and store inverse, returns false if\r\n// matrix is singular\r\nbool HiMatrixTools::HIinverse(void *inA, void *inInverse, int N)\r\n{\r\n\tcpp_dec_float_100 *A = (cpp_dec_float_100 *)inA;\r\n\tcpp_dec_float_100 *Inverse = (cpp_dec_float_100 *)inInverse;\r\n\t// Find determinant of A[][]\r\n\tcpp_dec_float_100 det;\r\n\tdouble ddet;\r\n\tHIdeterminant(A, &det, N);\r\n\tddet = det.convert_to<double>();\r\n\tif (abs(ddet) < 1.1e-10)\r\n\t{\r\n\t\t//cout << \"Singular matrix, can't find its inverse\";\r\n\t\treturn false;\r\n\t}\r\n\r\n\t// Find adjoint\r\n\tcpp_dec_float_100 *adj = (cpp_dec_float_100 *)malloc(N*N*sizeof(cpp_dec_float_100));\r\n\tif (adj == NULL) throw;\r\n\tHIadjoint(A, adj, N);\r\n\r\n\t// Find Inverse using formula \"inverse(A) = adj(A)/det(A)\"\r\n\tint ix = 0;\r\n\tfor (int i = 0; i<N; i++)\r\n\t{\r\n\t\tfor (int j = 0; j<N; j++)\r\n\t\t{\r\n\t\t\tInverse[ix + j] = adj[ix + j] / det;\r\n\t\t}\r\n\t\tix += N;\r\n\t}\r\n\tfree(adj);\r\n\treturn true;\r\n}\r\n\r\nvoid HiMatrixTools::HIMatrixMultiply(void *inA, void *inB, void *inC, int N)\r\n{\r\n\tint i, j, ix, k, kx;\r\n\tcpp_dec_float_100 *A = (cpp_dec_float_100 *)inA;\r\n\tcpp_dec_float_100 *B = (cpp_dec_float_100 *)inB;\r\n\tcpp_dec_float_100 *C = (cpp_dec_float_100 *)inC;\r\n\tix = 0;\r\n\tfor (i = 0; i<N; i++)\r\n\t{\r\n\t\tfor (j = 0; j<N; j++)\r\n\t\t{\r\n\t\t\tC[ix + j] = 0.0;\r\n\t\t\tkx = 0;\r\n\t\t\tfor (k = 0; k<N; k++)\r\n\t\t\t{\r\n\t\t\t\tC[ix + j] += A[ix + k] * B[kx + j];\r\n\t\t\t\tkx += N;\r\n\t\t\t}\r\n\t\t}\r\n\t\tix += N;\r\n\t}\r\n}\r\ndouble HiMatrixTools::HIinverseError(void *inA, void *inInverse, int N, double *errMax)\r\n{\r\n\tdouble err = 0.0;\r\n\tsize_t k;\r\n\tcpp_dec_float_100 *A = (cpp_dec_float_100 *)inA;\r\n\tcpp_dec_float_100 *B = (cpp_dec_float_100 *)inInverse;\r\n\tcpp_dec_float_100 *C = (cpp_dec_float_100 *)malloc(N*N*sizeof(cpp_dec_float_100));\r\n\tif (C == NULL)\r\n\t\tthrow;\r\n\tcpp_dec_float_100 e0,em = 0.0;\r\n\tHIMatrixMultiply(A, B, C, N);\r\n\tk = 0;\r\n\tfor ( int i = 0; i < N; i++)\r\n\t{\r\n\t\tfor ( int j = 0; j < N; j++)\r\n\t\t{\r\n\t\t\tif (i == j)\r\n\t\t\t{\r\n\t\t\t\te0 = 1.0 - C[k];\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\te0 = C[k];\r\n\t\t\t}\r\n\t\t\terr += abs(e0.convert_to<double>());\r\n\t\t\tif (e0 > em)\r\n\t\t\t{\r\n\t\t\t\tem = e0;\r\n\t\t\t}\r\n\t\t\tk++;\r\n\t\t}\r\n\t}\r\n\tfree(C);\r\n\t*errMax = em.convert_to<double>();\r\n\treturn err;\r\n}", "meta": {"hexsha": "4972926d6b630119b0cd495892b2b3b697570e53", "size": 5856, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Source Code V2/boostLib/HiMatrix.cpp", "max_stars_repo_name": "DavidGeUSA/TSS", "max_stars_repo_head_hexsha": "e364e324948c68efc6362a0db3aa51696227fa60", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2020-09-27T07:35:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T11:01:31.000Z", "max_issues_repo_path": "Source Code V2/boostLib/HiMatrix.cpp", "max_issues_repo_name": "DavidGeUSA/TSS", "max_issues_repo_head_hexsha": "e364e324948c68efc6362a0db3aa51696227fa60", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-10-28T13:14:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-28T21:04:44.000Z", "max_forks_repo_path": "Source Code V2/boostLib/HiMatrix.cpp", "max_forks_repo_name": "DavidGeUSA/TSS", "max_forks_repo_head_hexsha": "e364e324948c68efc6362a0db3aa51696227fa60", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2020-09-27T07:35:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-02T13:53:21.000Z", "avg_line_length": 23.424, "max_line_length": 131, "alphanum_fraction": 0.5517418033, "num_tokens": 2000, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248259606259, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.7398869585337082}}
{"text": "#include <iostream>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#include \"utils.hpp\"\n\nusing namespace std;\nusing namespace Eigen;\n\nint main(void)\n{\n    // Make skew symmetric matrix\n    Vector3d v;\n    v << 8, 5, 6;\n\n    cout << \"== The vector ==\" << endl;\n    cout << v << endl;\n    \n    Matrix3d v_hat;\n    Vector::wedge<double>(v_hat,v);\n    cout << \"== The skew symmetric matrix ==\" << endl;\n    cout << v_hat << endl;\n\n    // Example Vector\n    Vector3d a;\n    a << 2, 5, 7;\n\n    cout << \"== Example vector ==\" << endl;\n    cout << a << endl;\n    \n    // Make Cross\n    cout << \"== v_hat * a ==\" << endl;\n    cout << v_hat * a << endl;\n    cout << \"== v x a ==\" << endl;\n    cout << v.cross(a) << endl;\n    cout << \"== -v_hat * a ==\" << endl;\n    cout << -v_hat * a << endl;\n    cout << \"== a x v ==\" << endl;\n    cout << a.cross(v) << endl;\n    \n    return 0;\n}\n", "meta": {"hexsha": "86880d5465ee1a836e3b8a3b870b6d49d9f140ca", "size": 870, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/skew_symmetric_matrix.cpp", "max_stars_repo_name": "RyodoTanaka/eigen_example", "max_stars_repo_head_hexsha": "55da46919e02d0eb7cbea9da97ffa0f9067a6d98", "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/skew_symmetric_matrix.cpp", "max_issues_repo_name": "RyodoTanaka/eigen_example", "max_issues_repo_head_hexsha": "55da46919e02d0eb7cbea9da97ffa0f9067a6d98", "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/skew_symmetric_matrix.cpp", "max_forks_repo_name": "RyodoTanaka/eigen_example", "max_forks_repo_head_hexsha": "55da46919e02d0eb7cbea9da97ffa0f9067a6d98", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-30T03:32:04.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-30T03:32:04.000Z", "avg_line_length": 20.2325581395, "max_line_length": 54, "alphanum_fraction": 0.4954022989, "num_tokens": 255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122313857379, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.7396704049391172}}
{"text": "#include <ql/option.hpp>\n#include <ql/handle.hpp>\n#include <ql/quote.hpp>\n#include <ql/quotes/simplequote.hpp>\n#include <ql/termstructures/yieldtermstructure.hpp>\n#include <ql/termstructures/yield/flatforward.hpp>\n\n#include <ql/termstructures/volatility/equityfx/blackconstantvol.hpp>\n#include <ql/termstructures/volatility/equityfx/blackvoltermstructure.hpp>\n#include <ql/time/calendars/target.hpp>\n#include <ql/time/daycounters/actual360.hpp>\n#include <boost/make_shared.hpp>\n#include <iostream>\n#include <ql/math/distributions/normaldistribution.hpp>\n\nusing std::cout;\nusing std::endl;\nusing std::vector;\nusing boost::shared_ptr;\nusing boost::make_shared;\nusing namespace QuantLib;\n\nstruct blackscholes {\n    double value;\n    double delta;\n    double gamma;\n    double theta;\n\n\n};\n\nblackscholes black_scholes_formula(double S, double K, double T,\n                                   double r, double sigma, bool call);\n\n\n\n\nusing std::sqrt;\nusing std::exp;\nusing std::log;\n\nnamespace {\n    QuantLib::CumulativeNormalDistribution N;\n    QuantLib::NormalDistribution n;\n}\n\nblackscholes black_scholes_formula(double S, double K, double T,\n                                   double r, double sigma, bool call) {\n    double d1 = (1/(sigma*sqrt(T))) * (log(S/K) + (r+sigma*sigma/2)*T);\n    double d2 = d1 - sigma*sqrt(T);\n\n    blackscholes results;\n    if (call) {\n        cout << \"Call is called: \";\n        results.value = N(d1)*S - N(d2)*K*exp(-r*T);\n        results.delta = N(d1);\n        results.theta = -(S*n(d1)*sigma)/(2*sqrt(T)) - r*K*exp(-r*T)*N(d2);\n    } else {\n        cout << \"Put is called: \";\n        results.value = N(-d2)*K*exp(-r*T) -N(-d1)*S;\n        results.delta = -N(-d1);\n        results.theta = -(S*n(d1)*sigma)/(2*sqrt(T)) + r*K*exp(-r*T)*N(-d2);\n    }\n    results.gamma = n(d1)/(S*sigma*sqrt(T));\n\n    return results;\n}\n\nclass EuropeanOption : public Instrument {\n\n  public:\n    EuropeanOption(Real strike, Option::Type, const Date& exerciseDate,\n                   const Handle<Quote>& u,\n                   const Handle<YieldTermStructure>& r,\n                   const Handle<BlackVolTermStructure>& sigma);\n    bool isExpired() const;\n    void performCalculations() const;\n    Real delta() const;\n    Real gamma() const;\n    Real theta() const;\n  private:\n    Real strike_;\n    Option::Type type_;\n    const Date& exerciseDate_;\n    const Handle<Quote>& u_;\n    const Handle<YieldTermStructure>& r_;\n    const Handle<BlackVolTermStructure>& sigma_;\n    mutable Real delta_;\n    mutable Real gamma_;\n    mutable Real theta_;\n\n};\n\nEuropeanOption ::EuropeanOption(Real strike, Option::Type type, const Date& exerciseDate, const Handle<Quote>& u,\n                                const Handle<YieldTermStructure>& r, const Handle<BlackVolTermStructure>& sigma)\n: strike_(strike), type_(type), exerciseDate_(exerciseDate), u_(u), r_(r), sigma_(sigma){\n    cout << \"Type is \" <<type_<<endl;\n    registerWith(u_);\n    registerWith(r_);\n    registerWith(sigma_);\n}\n\nbool EuropeanOption::isExpired() const {\n    Date today = Settings::instance().evaluationDate();\n    return today >= exerciseDate_;\n}\n\nvoid EuropeanOption::performCalculations() const {\n    DayCounter dayCounter = r_->dayCounter();\n    Date today = Settings::instance().evaluationDate();\n    Time T = dayCounter.yearFraction(today, exerciseDate_);\n    Rate r = r_->zeroRate(T, Continuous);\n    Volatility sigma = sigma_->blackVol(T, strike_);\n    blackscholes results = black_scholes_formula(u_->value(), strike_, T, r, sigma,\n                                             type_ == Option::Call);\n\n    NPV_ = results.value;\n    delta_ = results.delta;\n    gamma_ = results.gamma;\n    theta_ = results.theta;\n}\n\nReal EuropeanOption::delta() const {\n\n    // before returning delta_, we ensure that it is calculated: checking calculated flag (whether instrument is\n    // upto date) or it's going to trigger the calculation in case its not.\n    calculate();\n    return delta_;\n}\n\nReal EuropeanOption::gamma() const {\n\n    // before returning gamma_, we ensure that it is calculated: checking calculated flag (whether instrument is\n    // upto date) or it's going to trigger the calculation in case its not.\n    calculate();\n    return gamma_;\n}\n\nReal EuropeanOption::theta() const {\n\n    // before returning theta_, we ensure that it is calculated: checking calculated flag (whether instrument is\n    // upto date) or it's going to trigger the calculation in case its not.\n    calculate();\n    return theta_;\n}\n\nint main() {\n    Date today(1, May, 2022);\n    Settings::instance().evaluationDate() = today;\n\n    Real strike = 100.0;\n    Option::Type type = Option::Call;\n    Date exerciseDate = today + 360*3;\n\n    shared_ptr<SimpleQuote> u = make_shared<SimpleQuote>(120.0);\n    Handle<Quote> U(u);\n\n    shared_ptr<YieldTermStructure> r =\n        make_shared<FlatForward>(today, 0.01, Actual360());\n    RelinkableHandle<YieldTermStructure> R(r);\n\n    shared_ptr<BlackVolTermStructure> sigma =\n        make_shared<BlackConstantVol>(today, TARGET(), 0.20, Actual360());\n    Handle<BlackVolTermStructure> Sigma(sigma);\n\n    EuropeanOption option(strike, type, exerciseDate, U, R, Sigma);\n\n    cout << \"option value: \" << option.NPV() << endl;\n    cout << \"delta: \" << option.delta() << endl;\n    cout << \"gamma: \" << option.gamma() << endl;\n    cout << \"theta: \" << option.theta() << endl;\n\n    u->setValue(115.0);\n    cout << \"option value after u decreases: \" << option.NPV() << endl;\n\n    /*\n     * OUTPUT:\n     *\n        Type is Call\n        option value: Call is called: 29.0795\n        delta: 0.784103\n        gamma: 0.00704601\n        theta: -2.67938\n        option value after u decreases: Call is called: 25.2511\n     */\n    return 0;\n}\n", "meta": {"hexsha": "2a3f8b189345dd8211cd1910a941510406f6966a", "size": 5722, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantLib Options Pricing/EuropeanCallOptionValueAndGreeks.cpp", "max_stars_repo_name": "harshvardhan-ranvir-singh/CPP-Design-For-Quantitative-Finance", "max_stars_repo_head_hexsha": "7d42fef013768d1520cf6f3fc4a642ea2ab2deae", "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": "QuantLib Options Pricing/EuropeanCallOptionValueAndGreeks.cpp", "max_issues_repo_name": "harshvardhan-ranvir-singh/CPP-Design-For-Quantitative-Finance", "max_issues_repo_head_hexsha": "7d42fef013768d1520cf6f3fc4a642ea2ab2deae", "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": "QuantLib Options Pricing/EuropeanCallOptionValueAndGreeks.cpp", "max_forks_repo_name": "harshvardhan-ranvir-singh/CPP-Design-For-Quantitative-Finance", "max_forks_repo_head_hexsha": "7d42fef013768d1520cf6f3fc4a642ea2ab2deae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-22T12:18:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-22T12:18:45.000Z", "avg_line_length": 30.4361702128, "max_line_length": 113, "alphanum_fraction": 0.6492485145, "num_tokens": 1444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122113355091, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7396703865570213}}
{"text": "// TestFactorial.cpp\n//\n// Factorials and Binomial Coefficients.\n//\n// Copyright Datasim Education BV 2009-2010\n// Copyright John Maddock and Paul A. Bristow 2010\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#include <boost/math/special_functions/factorials.hpp>\n#include <boost/math/special_functions.hpp>\n\n#include <iostream>\nusing namespace std;\n\nint main()\n{\n  using namespace boost::math;\n\n  // Factorials\n  unsigned int n = 3;\n \n  try\n  {\n     cout << \"Factorial: \" << factorial<double>(n) << endl;\n\n     // Caution: You must provide a return type template value, so this will not compile\n     // unsigned int nfac = factorial(n); // could not deduce template argument for 'T'\n     // You must provide an explicit floating-point (not integer) return type.\n     // If you do provide an integer type, like this:\n     // unsigned int uintfac = factorial<unsigned int>(n);\n     // you will also get a compile error, for MSVC C2338.\n     // If you really want an integer type, you can convert from double:\n     unsigned int intfac = static_cast<unsigned int>(factorial<double>(n));\n     // this will be exact, until the result of the factorial overflows the integer type.\n\n     cout << \"Unchecked factorial: \" << boost::math::unchecked_factorial<float>(n) << endl;\n     // Note:\n     // unsigned int unfac = boost::math::unchecked_factorial<unsigned int>(n);\n     // also fails to compile for the same reasons.\n  } \n  catch(exception& e)\n  {\n    cout << e.what() << endl;\n  }\n\n  // Double factorial n!!\n  try\n  {\n    //cout << \"Double factorial: \" << boost::math::double_factorial<unsigned>(n);\n  }\n  catch(exception& e)\n  {\n    cout << e.what() << endl;\n  }\n\n  // Rising and falling factorials\n  try\n  {\n    int i = 2; double x = 8;\n    cout << \"Rising factorial: \" << rising_factorial(x,i) << endl;\n    cout << \"Falling factorial: \" << falling_factorial(x,i) << endl;\n  }\n  catch(exception& e)\n  {\n    cout << e.what() << endl;\n  }\n\n  // Binomial coefficients\n  try\n  {\n    unsigned n = 10; unsigned k = 2;\n    // cout << \"Binomial coefficient: \" << boost::math::binomial_coefficient<unsigned>(n,k) << endl;\n  }\n  catch(exception& e)\n  {\n    cout << e.what() << endl;\n  }\n  return 0;\n}\n\n/*\n\nOutput:\n\n  factorial_example.vcxproj -> J:\\Cpp\\MathToolkit\\test\\Math_test\\Release\\factorial_example.exe\n  Factorial: 6\n  Unchecked factorial: 6\n  Rising factorial: 72\n  Falling factorial: 56\n\n*/\n\n\n", "meta": {"hexsha": "7a51e0746e39ceea7c9ae6a82c419166585cffbf", "size": 2539, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/math/example/factorial_example.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/factorial_example.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/factorial_example.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": 25.9081632653, "max_line_length": 100, "alphanum_fraction": 0.6565576999, "num_tokens": 680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505376715775, "lm_q2_score": 0.8175744850834648, "lm_q1q2_score": 0.7396191975173195}}
{"text": "\r\n#include \"cor_algorithm/sources/utilities.h\"\r\n#include \"cor_system/sources/logger.h\"\r\n#include \"cor_type/sources/math/vector3_tmpl_impl.h\"\r\n#include \"cor_type/sources/math/vector4_tmpl_impl.h\"\r\n\r\n#define BOOST_TEST_NO_LIB\r\n#include <boost/test/unit_test.hpp>\r\n\r\nBOOST_AUTO_TEST_SUITE(vector)\r\n\r\nBOOST_AUTO_TEST_CASE(vector_3)\r\n{\r\n    cor::type::Vector3F a(1.0f, 0.0f, 0.0f);\r\n    cor::type::Vector3F b(1.0f, 1.0f, 0.0f);\r\n    cor::type::Vector3F c = a.cross(b);\r\n    cor::RFloat d = a.dot(c);\r\n\r\n    BOOST_CHECK_EQUAL(d, 0);\r\n\r\n    cor::type::Vector3F ab = a + b;\r\n    cor::type::Vector3F e = a + b - b;\r\n\r\n    BOOST_CHECK_CLOSE((e - a).get_magnitude(), 0.0, 0.00001);\r\n\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(vector_4)\r\n{\r\n    cor::type::Vector4F a(1.0f, 0.0f, 0.0f, 2.0f);\r\n    cor::type::Vector4F b(1.0f, 1.0f, 3.0f, 1.0f);\r\n    cor::RFloat d = a.dot(b);\r\n\r\n    BOOST_CHECK_CLOSE(d, 3.0, 0.00001);\r\n\r\n    cor::type::Vector4F ab = a + b;\r\n    cor::type::Vector4F e = a + b - b;\r\n\r\n    BOOST_CHECK_CLOSE((e - a).get_magnitude(), 0.0, 0.00001);\r\n\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE_END()\r\n\r\n\r\n", "meta": {"hexsha": "3a919f2ca24c101ecbe51a980bd4fc3af3f6f189", "size": 1076, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/unit/sources/math/vector_test.cpp", "max_stars_repo_name": "rmake/cor-engine", "max_stars_repo_head_hexsha": "d8920325db490d19dc8c116ab8e9620fe55e9975", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T09:55:02.000Z", "max_stars_repo_stars_event_max_datetime": "2016-09-10T03:42:23.000Z", "max_issues_repo_path": "tests/unit/sources/math/vector_test.cpp", "max_issues_repo_name": "rmake/cor-engine", "max_issues_repo_head_hexsha": "d8920325db490d19dc8c116ab8e9620fe55e9975", "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/unit/sources/math/vector_test.cpp", "max_forks_repo_name": "rmake/cor-engine", "max_forks_repo_head_hexsha": "d8920325db490d19dc8c116ab8e9620fe55e9975", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-01-22T02:30:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-10T06:56:49.000Z", "avg_line_length": 23.3913043478, "max_line_length": 62, "alphanum_fraction": 0.6273234201, "num_tokens": 380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947101574299, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.7396119072398134}}
{"text": "// Copyright John Maddock 2006, 2007\n// Copyright Paul A. Bristow 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#include <iostream>\nusing std::cout; using std::endl;\nusing std::left; using std::fixed; using std::right; using std::scientific;\n#include <iomanip>\nusing std::setw;\nusing std::setprecision;\n#include <boost/math/distributions/chi_squared.hpp>\n#include <boost/math/distributions/normal.hpp>\n#include <boost/math/special_functions/erf.hpp>\n\ndouble upper_confidence_limit_on_std_deviation(\n        double Sd,    // Sample Standard Deviation\n        unsigned N,   // Sample size\n        double pds)   // Probability\n{\n  // Calculate confidence intervals for the standard deviation.\n  // For example if we set the confidence limit to\n  // 0.95, we know that if we repeat the sampling\n  // 100 times, then we expect that the true standard deviation\n  // will be between out limits on 95 occations.\n  // Note: this is not the same as saying a 95%\n  // confidence interval means that there is a 95%\n  // probability that the interval contains the true standard deviation.\n  // The interval computed from a given sample either\n  // contains the true standard deviation or it does not.\n  // See http://www.itl.nist.gov/div898/handbook/eda/section3/eda358.htm\n\n  // using namespace boost::math;\n  using boost::math::chi_squared;\n  using boost::math::quantile;\n  using boost::math::complement;\n\n  // Start by declaring the distribution we'll need:\n  chi_squared dist(N - 1);\n  \n  // Calculate limits:\n  double lower_limit = ((N - 1) * Sd * Sd / quantile(complement(dist, 1 - pds))); // Needs to be checked if its pds or pds/2\n  double upper_limit = ((N - 1) * Sd * Sd / quantile(dist, 1 - pds));\n  std::cout << \"Lower Limit = \" << lower_limit << \"\\n\";\n  std::cout << \"Upper Limit = \" << upper_limit << \"\\n\";\n\n  return upper_limit;\n} \n\ndouble upper_confidence_limit_gaussian(\n        double Sd,    // Sample Standard Deviation\n        double pdv)   // Probability\n{\n  // Calculate confidence intervals for the standard deviation.\n  // For example if we set the confidence limit to\n  // 0.95, we know that if we repeat the sampling\n  // 100 times, then we expect that the true standard deviation\n  // will be between out limits on 95 occations.\n  // Note: this is not the same as saying a 95%\n  // confidence interval means that there is a 95%\n  // probability that the interval contains the true standard deviation.\n  // The interval computed from a given sample either\n  // contains the true standard deviation or it does not.\n  // See http://www.itl.nist.gov/div898/handbook/eda/section3/eda358.htm\n\n  // using namespace boost::math;\n  using boost::math::normal;\n  using boost::math::quantile;\n  using boost::math::complement;\n\n  // Start by declaring the distribution we'll need:\n  normal normdist(0, Sd);\n  \n  // Calculate limits:\n  double upper_limit = quantile(normdist, pdv);\n\n  return upper_limit;\n}\n\ndouble get_inverse_error_func(double probability) \n{\n  // Calculate the inverse gaussian error function for a given probability\n  // Check if probability value is in a valid range (absolute value)\n  if(probability > 1 && probability < -1)\n    return 0;\n\n  return boost::math::erf_inv(probability);\n}\n", "meta": {"hexsha": "8797745b0d0d3af7bcd35919f68c4c532476fc3d", "size": 3360, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/micro-services/sync-service/sync/ProbabilityLib.cpp", "max_stars_repo_name": "quartz-roseline/quartz", "max_stars_repo_head_hexsha": "608e1bf43b4ad4a0d716c3e8fc3fa186ac693cac", "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": "src/micro-services/sync-service/sync/ProbabilityLib.cpp", "max_issues_repo_name": "quartz-roseline/quartz", "max_issues_repo_head_hexsha": "608e1bf43b4ad4a0d716c3e8fc3fa186ac693cac", "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/micro-services/sync-service/sync/ProbabilityLib.cpp", "max_forks_repo_name": "quartz-roseline/quartz", "max_forks_repo_head_hexsha": "608e1bf43b4ad4a0d716c3e8fc3fa186ac693cac", "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": 36.5217391304, "max_line_length": 124, "alphanum_fraction": 0.7119047619, "num_tokens": 860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896693699845, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.7395541365631737}}
{"text": "/**\n * @file\n * @brief We integrate a function over a square using quadrature rules of a\n * fixed degree and refine the mesh to achieve convergence.\n * @author Raffael Casagrande\n * @date   2018-09-02 05:17:45\n * @copyright MIT License\n */\n\n#include <lf/geometry/geometry.h>\n#include <lf/io/io.h>\n#include <lf/mesh/hybrid2d/hybrid2d.h>\n#include <lf/quad/quad.h>\n\n#include <Eigen/Eigen>\n#include <boost/math/constants/constants.hpp>\n#include <boost/program_options.hpp>\n\n#include \"lf/refinement/test/refinement_test_utils.h\"\n\ntemplate <class F>\ndouble integrate(const lf::mesh::Mesh& mesh, lf::quad::quadDegree_t degree,\n                 F f) {\n  double result = 0.;\n  auto qr_tria = lf::quad::make_QuadRule(lf::base::RefEl::kTria(), degree);\n  auto qr_quad = lf::quad::make_QuadRule(lf::base::RefEl::kQuad(), degree);\n\n  Eigen::MatrixXd points(1, 1);\n  Eigen::VectorXd weights(1);\n\n  for (const auto* e : mesh.Entities(0)) {\n    if (e->RefEl() == lf::base::RefEl::kTria()) {\n      points = qr_tria.Points();\n      weights = qr_tria.Weights();\n    } else {\n      points = qr_quad.Points();\n      weights = qr_quad.Weights();\n    }\n    auto mapped_points = e->Geometry()->Global(points);\n    auto integration_elements = e->Geometry()->IntegrationElement(points);\n    for (Eigen::Index j = 0; j < points.cols(); ++j) {\n      result += f(mapped_points.col(j)) * weights(j) * integration_elements(j);\n    }\n  }\n  return result;\n}\n\nint main(int argc, char** argv) {\n  // define allowed command line arguments:\n  namespace po = boost::program_options;\n  po::options_description desc(\"Allowed options\");\n  // clang-format off\n  desc.add_options()\n  (\"help\", \"produce this help message\")\n  (\"quad_degree\", po::value<int>()->default_value(3), \"The degree of the local quadrature rule.\")\n  (\"max_level\", po::value<int>()->default_value(5), \"The number of refinement levels\")\n  ;\n  // clang-format on\n  po::variables_map vm;\n  po::store(po::parse_command_line(argc, argv, desc), vm);\n  po::notify(vm);\n  if (vm.count(\"help\") != 0U) {\n    std::cout << desc << std::endl;\n    return 1;\n  }\n\n  int max_level = vm[\"max_level\"].as<int>();\n  int quad_degree = vm[\"quad_degree\"].as<int>();\n\n  // Create a three element mesh that contains two triangles and one\n  // quadrilateral\n  lf::mesh::hybrid2d::MeshFactory mesh_factory(2);\n  mesh_factory.AddPoint(Eigen::Vector2d{0, 0});\n  mesh_factory.AddPoint(Eigen::Vector2d{0.5, 0});\n  mesh_factory.AddPoint(Eigen::Vector2d{1, 0});\n  mesh_factory.AddPoint(Eigen::Vector2d{1, 1});\n  mesh_factory.AddPoint(Eigen::Vector2d{0.5, 1});\n  mesh_factory.AddPoint(Eigen::Vector2d{0, 1});\n  Eigen::MatrixXd node_coords(2, 3);\n  node_coords << 0, 0.5, 0.5, 0, 0, 1;\n  mesh_factory.AddEntity(lf::base::RefEl::kTria(),\n                         std::vector<lf::base::size_type>{0, 1, 4},\n                         std::make_unique<lf::geometry::TriaO1>(node_coords));\n  node_coords << 0, 0.5, 0, 0, 1, 1;\n  mesh_factory.AddEntity(lf::base::RefEl::kTria(),\n                         std::vector<lf::base::size_type>{0, 4, 5},\n                         std::make_unique<lf::geometry::TriaO1>(node_coords));\n  node_coords = Eigen::MatrixXd(2, 4);\n  node_coords << 0.5, 1, 1, 0.5, 0, 0, 1, 1;\n  mesh_factory.AddEntity(lf::base::RefEl::kQuad(),\n                         std::vector<lf::base::size_type>{1, 2, 3, 4},\n                         std::make_unique<lf::geometry::QuadO1>(node_coords));\n\n  auto base_mesh = mesh_factory.Build();\n\n  // parameters:\n  auto pi = boost::math::constants::pi<double>();\n  auto f = [&](const Eigen::Vector2d& x) {\n    return std::sin(pi * x(0)) * std::pow(std::cos(pi * x(1)), 2);\n  };\n  auto exact_integral = 1. / pi;\n\n  auto mesh = base_mesh;\n  auto errors = Eigen::VectorXd(max_level + 1);\n  for (int level = 0; level <= max_level; ++level) {\n    lf::io::VtkWriter vtk_writer(mesh,\n                                 \"level\" + std::to_string(level) + \".vtk\");\n\n    auto approx = integrate(*mesh, quad_degree, f);\n    errors(level) = std::abs(approx - exact_integral);\n\n    lf::refinement::MeshHierarchy mh(\n        mesh, std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2));\n    mh.RefineRegular();\n    mesh = mh.getMesh(1);\n  }\n\n  std::cout << \"measured errors for each level: \" << std::endl;\n  std::cout << errors << std::endl << std::endl;\n\n  // estimate the rate of convergence:\n  Eigen::MatrixXd A(max_level + 1, 2);\n  A.col(0).setOnes();\n  A.col(1) = (-Eigen::ArrayXd::LinSpaced(max_level + 1, 1, max_level + 1) *\n              std::log(2))\n                 .matrix();\n\n  Eigen::VectorXd b = errors.transpose().array().log().matrix();\n\n  // consider only the three smallest meshes:\n  A = A.bottomRows(3);\n  b = b.bottomRows(3);\n\n  Eigen::VectorXd x =\n      A.bdcSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(b);\n  std::cout << \"estimated order of convergence = \" << x(1) << std::endl;\n}\n", "meta": {"hexsha": "3ded13b044b3d5357317345ec88691cfd22f5ae4", "size": 4838, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/quad/quad_demo.cc", "max_stars_repo_name": "Fytch/lehrfempp", "max_stars_repo_head_hexsha": "c804b3e350aa893180f1a02ce57a93b3d7686e91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2018-08-30T19:55:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T16:38:06.000Z", "max_issues_repo_path": "examples/quad/quad_demo.cc", "max_issues_repo_name": "Fytch/lehrfempp", "max_issues_repo_head_hexsha": "c804b3e350aa893180f1a02ce57a93b3d7686e91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 151.0, "max_issues_repo_issues_event_min_datetime": "2018-05-27T13:01:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-04T14:50:50.000Z", "max_forks_repo_path": "examples/quad/quad_demo.cc", "max_forks_repo_name": "Fytch/lehrfempp", "max_forks_repo_head_hexsha": "c804b3e350aa893180f1a02ce57a93b3d7686e91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2018-11-13T13:46:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T17:33:52.000Z", "avg_line_length": 35.0579710145, "max_line_length": 97, "alphanum_fraction": 0.6254650682, "num_tokens": 1438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361580958427, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.7395102616448603}}
{"text": "#include <iostream>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <chrono>\n\nusing namespace std;\nusing namespace Eigen;\n\nint main(){\n    const int n = 100;\n    MatrixXd a = MatrixXd::Random(n,n);\n    MatrixXd A;\n    A.noalias() = a * a.transpose();\n    VectorXd b = VectorXd::Random(n);\n    VectorXd x;\n    \n    cout<<\"\u76f4\u63a5\u6c42\u9006\"<<endl;\n    auto t0 = chrono::steady_clock::now();\n    x = A.inverse()*b;\n    auto t1 = chrono::steady_clock::now();\n    cout<<\"Cost time: \"<< chrono::duration<double,std::milli>(t1-t0).count()<<\"ms\"<<endl;\n    cout<<\"x= \"<<x.transpose()<<endl;\n\n    cout<<\"QR \u5206\u89e3\"<<endl;\n    auto t2 = chrono::steady_clock::now();\n    x = A.colPivHouseholderQr().solve(b);\n    auto t3 = chrono::steady_clock::now();\n    cout<<\"Cost time: \"<< chrono::duration<double,std::milli>(t3-t2).count()<<\"ms\"<<endl;\n    cout<<\"x= \"<<x.transpose()<<endl;\n\n    cout<<\"Cholesky \u5206\u89e3\"<<endl;\n    auto t4 = chrono::steady_clock::now();\n    x = A.ldlt().solve(b);\n    auto t5 = chrono::steady_clock::now();\n    cout<<\"Cost time: \"<< chrono::duration<double,std::milli>(t5-t4).count()<<\"ms\"<<endl;\n    cout<<\"x= \"<<x.transpose()<<endl;\n\n    return 0;\n}", "meta": {"hexsha": "97579d850c69cb16539b3e1031e36f7a80962c33", "size": 1148, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "slamhw2/hw2.cpp", "max_stars_repo_name": "Yaozhuwa/slambook-homework", "max_stars_repo_head_hexsha": "0c0ede6df828e9bd03445545a1e4552f9148a7cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-04-23T03:27:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-20T15:29:10.000Z", "max_issues_repo_path": "slamhw2/hw2.cpp", "max_issues_repo_name": "Yaozhuwa/slambook-homework", "max_issues_repo_head_hexsha": "0c0ede6df828e9bd03445545a1e4552f9148a7cc", "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": "slamhw2/hw2.cpp", "max_forks_repo_name": "Yaozhuwa/slambook-homework", "max_forks_repo_head_hexsha": "0c0ede6df828e9bd03445545a1e4552f9148a7cc", "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.4358974359, "max_line_length": 89, "alphanum_fraction": 0.5958188153, "num_tokens": 339, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541610257062, "lm_q2_score": 0.785308583400079, "lm_q1q2_score": 0.7394890952478872}}
{"text": "#include <bits/stdc++.h>\n#include <boost/random.hpp>\n#include \"util.h\"\n\nusing namespace std;\n\nvoid Util::generate_divisors(const vector< pair<int,int> > &prime_factorization, vector<int> &ret, int at, int sofar) {\n  if (at == prime_factorization.size()) {\n    ret.push_back(sofar);\n  } else {\n    generate_divisors(prime_factorization, ret, at+1, sofar);\n    for (int i = 0; i < prime_factorization[at].second; ++i) {\n      sofar *= prime_factorization[at].first;\n      generate_divisors(prime_factorization, ret, at+1, sofar);\n    }\n  }\n}\n  \n// calculate generator for multiplicative group of F_q, q prime\nint Util::primitive_root(int q, boost::random::mt19937 &rng) {\n  int val = q-1;\n  vector< pair<int, int> > prime_factorization; // factorize q-1;\n  for (int d = 2; d*d <= q; ++d)\n    if (val % d == 0) {\n      int cnt = 0;\n      while (val % d == 0) {\n\t++cnt;\n\tval /= d;\n      }\n      prime_factorization.push_back(make_pair(d, cnt));    \n    }\n  if (val != 1)\n    prime_factorization.push_back(make_pair(val, 1));\n  vector<int> divisors;\n  generate_divisors(prime_factorization, divisors, 0, 1);\n  boost::uniform_int<> unif_int = boost::uniform_int<>(1, q - 1);\n  while (true) {\n    // a random element of F_p^* has probability 1-o(1) of being a generator\n    int z = unif_int(rng);\n    bool bad = false;\n    for (int div : divisors) {\n      if ((div == 1) || (div == q-1))\n\tcontinue;\n      if (fast_mod_pow(z, div, q) == 1) {\n\tbad = true;\n\tbreak;\n      }\n    }\n    if (!bad) \n      return z;\n  }\n}  \n\n\nvector<int> Util::hadamard_transform(vector<int> x) {\n  int n = x.size();\n  if (n == 1)\n    return x;\n  else {\n    assert((n&1) == 0);\n    vector<int> ret(n);\n    vector<int> xl(n/2);\n    vector<int> xh(n/2);\n    for (int i = 0; i < n/2; ++i)\n      xl[i] = x[i];\n    for (int i = n/2; i < n; ++i)\n      xh[i-n/2] = x[i];\n    xl = hadamard_transform(xl);\n    xh = hadamard_transform(xh);\n    for (int i = 0; i < n/2; ++i) {\n      ret[i] = xl[i] + xh[i];\n      ret[n/2+i] = xl[i] - xh[i];\n    }\n    return ret;\n  }\n}\n\nint Util::fast_mod_pow(int x, int n, int q) {\n  if (n==0)\n    return 1;\n  else {\n    int z = fast_mod_pow(x, n/2, q);\n    z = ((int64_t)z * z) % q;\n    if (n&1 == 1)\n      z = ((int64_t)z * x) % q;\n    return z;\n  }\n}   \n\nvector<int> Util::compute_inverse_table(int q, boost::random::mt19937 &rng) {\n  // primitive root of finite field F_q, allows us to calculate table of all\n  // compute table of all F_q multiplicative inverses in O(q) time; naively\n  // would be O(q log q), which is O(k log k) for t=2 since q=Theta(k) for t=2\n  assert(is_prime(q));\n  int z = primitive_root(q, rng);\n  vector<int> zpows(q), ret(q);\n  zpows[0] = 1;\n  for (int i = 1; i < q; ++i) \n    zpows[i] = ((int64_t)zpows[i-1] * z) % q;\n  for (int i = 0; i < q-1; ++i) \n    ret[zpows[i]] = zpows[q-i-1];\n  return ret;\n}\n\nint Util::first_non_zero(const vector<int> &v) {\n  int i = 0;\n  while ((i<v.size()) && !v[i])\n    ++i;\n  if (i == v.size())\n    return -1;\n  else\n    return i;\n}\n\n// normal a nonzero vector so that it's canonical (first non-entry is a 1)\nvoid Util::canonicalize(vector<int> &v, int q, const vector<int> &qinv) {\n  int i = first_non_zero(v);\n  assert(i != -1);\n  int g = qinv[v[i]];\n  for (int j = i; j < v.size(); ++j)\n    v[j] = ((int64_t)v[j] * g) % q;\n}\n\nvector<int> Util::canonicalized_index_to_vec(int j, int l, int q) {\n  // given an index in {0,...,K-1}, return the corresponding canonical vector\n  // recall a canonical vector is a vector in {0,...,q-1}^t which is nonzero,\n  // and its first nonzero entry (going from smallest vector index to largest)\n  // has the value 1\n  int tot = 0;\n  int qpow = 1;\n  int num_zeroes = l - 1;\n  while (j >= tot + qpow) {\n    tot += qpow;\n    qpow *= q;\n    num_zeroes -= 1;\n  }\n  vector<int> ret(l);\n  ret[num_zeroes] = 1;\n  int r = j - tot;\n  int at = l - 1;\n  while (r > 0) {\n    ret[at] = r % q;\n    r /= q;\n    at -= 1;\n  }\n  return ret;\n}\n\nint Util::canonicalized_vec_to_index(const vector<int> &v, int q, const vector<int> &qpows) {\n  // given a canonical vector in {0,...,q-1}^t, return its index in \n  // {0,...,K-1}\n  int leftmost_one = Util::first_non_zero(v);\n  assert((leftmost_one!=-1) && (v[leftmost_one]==1));\n  int ret = (qpows[v.size() - 1 - leftmost_one] - 1) / (q - 1);\n  int c = 0;\n  for (int i = leftmost_one + 1; i < v.size(); ++i) \n    c = (c*q) + v[i];\n  return ret + c;\n}\n\n// vindex is index (1-based indexing) to a canonical vector v in F_q^l\n// returns a 3dim-vector (v[0], g, vsuff_index), where g is the value of the\n// first non-zero entry of vsuffix (vector v with v[0] removed) or 1 if\n// vsuffix is the 0 vector. vsuff_index is the index of vsuffix amongst all\n// canonical vectors in F_q^{l-1}\nvector<int> Util::decompose_canonical_vector(int vindex, int l, int q,\n\t\t\t\t\t     const vector<int> &qpows, const vector<int> &qinv) {\n  assert(l > 0);\n  vector<int> v(l), vsuffix(l - 1); // vindex and its suffix as vectors\n  if (vindex) {\n    v = Util::canonicalized_index_to_vec(vindex - 1, l, q);\n    assert(Util::canonicalized_vec_to_index(v, q, qpows) == vindex - 1);\n    for (int i = 1; i < v.size(); ++i)  \n      vsuffix[i - 1] = v[i];\n  }\n  int g = 1; // value of first nonzero entry in vbsuffix, else 1 if it's all zeroes\n  bool vsuffix_all_zeroes = true;\n  for (int i = 0; i < vsuffix.size(); ++i)\n    if (vsuffix[i]) {\n      g = vsuffix[i];\n      vsuffix_all_zeroes = false;\n      break;\n    }\n  if (!vsuffix_all_zeroes)\n    Util::canonicalize(vsuffix, q, qinv); // multiplies vsuffix through by g^{-1} entry-wise (mod q)\n  int vsuff_index = 0; // a number in the range [0, (q^{l-1}-1)/(q-1) + 1]\n  if (!vsuffix_all_zeroes) {\n    vsuff_index = Util::canonicalized_vec_to_index(vsuffix, q, qpows) + 1;\n    assert(Util::canonicalized_index_to_vec(vsuff_index - 1, l - 1, q) == vsuffix);\n  }\n  assert(vsuff_index <= (qpows[l - 1] - 1) / (q - 1) + 1);\n  return vector<int>( { v[0], g, vsuff_index } );\n}\n\nint Util::mod_dot_product(const vector<int> &u, const vector<int> &v, int q) {\n  assert(u.size() == v.size());\n  int ret = 0;\n  for (int i = 0; i < u.size(); ++i)\n    (ret += ((int64_t)u[i]*v[i]) % q) %= q;\n  return ret;\n}\n\nbool Util::is_prime(int q) {\n  if (q < 2) return false;\n  else if (q == 2) return true;\n  else if (q % 2 == 0) return false;\n  else {\n    for (int d = 3; d < q; d += 2) {\n      if ((int64_t)d*d > q) break;\n      if (q % d == 0) return false;\n    }\n    return true;\n  }\n}\n\n// pick a random nonzero vector u in F_q^t amongst those with <u,v> = s\n// we assume here that v is not zero (else this isn't possible for all s)\nvector<int> Util::randvec_with_specified_dot_product(const vector<int>& v, int s, int q,\n\t\t\t\t\t\t     const vector<int> &qinv, boost::random::mt19937 &rng) {\n  boost::uniform_int<> unif_int = boost::uniform_int<>(0, q - 1);\n  vector<int> ret(v.size());\n  // pick ret to be a random element of (F_q)^t \\ {0} s.t. <ret,v> = s mod q\n  while (true) {\n    for (int i = 0; i < v.size(); ++i)\n      ret[i] = unif_int(rng);\n    if (accumulate(ret.begin(), ret.end(), 0) == 0)\n      continue;\n    \n    int i = first_non_zero(v);\n    assert(i != -1);\n    \n    // compute the dot product of ret with v, ignoring index i\n    int z = 0;\n    for (int j = 0; j < v.size(); ++j)\n      if (j != i)\n\tz = (z + (int64_t)v[j]*ret[j]) % q;\n    // now set ret[i] to make the dot product s\n    // we need z + ret[i]*v[i] = s, so ret[i] = (s - z)*v[i]^{-1}\n    ret[i] = ((int64_t)(q + s - z) * qinv[v[i]]) % q;\n    // be careful; ret might now be the 0 vector. try again if it is.\n    if (accumulate(ret.begin(), ret.end(), 0))\n      break;\n  }\n#ifdef DEBUG\n  // make sure the dot product is actually what we said it would be\n  int calc = 0;\n  for (int i = 0; i < v.size(); ++i)\n    (calc += (int64_t)v[i]*ret[i]) %= q;\n  assert(calc == s);\n#endif\n  return ret;\n}\n\n", "meta": {"hexsha": "9ec8ebe898e0a4e3d4dfcaa3695064304a35dd53", "size": 7789, "ext": "cc", "lang": "C++", "max_stars_repo_path": "oracles/util/util.cc", "max_stars_repo_name": "minilek/private_frequency_oracles", "max_stars_repo_head_hexsha": "7b4f9723b59b234fda504869e4ed8a2cbc2cf19b", "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": "oracles/util/util.cc", "max_issues_repo_name": "minilek/private_frequency_oracles", "max_issues_repo_head_hexsha": "7b4f9723b59b234fda504869e4ed8a2cbc2cf19b", "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": "oracles/util/util.cc", "max_forks_repo_name": "minilek/private_frequency_oracles", "max_forks_repo_head_hexsha": "7b4f9723b59b234fda504869e4ed8a2cbc2cf19b", "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": 30.6653543307, "max_line_length": 119, "alphanum_fraction": 0.5787649249, "num_tokens": 2692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206818021531, "lm_q2_score": 0.8198933315126792, "lm_q1q2_score": 0.7394787525629544}}
{"text": "/*=============================================================================\n\n  PHAS0100ASSIGNMENT2: PHAS0100 Assignment 2 Gravitational N-body Simulation\n\n  Copyright (c) University College London (UCL). All rights reserved.\n\n  This software is distributed WITHOUT ANY WARRANTY; without even\n  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n  PURPOSE.\n\n  See LICENSE.txt in the top level directory for details.\n\n=============================================================================*/\n\n#include \"catch.hpp\"\n#include \"nbsimCatchMain.h\"\n#include \"nbsimBasicTypes.h\"\n#include \"nbsimMyFunctions.h\"\n#include <iostream>\n#include <Eigen/Dense>\n#include <cmath>\n\n/* precision for isApprox() */\n#define PREC 0.01\n\nTEST_CASE( \"1: isApprox Test\", \"[PartA]\" ) {\n\tEigen::Vector3d v1(1,0,0), v2(0,1,0), exp(0,1.0001,0.0001);\n\tREQUIRE(v2.isApprox(exp, PREC));\n}\n\nTEST_CASE( \"2: particle move test\", \"[PartA]\" ) {\n\tEigen::Vector3d v1(1,0,0), v2(0,1,0), exp(0,1,0), zero(0,0,0), v1_1(1.00001, 0.00001, 0);\n\tnbsim::Particle parA(v1, v2), parB(v1, v2), parC(v1, v2);\n\t/* Check if correctly initialized. */\n\tREQUIRE(parA.getPosition() == v1);\n\tREQUIRE(parA.getVelocity() == v2);\n\tdouble ts = 0.0001;\n\t/* a. no acceleration. */\n\tfor (double t=0; t<2*M_PI; t+=ts) {\n\t\tparA.integrateTimestep(zero, ts);\n\t}\n\t/* xt should be x + v * t . */\n\tstd::cout << parA.getPosition() << std::endl;\n\tREQUIRE(parA.getPosition().isApprox(v1 + v2 * 2*M_PI, PREC));\n\n\t/* b. constant acc. */\n\tfor (double t=0; t<2*M_PI; t+=ts) {\n\t\tparB.integrateTimestep(v2, ts);\n\t}\n\t/* xt should be x + v*t + 0.5*a*t^2 */\n\tstd::cout << parB.getPosition() << std::endl;\n\tstd::cout << v1 + v2*2*M_PI + 0.5*v2*2*M_PI*2*M_PI << std::endl;\n\tREQUIRE(parB.getPosition().isApprox(v1 + v2*2*M_PI + 0.5*v2*2*M_PI*2*M_PI, PREC));\n\n\t/* c.  centripetal a=-x. */\n\tfor (double t=0; t<2*M_PI; t+=ts) {\n\t\tEigen::Vector3d acc = -parC.getPosition();\n\t\tparC.integrateTimestep(acc, ts);\n\t}\n\tstd::cout << parC.getPosition() << std::endl;\n\tREQUIRE(parC.getPosition().isApprox(v1, PREC));\n\n}\n\nTEST_CASE(\"MassiveParticle test\", \"[PartA]\") {\n\tEigen::Vector3d x1(1,0,0), v1(0,0.5,0), x2(-1,0,0), v2(0,-0.5,0);\n\tstd::shared_ptr<nbsim::MassiveParticle> mp0(new nbsim::MassiveParticle(x1, v1, 10)), \n\t\t\t\t\t\t\t\t\t\t\tmp1(new nbsim::MassiveParticle(x1, v1, 1/GRAV)), \n\t\t\t\t\t\t\t\t\t\t\tmp2(new nbsim::MassiveParticle(x2, v2, 1/GRAV));\n\tdouble ts = 0.0001, dur = 2*M_PI;\n\t/* check init */\n\tREQUIRE(mp0->getPosition().isApprox(x1));\n\tREQUIRE(mp0->getVelocity().isApprox(v1));\n\t/* a. no attractor test. */\n\tfor (double t=0; t<dur; t+=ts) {\n\t\tmp0->integrateTimestep(ts);\n\t}\n\t/* xt should be x + v * t . */\n\tstd::cout << mp0->getPosition() << std::endl;\n\tstd::cout << x1 + v1 * dur << std::endl;\n\tREQUIRE(mp0->getPosition().isApprox(x1 + v1 * dur, PREC));\n\n\t/* b. gravitationally attract */\n\tmp1->addAttractor(mp2);\n\tmp2->addAttractor(mp1);\n\tstd::cout << \"mu\" << mp1->getMu() << std::endl;\n\tfor (double t=0; t<dur; t+=ts) {\n\t\tmp1->calculateAcceleration();\n\t\tmp1->integrateTimestep(ts);\n\t\tmp2->calculateAcceleration();\n\t\tmp2->integrateTimestep(ts);\n\t}\n\t/* distance should be the same */\n\tEigen::Vector3d ro = (x1 - x2);\n\tEigen::Vector3d r = (mp1->getPosition() - mp2->getPosition());\n\tstd::cout << ro.norm() << std::endl;\n\tstd::cout << r.norm() << std::endl;\n\tREQUIRE(abs(ro.norm() - r.norm()) < PREC);\n\n}\n", "meta": {"hexsha": "4c2134b6f417d922faa05f6a83cdd37f0bc14125", "size": 3330, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Testing/nbsimSolarTest.cpp", "max_stars_repo_name": "Tr0py/cpp-lean", "max_stars_repo_head_hexsha": "c35d2425736389fed8e45d39238dd696aba5485e", "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": "Testing/nbsimSolarTest.cpp", "max_issues_repo_name": "Tr0py/cpp-lean", "max_issues_repo_head_hexsha": "c35d2425736389fed8e45d39238dd696aba5485e", "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": "Testing/nbsimSolarTest.cpp", "max_forks_repo_name": "Tr0py/cpp-lean", "max_forks_repo_head_hexsha": "c35d2425736389fed8e45d39238dd696aba5485e", "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.9702970297, "max_line_length": 90, "alphanum_fraction": 0.6114114114, "num_tokens": 1125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772318846386, "lm_q2_score": 0.8459424373085145, "lm_q1q2_score": 0.7394190239363707}}
{"text": "/*-------------ConjGrad.cpp---------------------------------------------------//\n*\n*              Conjugate Gradient Method\n*\n* Purpose: This file intends to solve a simple linear algebra equation:\n*              Ax = b\n*              Where A is a square Matrix of dimension N and x, b are vectors\n*              of length N. \n*\n*   Notes: This will use the eigen LA library for solving things.\n*\n*-----------------------------------------------------------------------------*/\n\n#include <iostream>\n#include <Eigen/Core>\n#include <memory>\n#include <cassert>\n#include <cmath>\n\nusing namespace Eigen;\n\n// Function for Conj Gradient -- All the big stuff happens here\nvoid conjgrad(const Matrix2d &A, const Vector2d &b, Vector2d &x_0, \n              double thresh);\n\n/*----------------------------------------------------------------------------//\n* MAIN\n*-----------------------------------------------------------------------------*/\n\nint main(){\n\n    double thresh = 0.001;\n\n    Matrix2d a(2,2);\n    Vector2d b, x;\n\n    a(0,0) = 4; a(1,0) = 1; a(0,1) = 1; a(1,1) = 3;\n    x(0) = 2; x(1) = 1;\n    b(0) = 1; b(1) = 2;\n\n    conjgrad(a, b, x, thresh);\n\n    std::cout << \"Conjugate Gradient output with threshold \" << thresh << '\\n';\n\n    std::cout << x(0) << '\\t' << x(1) <<'\\n';\n\n}\n\n/*----------------------------------------------------------------------------//\n* SUBROUTINES\n*-----------------------------------------------------------------------------*/\n\n// Function for Conj Gradient -- All the big stuff happens here\nvoid conjgrad(const Matrix2d &A, const Vector2d &b, Vector2d &x_0, \n              double thresh){\n\n    Vector2d r, p;\n    double alpha, diff, beta, temp1, temp2;\n\n    // definingin first r\n    Vector2d r_0 = b - (A * x_0);\n\n    // setting x arbitrarily high to start\n    Vector2d x = x_0 * 4;\n\n    // *grumble... gustorn... grumble*\n    Vector2d p_0 = r_0;\n\n    diff = (x - x_0).norm();\n    while (diff > thresh){\n\n        // Note, matmul will output a Matrix2d with one element.\n        temp1 = r_0.transpose() * r_0;\n        temp2 = p_0.transpose() * A * p_0;\n        alpha = temp1 / temp2;\n\n        x = x_0 + (p_0 * alpha);\n        r = r_0 - (A * alpha * p_0);\n\n        temp1 = r.transpose() * r;\n        temp2 = r_0.transpose() * r_0;\n\n        beta = temp1 / temp2;\n        \n        p = r + (p_0 * beta); \n\n        diff = (x - x_0).norm();;\n\n        // set all the values to naughts\n        x_0 = x;\n        r_0 = r;\n        p_0 = p;\n    }\n}\n\n", "meta": {"hexsha": "d420b7064ffeeed88724ec3498f7fee98eaa5295", "size": 2467, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Archive/LA/ConjGrad_eigen.cpp", "max_stars_repo_name": "mika314/simuleios", "max_stars_repo_head_hexsha": "0b05660c7df0cd6e31eb5e70864cbedaec29b55a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 197.0, "max_stars_repo_stars_event_min_datetime": "2015-07-26T02:04:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-21T11:53:33.000Z", "max_issues_repo_path": "Archive/LA/ConjGrad_eigen.cpp", "max_issues_repo_name": "shiffman/simuleios", "max_issues_repo_head_hexsha": "57239350d2cbed10893483bda65fa323e5e3a06d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 18.0, "max_issues_repo_issues_event_min_datetime": "2015-08-04T22:55:46.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-06T02:33:48.000Z", "max_forks_repo_path": "Archive/LA/ConjGrad_eigen.cpp", "max_forks_repo_name": "shiffman/simuleios", "max_forks_repo_head_hexsha": "57239350d2cbed10893483bda65fa323e5e3a06d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 55.0, "max_forks_repo_forks_event_min_datetime": "2015-08-02T21:43:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-13T18:25:08.000Z", "avg_line_length": 25.6979166667, "max_line_length": 80, "alphanum_fraction": 0.4398054317, "num_tokens": 666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628703, "lm_q2_score": 0.7981867705385763, "lm_q1q2_score": 0.7393633862689227}}
{"text": "#include<iostream>\n#include<fstream>\n#include<vector>\n#include <Eigen/Dense>\n#include<string>\n\nusing Eigen::MatrixXd;\nusing namespace std;\n\nvoid print_vector(vector<vector<double> > v);\nvoid print_matrix_vector(vector<double> v);\nMatrixXd* read_matrix(string filename);\nvoid write_matrix(string filename, MatrixXd m);\n\nint main(){\n\n    MatrixXd* data = read_matrix(\"83ppl.csv\");\n\n    // Data arrangement:\n    int Nsize = (*data).rows();\n    MatrixXd x_data(Nsize, 1);\n    MatrixXd y_data(Nsize, 1);\n    x_data << (*data).col(3);\n    y_data << (*data).col(2);\n    x_data = x_data.array() / y_data.array();\n\n    // Linear model:--------------------------------------------------------------------\n    // int Msize = 2;\n    // MatrixXd A(Nsize,Msize);\n    // MatrixXd b(Nsize,1);\n\n    // A << x_data, MatrixXd::Ones(Nsize,1);\n    // b << y_data;\n\n    // MatrixXd At = A.transpose();\n    // MatrixXd X(Msize,1); \n    // X = (At*A).inverse() * At * b;\n\n    // double m = X(0);\n    // double c = X(1);\n    // cout<<\"slope m: \"<<m<<endl<<\"const c: \"<<c<<endl;\n\n    // MatrixXd Yi_Xi(350,2);\n    // for(int i=0; i<350; i++){\n    //     Yi_Xi(i,0) = m*i + c;\n    //     Yi_Xi(i,1) = i;\n    // }\n    // write_matrix(\"linear_model.txt\", Yi_Xi);\n    \n    // Exp model--------------------------------------------------------------------\n\n    // int Msize = 2;\n    // MatrixXd A(Nsize,Msize);\n    // MatrixXd b(Nsize,1);\n\n    // A << x_data, MatrixXd::Ones(Nsize,1);\n    // b << y_data.array().log();\n\n    // MatrixXd At = A.transpose();\n    // MatrixXd X(Msize,1); \n    // X = (At*A).inverse() * At * b;\n\n    // long double a1 = exp(X(1)), b1 = X(0);\n    // cout<<\"Exp a: \"<<  a1 <<\"Exp b: \"<< b1<<endl;\n\n    // MatrixXd Yi_Xi(350,2);\n    // for(int i=0; i<350; i++){\n    //     Yi_Xi(i,0) = a1 * exp(b1*i);\n    //     Yi_Xi(i,1) = i;\n    // }\n    // write_matrix(\"exp_model.txt\", Yi_Xi);\n\n    // x-Exp model--------------------------------------------------------------------\n\n    // int Msize = 2;\n    // MatrixXd A(Nsize,Msize);\n    // MatrixXd b(Nsize,1);\n\n    // A << x_data.array().log() , MatrixXd::Ones(Nsize,1);\n    // b << y_data.array().log();\n\n    // MatrixXd At = A.transpose();\n    // MatrixXd X(Msize,1); \n    // X = (At*A).inverse() * At * b;\n\n    // double a1 = exp(X(1)), b1 = X(0);\n    // cout<<\"x-Exp a: \"<< a1  <<\"x-Exp b: \"<< b1 <<endl;\n\n    // MatrixXd Yi_Xi(350,2);\n    // for(int i=0; i<350; i++){\n    //     Yi_Xi(i,0) = a1 * pow(i, b1);\n    //     Yi_Xi(i,1) = i;\n    // }\n    // write_matrix(\"x_exp_model.txt\", Yi_Xi);\n\n    // Loagrithmic model--------------------------------------------------------------------\n\n    // int Msize = 2;\n    // MatrixXd A(Nsize,Msize);\n    // MatrixXd b(Nsize,1);\n\n    // A << x_data.array().log() , MatrixXd::Ones(Nsize,1);\n    // b << y_data;\n\n    // MatrixXd At = A.transpose();\n    // MatrixXd X(Msize,1); \n    // X = (At*A).inverse() * At * b;\n    // double a1 = X(0);\n    // double b1 = X(1);\n    // cout<<\"Log a: \"<<  a1 <<\"Log b: \"<< b1 <<endl;\n\n    // MatrixXd Yi_Xi(350,2);\n    // for(int i=0; i<350; i++){\n    //     Yi_Xi(i,0) = a1 * log(i) + b1;\n    //     Yi_Xi(i,1) = i;\n    // }\n    // write_matrix(\"log_model.txt\", Yi_Xi);\n\n    // inv model--------------------------------------------------------------------\n\n    int Msize = 1;\n    MatrixXd A(Nsize,Msize);\n    MatrixXd b(Nsize,1);\n\n    A << MatrixXd::Ones(Nsize,1);\n    b << y_data.array() * x_data.array();\n\n    MatrixXd At = A.transpose();\n    MatrixXd X(Msize,1); \n    X = (At*A).inverse() * At * b;\n    double a1 = X(0);\n    cout<<\"inv a: \"<< a1 <<endl;\n\n    MatrixXd Yi_Xi(350,2);\n    for(int i=0; i<350; i++){\n        Yi_Xi(i,0) = a1 / i;\n        Yi_Xi(i,1) = i;\n    }\n    write_matrix(\"inv_model.txt\", Yi_Xi);\n\n    return 0;\n}\n\n// Supporting functions used: \n\nMatrixXd* read_matrix(string filename){\n    ifstream myfile;\n    myfile.open(filename);\n    if (!myfile.is_open()) throw runtime_error(\"Could not open file\");\n    string row_item;\n    vector<vector<double> > rows;    \n    string line;\n    while(myfile.good()){\n        vector<double> row;\n        getline(myfile, line);\n        stringstream s(line);\n        while (getline(s,row_item,',')){\n            row.push_back(stod(row_item));\n        }\n        rows.push_back(row);\n    }\n    myfile.close();\n    int nrows,ncols;\n    nrows = rows.end() - rows.begin();\n    ncols = rows[0].end() - rows[0].begin();\n    MatrixXd* m = new MatrixXd(nrows,ncols);\n    for(int i=0; i<nrows; i++){\n        for (int j=0; j<ncols; j++){\n            (*m)(i,j) = rows[i][j];\n        }\n    } \n    // cout<<\"The following is a matrix of \"<<nrows<<\" rows and \"<<ncols<<\" coloumns: \"<<endl<<*m<<endl;\n    return m;\n}\n\nvoid write_matrix(string filename, MatrixXd m){\n    ofstream(myfile);\n    myfile.open(filename);\n    for(int i=0; i<m.rows(); i++){\n        for(int j=0; j<m.cols(); j++){\n            myfile << m(i,j) <<\",\";\n        }\n        myfile << endl;\n    }\n}\n\n\nvoid print_vector(vector<vector<double> > v){\n    vector<vector<double> >::iterator mvp;\n    vector<double>::iterator vp;\n    for(mvp= v.begin(); mvp!=v.end(); mvp++){\n        for(vp = mvp->begin(); vp!= mvp->end(); vp++){\n            cout<<*vp<<\" \";\n        }\n        cout<<endl;\n    }\n}\nvoid print_matrix_vector(vector<double> v){\n    vector<double>::iterator it;\n    for(it= v.begin(); it!= v.end(); it++){\n        cout<<*it<<\" \";\n    }cout<<endl;\n}", "meta": {"hexsha": "a25eb4598848910770af2587222da7c3531f495b", "size": 5379, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Least_squares_and_normal_equations/model_fitting.cpp", "max_stars_repo_name": "shorane/cpp_tracking_filtering_estimation", "max_stars_repo_head_hexsha": "a3cb564ac581f57eed17e014302bad3297c9d647", "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": "Least_squares_and_normal_equations/model_fitting.cpp", "max_issues_repo_name": "shorane/cpp_tracking_filtering_estimation", "max_issues_repo_head_hexsha": "a3cb564ac581f57eed17e014302bad3297c9d647", "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": "Least_squares_and_normal_equations/model_fitting.cpp", "max_forks_repo_name": "shorane/cpp_tracking_filtering_estimation", "max_forks_repo_head_hexsha": "a3cb564ac581f57eed17e014302bad3297c9d647", "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.4975369458, "max_line_length": 104, "alphanum_fraction": 0.4829894032, "num_tokens": 1622, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.947381048137938, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.7389504962279791}}
{"text": "//####### Test module for picsar_tables ####################################\n\n//Define Module name\n #define BOOST_TEST_MODULE \"containers/picsar_tables\"\n\n//Include Boost unit tests library & library for floating point comparison\n#include <boost/test/unit_test.hpp>\n#include <boost/test/tools/floating_point_comparison.hpp>\n\n#include <vector>\n#include <algorithm>\n#include <array>\n\n#include \"picsar_tables.hpp\"\n\n#include \"picsar_span.hpp\"\n\nusing namespace picsar::multi_physics::containers;\n\n//Tolerance for double precision calculations\nconst double double_tolerance = 1.0e-12;\n\n//Tolerance for single precision calculations\nconst float float_tolerance = 1.0e-5;\n\n//Templated tolerance\ntemplate <typename T>\nT constexpr tolerance()\n{\n    if(std::is_same<T,float>::value)\n        return float_tolerance;\n    else\n        return double_tolerance;\n}\n\ndouble linear_function(double x)\n{\n    const double m = -3.0;\n    const double q = 1.7;\n    return m*x + q;\n}\n\ndouble linear_function(double x, double y)\n{\n    const double a = 2.2;\n    const double b = -1.7;\n    const double c = -3.1;\n    return a*x + b*y + c;\n}\n\nconst double xmin = -10.0;\nconst double xmax = 10.0;\nconst double ymin = -8.0;\nconst double ymax = 8.0;\nconst int xsize = 100;\nconst int ysize = 100;\n\nequispaced_1d_table<double, std::vector<double> > make_1d_table()\n{\n    std::vector<double> data(xsize);\n    std::generate(data.begin(), data.end(),\n        [&, n = 0]() mutable {\n            double x = xmin+((xmax-xmin)*(n++))/(xsize-1);\n            return linear_function(x);\n        });\n\n    return equispaced_1d_table<double, std::vector<double>>(xmin, xmax,data);\n}\n\nequispaced_2d_table<double, std::vector<double> > make_2d_table()\n{\n    std::vector<double> data(xsize*ysize);\n    for (int i = 0; i < xsize; ++i){\n        for (int j = 0; j < ysize; ++j){\n            double x = xmin+i*(xmax-xmin)/(xsize-1);\n            double y = ymin+j*(ymax-ymin)/(ysize-1);\n            data[i*ysize+j] = linear_function(x, y);\n        }\n    }\n\n    return equispaced_2d_table<double, std::vector<double>>(\n        xmin, xmax, ymin, ymax, xsize, ysize, data);\n}\n\n\n// ------------- Tests --------------\n\nvoid check_table_1d(\n    const equispaced_1d_table<double, std::vector<double> >& tab)\n{\n    const auto rxmin = tab.get_x_min();\n    BOOST_CHECK_EQUAL(rxmin, xmin);\n    const auto rxmax = tab.get_x_max();\n    BOOST_CHECK_EQUAL(rxmax, xmax);\n    const auto rxsize = tab.get_x_size();\n    BOOST_CHECK_EQUAL(rxsize, xmax-xmin);\n    const auto rhowmany =  tab.get_how_many_x();\n    BOOST_CHECK_EQUAL(rhowmany, xsize);\n    const auto rdx = tab.get_dx();\n    BOOST_CHECK_EQUAL(rdx, (xmax-xmin)/(xsize-1));\n\n    const auto first_val = tab.get_values_reference()[0];\n    BOOST_CHECK_EQUAL(first_val, linear_function(xmin));\n\n    const auto x0 = tab.get_x_coord(0);\n    const auto x1 = tab.get_x_coord(xsize/2);\n    const auto x2 = tab.get_x_coord(xsize-1);\n    const auto x1exp = (xsize/2)*(xmax - xmin)/(xsize-1) + xmin;\n    BOOST_CHECK_SMALL((x0-xmin)/xmin, tolerance<double>());\n    BOOST_CHECK_SMALL((x1 - x1exp)/x1exp, tolerance<double>());\n    BOOST_CHECK_SMALL((x2 - xmax)/xmax, tolerance<double>());\n\n    const auto x3 = 0.732*(x1-x0) + x0;\n    const auto x4 = 0.118*(x2-x1) + x1;\n\n    const auto v0 = tab.get_val(0);\n    const auto v1 = tab.get_val(xsize/2);\n    const auto v2 = tab.get_val(xsize-1);\n    BOOST_CHECK_EQUAL(v0, linear_function(x0));\n    BOOST_CHECK_EQUAL(v1, linear_function(x1));\n    BOOST_CHECK_EQUAL(v2, linear_function(x2));\n\n    const auto xarr = std::array<double, 5>{x0,x1,x2,x3,x4};\n    for (const auto& xx : xarr)\n    {\n        const auto val = tab.interp(xx);\n        const auto expected = linear_function(xx);\n        BOOST_CHECK_SMALL((val - expected)/expected, tolerance<double>());\n    }\n\n    const auto all_coords = tab.get_all_coordinates();\n    BOOST_CHECK_EQUAL(all_coords.size(), xsize);\n    for (int i = 0; i < xsize; ++i){\n        BOOST_CHECK_EQUAL(all_coords[i], tab.get_x_coord(i));\n    }\n}\n\nvoid check_table_2d(\n    const equispaced_2d_table<double, std::vector<double> >& tab)\n{\n    const auto rxmin = tab.get_x_min();\n    BOOST_CHECK_EQUAL(rxmin, xmin);\n    const auto rxmax = tab.get_x_max();\n    BOOST_CHECK_EQUAL(rxmax, xmax);\n    const auto rhowmany_x =  tab.get_how_many_x();\n    BOOST_CHECK_EQUAL(rhowmany_x, xsize);\n    const auto rxsize =  tab.get_x_size();\n    BOOST_CHECK_EQUAL(rxsize, xmax-xmin);\n    const auto rdx =  tab.get_dx();\n    BOOST_CHECK_EQUAL(rdx, (xmax-xmin)/(rhowmany_x-1));\n    const auto rymin = tab.get_y_min();\n    BOOST_CHECK_EQUAL(rymin, ymin);\n    const auto rymax = tab.get_y_max();\n    BOOST_CHECK_EQUAL(rymax, ymax);\n    const auto rhowmany_y =  tab.get_how_many_y();\n    BOOST_CHECK_EQUAL(rhowmany_y, ysize);\n    const auto rysize =  tab.get_y_size();\n    BOOST_CHECK_EQUAL(rysize, ymax-ymin);\n    const auto rdy =  tab.get_dy();\n    BOOST_CHECK_EQUAL(rdy, (ymax-ymin)/(rhowmany_y-1));\n\n    const auto first_val = tab.get_values_reference()[0];\n    BOOST_CHECK_EQUAL(first_val, linear_function(xmin, ymin));\n\n    const auto x0 = tab.get_x_coord(0);\n    const auto x1 = tab.get_x_coord(xsize/2);\n    const auto x2 = tab.get_x_coord(xsize-1);\n    const auto x1exp = (xsize/2)*(xmax - xmin)/(xsize-1) + xmin;\n    BOOST_CHECK_SMALL((x0-xmin)/xmin, tolerance<double>());\n    BOOST_CHECK_SMALL((x1 - x1exp)/x1exp, tolerance<double>());\n    BOOST_CHECK_SMALL((x2 - xmax)/xmax, tolerance<double>());\n\n    const auto x3 = 0.732*(x1-x0) + x0;\n    const auto x4 = 0.118*(x2-x1) + x1;\n    const auto xarr = std::array<double, 5>{x0,x1,x2,x3,x4};\n\n    const auto y0 = tab.get_y_coord(0);\n    const auto y1 = tab.get_y_coord(ysize/2);\n    const auto y2 = tab.get_y_coord(ysize-1);\n    const auto y1exp = (ysize/2)*(ymax - ymin)/(ysize-1) + ymin;\n    BOOST_CHECK_SMALL((y0-ymin)/ymin, tolerance<double>());\n    BOOST_CHECK_SMALL((y1 - y1exp)/y1exp, tolerance<double>());\n    BOOST_CHECK_SMALL((y2 - ymax)/ymax, tolerance<double>());\n\n    const auto v00 = tab.get_val(0, 0);\n    const auto v10 = tab.get_val(xsize/2, 0);\n    const auto v20 = tab.get_val(xsize-1, 0);\n    const auto v01 = tab.get_val(0, ysize/2);\n    const auto v11 = tab.get_val(xsize/2, ysize/2);\n    const auto v21 = tab.get_val(xsize-1, ysize/2);\n    const auto v02 = tab.get_val(0, ysize-1);\n    const auto v12 = tab.get_val(xsize/2, ysize-1);\n    const auto v22 = tab.get_val(xsize-1, ysize-1);\n    BOOST_CHECK_EQUAL(v00, linear_function(x0,y0));\n    BOOST_CHECK_EQUAL(v10, linear_function(x1,y0));\n    BOOST_CHECK_EQUAL(v20, linear_function(x2,y0));\n    BOOST_CHECK_EQUAL(v01, linear_function(x0,y1));\n    BOOST_CHECK_EQUAL(v11, linear_function(x1,y1));\n    BOOST_CHECK_EQUAL(v21, linear_function(x2,y1));\n    BOOST_CHECK_EQUAL(v02, linear_function(x0,y2));\n    BOOST_CHECK_EQUAL(v12, linear_function(x1,y2));\n    BOOST_CHECK_EQUAL(v22, linear_function(x2,y2));\n\n    const auto y3 = 0.8569*(y1-y0) + y0;\n    const auto y4 = 0.3467*(y2-y1) + y1;\n    const auto yarr = std::array<double, 5>{y0,y1,y2,y3,y4};\n\n    for (const auto& xx : xarr)\n    {\n        for (const auto& yy : yarr)\n        {\n            const auto val = tab.interp(xx, yy);\n            const auto expected = linear_function(xx, yy);\n            BOOST_CHECK_SMALL((val - expected)/expected, tolerance<double>());\n        }\n    }\n\n    const auto all_coords = tab.get_all_coordinates();\n    int count = 0;\n    BOOST_CHECK_EQUAL(all_coords.size(), xsize*ysize);\n    for (int i = 0; i < xsize; ++i){\n        for (int j = 0; j < ysize; ++j){\n            auto cc = all_coords[count++];\n            BOOST_CHECK_EQUAL(cc[0], tab.get_x_coord(i));\n            BOOST_CHECK_EQUAL(cc[1], tab.get_y_coord(j));\n        }\n    }\n}\n\nvoid check_table_2d_interp_one_coord(\n        const equispaced_2d_table<double, std::vector<double> >& tab)\n{\n    const auto x0 = tab.get_x_coord(0);\n    const auto x1 = tab.get_x_coord(xsize/2);\n    const auto x2 = tab.get_x_coord(xsize-1);\n    const auto x3 = 0.732*(x1-x0) + x0;\n    const auto x4 = 0.118*(x2-x1) + x1;\n    const auto xarr = std::array<double, 5>{x0,x1,x2,x3,x4};\n    const auto jarr = std::array<int, 5>{0,1,5,27,ysize-1};\n\n    for (auto xx : xarr){\n        for (auto jj : jarr)\n        {\n            const auto yy = tab.get_y_coord(jj);\n            const auto res = tab.interp_first_coord(xx, jj);\n            const auto exp = linear_function(xx, yy);\n            BOOST_CHECK_SMALL((res - exp)/exp, tolerance<double>());\n        }\n    }\n\n\n    const auto y0 = tab.get_y_coord(0);\n    const auto y1 = tab.get_y_coord(ysize/2);\n    const auto y2 = tab.get_y_coord(ysize-1);\n    const auto y3 = 0.8569*(y1-y0) + y0;\n    const auto y4 = 0.3467*(y2-y1) + y1;\n    const auto yarr = std::array<double, 5>{y0,y1,y2,y3,y4};\n    const auto iarr = std::array<int, 5>{0,1,5,27,xsize-1};\n\n    for (auto yy : yarr){\n        for (auto ii : iarr)\n        {\n            const auto xx = tab.get_x_coord(ii);\n            const auto res = tab.interp_second_coord(ii, yy);\n            const auto exp = linear_function(xx, yy);\n            BOOST_CHECK_SMALL((res - exp)/exp, tolerance<double>());\n        }\n    }\n}\n\n// ***Test equispaced_1d_table constructor and getters\nBOOST_AUTO_TEST_CASE( picsar_equispaced_1d_table_constructor_getters)\n{\n    auto tab_1d = make_1d_table();\n    const auto const_tab_1d = make_1d_table();\n    auto copy_tab_1d = tab_1d;\n\n    check_table_1d(tab_1d);\n    check_table_1d(const_tab_1d);\n    check_table_1d(copy_tab_1d);\n}\n\n// ***Test equispaced_1d_table setter\nBOOST_AUTO_TEST_CASE( picsar_equispaced_1d_table_constructor_setter)\n{\n    auto tab_1d = make_1d_table();\n    const auto val = 1000.0;\n    const int where = 10;\n    tab_1d.set_val(where, val);\n    const auto x10 = tab_1d.get_x_coord(where);\n    const auto res =tab_1d.interp(x10);\n\n    BOOST_CHECK_SMALL((res - val)/val, tolerance<double>());\n\n}\n\n// ***Test equispaced_1d_table equality\nBOOST_AUTO_TEST_CASE( picsar_equispaced_1d_table_equality)\n{\n    auto tab_1d = make_1d_table();\n    auto tab_1d_2 = make_1d_table();\n    BOOST_CHECK_EQUAL(tab_1d == tab_1d_2, true);\n\n    tab_1d.set_val(1, 3.14);\n    BOOST_CHECK_EQUAL(tab_1d == tab_1d_2, false);\n}\n\n// ***Test equispaced_1d_table serialization\nBOOST_AUTO_TEST_CASE( picsar_equispaced_1d_table_serialization)\n{\n    auto tab_1d = make_1d_table();\n    auto raw_data = tab_1d.serialize();\n    auto tab_1d_2 = equispaced_1d_table<double, std::vector<double>>{raw_data};\n\n    BOOST_CHECK_EQUAL(tab_1d.get_x_min(), tab_1d_2.get_x_min());\n    BOOST_CHECK_EQUAL(tab_1d.get_x_max(), tab_1d_2.get_x_max());\n    BOOST_CHECK_EQUAL(tab_1d.get_x_size(), tab_1d_2.get_x_size());\n    BOOST_CHECK_EQUAL(tab_1d.get_how_many_x(), tab_1d_2.get_how_many_x());\n\n    for(int i = 0; i < tab_1d.get_how_many_x(); ++i){\n        BOOST_CHECK_EQUAL(tab_1d.get_val(i), tab_1d_2.get_val(i));\n    }\n}\n\n// ***Test equispaced_2d_table constructor and getters\nBOOST_AUTO_TEST_CASE( picsar_equispaced_2d_table_constructor_getters)\n{\n    auto tab_2d = make_2d_table();\n    const auto const_tab_2d = make_2d_table();\n    auto copy_tab_2d = tab_2d;\n\n    check_table_2d(tab_2d);\n    check_table_2d(const_tab_2d);\n    check_table_2d(copy_tab_2d);\n}\n\n// ***Test equispaced_2d_table setter\nBOOST_AUTO_TEST_CASE( picsar_equispaced_2d_table_interp_one_coord)\n{\n    const auto const_tab_2d = make_2d_table();\n\n    check_table_2d_interp_one_coord(const_tab_2d);\n}\n\n// ***Test equispaced_2d_table setter\nBOOST_AUTO_TEST_CASE( picsar_equispaced_2d_table_constructor_setter)\n{\n    auto tab_2d = make_2d_table();\n    const auto val = 1000.0;\n    const int i = 10;\n    const int j = 20;\n    tab_2d.set_val(i,j,val);\n    const auto xx = tab_2d.get_x_coord(i);\n    const auto yy = tab_2d.get_y_coord(j);\n    const auto res =tab_2d.interp(xx,yy);\n\n    BOOST_CHECK_SMALL((res - val)/val, tolerance<double>());\n}\n\n// ***Test equispaced_2_table equality\nBOOST_AUTO_TEST_CASE( picsar_equispaced_2d_table_equality)\n{\n    auto tab_2d = make_2d_table();\n    auto tab_2d_2 = make_2d_table();\n    BOOST_CHECK_EQUAL(tab_2d == tab_2d_2, true);\n\n    tab_2d.set_val(0, 10.0);\n    BOOST_CHECK_EQUAL(tab_2d == tab_2d_2, false);\n}\n\n// ***Test equispaced_2d_table serialization\nBOOST_AUTO_TEST_CASE( picsar_equispaced_2d_table_serialization)\n{\n    auto tab_2d = make_2d_table();\n    auto raw_data = tab_2d.serialize();\n    auto tab_2d_2 = equispaced_2d_table<double, std::vector<double>>{raw_data};\n\n    BOOST_CHECK_EQUAL(tab_2d.get_x_min(), tab_2d_2.get_x_min());\n    BOOST_CHECK_EQUAL(tab_2d.get_x_max(), tab_2d_2.get_x_max());\n    BOOST_CHECK_EQUAL(tab_2d.get_y_min(), tab_2d_2.get_y_min());\n    BOOST_CHECK_EQUAL(tab_2d.get_y_max(), tab_2d_2.get_y_max());\n    BOOST_CHECK_EQUAL(tab_2d.get_x_size(), tab_2d_2.get_x_size());\n    BOOST_CHECK_EQUAL(tab_2d.get_y_size(), tab_2d_2.get_y_size());\n    BOOST_CHECK_EQUAL(tab_2d.get_how_many_x(), tab_2d_2.get_how_many_x());\n    BOOST_CHECK_EQUAL(tab_2d.get_how_many_y(), tab_2d_2.get_how_many_y());\n\n    for(int i = 0; i < tab_2d.get_how_many_x()*tab_2d.get_how_many_x(); ++i){\n        BOOST_CHECK_EQUAL(tab_2d.get_values_reference()[i],\n            tab_2d_2.get_values_reference()[i]);\n    }\n}\n", "meta": {"hexsha": "c4517b9a70a82317b1a4fded58aa5e20897fb195", "size": 13085, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/multi_physics/QED_tests/test_picsar_tables.cpp", "max_stars_repo_name": "LDAmorim/picsar", "max_stars_repo_head_hexsha": "024db7c01daf820ae321c3473f2dd5ec73476946", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "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/multi_physics/QED_tests/test_picsar_tables.cpp", "max_issues_repo_name": "LDAmorim/picsar", "max_issues_repo_head_hexsha": "024db7c01daf820ae321c3473f2dd5ec73476946", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "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/multi_physics/QED_tests/test_picsar_tables.cpp", "max_forks_repo_name": "LDAmorim/picsar", "max_forks_repo_head_hexsha": "024db7c01daf820ae321c3473f2dd5ec73476946", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3801020408, "max_line_length": 79, "alphanum_fraction": 0.6672525793, "num_tokens": 3983, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851154320682, "lm_q2_score": 0.8633916099737806, "lm_q1q2_score": 0.7389347060268522}}
{"text": "#include <chrono>\n#include <functional>\n#include <iostream>\n#include <vector>\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <Eigen/SparseLU>\n\nstd::vector<Eigen::Triplet<double>> MakeTripletList(int n) {\n\tint nnz = 3 * n - 2;\n\tstd::vector<Eigen::Triplet<double>> tripletList(nnz);\n\n\tfor(int i = 0; i < n; i++) {\n\t\ttripletList.push_back(Eigen::Triplet<double>(i, i, 2));\n\n\t\tif(i > 0) {\n\t\t\ttripletList.push_back(Eigen::Triplet<double>(i, i - 1, -1));\n\t\t}\n\n\t\tif(i < n - 1) {\n\t\t\ttripletList.push_back(Eigen::Triplet<double>(i, i + 1, -1));\n\t\t}\n\t}\n\n\treturn tripletList;\n}\n\ndouble Runtime(const std::function<void(void)> &f) {\n\tdouble runtime = std::numeric_limits<double>::max();\n\tstd::chrono::duration<double, std::ratio<1> > duration;\n\tstd::chrono::time_point<std::chrono::high_resolution_clock> start, end;\n\n\tfor(int i = 0; i < 10; i++) {\n\t\tstart = std::chrono::high_resolution_clock::now();\n\t\tf();\n\t\tend = std::chrono::high_resolution_clock::now();\n\n\t\tduration = end - start;\n\t\truntime = std::min(runtime, duration.count());\n\t}\n\n\treturn runtime;\n}\n\ntemplate <class T>\nstd::ostream & operator<< (std::ostream &os, const std::vector<T> &v) {\n\tos << \"[\";\n\tif (!v.empty()) {\n\t\tos << v[0];\n\t\tfor (int i = 1; i < v.size(); ++i) os << \", \" << v[i];\n\t}\n    os << \"]\";\n\n    return os;\n}\n\nint main() {\n\t// print small example of the tridiagonal matrix\n\tint m = 4;\n\tstd::vector<Eigen::Triplet<double>> tripletList = MakeTripletList(m);\n\tEigen::SparseMatrix<double> S_(m, m);\n\tS_.setFromTriplets(tripletList.begin(), tripletList.end());\n\tstd::cout << \"If n = \" << m << \", then T equals\" << std::endl;\n\tstd::cout << Eigen::MatrixXd(S_) << std::endl;\n\n\t// matrix sizes for benchmark\n\tstd::vector<int> N = {64, 128, 256, 512};\n\tstd::cout << \"LU decomposition of T, where n = \" << N << std::endl;\n\n\t// set up variables for runtime measurement\n\tstd::vector<double> runtimeSparse;\n\tstd::vector<double> runtimeDense;\n\n\tfor (int n : N) {\n\t\ttripletList = MakeTripletList(n);\n\n\t\t// sparse LU decomposition\n\t\tEigen::SparseMatrix<double> S(n, n);\n\t\tS.setFromTriplets(tripletList.begin(), tripletList.end());\n\n\t\truntimeSparse.push_back(Runtime([&]() {\n\t\t\tEigen::SparseLU<Eigen::SparseMatrix<double>> solver;\n\t\t\tsolver.analyzePattern(S);\n\t\t\tsolver.factorize(S);\n\t\t}));\n\n\t\t// dense LU decomposition\n\t\tEigen::MatrixXd D(S);\n\n\t\truntimeDense.push_back(Runtime([&]() {\n\t\t\tD.fullPivLu();\n\t\t}));\n\t}\n\n\tstd::cout << \"Runtime in seconds using storage format...\" << std::endl;\n\tstd::cout << \"...sparse: \" << runtimeSparse << std::endl;\n\tstd::cout << \"...dense:  \" << runtimeDense << std::endl;\n\n\treturn 0;\n}\n", "meta": {"hexsha": "9f7249912382c337d325226e6ae78d798e1179f5", "size": 2580, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "exercise_2/sparse.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/sparse.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/sparse.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.2941176471, "max_line_length": 72, "alphanum_fraction": 0.6348837209, "num_tokens": 775, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.853912760387131, "lm_q1q2_score": 0.738825884706786}}
{"text": "#include \"MathUtil.h\"\n#include <Eigen/Geometry>\n#include \"Intersection.h\"\n\nnamespace ptgl {\n\n// https://github.com/s-nakaoka/choreonoid/src/Util/EigenUtil.cpp\nEigen::Matrix3d rotFromRpy(double r, double p, double y)\n{\n    const double cr = cos(r);\n    const double sr = sin(r);\n    const double cp = cos(p);\n    const double sp = sin(p);\n    const double cy = cos(y);\n    const double sy = sin(y);\n\n    Eigen::Matrix3d R;\n    R << cp*cy, sr*sp*cy - cr*sy, cr*sp*cy + sr*sy,\n         cp*sy, sr*sp*sy + cr*cy, cr*sp*sy - sr*cy,\n         -sp  , sr*cp           , cr*cp;\n\n    return R;\n}\n\n// https://github.com/s-nakaoka/choreonoid/src/Util/EigenUtil.cpp\nEigen::Vector3d omegaFromRot(const Eigen::Matrix3d& R)\n{\n    double alpha = (R(0,0) + R(1,1) + R(2,2) - 1.0) / 2.0;\n\n    if(fabs(alpha - 1.0) < 1.0e-6) {   //th=0,2PI;\n        return Eigen::Vector3d::Zero();\n\n    } else {\n        double th = acos(alpha);\n        double s = sin(th);\n\n        if (s < std::numeric_limits<double>::epsilon()) {   //th=PI\n            return Eigen::Vector3d( sqrt((R(0,0)+1)*0.5)*th, sqrt((R(1,1)+1)*0.5)*th, sqrt((R(2,2)+1)*0.5)*th );\n        }\n\n        double k = -0.5 * th / s;\n\n        return Eigen::Vector3d((R(1,2) - R(2,1)) * k,\n                       (R(2,0) - R(0,2)) * k,\n                       (R(0,1) - R(1,0)) * k);\n    }\n}\n\nEigen::Matrix3d rotFromAxisFromTo(const Eigen::Vector3d& from, const Eigen::Vector3d& to, const Eigen::Vector3d& axis)\n{\n    Eigen::Vector3d p0 = ptgl::calcIntersectionPointAndLine(from, Eigen::Vector3d::Zero(), axis);\n    Eigen::Vector3d from0 = from - p0;\n    Eigen::Vector3d to0 = to - p0;\n    return rotFromTo(from0, to0);\n}\n\nEigen::Matrix3d rotFromToSet(const Eigen::Vector3d& vecA0, const Eigen::Vector3d& vecB0, const Eigen::Vector3d& vecA1, const Eigen::Vector3d& vecB1)\n{\n    Eigen::Matrix3d R0 = ptgl::rotFromTo(vecA0, vecA1);\n    Eigen::Vector3d tempVecB = R0 * vecB0;\n    return rotFromAxisFromTo(tempVecB, vecB1, vecA1) * R0;\n}\n\ndouble angleFromAxisFromTo(const Eigen::Vector3d& from, const Eigen::Vector3d& to, const Eigen::Vector3d& axis) {\n    Eigen::Vector3d p0 = ptgl::calcIntersectionPointAndLine(from, Eigen::Vector3d::Zero(), axis);\n    Eigen::Vector3d from0 = from - p0;\n    Eigen::Vector3d to0 = to - p0;\n\n    Eigen::Quaterniond q;\n    q.setFromTwoVectors(from0, to0);\n\n    Eigen::AngleAxisd aa(q);\n    Eigen::Vector3d c = aa.axis();\n    double angle = aa.angle();\n\n    Eigen::Vector3d d1 = c - axis;\n    Eigen::Vector3d d2 = c + axis;\n    return d1.squaredNorm() < d2.squaredNorm() ? angle : -angle;\n};\n\ndouble angleFromDirectionFromTo(const Eigen::Vector3d& from, const Eigen::Vector3d& to, const Eigen::Vector3d& direction) {\n    Eigen::Quaterniond q;\n    q.setFromTwoVectors(from, to);\n\n    Eigen::AngleAxisd aa(q);\n    Eigen::Vector3d c = aa.axis();\n    double angle = aa.angle();\n\n    Eigen::Vector3d d1 = c - direction;\n    Eigen::Vector3d d2 = c + direction;\n    return d1.squaredNorm() < d2.squaredNorm() ? angle : -angle;\n};\n\n// glm/gtc/matrix_transform.inl ortho\nEigen::Matrix4d ortho(double left, double right, double bottom, double top)\n{\n    Eigen::Matrix4d Result(Eigen::Matrix4d::Identity());\n    Result(0,0) = 2.0 / (right - left);\n    Result(1,1) = 2.0 / (top - bottom);\n    Result(0,3) = - (right + left) / (right - left);\n    Result(1,3) = - (top + bottom) / (top - bottom);\n    return Result;\n}\n\n// glm/gtc/matrix_transform.inl  orthoRH_NO\nEigen::Matrix4d ortho(double left, double right, double bottom, double top, double zNear, double zFar)\n{\n    Eigen::Matrix4d Result(Eigen::Matrix4d::Identity());\n    Result(0,0) = 2.0 / (right - left);\n    Result(1,1) = 2.0 / (top - bottom);\n    Result(2,2) = - 2.0 / (zFar - zNear);\n    Result(0,3) = - (right + left) / (right - left);\n    Result(1,3) = - (top + bottom) / (top - bottom);\n    Result(2,3) = - (zFar + zNear) / (zFar - zNear);\n    return Result;\n}\n\n\n// project/unproject\n\n// glm/gtc/matrix_transform.inl  projectNO\n// object(x,y,z) -> window(x,y,z)\nEigen::Vector3d project(const Eigen::Vector3d& object_p, const Eigen::Matrix4d& modelMatrix, const Eigen::Matrix4d& projMatrix, const Eigen::Vector4d& viewport)\n{\n    Eigen::Vector4d tmp = Eigen::Vector4d(object_p(0), object_p(1), object_p(2), 1.0);\n    tmp = Eigen::Vector4d(modelMatrix * tmp);\n    tmp = Eigen::Vector4d(projMatrix * tmp);\n\n    tmp /= tmp.w();\n    tmp = tmp.array() * 0.5 + 0.5;\n    tmp[0] = tmp[0] * viewport[2] + viewport[0];\n    tmp[1] = tmp[1] * viewport[3] + viewport[1];\n    return Eigen::Vector3d(tmp[0], tmp[1], tmp[2]);\n}\n\n// glm/gtc/matrix_transform.inl  unProjectNO\n// window(x,y,z) -> object(x,y,z)\nEigen::Vector3d unProject(const Eigen::Vector3d& wp, const Eigen::Matrix4d& modelMatrix, const Eigen::Matrix4d& projMatrix, const Eigen::Vector4d& viewport)\n{\n    Eigen::Matrix4d Inverse = Eigen::Matrix4d(projMatrix * modelMatrix).inverse();\n\n    Eigen::Vector4d tmp = Eigen::Vector4d(wp(0), wp(1), wp(2), 1.0);\n    tmp(0) = (tmp(0) - viewport[0]) / viewport[2];\n    tmp(1) = (tmp(1) - viewport[1]) / viewport[3];\n    tmp = Eigen::Vector4d(tmp.array() * 2.0 - 1.0);\n\n    Eigen::Vector4d obj = Inverse * tmp;\n    obj /= obj.w();\n\n    return Eigen::Vector3d(obj[0], obj[1], obj[2]);\n}\n\n} /* namespace ptgl */\n", "meta": {"hexsha": "541f612c9fbbee2e9bb516c9dfbefe42185f1cff", "size": 5203, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ptgl/Util/MathUtil.cpp", "max_stars_repo_name": "tsumehashi/ptgl", "max_stars_repo_head_hexsha": "00434830fa6fbc7987513d6bdd9c967ca66a70c5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-04-06T11:46:02.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-06T11:46:02.000Z", "max_issues_repo_path": "ptgl/Util/MathUtil.cpp", "max_issues_repo_name": "tsumehashi/ptgl", "max_issues_repo_head_hexsha": "00434830fa6fbc7987513d6bdd9c967ca66a70c5", "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": "ptgl/Util/MathUtil.cpp", "max_forks_repo_name": "tsumehashi/ptgl", "max_forks_repo_head_hexsha": "00434830fa6fbc7987513d6bdd9c967ca66a70c5", "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": 33.7857142857, "max_line_length": 160, "alphanum_fraction": 0.6173361522, "num_tokens": 1772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951625409307, "lm_q2_score": 0.7905303087996143, "lm_q1q2_score": 0.7386676963843477}}
{"text": "#pragma once\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n#include <vector>\n\n#include \"mass_matrix.hpp\"\n\n//----------------AssembleMatrixBegin----------------\n//! Assemble the mass matrix\n//! for the linear system.\n//!\n//!\n//! @param[out] triplets will at the end contain the Galerkin matrix\n//! @param[in] vertices a list of triangle vertices\n//! @param[in] triangles a list of triangles\nSparseMatrix assembleMassMatrix(\n    const Eigen::MatrixXd &vertices,\n    const Eigen::MatrixXi &triangles) {\n\tstd::vector<Triplet> triplets;\n\tconst int            numberOfElements = triangles.rows();\n\tSparseMatrix         M(vertices.rows(), vertices.rows());\n\n\t// (write your solution here)\n\ttriplets.reserve(numberOfElements * 3 * 3);\n\tfor (int i = 0; i < numberOfElements; ++i) {\n\t\tauto &indexSet = triangles.row(i);\n\n\t\tconst auto &a = vertices.row(indexSet(0));\n\t\tconst auto &b = vertices.row(indexSet(1));\n\t\tconst auto &c = vertices.row(indexSet(2));\n\n\t\tEigen::Matrix3d massMatrix;\n\t\tcomputeMassMatrix(massMatrix, a, b, c);\n\n\t\tfor (int n = 0; n < 3; ++n) {\n\t\t\tfor (int m = 0; m < 3; ++m) {\n\t\t\t\ttriplets.emplace_back(indexSet(n), indexSet(m), massMatrix(n, m));\n\t\t\t}\n\t\t}\n\t}\n\n\tM.setFromTriplets(triplets.begin(), triplets.end());\n\n\treturn M;\n}\n//----------------AssembleMatrixEnd----------------\n", "meta": {"hexsha": "ce1c0db3d6a166ed6a99a0209b9f9d56223d1c8c", "size": 1289, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "series4/2d-rad-cooling/mass_matrix_assembly.hpp", "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": "series4/2d-rad-cooling/mass_matrix_assembly.hpp", "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": "series4/2d-rad-cooling/mass_matrix_assembly.hpp", "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": 27.4255319149, "max_line_length": 70, "alphanum_fraction": 0.6384794414, "num_tokens": 344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425399873763, "lm_q2_score": 0.8031737963569014, "lm_q1q2_score": 0.7386327901329646}}
{"text": "/*=================================================================\n* Create rotation around a line by an angle theta\n* \n* according to David Legland's matlab toolbox: geom3d \n* \n* Junjie Cao, 2013, jjcao1231@gmail.com\n*\n=================================================================*/\n\n#include <mex.h>\n#include <Eigen/Dense>\n#include <vector>\n\nEigen::Matrix4d create_translation3d(Eigen::Vector3d center)\n{\n\tdouble dx(center.coeff(0)),dy(center.coeff(1)),dz(center.coeff(2));\n\tEigen::Matrix4d trans;\n\ttrans << 1,0,0,dx,\n\t\t    0,1,0,dy,\n\t\t\t0,0,1,dz,\n\t\t\t0,0,0,1;\n\treturn trans;\n}\nEigen::Matrix4d recenter_transform3d(Eigen::Matrix4d &transfo, Eigen::Vector3d& center)\n{\n\t//% remove former translation part\n\tEigen::Matrix4d res = Eigen::Matrix4d::Identity();\n\tres.block(0, 0, 3, 3) = transfo.block(0, 0, 3, 3);\n\n\t//% create translations\n\tEigen::Matrix4d t1 = create_translation3d(-center);\n\tEigen::Matrix4d t2 = create_translation3d(center);\n\n\t//% compute translated transform\n\tres = t2*res*t1;\n\treturn res;\n}\nEigen::Matrix4d create_rotation3d_line_angle(Eigen::Vector3d& center,Eigen::Vector3d& v, double theta)\n{\n\t//% normalize vector\n\tv.normalize();\n\n\t//% compute projection matrix P and anti-projection matrix\n\tEigen::Matrix3d P = v * v.transpose();\n\tEigen::Matrix3d Q;\n\tQ << 0, -v.coeff(2), v.coeff(1),\n\t\tv.coeff(2), 0, -v.coeff(0),\n\t\t-v.coeff(1), v.coeff(0), 0;\n\tEigen::Matrix3d I = Eigen::Matrix3d::Identity();\n\n\t//% compute vectorial part of the transform\n\tEigen::Matrix4d mat = Eigen::Matrix4d::Identity();\n\tmat.block(0, 0, 3, 3) = P + (I - P)*cos(theta) + Q*sin(theta);\n\n\t//% add translation coefficient\n\tmat = recenter_transform3d(mat, center);\n\t\n\treturn mat;\n}\nvoid mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray*prhs[])\n{  \n\t////////////////// parse input\n\tif ( nrhs != 3)\n\t\tmexErrMsgTxt(\"3 arguments needed!\");\n\n\tdouble *center_, *vector_, *theta_;\n\tcenter_ = mxGetPr(prhs[0]);\n\tvector_ = mxGetPr(prhs[1]);\n\ttheta_ = mxGetPr(prhs[2]);\n\n\tif ( mxGetN(prhs[0]) != 3)\n\t\tmexErrMsgTxt(\"center must be 1*3 matrix!\");\n\tif ( mxGetN(prhs[1]) != 3)\n\t\tmexErrMsgTxt(\"vector must be 1*3 matrix!\");\n\t\n\tEigen::Vector3d center = Eigen::Map<Eigen::Vector3d>(center_);\n\tEigen::Vector3d v = Eigen::Map<Eigen::Vector3d>(vector_);\n\n\t/////////////////////////////\n\tEigen::Matrix4d rot = create_rotation3d_line_angle(center,v,*theta_);\n\n\t//////////////////////// output\n\tplhs[0] = mxCreateDoubleMatrix(4,4,mxREAL);\n\tdouble *rot_ = mxGetPr(plhs[0]);\n\tEigen::Map<Eigen::Matrix4d>(rot_, 4, 4) = rot;  // may contain mem error\n}\n\n", "meta": {"hexsha": "95f77b95ef729bc371581297c0f769e9cd0956e7", "size": 2535, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "matlab_code/jjcao_code-head/toolbox/jjcao_mesh/3d-transformation/create_rotation3d_line_angle.cpp", "max_stars_repo_name": "joycewangsy/normals_pointnet", "max_stars_repo_head_hexsha": "fc74a8ed1a009b18785990b1b4c20eda0549721c", "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": "matlab_code/jjcao_code-head/toolbox/jjcao_mesh/3d-transformation/create_rotation3d_line_angle.cpp", "max_issues_repo_name": "joycewangsy/normals_pointnet", "max_issues_repo_head_hexsha": "fc74a8ed1a009b18785990b1b4c20eda0549721c", "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": "matlab_code/jjcao_code-head/toolbox/jjcao_mesh/3d-transformation/create_rotation3d_line_angle.cpp", "max_forks_repo_name": "joycewangsy/normals_pointnet", "max_forks_repo_head_hexsha": "fc74a8ed1a009b18785990b1b4c20eda0549721c", "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.8068181818, "max_line_length": 102, "alphanum_fraction": 0.6276134122, "num_tokens": 796, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.905989822921759, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7385923325674941}}
{"text": "/**\n * @file TestProblem01.hpp\n * @author Brahayam Ponton (brahayam.ponton@tuebingen.mpg.de)\n * @license License BSD-3-Clause\n * @copyright Copyright (c) 2019, New York University and Max Planck Gesellschaft.\n * @date 2019-10-06\n */\n\n#pragma once\n\n#include <limits>\n#include <iostream>\n#include <Eigen/Dense>\n\n#include <solver/interface/NlpDescription.hpp>\n\nnamespace nlp_test_problems\n{\n\n  class TestProblem01 : public solver::NlpDescription\n  {\n    public:\n\t  TestProblem01(){};\n      virtual ~TestProblem01(){};\n\n      // definition of problem size\n      void getNlpParameters(int& n_vars, int& n_cons)\n      {\n        n_vars = 4;\n        n_cons = 2;\n      }\n\n      // definition of problem box constraints\n      void getNlpBounds(int n_vars, int /*n_cons*/, double* x_l, double* x_u, double* g_l, double* g_u)\n      {\n        // lower and upper bounds on variables\n        for (int id=0; id<n_vars; id++)\n        {\n          x_l[id] = 1.0;\n          x_u[id] = 5.0;\n        }\n\n    \t    // lower and upper bounds on inequality constraints\n    \t    g_l[0] = 25;\n    \t    g_u[0] = std::numeric_limits<double>::infinity();\n\n    \t    // lower and upper bounds on equality constraints\n    \t    g_l[1] = g_u[1] = 40.0;\n      }\n\n      // definition of starting point\n      void getStartingPoint(int /*n_vars*/, double* x)\n      {\n    \t    x[0] = 1.0;\n    \t    x[1] = 5.0;\n    \t    x[2] = 5.0;\n    \t    x[3] = 1.0;\n      }\n\n      // definition of objective function\n      double evaluateObjective(int /*n_vars*/, const double* x)\n      {\n    \t    return x[0]*x[3]*( x[0]+x[1]+x[2] ) + x[2];\n      }\n\n      // definition of constraints function\n      void evaluateConstraintsVector(int /*n_vars*/, int /*n_cons*/, const double* x, double* constraints)\n      {\n    \t    constraints[0] = x[0]*x[1]*x[2]*x[3];\n    \t    constraints[1] = x[0]*x[0] + x[1]*x[1] + x[2]*x[2] + x[3]*x[3];\n      }\n  };\n}\n", "meta": {"hexsha": "63275748a5e0a052378aced9f5373cbdeee1397f", "size": 1888, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "solver/tests/test_problems/TestProblem01.hpp", "max_stars_repo_name": "machines-in-motion/kino-dynamic-opt", "max_stars_repo_head_hexsha": "ba9188eea6b80b102b1d0880470bedc0faa5e243", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 26.0, "max_stars_repo_stars_event_min_datetime": "2019-11-18T17:39:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-18T00:38:22.000Z", "max_issues_repo_path": "solver/tests/test_problems/TestProblem01.hpp", "max_issues_repo_name": "machines-in-motion/kino_dynamic_opt", "max_issues_repo_head_hexsha": "ba9188eea6b80b102b1d0880470bedc0faa5e243", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 25.0, "max_issues_repo_issues_event_min_datetime": "2019-11-11T19:54:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-07T13:41:47.000Z", "max_forks_repo_path": "solver/tests/test_problems/TestProblem01.hpp", "max_forks_repo_name": "machines-in-motion/kino-dynamic-opt", "max_forks_repo_head_hexsha": "ba9188eea6b80b102b1d0880470bedc0faa5e243", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-15T14:36:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-29T10:42:19.000Z", "avg_line_length": 25.5135135135, "max_line_length": 106, "alphanum_fraction": 0.5662076271, "num_tokens": 564, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765281148513, "lm_q2_score": 0.8080672181749421, "lm_q1q2_score": 0.7383120503855072}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n//! Sparse Matrix type. Makes using this type easier.\ntypedef Eigen::SparseMatrix<double> SparseMatrix;\n\n//! Used for filling the sparse matrix.\ntypedef Eigen::Triplet<double> Triplet;\n#include \"boundary.hpp\"\n#include \"mass_matrix_assembly.hpp\"\n#include \"neumann_boundary_assemble.hpp\"\n#include \"stiffness_matrix_assembly.hpp\"\n\n//! Evolves the solution in time using the DIRK2 method.\n//!\n//! @param vertices the list of vertices that build the triangular mesh\n//! @param triangles the list of indices that represent the triangular mesh\n//! @param u0 the initial data\n//! @param gamma the parameter gamma (has to do with the boundary conditions)\n//! @param m number of timesteps to perform\n//! @returns a pair which contains as first parameter the solution at time = 1,\n//!          and second parameter the energy evolving over time.\nstd::pair<Eigen::VectorXd, std::vector<double>> radiativeTimeEvolutionImplicit(const Eigen::MatrixXd &vertices,\n                                                                               const Eigen::MatrixXi &triangles,\n                                                                               const Eigen::VectorXd &u0,\n                                                                               const double           gamma,\n                                                                               const int              m) {\n\tstd::vector<double> energy;\n\tEigen::VectorXd     u(u0.size());\n\tu = u0;\n\n\tdouble dt     = 1.0 / m;\n\tdouble lambda = 1 - 0.5 * std::sqrt(2);\n\n\t// Get the edges, this is used to compute the neumann boundary matrix\n\tEigen::MatrixXi edges = getBoundaryEdges(vertices, triangles);\n\n\t// Define the needed matrices. Note that these are constant in time,\n\t// so they can be defined before the time loop. Also set up the solver\n\t// (write your solution here)\n\n\tSparseMatrix M = assembleMassMatrix(vertices, triangles);\n\tSparseMatrix A = assembleStiffnessMatrix(vertices, triangles);\n\tSparseMatrix B = assembleBoundaryMatrix(vertices, edges, gamma);\n\tA += B;\n\n\tEigen::SimplicialLDLT<SparseMatrix> Solver;\n\tSolver.compute(M + dt * lambda * A);\n\n\tif (Solver.info() != Eigen::Success) {\n\t\tthrow std::runtime_error(\"Could not decompose matix for SDIRK\");\n\t}\n\n\tauto solveY1 = [&](const Eigen::VectorXd &mu) -> Eigen::VectorXd {\n\t\treturn Solver.solve(M * mu);\n\t};\n\n\tauto solveY2 = [&](const Eigen::VectorXd &mu, const Eigen::VectorXd &Y1) -> Eigen::VectorXd {\n\t\treturn Solver.solve(M * mu - dt * (1 - lambda) * A * Y1);\n\t};\n\n\tEigen::SimplicialLDLT<SparseMatrix> SolverM;\n\tSolverM.compute(M);\n\n\tif (SolverM.info() != Eigen::Success) {\n\t\tthrow std::runtime_error(\"Could not decompose matrix M\");\n\t}\n\n\tEigen::VectorXd Y1(u0.rows());\n\tEigen::VectorXd Y2(u0.rows());\n\tfor (int timestep = 0; timestep < m; ++timestep) {\n\t\t// Do one step forward in time\n\t\t// (write your solution here)\n\t\tY1 = solveY1(u);\n\t\tY2 = solveY2(u, Y1);\n\t\tu  = SolverM.solve(M * u - dt * A * ((1 - lambda) * Y1 + lambda * Y2)).eval();\n\t\t// Compute the energy for this level\n\t\tenergy.push_back(u.sum() / u.rows());\n\t}\n\n\treturn std::make_pair(u, energy);\n}\n", "meta": {"hexsha": "3b808f87f614f6f2293a4abe0391be7540d408ed", "size": 3172, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "series4/2d-rad-cooling/time_evolution_implicit.hpp", "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": "series4/2d-rad-cooling/time_evolution_implicit.hpp", "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": "series4/2d-rad-cooling/time_evolution_implicit.hpp", "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": 37.3176470588, "max_line_length": 112, "alphanum_fraction": 0.6295712484, "num_tokens": 749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096181702032, "lm_q2_score": 0.8056321843145404, "lm_q1q2_score": 0.7380473927580204}}
{"text": "#include <Eigen/Dense>\n#include <cmath>\n#include <vector>\n#include \"Adagrad.hpp\"\n\n#define EIGEN_MPL2_ONLY\nusing namespace Eigen;\nusing namespace std;\n\ndouble Adagrad::sigma(const MatrixXd& _x, int i){\n  return sigmoid(_x.row(i).dot(w));\n}\n\ndouble Adagrad::sigmoid(double z){\n  return 1.0 / (1.0 + exp(-z));\n}\n\nAdagrad::Adagrad(int _N,int _d,MatrixXd _x,VectorXd _label,double _C,double _eta,int iter):\n  N(_N),\n  d(_d),\n  X(_x),\n  label(_label),\n  C(_C),\n  eta(_eta),\n  iteration(iter),\n  E(VectorXd::Zero(d)),\n  w(VectorXd::Random(d))\n{}\n\ndouble Adagrad::Acc(vector<double>& pred,VectorXd &l){\n  int t =0;\n  double loss =0;\n  for(int i = 0; i< pred.size();i++){\n    loss += (l(i) - pred[i]) * (l(i) - pred[i]);\n    int s = pred[i] > 0.5 ? 1 : 0;\n    if(s == l(i)){\n      t++;\n    }\n  }\n  return (double)t/pred.size();\n}\n\nvoid Adagrad::train(){\n  for(int iter = 0; iter< iteration; iter++){\n    for(int i = 0; i < N; i++){\n      double pred = sigma(X,i);\n      for(int idx = 0; idx < d; idx++){\n        if(X(i,idx) != 0){\n          double grad = (pred - label(i)) * X(i,idx) + C * w(idx);\n          E(idx) +=grad * grad;\n          w(idx) -= (eta/sqrt(E(idx)))*grad;\n        }\n      }\n    }\n    vector<double> ret;\n    predict(X,label,ret);\n    iterscores.push_back(Acc(ret,label));\n  }\n}\nvoid Adagrad::predict(MatrixXd& _x,VectorXd& _l,vector<double>& ret){\n  for(int i = 0; i < _x.rows(); i++){\n    ret.push_back(sigma(_x,i));\n  }\n}\n\n", "meta": {"hexsha": "87a7fd0ba6b883733098a38b4a76cd58b71d2fc0", "size": 1435, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Adagrad.cpp", "max_stars_repo_name": "saiias/Adadelta", "max_stars_repo_head_hexsha": "2a8d94ec32b887d078409b5252170d4e9ffeb402", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2015-08-27T10:49:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-01T07:42:49.000Z", "max_issues_repo_path": "Adagrad.cpp", "max_issues_repo_name": "huangpingchun/Adadelta", "max_issues_repo_head_hexsha": "2a8d94ec32b887d078409b5252170d4e9ffeb402", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2016-02-20T12:33:39.000Z", "max_issues_repo_issues_event_max_datetime": "2017-06-23T08:12:09.000Z", "max_forks_repo_path": "Adagrad.cpp", "max_forks_repo_name": "huangpingchun/Adadelta", "max_forks_repo_head_hexsha": "2a8d94ec32b887d078409b5252170d4e9ffeb402", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-08-27T10:49:48.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-08T08:36:07.000Z", "avg_line_length": 21.7424242424, "max_line_length": 91, "alphanum_fraction": 0.5602787456, "num_tokens": 472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632996617212, "lm_q2_score": 0.795658095217705, "lm_q1q2_score": 0.7378641165836508}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n\nusing Eigen::MatrixBase;\nusing Eigen::MatrixXd;\nusing Eigen::Ref;\nusing Eigen::VectorXd;\n\nstruct Params {\n    VectorXd weight;\n    double bias;\n};\n\nnamespace LinearRegression {\n\nclass Core {\npublic:\n    Core(double learning_rate, double weight_decay) noexcept;\n\n    const Params& get_params() const;\n\n    void set_params(const Params& params);\n\n    void init_params(const Ref<const MatrixXd> input, const Ref<const VectorXd> target);\n\n    VectorXd compute_prediction(const Ref<const MatrixXd> input) const;\n\n    double compute_cost(const Ref<const VectorXd> prediction, const Ref<const VectorXd> target) const;\n\n    void optimize_step(const Ref<const MatrixXd> input, const Ref<const VectorXd> prediction, const Ref<const VectorXd> target);\n\nprivate:\n    Params compute_grads(const Ref<const MatrixXd> input, const Ref<const VectorXd> error) const;\n\n    void update_params(const Params& grads);\n\n    Params params;\n    const double learning_rate;\n    const double weight_decay;\n};\n\n}\n", "meta": {"hexsha": "b02632106d36f60b857a5d43010347e035b07d23", "size": 1022, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/gradient_descent/core.hpp", "max_stars_repo_name": "ShkarupaDC/parallel-gradient-descent", "max_stars_repo_head_hexsha": "269c0e0fcb2272a25f69a4656e2b0d369f7b7b63", "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/gradient_descent/core.hpp", "max_issues_repo_name": "ShkarupaDC/parallel-gradient-descent", "max_issues_repo_head_hexsha": "269c0e0fcb2272a25f69a4656e2b0d369f7b7b63", "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": "include/gradient_descent/core.hpp", "max_forks_repo_name": "ShkarupaDC/parallel-gradient-descent", "max_forks_repo_head_hexsha": "269c0e0fcb2272a25f69a4656e2b0d369f7b7b63", "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.2272727273, "max_line_length": 128, "alphanum_fraction": 0.7436399217, "num_tokens": 219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363293639213, "lm_q2_score": 0.7956580927949806, "lm_q1q2_score": 0.7378641095450478}}
{"text": "// Released under the terms of the BSD License\n// (C) 2014-2017\n//   Analog Devices, Inc\n//   Kevin Mehall <km@kevinmehall.net>\n//   Ian Daniher <itdaniher@gmail.com>\n\n\n#include <cmath>\n#include <vector>\n\n#include \"debug.hpp\"\n#include <libsmu/libsmu.hpp>\n#include <boost/math/constants/constants.hpp>\n\nconst double PI = boost::math::constants::pi<double>();\n\nusing namespace smu;\n\nvoid Signal::constant(std::vector<float>& buf, uint64_t samples, float val)\n{\n\tm_src = CONSTANT;\n\tm_src_v1 = val;\n\n\tfor (unsigned i = 0; i < samples; i++) {\n\t\tbuf.push_back(get_sample());\n\t}\n}\n\nvoid Signal::square(std::vector<float>& buf, uint64_t samples, float midpoint, float peak, double period, double phase, double duty)\n{\n\tm_src = SQUARE;\n\tm_src_phase = phase;\n\tm_src_period = period;\n\tm_src_v1 = midpoint;\n\tm_src_v2 = peak;\n\tm_src_duty = duty;\n\n\tfor (unsigned i = 0; i < samples; i++) {\n\t\tbuf.push_back(get_sample());\n\t}\n}\n\nvoid Signal::sawtooth(std::vector<float>& buf, uint64_t samples, float midpoint, float peak, double period, double phase)\n{\n\tm_src = SAWTOOTH;\n\tm_src_phase = phase;\n\tm_src_period = period;\n\tm_src_v1 = midpoint;\n\tm_src_v2 = peak;\n\n\tfor (unsigned i = 0; i < samples; i++) {\n\t\tbuf.push_back(get_sample());\n\t}\n}\n\nvoid Signal::stairstep(std::vector<float>& buf, uint64_t samples, float midpoint, float peak, double period, double phase)\n{\n\tm_src = STAIRSTEP;\n\tm_src_phase = phase;\n\tm_src_period = period;\n\tm_src_v1 = midpoint;\n\tm_src_v2 = peak;\n\n\tfor (unsigned i = 0; i < samples; i++) {\n\t\tbuf.push_back(get_sample());\n\t}\n}\n\nvoid Signal::sine(std::vector<float>& buf, uint64_t samples, float midpoint, float peak, double period, double phase)\n{\n\tm_src = SINE;\n\tm_src_phase = phase;\n\tm_src_period = period;\n\tm_src_v1 = midpoint;\n\tm_src_v2 = peak;\n\n\tfor (unsigned i = 0; i < samples; i++) {\n\t\tbuf.push_back(get_sample());\n\t}\n}\n\nvoid Signal::triangle(std::vector<float>& buf, uint64_t samples, float midpoint, float peak, double period, double phase)\n{\n\tm_src = TRIANGLE;\n\tm_src_phase = phase;\n\tm_src_period = period;\n\tm_src_v1 = midpoint;\n\tm_src_v2 = peak;\n\n\tfor (unsigned i = 0; i < samples; i++) {\n\t\tbuf.push_back(get_sample());\n\t}\n}\n\n// Internal function to generate waveform values.\nfloat Signal::get_sample()\n{\n\tswitch (m_src) {\n\t\tcase CONSTANT:\n\t\t\treturn m_src_v1;\n\n\t\tcase SQUARE:\n\t\tcase SAWTOOTH:\n\t\tcase SINE:\n\t\tcase STAIRSTEP:\n\t\tcase TRIANGLE: {\n\n\t\t\tauto peak_to_peak = m_src_v2 - m_src_v1;\n\t\t\tauto phase = m_src_phase;\n\t\t\tauto norm_phase = phase / m_src_period;\n\t\t\tif (norm_phase < 0)\n\t\t\t\tnorm_phase += 1;\n\t\t\tm_src_phase = fmod(m_src_phase + 1, m_src_period);\n\n\t\t\tswitch (m_src) {\n\t\t\t\tcase SQUARE:\n\t\t\t\t\treturn (norm_phase < m_src_duty) ? m_src_v1 : m_src_v2;\n\n\t\t\t\tcase SAWTOOTH: {\n\t\t\t\t\tfloat int_period = truncf(m_src_period);\n\t\t\t\t\tfloat int_phase = truncf(phase);\n\t\t\t\t\tfloat frac_period = m_src_period - int_period;\n\t\t\t\t\tfloat frac_phase = phase - int_phase;\n\t\t\t\t\tfloat max_int_phase;\n\n\t\t\t\t\t// Get the integer part of the maximum value phase will be set at.\n\t\t\t\t\t// For example:\n\t\t\t\t\t// - If m_src_period = 100.6, phase first value = 0.3 then\n\t\t\t\t\t//   phase will take values: 0.3, 1.3, ..., 98.3, 99.3, 100.3\n\t\t\t\t\t// - If m_src_period = 100.6, phase first value = 0.7 then\n\t\t\t\t\t//   phase will take values: 0.7, 1.7, ..., 98.7, 99.7\n\t\t\t\t\tif (frac_period <= frac_phase)\n\t\t\t\t\t\tmax_int_phase = int_period - 1;\n\t\t\t\t\telse\n\t\t\t\t\t\tmax_int_phase = int_period;\n                    auto nphase = int_phase / max_int_phase;\n                    if(nphase < 0)\n                        nphase += 1;\n                    return m_src_v2 - nphase * peak_to_peak;\n\t\t\t\t}\n\n\t\t\t\tcase STAIRSTEP:\n\t\t\t\t\treturn m_src_v2 - floorf(norm_phase * 10) * peak_to_peak / 9;\n\n\t\t\t\tcase SINE:\n                    return m_src_v1 + (1 + cos(norm_phase * 2 * PI)) * peak_to_peak / 2;\n\n\t\t\t\tcase TRIANGLE:\n\t\t\t\t\treturn m_src_v1 + fabs(1 - norm_phase * 2) * peak_to_peak;\n\t\t\t\tdefault:\n\t\t\t\t\tthrow std::runtime_error(\"unknown waveform\");\n\t\t\t}\n\t\t}\n\t}\n\tthrow std::runtime_error(\"unknown waveform\");\n}\n", "meta": {"hexsha": "982e3004bad476b49217f15ff77a2851d1d19625", "size": 3970, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/signal.cpp", "max_stars_repo_name": "damercer/libsmu", "max_stars_repo_head_hexsha": "6f141ea37a0778299ad1771cc9385fef14010bc0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2015-03-28T23:19:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T14:44:36.000Z", "max_issues_repo_path": "src/signal.cpp", "max_issues_repo_name": "damercer/libsmu", "max_issues_repo_head_hexsha": "6f141ea37a0778299ad1771cc9385fef14010bc0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 147.0, "max_issues_repo_issues_event_min_datetime": "2015-03-06T18:37:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T08:26:47.000Z", "max_forks_repo_path": "src/signal.cpp", "max_forks_repo_name": "damercer/libsmu", "max_forks_repo_head_hexsha": "6f141ea37a0778299ad1771cc9385fef14010bc0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2015-03-14T06:04:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T16:37:48.000Z", "avg_line_length": 25.2866242038, "max_line_length": 132, "alphanum_fraction": 0.6534005038, "num_tokens": 1159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850075259039, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.7377281701049495}}
{"text": "//####### Test module for mathematical constants ##################\n\n//Define Module name\n #define BOOST_TEST_MODULE \"math/constants\"\n\n#include <cmath>\n\n//Include Boost unit tests library & library for floating point comparison\n#include <boost/test/unit_test.hpp>\n#include <boost/test/tools/floating_point_comparison.hpp>\n\n#include \"math_constants.h\"\n\nusing namespace picsar::multi_physics::math;\n\n// ------------- Tests --------------\n\n// ***Test math constants\n\ntemplate<typename RealType>\nvoid test_case_const_math()\n{\n    const auto exp_pi =\n        static_cast<RealType>(3.14159265358979323846264338327950288);\n\n    const auto exp_zero = static_cast<RealType>(0.0);\n    const auto exp_half = static_cast<RealType>(0.5);\n    const auto exp_one = static_cast<RealType>(1.0);\n    const auto exp_two = static_cast<RealType>(2.0);\n    const auto exp_three = static_cast<RealType>(3.0);\n    const auto exp_four = static_cast<RealType>(4.0);\n    const auto exp_one_third = static_cast<RealType>(1.0/3.0);\n    const auto exp_two_thirds = static_cast<RealType>(2.0/3.0);\n    const auto exp_five_thirds = static_cast<RealType>(5.0/3.0);\n\n    BOOST_CHECK_EQUAL(pi<RealType>, exp_pi);\n    BOOST_CHECK_EQUAL(zero<RealType>, exp_zero);\n    BOOST_CHECK_EQUAL(half<RealType>, exp_half);\n    BOOST_CHECK_EQUAL(one<RealType>, exp_one);\n    BOOST_CHECK_EQUAL(two<RealType>, exp_two);\n    BOOST_CHECK_EQUAL(three<RealType>, exp_three);\n    BOOST_CHECK_EQUAL(four<RealType>, exp_four);\n    BOOST_CHECK_EQUAL(one_third<RealType>, exp_one_third);\n    BOOST_CHECK_EQUAL(two_thirds<RealType>, exp_two_thirds);\n    BOOST_CHECK_EQUAL(five_thirds<RealType>, exp_five_thirds);\n}\n\nBOOST_AUTO_TEST_CASE( picsar_const_math )\n{\n    test_case_const_math<double>();\n    test_case_const_math<float>();\n}\n\n// *******************************\n", "meta": {"hexsha": "c702ec8be53a787be88f75ee23bc1c3a20224827", "size": 1809, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/multi_physics/QED_tests/test_picsar_math_constants.cpp", "max_stars_repo_name": "LDAmorim/picsar", "max_stars_repo_head_hexsha": "024db7c01daf820ae321c3473f2dd5ec73476946", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "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/multi_physics/QED_tests/test_picsar_math_constants.cpp", "max_issues_repo_name": "LDAmorim/picsar", "max_issues_repo_head_hexsha": "024db7c01daf820ae321c3473f2dd5ec73476946", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "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/multi_physics/QED_tests/test_picsar_math_constants.cpp", "max_forks_repo_name": "LDAmorim/picsar", "max_forks_repo_head_hexsha": "024db7c01daf820ae321c3473f2dd5ec73476946", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.8909090909, "max_line_length": 74, "alphanum_fraction": 0.7119955777, "num_tokens": 435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122288794595, "lm_q2_score": 0.8128673087708699, "lm_q1q2_score": 0.7375244497041458}}
{"text": "#include \"Optimize.h\"\r\n\r\n#include <armadillo>\r\n#include <functional>\r\n\r\narma::vec Gradient_Approximate( const arma::vec & x,\r\n\t\t\t\t\t\t\t\tstd::function<double( const arma::vec & )> func,\r\n\t\t\t\t\t\t\t\tdouble resolution )\r\n{\r\n\tarma::vec gradient_vector = arma::zeros( x.size() );\r\n\tfor( auto i = 0; i < x.size(); i++ )\r\n\t{\r\n\t\tarma::vec offset = arma::zeros<arma::vec>( x.size() );\r\n\t\toffset( i ) = resolution;\r\n\t\t//double debug1 = func( x + offset );\r\n\t\t//double debug2 = func( x - offset );\r\n\r\n\t\t//gradient_vector( i ) = (func( x + offset ) - func( x - offset )) / (2 * resolution);\r\n\t\tgradient_vector( i ) = (func( x + offset ) - func( x - offset ));// / (2 * resolution);\r\n\t}\r\n\r\n\treturn gradient_vector;\r\n}\r\n\r\narma::mat Hessian_Approximate( const arma::vec & x,\r\n\t\t\t\t\t\t\t   std::function<double( const arma::vec & )> func,\r\n\t\t\t\t\t\t\t   double resolution )\r\n{\r\n\tarma::mat hessian_matrix( x.size(), x.size() );\r\n\tconst double denominator = 4 * resolution * resolution;\r\n\tfor( int j = 0; j < x.size(); j++ )\r\n\t{\r\n\t\tarma::vec offset_j = arma::zeros<arma::vec>( x.size() );\r\n\t\toffset_j( j ) = resolution;\r\n\t\tfor( int i = 0; i <= j; i++ )\r\n\t\t{\r\n\t\t\tarma::vec offset_i = arma::zeros<arma::vec>( x.size() );\r\n\t\t\toffset_i( i ) = resolution;\r\n\t\t\t//double debug1 = func( x + offset_i + offset_j );\r\n\t\t\t//double debug2 = func( x + offset_i - offset_j );\r\n\t\t\t//double debug3 = func( x - offset_i + offset_j );\r\n\t\t\t//double debug4 = func( x - offset_i - offset_j );\r\n\t\t\tdouble delta_f = func( x + offset_i + offset_j ) - func( x + offset_i - offset_j ) - func( x - offset_i + offset_j ) + func( x - offset_i - offset_j );\r\n\t\t\tif( abs( delta_f ) < 1E-9 )\r\n\t\t\t\tint i = 0;\r\n\t\t\t//double debug5 = delta_f / denominator;\r\n\t\t\tdouble result = delta_f;// / denominator;\r\n\t\t\thessian_matrix( i, j ) = result;\r\n\t\t\thessian_matrix( j, i ) = result;\r\n\t\t}\r\n\t}\r\n\r\n\treturn hessian_matrix;\r\n}\r\n\r\narma::vec Minimize_Function_Starting_Point( std::function<double( const arma::vec & )> function_to_minimize,\r\n\t\t\t\t\t\t\t\t\t\t\tconst arma::vec & starting_point,\r\n\t\t\t\t\t\t\t\t\t\t\tint max_iteration_count,\r\n\t\t\t\t\t\t\t\t\t\t\tdouble attenuation_coefficient,\r\n\t\t\t\t\t\t\t\t\t\t\tdouble resolution,\r\n\t\t\t\t\t\t\t\t\t\t\tdouble biggest_step_size,\r\n\t\t\t\t\t\t\t\t\t\t\tstd::function<void( arma::vec )> iteration_finished_callback )\r\n{\r\n\tarma::vec current_guess = starting_point;\r\n\tarma::vec previous_direction = arma::zeros( current_guess.size() );\r\n\tfor( int i = 0; i < max_iteration_count; i++ )\r\n\t{\r\n\t\tstd::cout << \"current_guess: \" << function_to_minimize( current_guess ) << \" =\";\r\n\t\tfor( double x : current_guess )\r\n\t\t\tstd::cout << \" \" << x;\r\n\t\tstd::cout << std::endl;\r\n\r\n\t\tarma::vec gradient = Gradient_Approximate( current_guess, function_to_minimize, resolution );\r\n\t\t//gradient = gradient( arma::span( 0, 1 ) );\r\n\t\t//std::cout << \"gradient: \" << gradient << std::endl;\r\n\t\t//arma::mat hessian = Hessian_Approximate( current_guess, function_to_minimize, resolution );\r\n\t\t////hessian = hessian( arma::span( 0, 1 ), arma::span( 0, 1 ) );\r\n\t\t////std::cout << \"hessian: \" << hessian << std::endl;\r\n\t\t//arma::mat inverse_hessian;\r\n\t\t//try\r\n\t\t//{\r\n\t\t//\tinverse_hessian = arma::inv( hessian );\r\n\t\t//}\r\n\t\t//catch( ... )\r\n\t\t//{\r\n\t\t//\tcurrent_guess = 1.1 * current_guess;\r\n\t\t//\tcontinue;\r\n\t\t//}\r\n\t\t//std::cout << \"inverse_hessian: \" << inverse_hessian << std::endl;\r\n\r\n\t\t//arma::vec move_vector = -attenuation_coefficient * (inverse_hessian * gradient) * (2 * resolution);\r\n\t\t//if( arma::norm( move_vector ) > 10 * resolution )\r\n\t\t//\tmove_vector = move_vector / arma::norm( move_vector ) * 10 * resolution;\r\n\t\t//for( int j = 0; j < current_guess.size(); j++ )\r\n\t\t//{\r\n\t\t//\tif( abs( move_vector( j ) ) > 0.0005 * abs( current_guess( j ) ) )\r\n\t\t//\t\tmove_vector( j ) = 0.0005 * abs( current_guess( j ) ) * move_vector( j ) / abs( move_vector( j ) );\r\n\t\t//}\r\n\t\tarma::vec to_zero = -gradient / (2 * resolution) / function_to_minimize( current_guess );\r\n\t\tarma::vec move_vector = std::min( arma::norm( to_zero ), biggest_step_size ) * arma::normalise( to_zero );\r\n\t\t//double length = arma::norm( gradient ) / (2 * resolution);\r\n\t\t//arma::vec move_vector = -arma::normalise( gradient ) * std::min( length, 1000 * resolution );\r\n\t\t//arma::vec extend_thing = { 0, 0, 0 };\r\n\t\t//extend_thing( arma::span( 0, 1 ) ) = move_vector;\r\n\t\t//move_vector = extend_thing;\r\n\t\t//move_vector( 2 ) = 0;\r\n\t\tstd::cout << \"Move vector: \";\r\n\t\tfor( double x : move_vector )\r\n\t\t\tstd::cout << \" \" << x;\r\n\t\tstd::cout << std::endl;\r\n\t\tcurrent_guess = current_guess + move_vector;\r\n\t\titeration_finished_callback( current_guess );\r\n\t\t//std::cout << \"current_guess: \" << current_guess( 0 ) << \" \" << current_guess( 1 ) << std::endl;\r\n\t\tif( arma::dot( move_vector, move_vector ) < resolution * resolution )\r\n\t\t\tbreak; // Quit out if we are barely moving anymore\r\n\t\tif( arma::dot( move_vector, previous_direction ) < 0 )\r\n\t\t\tbiggest_step_size *= 0.9;\r\n\r\n\t\tprevious_direction = move_vector;\r\n\t}\r\n\r\n\treturn current_guess;\r\n}\r\n\r\narma::mat Minimize_Function( std::function<double( const arma::vec & )> function_to_minimize,\r\n\t\t\t\t\t\t\t const std::vector< std::tuple<double, double> > & bounds,\r\n\t\t\t\t\t\t\t const int max_iteration_count )\r\n{\r\n\treturn arma::mat();\r\n}\r\n\r\ndouble Newtons_Method( std::function<double( double )> func, std::function<double( double )> derivative, double starting_point, double resolution, int max_iteration_count )\r\n{\r\n\tdouble x_i = starting_point;\r\n\tdouble x_i_old;\r\n\tint iteration = 0;\r\n\tfor( int iteration = 0; iteration < max_iteration_count; iteration++ )\r\n\t{\r\n\t\tx_i_old = x_i;\r\n\t\tx_i = x_i - func( x_i ) / derivative( x_i );\r\n\t\tif( abs( x_i - x_i_old ) < resolution )\r\n\t\t{\r\n\t\t\treturn x_i;\r\n\t\t}\r\n\t}\r\n}\r\n\r\ndouble Binary_Search( std::function<double( double )> func, double left_most, double right_most, double resolution, int max_iteration_count )\r\n{\r\n\t// Binary search\r\n\tdouble left = left_most, right = right_most;\r\n\twhile( right - left > resolution )\r\n\t{\r\n\t\tdouble center = (right + left) / 2;\r\n\t\tif( func( center ) > 0 )\r\n\t\t\tright = center;\r\n\t\telse\r\n\t\t\tleft = center;\r\n\t}\r\n\tdouble center = (right + left) / 2;\r\n\r\n\treturn center;\r\n}\r\n", "meta": {"hexsha": "efc13ec77c5f5cf870fc3b7bfd8ec8754437e567", "size": 6017, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Optimize.cpp", "max_stars_repo_name": "Ryan3141/IVCV_Plotter", "max_stars_repo_head_hexsha": "514fa15f7ecb5da99ea1d0e1fdfcaa7844b99eef", "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": "Optimize.cpp", "max_issues_repo_name": "Ryan3141/IVCV_Plotter", "max_issues_repo_head_hexsha": "514fa15f7ecb5da99ea1d0e1fdfcaa7844b99eef", "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": "Optimize.cpp", "max_forks_repo_name": "Ryan3141/IVCV_Plotter", "max_forks_repo_head_hexsha": "514fa15f7ecb5da99ea1d0e1fdfcaa7844b99eef", "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.6890243902, "max_line_length": 173, "alphanum_fraction": 0.6160877514, "num_tokens": 1749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.7374604453706324}}
{"text": "// -*- coding: utf-16 -*-\n#pragma once\n\n/*! @file include/fractions.hpp\n *  This is a C++ Library header.\n */\n\n#include <boost/operators.hpp>\n#include <cmath>\n#include <numeric>\n#include <type_traits>\n\nnamespace fun\n{\n\n/*!\n * @brief Greatest common divider\n *\n * @tparam _Mn\n * @param[in] __m\n * @param[in] __n\n * @return _Mn\n */\ntemplate <typename Mn>\nconstexpr auto gcd(Mn _m, Mn _n) -> Mn\n{\n    return _m == 0 ? abs(_n) : _n == 0 ? abs(_m) : gcd(_n, _m % _n);\n}\n\n/*!\n * @brief Least common multiple\n *\n * @tparam _Mn\n * @param[in] __m\n * @param[in] __n\n * @return _Mn\n */\ntemplate <typename Mn>\nconstexpr auto lcm(Mn _m, Mn _n) -> Mn\n{\n    return (_m != 0 && _n != 0) ? (abs(_m) / gcd(_m, _n)) * abs(_n) : 0;\n}\n\ntemplate <typename Z>\nstruct Fraction : boost::totally_ordered<Fraction<Z>,\n                      boost::totally_ordered2<Fraction<Z>, Z,\n                          boost::multipliable2<Fraction<Z>, Z,\n                              boost::dividable2<Fraction<Z>, Z>>>>\n{\n    Z _numerator;\n    Z _denominator;\n\n    /*!\n     * @brief Construct a new Fraction object\n     *\n     * @param[in] numerator\n     * @param[in] denominator\n     */\n    constexpr Fraction(Z&& numerator, Z&& denominator) noexcept\n        : _numerator {std::move(numerator)}\n        , _denominator {std::move(denominator)}\n    {\n        this->normalize();\n    }\n\n    /*!\n     * @brief Construct a new Fraction object\n     *\n     * @param[in] numerator\n     * @param[in] denominator\n     */\n    constexpr Fraction(const Z& numerator, const Z& denominator)\n        : _numerator {numerator}\n        , _denominator {denominator}\n    {\n        this->normalize();\n    }\n\n    constexpr void normalize()\n    {\n        auto common = gcd(this->_numerator, this->_denominator);\n        if (common == Z(1))\n        {\n            return;\n        }\n        // if (common == Z(0)) [[unlikely]] return; // both num and den are zero\n        if (this->_denominator < Z(0))\n        {\n            common = -common;\n        }\n        this->_numerator /= common;\n        this->_denominator /= common;\n    }\n\n    /*!\n     * @brief Construct a new Fraction object\n     *\n     * @param[in] numerator\n     */\n    constexpr explicit Fraction(Z&& numerator) noexcept\n        : _numerator {std::move(numerator)}\n        , _denominator(Z(1))\n    {\n    }\n\n    /*!\n     * @brief Construct a new Fraction object\n     *\n     * @param[in] numerator\n     */\n    constexpr explicit Fraction(const Z& numerator)\n        : _numerator {numerator}\n        , _denominator(Z(1))\n    {\n    }\n\n    /*!\n     * @brief\n     *\n     * @return const Z&\n     */\n    constexpr auto numerator() const -> const Z&\n    {\n        return _numerator;\n    }\n\n    /*!\n     * @brief\n     *\n     * @return const Z&\n     */\n    constexpr auto denominator() const -> const Z&\n    {\n        return _denominator;\n    }\n\n    /*!\n     * @brief\n     *\n     * @return Fraction\n     */\n    constexpr auto abs() const -> Fraction\n    {\n        return Fraction(std::abs(_numerator), std::abs(_denominator));\n    }\n\n    /*!\n     * @brief\n     *\n     */\n    constexpr void reciprocal()\n    {\n        std::swap(_numerator, _denominator);\n    }\n\n    /*!\n     * @brief\n     *\n     * @return Fraction\n     */\n    constexpr auto operator-() const -> Fraction\n    {\n        auto res = Fraction(*this);\n        res._numerator = -res._numerator;\n        return res;\n    }\n\n    /*!\n     * @brief\n     *\n     * @param[in] frac\n     * @return Fraction\n     */\n    constexpr auto operator+(const Fraction& frac) const -> Fraction\n    {\n        if (_denominator == frac._denominator)\n        {\n            return Fraction(_numerator + frac._numerator, _denominator);\n        }\n        auto d = _denominator * frac._denominator;\n        auto n =\n            frac._denominator * _numerator + _denominator * frac._numerator;\n        return Fraction(n, d);\n    }\n\n    /*!\n     * @brief\n     *\n     * @param[in] frac\n     * @return Fraction\n     */\n    constexpr auto operator-(const Fraction& frac) const -> Fraction\n    {\n        return *this + (-frac);\n    }\n\n    /*!\n     * @brief\n     *\n     * @param[in] frac\n     * @return Fraction\n     */\n    constexpr auto operator*(const Fraction& frac) const -> Fraction\n    {\n        auto n = _numerator * frac._numerator;\n        auto d = _denominator * frac._denominator;\n        return Fraction(std::move(n), std::move(d));\n    }\n\n    /*!\n     * @brief\n     *\n     * @param[in] frac\n     * @return Fraction\n     */\n    constexpr auto operator/(Fraction frac) const -> Fraction\n    {\n        frac.reciprocal();\n        return *this * frac;\n    }\n\n    /*!\n     * @brief\n     *\n     * @param[in] i\n     * @return Fraction\n     */\n    constexpr auto operator+(const Z& i) const -> Fraction\n    {\n        auto n = _numerator + _denominator * i;\n        return Fraction(std::move(n), _denominator);\n    }\n\n    /*!\n     * @brief\n     *\n     * @param[in] i\n     * @return Fraction\n     */\n    constexpr auto operator-(const Z& i) const -> Fraction\n    {\n        return *this + (-i);\n    }\n\n    // /*!\n    //  * @brief\n    //  *\n    //  * @param[in] i\n    //  * @return Fraction\n    //  */\n    // constexpr Fraction operator*(const Z& i) const\n    // {\n    //     auto n = _numerator * i;\n    //     return Fraction(n, _denominator);\n    // }\n\n    // /*!\n    //  * @brief\n    //  *\n    //  * @param[in] i\n    //  * @return Fraction\n    //  */\n    // constexpr Fraction operator/(const Z& i) const\n    // {\n    //     auto d = _denominator * i;\n    //     return Fraction(_numerator, d);\n    // }\n\n    /*!\n     * @brief\n     *\n     * @param[in] frac\n     * @return Fraction\n     */\n    constexpr auto operator+=(const Fraction& frac) -> Fraction&\n    {\n        return *this = *this + frac;\n    }\n\n    /*!\n     * @brief\n     *\n     * @param[in] frac\n     * @return Fraction\n     */\n    constexpr auto operator-=(const Fraction& frac) -> Fraction&\n    {\n        return *this = *this - frac;\n    }\n\n    /*!\n     * @brief\n     *\n     * @param[in] frac\n     * @return Fraction\n     */\n    constexpr auto operator*=(const Fraction& frac) -> Fraction&\n    {\n        return *this = *this * frac;\n    }\n\n    /*!\n     * @brief\n     *\n     * @param[in] frac\n     * @return Fraction\n     */\n    constexpr auto operator/=(const Fraction& frac) -> Fraction&\n    {\n        return *this = *this / frac;\n    }\n\n    /*!\n     * @brief\n     *\n     * @param[in] i\n     * @return Fraction\n     */\n    constexpr auto operator+=(const Z& i) -> Fraction&\n    {\n        return *this = *this + i;\n    }\n\n    /*!\n     * @brief\n     *\n     * @param[in] i\n     * @return Fraction\n     */\n    constexpr auto operator-=(const Z& i) -> Fraction&\n    {\n        return *this = *this - i;\n    }\n\n    /*!\n     * @brief\n     *\n     * @param[in] i\n     * @return Fraction\n     */\n    constexpr auto operator*=(const Z& i) -> Fraction&\n    {\n        const auto common = gcd(i, this->_denominator);\n        if (common == Z(1))\n        {\n            this->_numerator *= i;\n        }\n        // else if (common == Z(0)) [[unlikely]] // both i and den are zero\n        // {\n        //     this->_numerator = Z(0);\n        // }\n        else\n        {\n            this->_numerator *= (i / common);\n            this->_denominator /= common;\n        }\n        return *this;\n    }\n\n    /*!\n     * @brief\n     *\n     * @param[in] i\n     * @return Fraction\n     */\n    constexpr auto operator/=(const Z& i) -> Fraction&\n    {\n        const auto common = gcd(this->_numerator, i);\n        if (common == Z(1))\n        {\n            this->_denominator *= i;\n        }\n        // else if (common == Z(0)) [[unlikely]] // both i and num are zero\n        // {\n        //     this->_denominator = Z(0);\n        // }\n        else\n        {\n            this->_denominator *= (i / common);\n            this->_numerator /= common;\n        }\n        return *this;\n    }\n\n    /*!\n     * @brief Three way comparison\n     *\n     * @param[in] frac\n     * @return auto\n     */\n    template <typename U>\n    constexpr auto cmp(const Fraction<U>& frac) const\n    {\n        // if (_denominator == frac._denominator) {\n        //     return _numerator - frac._numerator;\n        // }\n        return _numerator * frac._denominator - _denominator * frac._numerator;\n    }\n\n    constexpr auto operator==(const Fraction<Z>& rhs) const -> bool\n    {\n        if (this->_denominator == rhs._denominator)\n        {\n            return this->_numerator == rhs._numerator;\n        }\n\n        return (this->_numerator * rhs._denominator) ==\n            (this->_denominator * rhs._numerator);\n    }\n\n    constexpr auto operator<(const Fraction<Z>& rhs) const -> bool\n    {\n        if (this->_denominator == rhs._denominator)\n        {\n            return this->_numerator < rhs._numerator;\n        }\n\n        return (this->_numerator * rhs._denominator) <\n            (this->_denominator * rhs._numerator);\n    }\n\n    /**\n     * @brief\n     *\n     */\n    constexpr auto operator==(const Z& rhs) const -> bool\n    {\n        return this->_denominator == Z(1) && this->_numerator == rhs;\n    }\n\n    /**\n     * @brief\n     *\n     */\n    constexpr auto operator<(const Z& rhs) const -> bool\n    {\n        return this->_numerator < (this->_denominator * rhs);\n    }\n\n    /**\n     * @brief\n     *\n     */\n    constexpr auto operator>(const Z& rhs) const -> bool\n    {\n        return this->_numerator > (this->_denominator * rhs);\n    }\n\n    // /*!\n    //  * @brief\n    //  *\n    //  * @return double\n    //  */\n    // constexpr explicit operator double()\n    // {\n    //     return double(_numerator) / _denominator;\n    // }\n\n    // /**\n    //  * @brief\n    //  *\n    //  */\n    // friend constexpr bool operator<(const Z& lhs, const Fraction<Z>& rhs)\n    // {\n    //     return lhs * rhs.denominator() < rhs.numerator();\n    // }\n};\n\n\n/*!\n * @brief\n *\n * @param[in] c\n * @param[in] frac\n * @return Fraction<Z>\n */\ntemplate <typename Z>\nconstexpr auto operator+(const Z& c, const Fraction<Z>& frac) -> Fraction<Z>\n{\n    return frac + c;\n}\n\n/*!\n * @brief\n *\n * @param[in] c\n * @param[in] frac\n * @return Fraction<Z>\n */\ntemplate <typename Z>\nconstexpr auto operator-(const Z& c, const Fraction<Z>& frac) -> Fraction<Z>\n{\n    return c + (-frac);\n}\n\n// /*!\n//  * @brief\n//  *\n//  * @param[in] c\n//  * @param[in] frac\n//  * @return Fraction<Z>\n//  */\n// template <typename Z>\n// constexpr Fraction<Z> operator*(const Z& c, const Fraction<Z>& frac)\n// {\n//     return frac * c;\n// }\n\n/*!\n * @brief\n *\n * @param[in] c\n * @param[in] frac\n * @return Fraction<Z>\n */\ntemplate <typename Z>\nconstexpr auto operator+(int&& c, const Fraction<Z>& frac) -> Fraction<Z>\n{\n    return frac + c;\n}\n\n/*!\n * @brief\n *\n * @param[in] c\n * @param[in] frac\n * @return Fraction<Z>\n */\ntemplate <typename Z>\nconstexpr auto operator-(int&& c, const Fraction<Z>& frac) -> Fraction<Z>\n{\n    return (-frac) + c;\n}\n\n/*!\n * @brief\n *\n * @param[in] c\n * @param[in] frac\n * @return Fraction<Z>\n */\ntemplate <typename Z>\nconstexpr auto operator*(int&& c, const Fraction<Z>& frac) -> Fraction<Z>\n{\n    return frac * c;\n}\n\n/*!\n * @brief\n *\n * @tparam _Stream\n * @tparam Z\n * @param[in] os\n * @param[in] frac\n * @return _Stream&\n */\ntemplate <typename Stream, typename Z>\nauto operator<<(Stream& os, const Fraction<Z>& frac) -> Stream&\n{\n    os << frac.numerator() << \"/\" << frac.denominator();\n    return os;\n}\n\n// For template deduction\n// Integral{Z} Fraction(const Z &, const Z &) -> Fraction<Z>;\n\n} // namespace fun\n", "meta": {"hexsha": "67bc14dc04d7dfb3942b034dfb65cad304d4ea73", "size": 11419, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/include/py2cpp/fractions.hpp", "max_stars_repo_name": "luk036/primal-dual-approx-cpp", "max_stars_repo_head_hexsha": "930d2b99f8fc9280bc399cb2391707d5bf6111fb", "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": "lib/include/py2cpp/fractions.hpp", "max_issues_repo_name": "luk036/primal-dual-approx-cpp", "max_issues_repo_head_hexsha": "930d2b99f8fc9280bc399cb2391707d5bf6111fb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-07-23T14:21:48.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-20T10:48:07.000Z", "max_forks_repo_path": "lib/include/py2cpp/fractions.hpp", "max_forks_repo_name": "luk036/primal-dual-approx-cpp", "max_forks_repo_head_hexsha": "930d2b99f8fc9280bc399cb2391707d5bf6111fb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-13T12:33:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-13T12:33:24.000Z", "avg_line_length": 20.1038732394, "max_line_length": 80, "alphanum_fraction": 0.509063841, "num_tokens": 3085, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242132, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.737460443287982}}
{"text": "#pragma once\n#include <Eigen/Core>\n#include <igl/readMESH.h>\n#include <iostream>\n#include <tuple>\n\n#include \"fem_solve.hpp\"\n#include \"writer.hpp\"\n\ndouble f_lshape(double x, double y) {\n\tstd::ignore = x;\n\tstd::ignore = y;\n\treturn 0;\n}\n\ndouble g_lshape(double x, double y) {\n\tdouble r = std::sqrt(x * x + y * y);\n\n\tdouble theta = std::atan2(y, x);\n\n\t// Adjust for the region where theta < 0\n\tif (theta < 0) {\n\t\ttheta += 2 * M_PI;\n\t}\n\n\treturn std::pow(r, 2.0 / 3.0) * std::sin(2 * theta / 3);\n}\n\nEigen::Vector2d g_grad_lshape(double x, double y) {\n\tdouble r = std::sqrt(x * x + y * y);\n\n\tdouble theta = std::atan2(y, x);\n\n\t// Adjust for the region where theta < 0\n\tif (theta < 0) {\n\t\ttheta += 2 * M_PI;\n\t}\n\tEigen::Vector2d grad;\n\tgrad << -2.0 / 3.0 * std::pow(r, -1.0 / 3.0) * std::sin(theta / 3), 2.0 / 3.0 * std::pow(r, -1.0 / 3.0) * std::cos(theta / 3);\n\treturn grad;\n}\n\nvoid solveL(double r) {\n\tstd::cout << \"Solving L-shape\" << std::endl;\n\tVector u;\n\n\tEigen::MatrixXd vertices;\n\tEigen::MatrixXi triangles;\n\tEigen::MatrixXi tetrahedra;\n\n\tigl::readMESH(NPDE_DATA_PATH \"Lshape_5.mesh\", vertices, tetrahedra, triangles);\n\n\tsolveFiniteElement(u, vertices, triangles, f_lshape, constantFunction, g_lshape, r);\n\n\twriteToFile(\"Lshape_values.txt\", u);\n\twriteMatrixToFile(\"Lshape_vertices.txt\", vertices);\n\twriteMatrixToFile(\"Lshape_triangles.txt\", triangles);\n}\n", "meta": {"hexsha": "e7e8326c0bdb276e893d10464ee7e528d2173393", "size": 1355, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "series2/2d-linFEM/Lshape.hpp", "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/Lshape.hpp", "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/Lshape.hpp", "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": 22.9661016949, "max_line_length": 127, "alphanum_fraction": 0.6516605166, "num_tokens": 452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206870747657, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7373873353078412}}
{"text": "#include \"libphysica/Integration.hpp\"\n\n#include <algorithm>\n#include <iostream>\n\n#include <boost/math/quadrature/gauss.hpp>\n#include <boost/math/quadrature/gauss_kronrod.hpp>\n#include <boost/math/quadrature/trapezoidal.hpp>\n\n#include \"libphysica/Special_Functions.hpp\"\n#include \"libphysica/Statistics.hpp\"\n\nnamespace libphysica\n{\nusing namespace boost::math::quadrature;\n\n// 1. One-dimensional MC integration\n// 1.1 One-dimensional integration via adaptive Simpson method\n\n//Function to return a reasonable precision.\ndouble Find_Epsilon(std::function<double(double)> func, double a, double b, double precision)\n{\n\tdouble c\t   = (a + b) / 2;\n\tdouble h\t   = b - a;\n\tdouble fa\t   = func(a);\n\tdouble fb\t   = func(b);\n\tdouble fc\t   = func(c);\n\tdouble S\t   = (h / 6) * (fa + 4 * fc + fb);\n\tdouble epsilon = precision * S;\n\treturn epsilon;\n}\n\ndouble Adaptive_Simpson_Integration(std::function<double(double)> func, double a, double b, double epsilon, double S, double fa, double fb, double fc, int bottom, bool& warning)\n{\n\tdouble c\t  = (a + b) / 2;\n\tdouble h\t  = b - a;\n\tdouble d\t  = (a + c) / 2;\n\tdouble e\t  = (b + c) / 2;\n\tdouble fd\t  = func(d);\n\tdouble fe\t  = func(e);\n\tdouble Sleft  = (h / 12) * (fa + 4 * fd + fc);\n\tdouble Sright = (h / 12) * (fc + 4 * fe + fb);\n\tdouble S2\t  = Sleft + Sright;\n\tif(bottom <= 0 || fabs(S2 - S) <= 15 * epsilon)\t  //15 due to error analysis\n\t{\n\t\tif(bottom <= 0 && fabs(S2 - S) > 15 * epsilon)\n\t\t\twarning = true;\n\t\treturn S2 + (S2 - S) / 15;\n\t}\n\telse\n\t{\n\t\treturn Adaptive_Simpson_Integration(func, a, c, epsilon / 2, Sleft, fa, fc, fd, bottom - 1, warning) + Adaptive_Simpson_Integration(func, c, b, epsilon / 2, Sright, fc, fb, fe, bottom - 1, warning);\n\t}\n}\n\n//Recursive functions for one-dimensional integration\nvoid Check_Integration_Limits(double& a, double& b, double& sign)\n{\n\tif(a > b)\n\t{\n\t\tstd::cerr << \"Warning in libphysica::Integrate(): From the integral from a to b, a>b (a = \" << a << \", b = \" << b << \"). Sign will get swapped.\" << std::endl;\n\t\tstd::swap(a, b);\n\t\tsign = -1.0;\n\t}\n}\n\ndouble Integrate(std::function<double(double)> func, double a, double b, double epsilon, int maxRecursionDepth)\n{\n\tdouble sign = +1.0;\n\tif(a == b)\n\t\treturn 0.0;\n\telse\n\t\tCheck_Integration_Limits(a, b, sign);\n\tdouble c\t  = (a + b) / 2;\n\tdouble h\t  = b - a;\n\tdouble fa\t  = func(a);\n\tdouble fb\t  = func(b);\n\tdouble fc\t  = func(c);\n\tdouble S\t  = (h / 6) * (fa + 4 * fc + fb);\n\tbool warning  = false;\n\tdouble result = Adaptive_Simpson_Integration(func, a, b, fabs(epsilon), S, fa, fb, fc, maxRecursionDepth, warning);\n\tif(warning)\n\t{\n\t\tstd::cout << \"Warning in libphysica::Integrate(): Numerical integration on the interval (\" << a << \",\" << b << \") did not converge to the desired precision.\" << std::endl;\n\t\tstd::cout << \"\\tDesired precision: \" << Round(fabs(epsilon)) << \" Result: \" << Round(result) << std::endl;\n\t}\n\tif(std::isnan(result))\n\t\tstd::cout << \"Warning in libphysica::Integrate(): Result is nan.\" << std::endl;\n\telse if(std::isinf(result))\n\t\tstd::cout << \"Warning in libphysica::Integrate(): Result is inf.\" << std::endl;\n\treturn sign * result;\n}\n\n// 1.2 1D integration with boost functions\ndouble Integrate(std::function<double(double)> func, double a, double b, const std::string& method)\n{\n\tdouble sign = 1.0;\n\tif(a == b)\n\t\treturn 0.0;\n\telse\n\t\tCheck_Integration_Limits(a, b, sign);\n\tif(method == \"Trapezoidal\")\n\t\treturn sign * trapezoidal(func, a, b);\n\telse if(method == \"Gauss-Legendre\")\n\t\treturn sign * gauss<double, 30>::integrate(func, a, b);\n\telse if(method == \"Gauss-Kronrod\")\n\t\treturn sign * gauss_kronrod<double, 31>::integrate(func, a, b, 5, 1e-9);\n\telse\n\t{\n\t\tstd::cerr << \"Error in libphysica::Integrate(): Method \" << method << \" not recognized.\" << std::endl;\n\t\tstd::exit(EXIT_FAILURE);\n\t}\n}\n\n// 2. Multidimensional integration\n// 2.1 Multidimensional integration via nesting 1D integration\ndouble Integrate_2D(std::function<double(double, double)> func, double x1, double x2, double y1, double y2, const std::string& method)\n{\n\tauto integrand_x = [&func, y1, y2, method](double x) {\n\t\tauto integrand_y = [&func, x](double y) {\n\t\t\treturn func(x, y);\n\t\t};\n\t\treturn Integrate(integrand_y, y1, y2, method);\n\t};\n\treturn Integrate(integrand_x, x1, x2, method);\n}\n\ndouble Integrate_3D(std::function<double(double, double, double)> func, double x1, double x2, double y1, double y2, double z1, double z2, const std::string& method)\n{\n\tauto integrand_x = [&func, y1, y2, z1, z2, method](double x) {\n\t\tauto integrand_y = [&func, z1, z2, x, method](double y) {\n\t\t\tauto integrand_z = [&func, x, y, method](double z) {\n\t\t\t\treturn func(x, y, z);\n\t\t\t};\n\t\t\treturn Integrate(integrand_z, z1, z2, method);\n\t\t};\n\t\treturn Integrate(integrand_y, y1, y2, method);\n\t};\n\treturn Integrate(integrand_x, x1, x2, method);\n}\n\ndouble Integrate_3D(std::function<double(Vector)> func, double r1, double r2, double costheta_1, double costheta_2, double phi_1, double phi_2, const std::string& method)\n{\n\tauto integrand = [&func](double r, double cos_theta, double phi) {\n\t\tVector rVec = Spherical_Coordinates(r, acos(cos_theta), phi);\n\t\treturn r * r * func(rVec);\n\t};\n\treturn Integrate_3D(integrand, r1, r2, costheta_1, costheta_2, phi_1, phi_2, method);\n}\n\n// 2.2 Monte Carlo Integration\n// Reference: Some of these functions are taken from http://numerical.recipes/webnotes/nr3web9.pdf\n\n// Utility routine used by vegas, to rebin a vector of densities contained in row j of xi into new bins defined by a vector r.\nvoid Rebin(const double rc, const int nd, std::vector<double>& r, std::vector<double>& xin, libphysica::Matrix& xi, const int j)\n{\n\tint i, k = 0;\n\tdouble dr = 0.0, xn = 0.0, xo = 0.0;\n\n\tfor(i = 0; i < nd - 1; i++)\n\t{\n\t\twhile(rc > dr)\n\t\t\tdr += r[(++k) - 1];\n\t\tif(k > 1)\n\t\t\txo = xi[j][k - 2];\n\t\txn = xi[j][k - 1];\n\t\tdr -= rc;\n\t\txin[i] = xn - (xn - xo) * dr / r[k - 1];\n\t}\n\tfor(i = 0; i < nd - 1; i++)\n\t\txi[j][i] = xin[i];\n\txi[j][nd - 1] = 1.0;\n}\n\ndouble Integrate_MC_Vegas(std::function<double(std::vector<double>&, const double)> func, std::vector<double>& region, const int init, const int ncall, const int itmx, const int nprn)\n{\n\tdouble integral, chi2a, standard_deviation;\n\t// Best make everything static, allowing restarts.\n\tstatic const int NDMX = 50, MXDIM = 10;\n\tstatic const double ALPH = 1.5, TINY = 1.0e-30;\n\tstatic int i, it, j, k, mds, nd, ndo, ng, npg;\n\tstatic double calls, dv2g, dxg, f, f2, f2b, fb, rc, ti;\n\tstatic double tsi, wgt, xjac, xn, xnd, xo, schi, si, swgt;\n\tstatic std::vector<int> ia(MXDIM), kg(MXDIM);\n\tstatic std::vector<double> dt(MXDIM), dx(MXDIM), r(NDMX), x(MXDIM), xin(NDMX);\n\tstatic libphysica::Matrix d(NDMX, MXDIM), di(NDMX, MXDIM), xi(MXDIM, NDMX);\n\n\t// Initialize  captive, static random number generator\n\tstd::random_device rd;\n\tstd::mt19937 PRNG(rd());\n\n\tint ndim = region.size() / 2;\n\tif(init <= 0)\n\t{\n\t\tmds = ndo = 1;\n\t\tfor(j = 0; j < ndim; j++)\n\t\t\txi[j][0] = 1.0;\n\t}\n\tif(init <= 1)\n\t\tsi = swgt = schi = 0.0;\n\tif(init <= 2)\n\t{\n\t\tnd = NDMX;\n\t\tng = 1;\n\t\tif(mds != 0)\n\t\t{\n\t\t\tng\t= int(pow(ncall / 2.0 + 0.25, 1.0 / ndim));\n\t\t\tmds = 1;\n\t\t\tif((2 * ng - NDMX) >= 0)\n\t\t\t{\n\t\t\t\tmds = -1;\n\t\t\t\tnpg = ng / NDMX + 1;\n\t\t\t\tnd\t= ng / npg;\n\t\t\t\tng\t= npg * nd;\n\t\t\t}\n\t\t}\n\t\tfor(k = 1, i = 0; i < ndim; i++)\n\t\t\tk *= ng;\n\t\tnpg\t  = std::max(int(ncall / k), 2);\n\t\tcalls = double(npg) * double(k);\n\t\tdxg\t  = 1.0 / ng;\n\t\tfor(dv2g = 1, i = 0; i < ndim; i++)\n\t\t\tdv2g *= dxg;\n\t\tdv2g = calls * dv2g * calls * dv2g / npg / npg / (npg - 1.0);\n\t\txnd\t = nd;\n\t\tdxg *= xnd;\n\t\txjac = 1.0 / calls;\n\t\tfor(j = 0; j < ndim; j++)\n\t\t{\n\t\t\tdx[j] = region[j + ndim] - region[j];\n\t\t\txjac *= dx[j];\n\t\t}\n\t\tif(nd != ndo)\n\t\t{\n\t\t\tfor(i = 0; i < std::max(nd, ndo); i++)\n\t\t\t\tr[i] = 1.0;\n\t\t\tfor(j = 0; j < ndim; j++)\n\t\t\t\tRebin(ndo / xnd, nd, r, xin, xi, j);\n\t\t\tndo = nd;\n\t\t}\n\t\tif(nprn >= 0)\n\t\t{\n\t\t\tstd::cout << \" Input parameters for vegas\";\n\t\t\tstd::cout << \"  ndim= \" << std::setw(4) << ndim;\n\t\t\tstd::cout << \"  ncall= \" << std::setw(8) << calls << std::endl;\n\t\t\tstd::cout << std::setw(34) << \"  it=\" << std::setw(5) << it;\n\t\t\tstd::cout << \"  itmx=\" << std::setw(5) << itmx << std::endl;\n\t\t\tstd::cout << std::setw(34) << \"  nprn=\" << std::setw(5) << nprn;\n\t\t\tstd::cout << \"  ALPH=\" << std::setw(9) << ALPH << std::endl;\n\t\t\tstd::cout << std::setw(34) << \"  mds=\" << std::setw(5) << mds;\n\t\t\tstd::cout << \"  nd=\" << std::setw(5) << nd << std::endl;\n\t\t\tfor(j = 0; j < ndim; j++)\n\t\t\t{\n\t\t\t\tstd::cout << std::setw(30) << \" x1[\" << std::setw(2) << j;\n\t\t\t\tstd::cout << \"]= \" << std::setw(11) << region[j] << \" xu[\";\n\t\t\t\tstd::cout << std::setw(2) << j << \"]= \";\n\t\t\t\tstd::cout << std::setw(11) << region[j + ndim] << std::endl;\n\t\t\t}\n\t\t}\n\t}\n\tfor(it = 0; it < itmx; it++)\n\t{\n\t\tti = tsi = 0.0;\n\t\tfor(j = 0; j < ndim; j++)\n\t\t{\n\t\t\tkg[j] = 1;\n\t\t\tfor(i = 0; i < nd; i++)\n\t\t\t\td[i][j] = di[i][j] = 0.0;\n\t\t}\n\t\tfor(;;)\n\t\t{\n\t\t\tfb = f2b = 0.0;\n\t\t\tfor(k = 0; k < npg; k++)\n\t\t\t{\n\t\t\t\twgt = xjac;\n\t\t\t\tfor(j = 0; j < ndim; j++)\n\t\t\t\t{\n\t\t\t\t\txn\t  = (kg[j] - libphysica::Sample_Uniform(PRNG)) * dxg + 1.0;\n\t\t\t\t\tia[j] = std::max(std::min(int(xn), NDMX), 1);\n\t\t\t\t\tif(ia[j] > 1)\n\t\t\t\t\t{\n\t\t\t\t\t\txo = xi[j][ia[j] - 1] - xi[j][ia[j] - 2];\n\t\t\t\t\t\trc = xi[j][ia[j] - 2] + (xn - ia[j]) * xo;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\txo = xi[j][ia[j] - 1];\n\t\t\t\t\t\trc = (xn - ia[j]) * xo;\n\t\t\t\t\t}\n\t\t\t\t\tx[j] = region[j] + rc * dx[j];\n\t\t\t\t\twgt *= xo * xnd;\n\t\t\t\t}\n\t\t\t\tf  = wgt * func(x, wgt);\n\t\t\t\tf2 = f * f;\n\t\t\t\tfb += f;\n\t\t\t\tf2b += f2;\n\t\t\t\tfor(j = 0; j < ndim; j++)\n\t\t\t\t{\n\t\t\t\t\tdi[ia[j] - 1][j] += f;\n\t\t\t\t\tif(mds >= 0)\n\t\t\t\t\t\td[ia[j] - 1][j] += f2;\n\t\t\t\t}\n\t\t\t}\n\t\t\tf2b = sqrt(f2b * npg);\n\t\t\tf2b = (f2b - fb) * (f2b + fb);\n\t\t\tif(f2b <= 0.0)\n\t\t\t\tf2b = TINY;\n\t\t\tti += fb;\n\t\t\ttsi += f2b;\n\t\t\tif(mds < 0)\n\t\t\t{\n\t\t\t\tfor(j = 0; j < ndim; j++)\n\t\t\t\t\td[ia[j] - 1][j] += f2b;\n\t\t\t}\n\t\t\tfor(k = ndim - 1; k >= 0; k--)\n\t\t\t{\n\t\t\t\tkg[k] %= ng;\n\t\t\t\tif(++kg[k] != 1)\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif(k < 0)\n\t\t\t\tbreak;\n\t\t}\n\t\ttsi *= dv2g;\n\t\twgt = 1.0 / tsi;\n\t\tsi += wgt * ti;\n\t\tschi += wgt * ti * ti;\n\t\tswgt += wgt;\n\t\tintegral = si / swgt;\n\t\tchi2a\t = (schi - si * integral) / (it + 0.0001);\n\t\tif(chi2a < 0.0)\n\t\t\tchi2a = 0.0;\n\t\tstandard_deviation = sqrt(1.0 / swgt);\n\t\ttsi\t\t\t\t   = sqrt(tsi);\n\t\tif(nprn >= 0)\n\t\t{\n\t\t\tstd::cout << \" iteration no. \" << std::setw(3) << (it + 1);\n\t\t\tstd::cout << \" : integral = \" << std::setw(14) << ti;\n\t\t\tstd::cout << \" +/- \" << std::setw(9) << tsi << std::endl;\n\t\t\tstd::cout << \" all iterations:  \"\n\t\t\t\t\t  << \" integral =\";\n\t\t\tstd::cout << std::setw(14) << integral << \"+-\" << std::setw(9) << standard_deviation;\n\t\t\tstd::cout << \" chi**2/IT n =\" << std::setw(9) << chi2a << std::endl;\n\t\t\tif(nprn != 0)\n\t\t\t{\n\t\t\t\tfor(j = 0; j < ndim; j++)\n\t\t\t\t{\n\t\t\t\t\tstd::cout << \" DATA FOR axis  \" << std::setw(2) << j << std::endl;\n\t\t\t\t\tstd::cout << \"     X      delta i          X      delta i\";\n\t\t\t\t\tstd::cout << \"          X       deltai\" << std::endl;\n\t\t\t\t\tfor(i = nprn / 2; i < nd - 2; i += nprn + 2)\n\t\t\t\t\t{\n\t\t\t\t\t\tstd::cout << std::setw(8) << xi[j][i] << std::setw(12) << di[i][j];\n\t\t\t\t\t\tstd::cout << std::setw(12) << xi[j][i + 1] << std::setw(12) << di[i + 1][j];\n\t\t\t\t\t\tstd::cout << std::setw(12) << xi[j][i + 2] << std::setw(12) << di[i + 2][j];\n\t\t\t\t\t\tstd::cout << std::endl;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor(j = 0; j < ndim; j++)\n\t\t{\n\t\t\txo\t\t= d[0][j];\n\t\t\txn\t\t= d[1][j];\n\t\t\td[0][j] = (xo + xn) / 2.0;\n\t\t\tdt[j]\t= d[0][j];\n\t\t\tfor(i = 2; i < nd; i++)\n\t\t\t{\n\t\t\t\trc\t\t\t= xo + xn;\n\t\t\t\txo\t\t\t= xn;\n\t\t\t\txn\t\t\t= d[i][j];\n\t\t\t\td[i - 1][j] = (rc + xn) / 3.0;\n\t\t\t\tdt[j] += d[i - 1][j];\n\t\t\t}\n\t\t\td[nd - 1][j] = (xo + xn) / 2.0;\n\t\t\tdt[j] += d[nd - 1][j];\n\t\t}\n\t\tfor(j = 0; j < ndim; j++)\n\t\t{\n\t\t\trc = 0.0;\n\t\t\tfor(i = 0; i < nd; i++)\n\t\t\t{\n\t\t\t\tif(d[i][j] < TINY)\n\t\t\t\t\td[i][j] = TINY;\n\t\t\t\tr[i] = pow((1.0 - d[i][j] / dt[j]) /\n\t\t\t\t\t\t\t   (log(dt[j]) - log(d[i][j])),\n\t\t\t\t\t\t   ALPH);\n\t\t\t\trc += r[i];\n\t\t\t}\n\t\t\tRebin(rc / xnd, nd, r, xin, xi, j);\n\t\t}\n\t}\n\treturn integral;\n}\n\ndouble Integrate_MC_Brute_Force(std::function<double(std::vector<double>&, const double)> func, std::vector<double>& region, const int ncall)\n{\n\tint dim = region.size() / 2.0;\n\tstd::random_device rd;\n\tstd::mt19937 PRNG(rd());\n\n\tdouble volume = 1.0;\n\tfor(int i = 0; i < dim; i++)\n\t\tvolume *= (region[i + dim] - region[i]);\n\n\tdouble sum = 0.0;\n\t// double sum_2 = 0.0;\n\tfor(int i = 0; i < ncall; i++)\n\t{\n\t\tstd::vector<double> args(dim);\n\t\tfor(int j = 0; j < dim; j++)\n\t\t\targs[j] = region[j] + libphysica::Sample_Uniform(PRNG) * (region[j + dim] - region[j]);\n\t\tdouble fct = func(args, 0.0);\n\t\tsum += volume * fct;\n\t\t// sum_2 += volume * volume * fct * fct;\n\t}\n\tdouble integral = sum / ncall;\n\t// double standard_deviation = sqrt((sum_2 / ncall - integral * integral) / (ncall - 1.0));\n\t// double chi2a\t\t\t  = 0.0;\n\treturn integral;\n}\n\ndouble Integrate_MC(std::function<double(std::vector<double>&, const double)> func, std::vector<double>& region, const int ncalls, const std::string& method)\n{\n\tif(method == \"Brute force\")\n\t\treturn Integrate_MC_Brute_Force(func, region, ncalls);\n\telse if(method == \"Vegas\")\n\t{\n\t\tint init\t   = 0;\n\t\tconst int itmx = 5;\n\t\tconst int nprn = -1;\n\t\treturn Integrate_MC_Vegas(func, region, init, ncalls, itmx, nprn);\n\t}\n\telse\n\t{\n\t\tstd::cerr << \"Error in libphysica::Integrate_MC(): Method \" << method << \" not recognized.\" << std::endl;\n\t\tstd::exit(EXIT_FAILURE);\n\t}\n}\n\n}\t// namespace libphysica", "meta": {"hexsha": "286462675808be662afeb0702dae598c8e6f0ab3", "size": 13100, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Integration.cpp", "max_stars_repo_name": "temken/libphysica", "max_stars_repo_head_hexsha": "0b0f3d4377cfd1ab0ec5a25a3753848d6e6ea657", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-13T12:55:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-13T12:55:16.000Z", "max_issues_repo_path": "src/Integration.cpp", "max_issues_repo_name": "temken/libphysica", "max_issues_repo_head_hexsha": "0b0f3d4377cfd1ab0ec5a25a3753848d6e6ea657", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2020-05-11T10:01:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T12:33:17.000Z", "max_forks_repo_path": "src/Integration.cpp", "max_forks_repo_name": "temken/libphysica", "max_forks_repo_head_hexsha": "0b0f3d4377cfd1ab0ec5a25a3753848d6e6ea657", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-29T15:49:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-29T15:49:59.000Z", "avg_line_length": 29.7052154195, "max_line_length": 200, "alphanum_fraction": 0.5550381679, "num_tokens": 4917, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361509525463, "lm_q2_score": 0.808067204308405, "lm_q1q2_score": 0.7373097296101458}}
{"text": "#include \"problemes.h\"\n#include \"arithmetique.h\"\n\n#include <boost/range/adaptor/reversed.hpp>\n\ntypedef unsigned long long nombre;\n\nENREGISTRER_PROBLEME(14, \"Longest Collatz sequence\") {\n    // The following iterative sequence is defined for the set of positive integers:\n    // \n    // n -> n/2 (n is even)\n    // n -> 3n + 1 (n is odd)\n    // \n    // Using the rule above and starting with 13, we generate the following sequence:\n    // \n    // 13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1\n    // It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. \n    // Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.\n    // \n    // Which starting number, under one million, produces the longest chain?\n    // \n    // NOTE: Once the chain starts the terms are allowed to go above one million.\n    std::map<nombre, nombre> cache;\n    cache[1] = 1;\n\n    nombre max_longueur = 1;\n    nombre max_nombre = 1;\n    for (nombre n = 2; n < 1000000; ++n) {\n        std::vector<nombre> chaine;\n        chaine.push_back(n);\n        nombre p = n;\n        while (cache.find(p) == cache.end()) {\n            if (p % 2 == 0)\n                p /= 2;\n            else\n                p = 3 * p + 1;\n            chaine.push_back(p);\n        }\n\n        nombre longueur = cache[p];\n        for (const auto &c : boost::adaptors::reverse(chaine)) {\n            cache[c] = ++longueur;\n        }\n\n        if (cache[n] > max_longueur) {\n            max_longueur = cache[n];\n            max_nombre = n;\n        }\n    }\n\n    return std::to_string(max_nombre);\n}\n", "meta": {"hexsha": "2db93b8ba5b76a617e7e573f9eb94e4314aa2579", "size": 1626, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problemes/probleme0xx/probleme014.cpp", "max_stars_repo_name": "ZongoForSpeed/ProjectEuler", "max_stars_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-10-13T17:07:21.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-08T11:50:22.000Z", "max_issues_repo_path": "problemes/probleme0xx/probleme014.cpp", "max_issues_repo_name": "ZongoForSpeed/ProjectEuler", "max_issues_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "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": "problemes/probleme0xx/probleme014.cpp", "max_forks_repo_name": "ZongoForSpeed/ProjectEuler", "max_forks_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "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.679245283, "max_line_length": 114, "alphanum_fraction": 0.5621156212, "num_tokens": 450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.7372707198117023}}
{"text": "#pragma once\n\n#include <vector>\n#include <cassert>\n\n#include <iostream>\n#include <iomanip>\n\n#include <Eigen/Dense>\n\n//! \\file rkintegrator.hpp Solution for Problem 1a, implementing RkIntegrator class\n\n//! \\brief Implements a Runge-Kutta explicit solver for a given Butcher tableau for autonomous ODEs\n//! \\tparam State a type representing the space in which the solution lies, e.g. R^d, represented by e.g. Eigen::VectorXd.\ntemplate <class State>\nclass RKIntegrator {\npublic:\n    //! \\brief Constructor for the RK method.\n    //! Performs size checks and copies A and b into internal storage\n    //! \\param[in] A matrix containing coefficents of Butcher tableau, must be (strictly) lower triangular (no check)\n    //! \\param[in] b vector containing coefficients of lower part of Butcher tableau\n    RKIntegrator(const Eigen::MatrixXd & A, const Eigen::VectorXd & b): A_(A),b_(b){\n\t\tn=A_.rows();\n\t\tassert(n==b_.size() && \"size missmatch custom error\");\n\t\tassert(A_.rows()==A_.cols() && \"matrix not square custom error\");\n\t\t\n        // TODO: implement size checks and initialize internal data (DONE?)\n    }\n    \n    //! \\brief Perform the solution of the ODE\n    //! Solve an autonomous ODE y' = f(y), y(0) = y0, using a RK scheme given in the Butcher tableau provided in the\n    //! constructor. Performs N equidistant steps upto time T with initial data y0\n    //! \\tparam Function type for function implementing the rhs function. Must have State operator()(State x)\n    //! \\param[in] f function handle for rhs in y' = f(y), e.g. implemented using lambda funciton\n    //! \\param[in] T final time T\n    //! \\param[in] y0 initial data y(0) = y0 for y' = f(y)\n    //! \\param[in] N number of steps to perform. Step size is h = T / N. Steps are equidistant.\n    //! \\return vector containing all steps y^n (for each n) including initial and final value\n    template <class Function>\n    std::vector<State> solve(const Function &f, double T, const State & y0, unsigned int N) const {\n\t\tdouble h = T/N;\n\t\tstd::vector<State> y_f;\n\t\ty_f.reserve(N);\n\t\ty_f.push_back(y0);\n\t\t\n\t\tState ytemp1 = y0;\n        State ytemp2 = y0;\n        // Pointers to swap previous value\n        State * yold = &ytemp1;\n        State * ynew = &ytemp2;\n\t\t\n\t\tfor (int i =1; i<N;++i){\n\t\t\tstep(f,h,*yold,*ynew);\n\t\t\ty_f.push_back(*ynew);\n\t\t\tstd::swap(yold,ynew);\n\t\t}\n\t\treturn y_f;\n        // TODO: implement solver from 0 to T, calling function step appropriately\n    }\n    \nprivate:\n    \n    //! \\brief Perform a single step of the RK method for the solution of the autonomous ODE\n    //! Compute a single explicit RK step y^{n+1} = y_n + \\sum ... starting from value y0 and storing next value in y1\n    //! \\tparam Function type for function implementing the rhs. Must have State operator()(State x)\n    //! \\param[in] f function handle for ths f, s.t. y' = f(y)\n    //! \\param[in] h step size\n    //! \\param[in] y0 initial state \n    //! \\param[out] y1 next step y^{n+1} = y^n + ...\n    template <class Function>\n    void step(const Function &f, double h, const State & y0, State & y1) const {\n\t\ty1 = y0;\n\t\tstd::vector<State> k;\n        k.reserve(n);\n\t\tfor (int i=0;i<n;++i){\n\t\t\tState incr=y0;\n\t\t\tfor (int j=0;j<i;++j){\n\t\t\t\tincr+=h*A_(i,j)*k.at(j);\n\t\t\t}\n\t\t\tk.push_back(f(incr));\n\t\t\ty1+=h*b_(i)*k.back();\n\t\t}\n        // TODO: implement a single step of the RK method using provided Butcher scheme\n    }\n    \n    //! TODO: put here suitable internal data storage\n    const Eigen::VectorXd b_;\n    const Eigen::MatrixXd A_;\n    unsigned n;\n};\n", "meta": {"hexsha": "ba5d554258408b6e60b6955d0a90363120abd0d0", "size": 3506, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/PS12/rkintegrator_cus.hpp", "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/PS12/rkintegrator_cus.hpp", "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/PS12/rkintegrator_cus.hpp", "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": 38.5274725275, "max_line_length": 122, "alphanum_fraction": 0.6503137479, "num_tokens": 963, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.8539127548105611, "lm_q1q2_score": 0.7372610961467468}}
{"text": "#pragma once\n\n#include <vector>\n#include <cassert>\n#include <iostream>\n#include <iomanip>\n#include <Eigen/Dense>\n\n#include \"dampnewton.hpp\"\n\n//! \\file implicit_rkintegrator.hpp Solution for Problem 1, implementing implicit_RkIntegrator class\n\n//! \\brief Compute the Kronecker product $C = A \\otimes B$.\n//! \\param[in] A Matrix $m \\times n$\n//! \\param[in] B Matrix $l \\times k$\n//! \\param[out] C Kronecker product of A and B of dim $ml \\times nk$\nEigen::MatrixXd kron(const Eigen::MatrixXd & A, const Eigen::MatrixXd & B)\n{\n    Eigen::MatrixXd C(A.rows()*B.rows(), A.cols()*B.cols());\n    for(unsigned int i = 0; i < A.rows(); ++i) {\n        for(unsigned int j = 0; j < A.cols(); ++j) {\n            C.block(i*B.rows(),j*B.cols(), B.rows(), B.cols()) = A(i,j)*B;\n        }\n    }\n    return C;\n}\n\n\n//! \\brief Implements a Runge-Kutta implicit solver for a given Butcher tableau for autonomous ODEs\n\nclass implicit_RKIntegrator {\npublic:\n    //! \\brief Constructor for the implicit RK method.\n    //! Performs size checks and copies A and b into internal storage\n    //! \\param[in] A matrix containing coefficents of Butcher tableau, must be (strictly) lower triangular (no check)\n    //! \\param[in] b vector containing coefficients of lower part of Butcher tableau\n    implicit_RKIntegrator(const Eigen::MatrixXd & A, const Eigen::VectorXd & b)\n        : A(A), b(b), s(b.size()) {\n        assert( A.cols() == A.rows() && \"Matrix must be square.\");\n        assert( A.cols() == b.size() && \"Incompatible matrix/vector size.\");\n    }\n    \n    //! \\brief Perform the solution of the ODE\n    //! Solve an autonomous ODE y' = f(y), y(0) = y0, using an implicit RK scheme given in the Butcher tableau provided in the\n    //! constructor. Performs N equidistant steps upto time T with initial data y0\n    //! \\tparam Function type for function implementing the rhs function. Must have Eigen::VectorXd operator()(Eigen::VectorXd x)\n    //! \\tparam Function2 type for function implementing the Jacobian of f. Must have Eigen::MatrixXd operator()(Eigen::VectorXd x)\n    //! \\param[in] f function handle for rhs in y' = f(y), e.g. implemented using lambda funciton\n    //! \\param[in] Jf function handle for Jf, e.g. implemented using lambda funciton\n    //! \\param[in] T final time T\n    //! \\param[in] y0 initial data y(0) = y0 for y' = f(y)\n    //! \\param[in] N number of steps to perform. Step size is h = T / N. Steps are equidistant.\n    //! \\return vector containing all steps y^n (for each n) including initial and final value\n    template <class Function, class Function2>\n    std::vector<Eigen::VectorXd> solve(const Function &f, const Function2 &Jf, double T, const Eigen::VectorXd & y0, unsigned int N) const {\n        // Iniz step size\n        double h = T / N;\n        \n        // Will contain all steps, reserve memory for efficiency\n        std::vector<Eigen::VectorXd> res;\n        res.reserve(N+1);\n        \n        // Store initial data\n        res.push_back(y0);\n        \n        // Initialize some memory to store temporary values\n        Eigen::VectorXd ytemp1 = y0;\n        Eigen::VectorXd ytemp2 = y0;\n        // Pointers to swap previous value\n        Eigen::VectorXd * yold = &ytemp1;\n        Eigen::VectorXd * ynew = &ytemp2;\n        \n        // Loop over all fixed steps\n        for(unsigned int k = 0; k < N; ++k) {\n            // Compute, save and swap next step\n            step(f, Jf, h, *yold, *ynew);\n            res.push_back(*ynew);\n            std::swap(yold, ynew);\n        }\n        return res;\n    }\n    \nprivate:\n    \n    //! \\brief Perform a single step of the RK method for the solution of the autonomous ODE\n    //! Compute a single explicit RK step y^{n+1} = y_n + \\sum ... starting from value y0 and storing next value in y1\n    //! \\tparam Function type for function implementing the rhs. Must have Eigen::VectorXd operator()(Eigen::VectorXd x)\n    //! \\tparam Function2 type for function implementing the Jacobian of f. Must have Eigen::MatrixXd operator()(Eigen::VectorXd x)\n    //! \\param[in] f function handle for ths f, s.t. y' = f(y)\n    //! \\param[in] Jf function handle for Jf, e.g. implemented using lambda funciton\n    //! \\param[in] h step size\n    //! \\param[in] y0 initial Eigen::VectorXd \n    //! \\param[out] y1 next step y^{n+1} = y^n + ...\n    template <class Function, class Function2>\n    void step(const Function &f, const Function2 &Jf, double h, const Eigen::VectorXd & y0, Eigen::VectorXd & y1) const {\n        \n        int d = y0.size();\n        \n        // Handle for the function F describing the equation satisfied by the stages g\n        auto F = [y0, h, d, this, f] (Eigen::VectorXd gv) {\n            Eigen::VectorXd Fv = gv;\n            for (int j = 0; j < s; j++)\n                Fv = Fv - h*kron(A.col(j),Eigen::MatrixXd::Identity(d,d))*f(y0+gv.segment(j*d,d));\n            return Fv;\n        };\n        \n        // Handle for the Jacobian of F.\n        auto JF = [y0, h, d, Jf, this] (Eigen::VectorXd gv) {\n            Eigen::MatrixXd DF(s*d,s*d);\n            for (int j = 0; j < s; j++)\n                DF.block(0,j*d,s*d,d) = kron(A.col(j),Eigen::MatrixXd::Identity(d,d))*Jf(y0+gv.segment(j*d,d));\n            DF = Eigen::MatrixXd::Identity(s*d,s*d) - h*DF;\n            return DF;\n        };\n        \n        // Obtain stages with damped Newton method\n        Eigen::VectorXd gv = Eigen::VectorXd::Zero(s*d);\n        dampnewton(F, JF, gv);\n        \n        // Calculate y1\n        Eigen::MatrixXd K(d,s);\n        for (int j = 0; j < s; j++) K.col(j) = f(y0+gv.segment(j*d,d));\n        y1 = y0 + h*K*b;\n    }\n    \n    \n    //! Matrix A in Butcher scheme\n    const Eigen::MatrixXd A;\n    //! Vector b in Butcher scheme\n    const Eigen::VectorXd b;\n    //! Size of Butcher matrix and vector A and b\n    unsigned int s;\n};", "meta": {"hexsha": "3c37fc864e6a6432bee33e581de949d1d9e28796", "size": 5783, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/PS14/solutions_ps14/implicit_rkintegrator.hpp", "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/PS14/solutions_ps14/implicit_rkintegrator.hpp", "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/PS14/solutions_ps14/implicit_rkintegrator.hpp", "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": 43.4812030075, "max_line_length": 140, "alphanum_fraction": 0.6034929967, "num_tokens": 1538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.851952809486198, "lm_q1q2_score": 0.7371300939081955}}
{"text": "// The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt\r\n/*\r\n\r\n    This is an example illustrating the use the general purpose non-linear \r\n    least squares optimization routines from the dlib C++ Library.\r\n\r\n    This example program will demonstrate how these routines can be used for data fitting.\r\n    In particular, we will generate a set of data and then use the least squares  \r\n    routines to infer the parameters of the model which generated the data.\r\n*/\r\n\r\n\r\n#include <dlib/optimization.h>\r\n#include <iostream>\r\n#include <vector>\r\n\r\n\r\nusing namespace std;\r\nusing namespace dlib;\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\ntypedef matrix<double,2,1> input_vector;\r\ntypedef matrix<double,3,1> parameter_vector;\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\n// We will use this function to generate data.  It represents a function of 2 variables\r\n// and 3 parameters.   The least squares procedure will be used to infer the values of \r\n// the 3 parameters based on a set of input/output pairs.\r\ndouble model (\r\n    const input_vector& input,\r\n    const parameter_vector& params\r\n)\r\n{\r\n    const double p0 = params(0);\r\n    const double p1 = params(1);\r\n    const double p2 = params(2);\r\n\r\n    const double i0 = input(0);\r\n    const double i1 = input(1);\r\n\r\n    const double temp = p0*i0 + p1*i1 + p2;\r\n\r\n    return temp*temp;\r\n}\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\n// This function is the \"residual\" for a least squares problem.   It takes an input/output\r\n// pair and compares it to the output of our model and returns the amount of error.  The idea\r\n// is to find the set of parameters which makes the residual small on all the data pairs.\r\ndouble residual (\r\n    const std::pair<input_vector, double>& data,\r\n    const parameter_vector& params\r\n)\r\n{\r\n    return model(data.first, params) - data.second;\r\n}\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\n// This function is the derivative of the residual() function with respect to the parameters.\r\nparameter_vector residual_derivative (\r\n    const std::pair<input_vector, double>& data,\r\n    const parameter_vector& params\r\n)\r\n{\r\n    parameter_vector der;\r\n\r\n    const double p0 = params(0);\r\n    const double p1 = params(1);\r\n    const double p2 = params(2);\r\n\r\n    const double i0 = data.first(0);\r\n    const double i1 = data.first(1);\r\n\r\n    const double temp = p0*i0 + p1*i1 + p2;\r\n\r\n    der(0) = i0*2*temp;\r\n    der(1) = i1*2*temp;\r\n    der(2) = 2*temp;\r\n\r\n    return der;\r\n}\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    try\r\n    {\r\n        // randomly pick a set of parameters to use in this example\r\n        const parameter_vector params = 10*randm(3,1);\r\n        cout << \"params: \" << trans(params) << endl;\r\n\r\n\r\n        // Now let's generate a bunch of input/output pairs according to our model.\r\n        std::vector<std::pair<input_vector, double> > data_samples;\r\n        input_vector input;\r\n        for (int i = 0; i < 1000; ++i)\r\n        {\r\n            input = 10*randm(2,1);\r\n            const double output = model(input, params);\r\n\r\n            // save the pair\r\n            data_samples.push_back(make_pair(input, output));\r\n        }\r\n\r\n        // Before we do anything, let's make sure that our derivative function defined above matches\r\n        // the approximate derivative computed using central differences (via derivative()).  \r\n        // If this value is big then it means we probably typed the derivative function incorrectly.\r\n        cout << \"derivative error: \" << length(residual_derivative(data_samples[0], params) - \r\n                                               derivative(residual)(data_samples[0], params) ) << endl;\r\n\r\n\r\n\r\n\r\n\r\n        // Now let's use the solve_least_squares_lm() routine to figure out what the\r\n        // parameters are based on just the data_samples.\r\n        parameter_vector x;\r\n        x = 1;\r\n\r\n        cout << \"Use Levenberg-Marquardt\" << endl;\r\n        // Use the Levenberg-Marquardt method to determine the parameters which\r\n        // minimize the sum of all squared residuals.\r\n        solve_least_squares_lm(objective_delta_stop_strategy(1e-7).be_verbose(), \r\n                               residual,\r\n                               residual_derivative,\r\n                               data_samples,\r\n                               x);\r\n\r\n        // Now x contains the solution.  If everything worked it will be equal to params.\r\n        cout << \"inferred parameters: \"<< trans(x) << endl;\r\n        cout << \"solution error:      \"<< length(x - params) << endl;\r\n        cout << endl;\r\n\r\n\r\n\r\n\r\n        x = 1;\r\n        cout << \"Use Levenberg-Marquardt, approximate derivatives\" << endl;\r\n        // If we didn't create the residual_derivative function then we could\r\n        // have used this method which numerically approximates the derivatives for you.\r\n        solve_least_squares_lm(objective_delta_stop_strategy(1e-7).be_verbose(), \r\n                               residual,\r\n                               derivative(residual),\r\n                               data_samples,\r\n                               x);\r\n\r\n        // Now x contains the solution.  If everything worked it will be equal to params.\r\n        cout << \"inferred parameters: \"<< trans(x) << endl;\r\n        cout << \"solution error:      \"<< length(x - params) << endl;\r\n        cout << endl;\r\n\r\n\r\n\r\n\r\n        x = 1;\r\n        cout << \"Use Levenberg-Marquardt/quasi-newton hybrid\" << endl;\r\n        // This version of the solver uses a method which is appropriate for problems\r\n        // where the residuals don't go to zero at the solution.  So in these cases\r\n        // it may provide a better answer.\r\n        solve_least_squares(objective_delta_stop_strategy(1e-7).be_verbose(), \r\n                            residual,\r\n                            residual_derivative,\r\n                            data_samples,\r\n                            x);\r\n\r\n        // Now x contains the solution.  If everything worked it will be equal to params.\r\n        cout << \"inferred parameters: \"<< trans(x) << endl;\r\n        cout << \"solution error:      \"<< length(x - params) << endl;\r\n\r\n    }\r\n    catch (std::exception& e)\r\n    {\r\n        cout << e.what() << endl;\r\n    }\r\n}\r\n\r\n// Example output:\r\n/*\r\nparams: 8.40188 3.94383 7.83099 \r\n\r\nderivative error: 9.78267e-06\r\nUse Levenberg-Marquardt\r\niteration: 0   objective: 2.14455e+10\r\niteration: 1   objective: 1.96248e+10\r\niteration: 2   objective: 1.39172e+10\r\niteration: 3   objective: 1.57036e+09\r\niteration: 4   objective: 2.66917e+07\r\niteration: 5   objective: 4741.9\r\niteration: 6   objective: 0.000238674\r\niteration: 7   objective: 7.8815e-19\r\niteration: 8   objective: 0\r\ninferred parameters: 8.40188 3.94383 7.83099 \r\n\r\nsolution error:      0\r\n\r\nUse Levenberg-Marquardt, approximate derivatives\r\niteration: 0   objective: 2.14455e+10\r\niteration: 1   objective: 1.96248e+10\r\niteration: 2   objective: 1.39172e+10\r\niteration: 3   objective: 1.57036e+09\r\niteration: 4   objective: 2.66917e+07\r\niteration: 5   objective: 4741.87\r\niteration: 6   objective: 0.000238701\r\niteration: 7   objective: 1.0571e-18\r\niteration: 8   objective: 4.12469e-22\r\ninferred parameters: 8.40188 3.94383 7.83099 \r\n\r\nsolution error:      5.34754e-15\r\n\r\nUse Levenberg-Marquardt/quasi-newton hybrid\r\niteration: 0   objective: 2.14455e+10\r\niteration: 1   objective: 1.96248e+10\r\niteration: 2   objective: 1.3917e+10\r\niteration: 3   objective: 1.5572e+09\r\niteration: 4   objective: 2.74139e+07\r\niteration: 5   objective: 5135.98\r\niteration: 6   objective: 0.000285539\r\niteration: 7   objective: 1.15441e-18\r\niteration: 8   objective: 3.38834e-23\r\ninferred parameters: 8.40188 3.94383 7.83099 \r\n\r\nsolution error:      1.77636e-15\r\n*/\r\n", "meta": {"hexsha": "aa3cf9fcef38d7ff23ecee74ed2c5047b4a6bff0", "size": 7984, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/least_squares_ex.cpp", "max_stars_repo_name": "ckproc/dlib-19.7", "max_stars_repo_head_hexsha": "0ca40f5e85de2436e557bee9a805d3987d2d9507", "max_stars_repo_licenses": ["BSL-1.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": "examples/least_squares_ex.cpp", "max_issues_repo_name": "ckproc/dlib-19.7", "max_issues_repo_head_hexsha": "0ca40f5e85de2436e557bee9a805d3987d2d9507", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2018-02-27T15:44:25.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-28T01:26:03.000Z", "max_forks_repo_path": "examples/least_squares_ex.cpp", "max_forks_repo_name": "ckproc/dlib-19.7", "max_forks_repo_head_hexsha": "0ca40f5e85de2436e557bee9a805d3987d2d9507", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.864628821, "max_line_length": 104, "alphanum_fraction": 0.5849198397, "num_tokens": 1905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.8519527963298947, "lm_q1q2_score": 0.737130082525045}}
{"text": "#include \"vicon_odom/filter.h\"\n#include <Eigen/LU> // For matrix inverse\n\nKalmanFilter::KalmanFilter()\n{\n}\n\nKalmanFilter::KalmanFilter(const KalmanFilter::State_t &state,\n                           const KalmanFilter::ProcessCov_t &initial_cov,\n                           const KalmanFilter::ProcessCov_t &process_noise,\n                           const KalmanFilter::MeasurementCov_t &meas_noise)\n{\n  x = state;\n  P = initial_cov;\n  Q = process_noise;\n  R = meas_noise;\n}\n\nvoid KalmanFilter::initialize(const State_t &state,\n                              const ProcessCov_t &initial_cov,\n                              const ProcessCov_t &process_noise,\n                              const MeasurementCov_t &meas_noise)\n{\n  x = state;\n  P = initial_cov;\n  Q = process_noise;\n  R = meas_noise;\n}\n\nvoid KalmanFilter::processUpdate(double dt)\n{\n  ProcessCov_t A = ProcessCov_t::Identity();\n  A.topRightCorner<3,3>() = Eigen::Vector3d(dt, dt, dt).asDiagonal();\n\n  x = A*x;\n  P = A*P*A.transpose() + Q;\n}\n\nvoid KalmanFilter::measurementUpdate(const Measurement_t &meas, double dt)\n{\n  Eigen::Matrix<double, n_meas, n_states> H;\n  H.setZero();\n  H(0, 0) = 1;\n  H(1, 1) = 1;\n  H(2, 2) = 1;\n\n  const Eigen::Matrix<double, n_states, n_meas> K = P * H.transpose() *\n      (H*P*H.transpose() + R).inverse();\n  const Measurement_t inno = meas - H*x;\n  x += K*inno;\n  P = (ProcessCov_t::Identity() - K*H) * P;\n}\n\nvoid KalmanFilter::setProcessNoise(const ProcessCov_t &process_noise)\n{\n  Q = process_noise;\n}\n\nvoid KalmanFilter::setMeasurementNoise(const MeasurementCov_t &meas_noise)\n{\n  R = meas_noise;\n}\n\nconst KalmanFilter::State_t &KalmanFilter::getState(void)\n{\n  return x;\n}\n\nconst KalmanFilter::ProcessCov_t &KalmanFilter::getProcessNoise(void)\n{\n  return P;\n}\n", "meta": {"hexsha": "1d20b97feda3289abcfbfe30a2eb87af4cf88e7a", "size": 1755, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "vicon_odom/src/filter.cpp", "max_stars_repo_name": "zheng-rong/vicon_mocap", "max_stars_repo_head_hexsha": "43baabf440cfebc00dc48532c939b46683ffebe3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-07-16T19:09:01.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-16T19:09:01.000Z", "max_issues_repo_path": "vicon_odom/src/filter.cpp", "max_issues_repo_name": "zheng-rong/vicon_mocap", "max_issues_repo_head_hexsha": "43baabf440cfebc00dc48532c939b46683ffebe3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-08-21T17:25:23.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-21T17:25:23.000Z", "max_forks_repo_path": "vicon_odom/src/filter.cpp", "max_forks_repo_name": "zheng-rong/vicon_mocap", "max_forks_repo_head_hexsha": "43baabf440cfebc00dc48532c939b46683ffebe3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-06-06T02:04:15.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-28T10:56:42.000Z", "avg_line_length": 24.0410958904, "max_line_length": 76, "alphanum_fraction": 0.6393162393, "num_tokens": 498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947117065459, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.7370891610758932}}
{"text": "#include \"Math/math_3dh.hpp\"\n#include <Eigen/Dense>\nusing Eigen::MatrixXf;\nusing Eigen::VectorXf;\n\nnamespace math_3dh {\nfloat multiquadric_rbf(float r) {\n  float R = 1.0f; // smoothing parameter\n  float e = 3.0f; // shape parameter\n  return -sqrtf(R + powf(e * r, 2));\n}\nfloat rbf_interp(glm::vec2 point, std::vector<glm::vec3> data,\n                 float (*rbf)(float)) {\n  // Construct A\n  size_t n = data.size();\n  MatrixXf A(n, n);\n  for (size_t j = 0; j < n; j++) {\n    for (size_t i = 0; i < n; i++) {\n      if (i == j) {\n        A(i, j) = 0.0f;\n      } else {\n        A(i, j) = rbf(glm::length(glm::vec2(data[i]) - glm::vec2(data[j])));\n      }\n    }\n  }\n  // Construct z\n  VectorXf z(n);\n  for (size_t i = 0; i < n; i++) {\n    z(i) = data[i].z;\n  }\n  // Construct p\n  VectorXf p(n);\n  for (size_t i = 0; i < n; i++) {\n    p(i) = rbf(glm::length(point - glm::vec2(data[i])));\n  }\n  // elevation(point) = p*(A^(-1)z) = p*w\n  VectorXf w = A.partialPivLu().solve(z);\n  return p.dot(w);\n}\n} // namespace math_3dh\n", "meta": {"hexsha": "c86b18b1747de30400dfada0e9b3b2a141a0b1b0", "size": 1017, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Math/math_3dh.cpp", "max_stars_repo_name": "barne856/3DHydraulics", "max_stars_repo_head_hexsha": "79972540819a43eed6d96fcab3e1759a2423c339", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-07-06T08:06:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-19T06:51:58.000Z", "max_issues_repo_path": "src/Math/math_3dh.cpp", "max_issues_repo_name": "barne856/3DHydraulics", "max_issues_repo_head_hexsha": "79972540819a43eed6d96fcab3e1759a2423c339", "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/math_3dh.cpp", "max_forks_repo_name": "barne856/3DHydraulics", "max_forks_repo_head_hexsha": "79972540819a43eed6d96fcab3e1759a2423c339", "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.8048780488, "max_line_length": 76, "alphanum_fraction": 0.5388397247, "num_tokens": 375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545377452443, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.7370004003444474}}
{"text": "#include <cmath>\n#include <iostream>\n#include <fstream>\n#include <OpenEXR/ImathVec.h>\n#include <boost/format.hpp>\n\n/*!\n * see http://cubic.org/docs/hermite.htm\n *\n */\nnamespace interpolate\n{\n\ttemplate <typename T> void hermite(const Imath::Vec3<T>& P1,\n\t\t\t\t\t\t\t\t\t   const Imath::Vec3<T>& T1,\n\t\t\t\t\t\t\t\t\t   const Imath::Vec3<T>& P2,\n\t\t\t\t\t\t\t\t\t   const Imath::Vec3<T>& T2,\n\t\t\t\t\t\t\t\t\t   T s,\n\t\t\t\t\t\t\t\t\t   Imath::Vec3<T>& P)\n\t{\n\t\tT h1 =  2.0*std::pow(s,3.0) - 3.0*std::pow(s,2.0) + 1.0; // calculate basis function 1\n\t\tT h2 = -2.0*std::pow(s,3.0) + 3.0*std::pow(s,2.0)      ; // calculate basis function 2\n\t\tT h3 =  std::pow(s,3.0)     - 2.0*std::pow(s,2.0) + s  ; // calculate basis function 3\n\t\tT h4 =  std::pow(s,3.0)     - std::pow(s,2.0)          ; // calculate basis function 4\n\n\t\tP = h1*P1 + // multiply and sum all funtions\n\t\t\th2*P2 + // together to build the interpolated\n\t\t\th3*T1 + // point along the curve.\n\t\t\th4*T2;\n\t}\n}\n\n// == Emacs ================\n// -------------------------\n// Local variables:\n// tab-width: 4\n// indent-tabs-mode: t\n// c-basic-offset: 4\n// end:\n//\n// == vi ===================\n// -------------------------\n// Format block\n// ex:ts=4:sw=4:expandtab\n// -------------------------\n", "meta": {"hexsha": "c5aec3b71d4da4c65dfb710153c419a2c9e5578f", "size": 1202, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/interpolate.hpp", "max_stars_repo_name": "nyue/SegmentedInterpolativeMotionBlurAlembic", "max_stars_repo_head_hexsha": "1f02ff5516b6e114410b5977885133bb4b5bb490", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-28T23:33:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-28T23:33:00.000Z", "max_issues_repo_path": "lib/interpolate.hpp", "max_issues_repo_name": "nyue/SegmentedInterpolativeMotionBlurAlembic", "max_issues_repo_head_hexsha": "1f02ff5516b6e114410b5977885133bb4b5bb490", "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": "lib/interpolate.hpp", "max_forks_repo_name": "nyue/SegmentedInterpolativeMotionBlurAlembic", "max_forks_repo_head_hexsha": "1f02ff5516b6e114410b5977885133bb4b5bb490", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-10T11:49:02.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-10T11:49:02.000Z", "avg_line_length": 26.7111111111, "max_line_length": 88, "alphanum_fraction": 0.5083194676, "num_tokens": 407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541626630935, "lm_q2_score": 0.782662489091802, "lm_q1q2_score": 0.7369973908135534}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n\r\n// Copyright (c) 2007-2011 Barend Gehrels, Amsterdam, the Netherlands.\r\n// Copyright (c) 2008-2011 Bruno Lalande, Paris, France.\r\n// Copyright (c) 2009-2011 Mateusz Loskot, London, UK.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n//\r\n// Custom Triangle Example\r\n\r\n#include <iostream>\r\n\r\n#include <boost/array.hpp>\r\n\r\n#include <boost/geometry/algorithms/area.hpp>\r\n#include <boost/geometry/algorithms/centroid.hpp>\r\n#include <boost/geometry/geometries/point_xy.hpp>\r\n#include <boost/geometry/geometries/register/ring.hpp>\r\n#include <boost/geometry/strategies/strategies.hpp>\r\n#include <boost/geometry/util/write_dsv.hpp>\r\n\r\n\r\nstruct triangle : public boost::array<boost::geometry::model::d2::point_xy<double>, 4>\r\n{\r\n    inline void close()\r\n    {\r\n        (*this)[3] = (*this)[0];\r\n    }\r\n};\r\n\r\n\r\n// Register triangle as a ring\r\nBOOST_GEOMETRY_REGISTER_RING(triangle)\r\n\r\n\r\n// Specializations of algorithms, where useful. If not specialized the default ones\r\n// (for linear rings) will be used for triangle. Which is OK as long as the triangle\r\n// is closed, that means, has 4 points (the last one being the first).\r\nnamespace boost { namespace geometry {\r\n\r\ntemplate<>\r\ninline double area<triangle>(const triangle& t)\r\n{\r\n    /*         C\r\n              / \\\r\n             /   \\\r\n            A-----B\r\n\r\n           ((Bx - Ax) * (Cy - Ay)) - ((Cx - Ax) * (By - Ay))\r\n           -------------------------------------------------\r\n                                   2\r\n    */\r\n\r\n    return 0.5 * ((t[1].x() - t[0].x()) * (t[2].y() - t[0].y())\r\n                - (t[2].x() - t[0].x()) * (t[1].y() - t[0].y()));\r\n}\r\n\r\n}} // namespace boost::geometry\r\n\r\nint main()\r\n{\r\n    triangle t;\r\n\r\n    t[0].x(0);\r\n    t[0].y(0);\r\n    t[1].x(5);\r\n    t[1].y(0);\r\n    t[2].x(2.5);\r\n    t[2].y(2.5);\r\n\r\n    t.close();\r\n\r\n    std::cout << \"Triangle: \" << boost::geometry::dsv(t) << std::endl;\r\n    std::cout << \"Area: \" << boost::geometry::area(t) << std::endl;\r\n\r\n    boost::geometry::model::d2::point_xy<double> c;\r\n    boost::geometry::centroid(t, c);\r\n    std::cout << \"Centroid: \" << boost::geometry::dsv(c) << std::endl;\r\n\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "0f0657dd61a39beed1ef8c6f3ee25d26019dd0f1", "size": 2331, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/example/c04_a_custom_triangle_example.cpp", "max_stars_repo_name": "Ron2014/boost_1_48_0", "max_stars_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "max_stars_repo_licenses": ["BSL-1.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/geometry/example/c04_a_custom_triangle_example.cpp", "max_issues_repo_name": "Ron2014/boost_1_48_0", "max_issues_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "max_issues_repo_licenses": ["BSL-1.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/geometry/example/c04_a_custom_triangle_example.cpp", "max_forks_repo_name": "Ron2014/boost_1_48_0", "max_forks_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.75, "max_line_length": 87, "alphanum_fraction": 0.5684255684, "num_tokens": 645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357460591569, "lm_q2_score": 0.8499711794579722, "lm_q1q2_score": 0.7369553957101245}}
{"text": "/*This is a simple test from the official boost documentation to assess whether boost libraries have\n * been installed correctly\n */\n\n#include <boost/math/differentiation/autodiff.hpp>\n//#include <boost/multiprecision/cpp>\n#include <boost/math/constants/constants.hpp>\n#include <iostream>\n#include <vector>\n#include <tuple>\n#include <random>\n#include \"ceinms2/testingUtilities.h\"\n#include \"ceinms2/Lloyd2003Muscle.h\"\n\nnamespace df = boost::math::differentiation;\n\ntemplate<typename T>\nT fourth_power(T const &x) {\n    T x4 = x * x;// retval in operator*() uses x4's memory via NRVO.\n    x4 *= x4;// No copies of x4 are made within operator*=() even when squaring.\n    return x4;// x4 uses y's memory in main() via NRVO.\n}\n\nbool test1() {\n\n    constexpr unsigned Order = 5;// Highest order derivative to be calculated.\n    auto const x = df::make_fvar<double, Order>(2.0);// Find derivatives at x=2.\n    auto const y = fourth_power(x);\n    const std::vector<double> expected{ 16., 32., 48., 48., 24., 0. };\n    bool failed = false;\n    for (unsigned i = 0; i <= Order; ++i) {\n        std::cout << \"y.derivative(\" << i << \") = \" << y.derivative(i) << std::endl;\n        failed |= (y.derivative(i) != expected.at(i));\n    }\n    return failed;\n}\n\n\n\ntemplate<typename W, typename X, typename Y, typename Z>\nauto f(const W &w, const X &x, const Y &y, const Z &z) {\n    using namespace std;\n    return exp(w * sin(x * log(y) / z) + sqrt(w * z / (x * y))) + w * w / tan(z);\n}\n\n\n/*\nbool test2() {\n    using float50 = boost::multiprecision::cpp_bin_float_50;\n\n    constexpr unsigned Nw = 3;// Max order of derivative to calculate for w\n    constexpr unsigned Nx = 2;// Max order of derivative to calculate for x\n    constexpr unsigned Ny = 4;// Max order of derivative to calculate for y\n    constexpr unsigned Nz = 3;// Max order of derivative to calculate for z\n    // Declare 4 independent variables together into a std::tuple.\n    auto const variables = make_ftuple<float50, Nw, Nx, Ny, Nz>(11, 12, 13, 14);\n    auto const &w = std::get<0>(variables);// Up to Nw derivatives at w=11\n    auto const &x = std::get<1>(variables);// Up to Nx derivatives at x=12\n    auto const &y = std::get<2>(variables);// Up to Ny derivatives at y=13\n    auto const &z = std::get<3>(variables);// Up to Nz derivatives at z=14\n    auto const v = f(w, x, y, z);\n    // Calculated from Mathematica symbolic differentiation.\n    float50 const answer(\"1976.319600747797717779881875290418720908121189218755\");\n    std::cout << std::setprecision(std::numeric_limits<float50>::digits10)\n              << \"mathematica   : \" << answer << '\\n'\n              << \"autodiff      : \" << v.derivative(Nw, Nx, Ny, Nz) << '\\n'\n              << std::setprecision(3)\n              << \"relative error: \" << (v.derivative(Nw, Nx, Ny, Nz) / answer - 1) << '\\n';\n    return 0;\n}\n*/\n\ntemplate<typename X, typename Y>\nauto test_fun(const X& x, const Y& y) {\n    auto val = x *x *x *x + 2 * y *y;\n    return val;\n}\n\nbool test3() {\n    constexpr unsigned Order = 1;// Highest order derivative to be calculated.\n    auto const variables = df::make_ftuple<double, 2, 2>(2, 2);\n    auto const &x = std::get<0>(variables);\n    auto const &y = std::get<1>(variables);\n    auto const z = test_fun(x, y);\n    std::cout << z.at(0, 0) << std::endl;\n    std::cout << z.at(1, 0) << std::endl;\n    std::cout << z.at(0, 1) << std::endl;\n\n    bool failed = false;\n    failed |= (z.at(0, 0) != 24);\n    failed |= (z.at(1, 0) != 32);\n    failed |= (z.at(0, 1) != 8);\n\n    return failed;\n\n}\n\nbool test4() {\n    const size_t N = 1000;\n    const double dt = 0.1;\n    const double w = boost::math::double_constants::two_pi * 3.;\n    std::vector<double> x, y;\n    for (size_t i{ 0 }; i < N; ++i) {\n        const double t{ i * dt };\n        x.push_back(t);\n        y.push_back(std::cos(w * t));\n    }\n\n    // Get derivative through object-provided method\n    ceinms::CubicSpline spline(x, y);\n\n    bool failed = false;\n    for (size_t i{ 0 }; i < N; ++i) {\n        const double t{ i * dt * 0.9 };\n        auto yp = spline.getFirstDerivative(t);\n        // get derivative using autodiff\n        auto const xx = df::make_fvar<double, 1>(t);\n        auto yy = spline.get(xx);\n        failed |= (yy.derivative(1) != yp);\n    }\n    return failed;\n}\n/*\nbool test5() {\n    using boost::math::epsilon_difference;\n\n    auto fun([](auto x) {\n        if (x > 0)\n            return x * x;\n        else\n            return x * x * x;\n        });\n\n    auto dfun([](auto x) {\n        if (x > 0)\n            return 2*x;\n        else\n            return 3 * x * x;\n    });\n\n    // Get derivative through object-provided method\n\n    std::random_device rd;// Will be used to obtain a seed for the random number engine\n    std::mt19937 gen(rd());// Standard mersenne_twister_engine seeded with rd()\n    std::uniform_real_distribution<> dis(-10.0, 20.0);\n    bool failed = false;\n    for (int n = 0; n < 100; ++n) {\n        auto const val = dis(gen);\n        auto const x = df::make_fvar<double, 1>(val);\n        //check the value of the two derivatives is the same, within 2 epsilons \n        bool isEqual = epsilon_difference(fun(x).derivative(1),dfun(val)) < 2.0;\n        std::cout << fun(x).derivative(1) << \"=?\" << dfun(val);\n        if (isEqual) \n            std::cout << \" True\";\n        else\n            std::cout << \" False\";\n        std::cout << std::endl;\n        failed |= !isEqual;\n    }\n    return failed;\n}\n*/\n\nint main() {\n    bool failed = false;\n    failed |= ceinms::runTest(&test1, \"Fifith order derivative\");\n   // failed |= test2();\n    failed |= ceinms::runTest(&test3, \"Derivative extraction\");\n    failed |= ceinms::runTest(&test4, \"Cubic Spine and autodiff\");\n  //  failed |= test5();\n\n    return failed;\n}\n\n\n", "meta": {"hexsha": "634ed5c27c66f6a321da7ac9fa4e9794e3673ef2", "size": 5738, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/testBoostAutodiff.cpp", "max_stars_repo_name": "RealTimeBiomechanics/ceinms2", "max_stars_repo_head_hexsha": "1074afabc40249d374778f320e43ee4bc4e77f0b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-05-07T07:12:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-07T10:25:03.000Z", "max_issues_repo_path": "test/testBoostAutodiff.cpp", "max_issues_repo_name": "RealTimeBiomechanics/ceinms2", "max_issues_repo_head_hexsha": "1074afabc40249d374778f320e43ee4bc4e77f0b", "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": "test/testBoostAutodiff.cpp", "max_forks_repo_name": "RealTimeBiomechanics/ceinms2", "max_forks_repo_head_hexsha": "1074afabc40249d374778f320e43ee4bc4e77f0b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-05-15T00:48:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-01T05:00:13.000Z", "avg_line_length": 32.6022727273, "max_line_length": 100, "alphanum_fraction": 0.5921924015, "num_tokens": 1671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391664210673, "lm_q2_score": 0.7981867825403177, "lm_q1q2_score": 0.7367576624043286}}
{"text": "#include <iostream>\n#include <fstream>\n#include <vector>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\nusing Matrix3d = Eigen::Matrix3d;\nusing Vector3d = Eigen::Vector3d;\n\nMatrix3d euler_to_mat( const double roll,\n                        const double pitch,\n                        const double yaw )\n{\n    Eigen::AngleAxisd rollAngle(roll, Eigen::Vector3d::UnitX());\n    Eigen::AngleAxisd pitchAngle(pitch, Eigen::Vector3d::UnitY());\n    Eigen::AngleAxisd yawAngle(yaw, Eigen::Vector3d::UnitZ());\n\n    Eigen::Quaterniond q = yawAngle * pitchAngle * rollAngle;\n    return q.matrix();\n}\n\nMatrix3d qua_integration(const Matrix3d &R0, const std::vector<Vector3d> &w_vec) \n{\n    std::cout << \"============= qua_integration =============\" << std::endl;\n\n    Eigen::Quaterniond q(R0);\n\n    for(int i = 0; i < w_vec.size(); ++i) {\n        Vector3d omega_measured_ = w_vec[i];\n        constexpr double DT = 1.0;\n\n        Eigen::Quaterniond q_new;\n        Eigen::Quaterniond q_add; \n\n        // Method 1 \n        // Eigen::Quaterniond q_omega;\n        // q_omega.w() = 0;\n        // q_omega.vec() = omega_measured_ * DT * 0.5;\n        // q_add = q_omega * q;\n        // q_new.w() = q.w() + q_add.w();\n        // q_new.vec() = q.vec() + q_add.vec();\n\n        // Method 2\n        Eigen::Vector3d rotated = omega_measured_ * DT;\n        double angle = rotated.norm();\n        Eigen::Vector3d axis = rotated.normalized();\n        q_add = Eigen::AngleAxisd(angle, axis);\n        q_new = q * q_add;\n\n        q = q_new;\n\n        std::cout << \"i:\" << i << \" w:\" << omega_measured_.transpose() << \"\\nR:\" << q.matrix() << std::endl;\n    }\n    return q.matrix();\n}\n\n\ninline Eigen::Matrix3d skewm(const Eigen::Vector3d& v)\n{\n    double x = v(0);\n    double y = v(1);\n    double z = v(2);\n\n    Eigen::Matrix3d S;\n    S << 0.0, -z, y, z, 0.0, -x, -y, x, 0.0;\n\n    return S;\n}\n\ninline Eigen::Matrix3d exp_hat_so3(const Eigen::Vector3d& v)\n{\n    const double theta = v.norm();\n    if (theta < 1e-10)\n    {\n        return Matrix3d::Identity();\n    }\n    const Vector3d w = v / theta;\n    Matrix3d W = skewm(w);\n    // NOTE(Ning): W*W = -I + w * w^T\n    // NOTE(Ning): Rodrigues rotation formula\n    Matrix3d SO3 = Matrix3d::Identity() + std::sin(theta) * W + (1 - std::cos(theta)) * W * W;\n    return SO3;\n}\n\nMatrix3d mat_integration(const Matrix3d &R0, const std::vector<Vector3d> &w_vec) {\n    std::cout << \"============= mat_integration =============\" << std::endl;\n    Eigen::Matrix3d R = R0;\n    for(int i = 0; i < w_vec.size(); ++i) {\n        Vector3d w = w_vec[i];\n        R = R * exp_hat_so3(w);\n        std::cout << \"i:\" << i << \" w:\" << w.transpose() << \"\\nR:\" << R << std::endl;\n    }\n\n    return R;\n}\n\nvoid test1()\n{\n    std::cout << \"test1\" << std::endl;\n    std::vector<Eigen::Vector3d> w_vec = \n        {\n            {0,0,0},\n            {1,0,0},\n            {0,1,0},\n            {0,0,1},\n            {1,1,1},\n            {-1,-2,-3}\n        };\n\n    Matrix3d R0 = euler_to_mat(0.1,0.2,-0.1);\n\n    mat_integration(R0, w_vec);\n\n    qua_integration(R0, w_vec);\n    \n    std::cout << std::endl;\n}\n\nvoid test2()\n{\n    std::cout << \"test2\" << std::endl;\n\n    std::vector<Eigen::Vector3d> w_vec = \n    {\n        {0,0,0},\n        {0,0,0}\n    };\n\n    Matrix3d R0 = euler_to_mat(0.0,0.0,0.0);\n\n    mat_integration(R0, w_vec);\n\n    qua_integration(R0, w_vec);\n    \n    std::cout << std::endl;\n}\n\n\nvoid test3()\n{\n    std::cout << \"test3\" << std::endl;\n\n    std::vector<Eigen::Vector3d> w_vec = \n    {\n        {0.01,0.01,0.01},\n        {0.01,0.01,0.01},\n        {0.01,0.01,0.01},\n        {0.01,0.01,0.01}\n    };\n\n    Matrix3d R0 = euler_to_mat(0.0,0.0,0.0);\n\n    mat_integration(R0, w_vec);\n\n    qua_integration(R0, w_vec);\n\n    std::cout << std::endl;\n}\n\nint main() {\n    test1();\n    test2();\n    test3();\n}", "meta": {"hexsha": "f4c4a8aab357b4c7d6eab4df4f92d29d524ec6eb", "size": 3788, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "experimental/tests/imu_integration.cpp", "max_stars_repo_name": "yimuw/expriment", "max_stars_repo_head_hexsha": "5c4185d969556e7ec007aceaf0eb82f7e79f8abb", "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": "experimental/tests/imu_integration.cpp", "max_issues_repo_name": "yimuw/expriment", "max_issues_repo_head_hexsha": "5c4185d969556e7ec007aceaf0eb82f7e79f8abb", "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": "experimental/tests/imu_integration.cpp", "max_forks_repo_name": "yimuw/expriment", "max_forks_repo_head_hexsha": "5c4185d969556e7ec007aceaf0eb82f7e79f8abb", "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.9575757576, "max_line_length": 108, "alphanum_fraction": 0.5242872228, "num_tokens": 1225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026573249612, "lm_q2_score": 0.8031737892899222, "lm_q1q2_score": 0.7367534512094042}}
{"text": "#include \"writer.hpp\"\n#include <Eigen/Core>\n#include <algorithm>\n#include <cmath>\n#include <functional>\n#include <iostream>\n#include <stdexcept>\n#include <tuple>\n#include <utility>\n\n// Simpson integrator\ninline double integrate(std::function<double(double)> f, double a, double b) {\n\treturn (b-a) / 6 * (f(a) + 4 * f((a + b) / 2) + f(b));\n}\n\n//----------------GodunovBegin----------------\n/// @param[in] N the number of grid points, NOT INCLUDING BOUNDARY POINTS\n/// @param[in] T the final time at which to compute the solution\n/// @param[in] f flux function, as function\n/// @param[in] df derivative of flux function, as function\n/// @param[in] u0 the initial conditions, as function\n/// @param[out] u solution at time T\n/// @param[out] X Grid Points\nvoid Godunov(int N, double T, const std::function<double(double)> &f, const std::function<double(double)> &df, const std::function<double(double)> &u0, Eigen::VectorXd &u, Eigen::VectorXd &X) {\n\t// Create space discretization for interval [-2,2]\n\t// (write your solution here)\n\tu.resize(N + 1);\n\tX.setLinSpaced(N + 2, -2, 2);\n\tdouble dx = (X.maxCoeff() - X.minCoeff()) / (N + 1);\n\n\t// The Godunov flux\n\t// (write your solution here)\n\t// $F_{j + \\frac{1}{2}}^n = \\max(f(max(U_j^n, \\omega)), f(min(U_{j + 1}^n, \\omega)))$\n\t// where $\\omega$ minimum of $f$\n\tauto F = [&f](double a, double b) -> double {\n\t\tusing std::max;\n\t\tusing std::min;\n\t\t// TODO: find minimum of f\n\t\tdouble omega{0};\n\t\treturn max(f(max(a, omega)), f(min(b, omega)));\n\t};\n\n\t//setup vectors to store (old) solution\n\t// (write your solution here)\n\tfor (int i = 0; i < N + 1; ++i) {\n\t\tu(i) = 1 / dx * integrate(u0, X(i), X(i + 1));\n\t}\n\tEigen::VectorXd u_old{u};\n\n\t// choose dt such that if obeys CFL condition\n\t// (write your solution here)\n\tdouble t = 0;\n\n\t//Please uncomment the next line:\n\twhile (t < T) {\n\t\t// Update dT according to current CFL condition\n\t\t// (write your solution here)\n\t\t// $\\increment t = \\frac{\\increment x}{2 \\max_j \\abs{f'(U_j^n)}$\n\t\tdouble dt = std::min(T - t, dx / (2 * u.unaryExpr([&df](double x) -> double {\n\t\t\t                       return std::abs(df(x));\n\t\t\t                     }).maxCoeff()));\n\n\t\t// Update current time\n\t\t// (write your solution here)\n\t\tt += dt;\n\n\t\t// Update the internal values of u\n\t\t// (write your solution here)\n\t\t// $U_j^{n + 1} = U_j^n - \\frac{\\increment t}{\\increment x} \\left( F_{j + \\frac{1}{2}}^n - F_{j - \\frac{1}{2}}^n \\right)$\n\t\tstd::swap(u, u_old);\n\t\tfor (int i = 1; i < N; ++i) {\n\t\t\tu(i) = u_old(i) - dt / dx * (F(u_old(i), u_old(i + 1)) - F(u_old(i - 1), u_old(i)));\n\t\t}\n\n\t\t// Update boundary with non-reflecting Neumann bc\n\t\t// (write your solution here)\n\t\tu(0) = u(1);\n\t\tu(N) = u(N - 1);\n\n\t\t//Please uncomment the next line:\n\t}\n}\n//----------------GodunovEnd----------------\n\n//----------------convGodBegin----------------\n//! Computes error for a range of cell lengths and stores them to error vectors\n/// @param[in] T the final time at which to compute the solution\n/// @param[in] f flux function, as function\n/// @param[in] df derivative of flux function, as function\n/// @param[in] u0 the initial conditions, as function\n/// @param[in] uex exact solution\n/// @param[in] baseName string containing name to save the computed errors and resolution\nvoid GodunovConvergence(double T, const std::function<double(double)> &f, const std::function<double(double)> &df, const std::function<double(double)> &u0, const std::function<double(double, double)> &uex, const std::string &baseName) {\n\tstd::vector<int>    resolutions = {100, 200, 400, 800, 1600};\n\tstd::vector<double> L1_errors;\n\tstd::vector<double> Linf_errors;\n\n\tfor (auto &N : resolutions) {\n\t\t// find approximate solution using Godunov scheme\n\t\t// (write your solution here)\n\t\tEigen::VectorXd u;\n\t\tEigen::VectorXd X;\n\t\tGodunov(N, T, f, df, u0, u, X);\n\n\t\t// compute errors and push them bach to the corresponfing error vectors\n\t\t// (write your solution here)\n\t\tdouble L1_error{0};\n\t\tdouble Linf_error{0};\n\t\tfor (int i = 0; i < N + 1; ++i) {\n\t\t\tdouble dx = X(i + 1) - X(i);\n\t\t\tdouble error = std::abs(u(i) - 1.0 / dx * integrate([&](double x) -> double {return uex(x, T);}, X(i), X(i + 1)));\n\t\t\tL1_error += dx * error;\n\t\t\tLinf_error = std::max(Linf_error, error);\n\t\t}\n\t\tL1_errors.emplace_back(L1_error);\n\t\tLinf_errors.emplace_back(Linf_error);\n\t}\n\n\twriteToFile(baseName + \"_L1errors_Godunov.txt\", L1_errors);\n\twriteToFile(baseName + \"_Linferrors_Godunov.txt\", Linf_errors);\n\twriteToFile(baseName + \"_resolutions.txt\", resolutions);\n}\n//----------------convGodEnd----------------\n\n//----------------LFBegin----------------\n/// @param[in] N the number of grid points, NOT INCLUDING BOUNDARY POINTS\n/// @param[in] T the final time at which to compute the solution\n/// @param[in] f flux function, as function\n/// @param[in] df derivative of flux function, as function\n/// @param[in] u0 the initial conditions, as function\n/// @param[out] u solution at time T\n/// @param[out] X Grid Points\nvoid LaxFriedrichs(int N, double T, const std::function<double(double)> &f, const std::function<double(double)> &df, const std::function<double(double)> &u0, Eigen::VectorXd &u, Eigen::VectorXd &X) {\n\tstd::ignore = df;\n\t// Create space discretization for interval [-2,2]\n\t// (write your solution here)\n\tdouble CFL = 0.5;\n\tX.setLinSpaced(N + 2, -2, 2);\n\tdouble dx  = (X.maxCoeff() - X.minCoeff()) / (N + 1);\n\n\t//setup vectors to store solution\n\t// (write your solution here)\n\tu.resize(N + 1);\n\tfor (int i = 0; i < N + 1; ++i) {\n\t\tu(i) = 1 / dx * integrate(u0, X(i), X(i + 1));\n\t}\n\tEigen::VectorXd u_old{u};\n\n\t// choose dt such that if obeys CFL condition\n\t// (write your solution here)\n\tdouble t  = 0;\n\tdouble dt;\n\n\t// The Lax-Friedrichs flux\n\t// (write your solution here)\n\tauto F = [&](double a, double b) -> double {\n\t\treturn (f(a) + f(b)) / 2 - dx / (2 * dt) * (b - a);\n\t};\n\n\t//Please uncomment the next line:\n\twhile (t < T) {\n\t\t// Update dT according to current CFL condition\n\t\t// (write your solution here)\n\t\tdt = std::min(T - t, CFL * dx / u.unaryExpr([&df](double x) -> double {\n\t\t\t                       return std::abs(df(x));\n\t\t\t                     }).maxCoeff());\n\n\t\t// Update current time\n\t\t// (write your solution here)\n\t\tt += dt;\n\n\t\t// Update the internal values of u\n\t\t// (write your solution here)\n\t\tstd::swap(u, u_old);\n\t\tfor (int i = 1; i < N; ++i) {\n\t\t\tu(i) = u_old(i) - dt / dx * (F(u_old(i), u_old(i + 1)) - F(u_old(i - 1), u_old(i)));\n\t\t}\n\n\t\t// Update boundary with non-reflecting Neumann bc\n\t\t// (write your solution here)\n\t\tu(0) = u(1);\n\t\tu(N) = u(N - 1);\n\n\t\t//Please uncomment the next line:\n\t}\n}\n//----------------LFEnd----------------\n\n//----------------convLFBegin----------------\n//! Computes error for a range of cell lengths and stores them to error vectors\n/// @param[in] T the final time at which to compute the solution\n/// @param[in] f flux function, as function\n/// @param[in] df derivative of flux function, as function\n/// @param[in] u0 the initial conditions, as function\n/// @param[in] uex exact solution\n/// @param[in] baseName string containing name to save the computed errors and resolution\nvoid LFConvergence(double T, const std::function<double(double)> &f, const std::function<double(double)> &df, const std::function<double(double)> &u0, const std::function<double(double, double)> &uex, const std::string &baseName) {\n\tstd::vector<int>    resolutions = {100, 200, 400, 800, 1600};\n\tstd::vector<double> L1_errors;\n\tstd::vector<double> Linf_errors;\n\n\tfor (auto &N : resolutions) {\n\t\t// find approximate solution using Lax-Friedrichs scheme\n\t\t// (write your solution here)\n\t\tEigen::VectorXd u;\n\t\tEigen::VectorXd X;\n\t\tLaxFriedrichs(N, T, f, df, u0, u, X);\n\n\t\t// compute errors and push them bach to the corresponfing error vectors\n\t\t// (write your solution here)\n\t\tdouble L1_error{0};\n\t\tdouble Linf_error{0};\n\t\tfor (int i = 0; i < N + 1; ++i) {\n\t\t\tdouble dx = X(i + 1) - X(i);\n\t\t\tdouble error = std::abs(u(i) - 1.0 / dx * integrate([&](double x) -> double {return uex(x, T);}, X(i), X(i + 1)));\n\t\t\tL1_error += dx * error;\n\t\t\tLinf_error = std::max(Linf_error, error);\n\t\t}\n\t\tL1_errors.emplace_back(L1_error);\n\t\tLinf_errors.emplace_back(Linf_error);\n\t}\n\n\twriteToFile(baseName + \"_L1errors_LF.txt\", L1_errors);\n\twriteToFile(baseName + \"_Linferrors_LF.txt\", Linf_errors);\n\twriteToFile(baseName + \"_resolutions.txt\", resolutions);\n}\n//----------------convLFEnd----------------\n\n/* Fluxes for Burgers' equation */\ndouble fBurgers(double u) {\n\treturn std::pow(u, 2) / 2.;\n}\n\ndouble dfBurgers(double u) {\n\treturn u;\n}\n\n/* Initial data and exact solutions for Burgers' equation  */\n// i)\ndouble U0i(double x) {\n\tif (x < 0.)\n\t\treturn 1.;\n\telse\n\t\treturn 0.;\n}\ndouble Uexi(double x, double t) {\n\tif (x < 0.5 * t)\n\t\treturn 1.;\n\telse\n\t\treturn 0.;\n}\n\n// ii)\ndouble U0ii(double x) {\n\tif (x < 0.)\n\t\treturn 0.;\n\telse\n\t\treturn -2.;\n}\ndouble Uexii(double x, double t) {\n\tif (x < -t)\n\t\treturn 0.;\n\telse\n\t\treturn -2.;\n}\n\n// iii)\ndouble U0iii(double x) {\n\tif (x < 0.)\n\t\treturn 0.;\n\telse\n\t\treturn 1.;\n}\ndouble Uexiii(double x, double t) {\n\tif (x < 0)\n\t\treturn 0.;\n\telse if (x < t && t < 2)\n\t\treturn x / t;\n\telse\n\t\treturn 1.;\n}\n\n// iv)\ndouble U0iv(double x) {\n\tif (0. < x && x < 1.)\n\t\treturn 1.;\n\telse\n\t\treturn 0.;\n}\ndouble Uexiv(double x, double t) {\n\tif (x <= 0)\n\t\treturn 0.;\n\telse if ((x <= t && t <= 2) || (x < std::sqrt(2 * t) && t > 2))\n\t\treturn x / t;\n\telse if (t <= 2 && t < x && (x < 1 + t / 2.))\n\t\treturn 1.;\n\telse\n\t\treturn 0.;\n}\n\n/* Flux for Buckley-Leverett equation*/\ndouble fBL(double u) {\n\treturn std::pow(u, 2) / (std::pow(u, 2) + std::pow(1 - u, 2));\n}\n\ndouble dfBL(double u) {\n\treturn (2 * u * (u * u + (1 - u) * (1 - u)) - u * u * (2 * u - 2 * (1 - u))) / std::pow(u * u + (1 - u) * (1 - u), 2);\n}\n\n/* Initial data for Buckley-Leverett */\ndouble U0BL(double x) {\n\tif (x < 0.)\n\t\treturn 0.1;\n\telse\n\t\treturn 0.9;\n}\n\nint main(int, char **) {\n\tdouble T = 0.8;\n\tint    N = 400;\n\n\tEigen::VectorXd u, X;\n\t// Test for Burgers with initiald data i\n\tGodunov(N, T, fBurgers, dfBurgers, U0i, u, X);\n\twriteToFile(\"uBi_G.txt\", u);\n\tLaxFriedrichs(N, T, fBurgers, dfBurgers, U0i, u, X);\n\twriteToFile(\"uBi_LF.txt\", u);\n\n\tGodunov(N, T, fBurgers, dfBurgers, U0ii, u, X);\n\twriteToFile(\"uBii_G.txt\", u);\n\tLaxFriedrichs(N, T, fBurgers, dfBurgers, U0ii, u, X);\n\twriteToFile(\"uBii_LF.txt\", u);\n\n\tGodunov(N, T, fBurgers, dfBurgers, U0iii, u, X);\n\twriteToFile(\"uBiii_G.txt\", u);\n\tLaxFriedrichs(N, T, fBurgers, dfBurgers, U0iii, u, X);\n\twriteToFile(\"uBiii_LF.txt\", u);\n\n\tGodunov(N, T, fBurgers, dfBurgers, U0iv, u, X);\n\twriteToFile(\"uBiv_G.txt\", u);\n\tLaxFriedrichs(N, T, fBurgers, dfBurgers, U0iv, u, X);\n\twriteToFile(\"uBiv_LF.txt\", u);\n\n\t// compute convergence for Burgers with initial data i\n\tGodunovConvergence(T, fBurgers, dfBurgers, U0i, Uexi, \"Burgers1\");\n\tLFConvergence(T, fBurgers, dfBurgers, U0i, Uexi, \"Burgers1\");\n\n\t// compute convergence for Burgers with initial data ii\n\tGodunovConvergence(T, fBurgers, dfBurgers, U0ii, Uexii, \"Burgers2\");\n\tLFConvergence(T, fBurgers, dfBurgers, U0ii, Uexii, \"Burgers2\");\n\n\t// compute convergence for Burgers with initial data iii\n\tGodunovConvergence(T, fBurgers, dfBurgers, U0iii, Uexiii, \"Burgers3\");\n\tLFConvergence(T, fBurgers, dfBurgers, U0iii, Uexiii, \"Burgers3\");\n\n\t// compute convergence for Burgers with initial data iv\n\tGodunovConvergence(T, fBurgers, dfBurgers, U0iv, Uexiv, \"Burgers4\");\n\tLFConvergence(T, fBurgers, dfBurgers, U0iv, Uexiv, \"Burgers4\");\n\n\t// Test for Buckley-Leverett\n\tGodunov(N, T, fBL, dfBL, U0BL, u, X);\n\twriteToFile(\"uBL_G.txt\", u);\n\tLaxFriedrichs(N, T, fBL, dfBL, U0BL, u, X);\n\twriteToFile(\"uBL_LF.txt\", u);\n}\n", "meta": {"hexsha": "0bb2ec3fdf2869d36f9cf0ee7372f2f181ec4d57", "size": 11523, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "series5/scalar-cons/scalarconservationlaw.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": "series5/scalar-cons/scalarconservationlaw.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": "series5/scalar-cons/scalarconservationlaw.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": 31.4836065574, "max_line_length": 236, "alphanum_fraction": 0.622841274, "num_tokens": 3805, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267796346599, "lm_q2_score": 0.8479677622198947, "lm_q1q2_score": 0.7367371000835201}}
{"text": "#pragma once\n#include \"H1_norm.hpp\"\n#include \"L2_norm.hpp\"\n#include \"fem_solve.hpp\"\n#include \"writer.hpp\"\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <functional>\n#include <igl/readMESH.h>\n#include <vector>\n\n//----------------convBegin----------------\n//! Compute the L2 and H1-error for different meshes using quadratic FEM\n//!\n//! @param baseMeshName the basename for the mesh (eg. Square).\n//!                     the method will automatically append _<n>.stl\n//!\n//! @param maxLevel the max mesh level to use. Will read up to and including\n//!                 baseMeshName_<maxLevel>.stl\n//!\n//! @param f the function f as in the exercise (LHS)\n//! @param exactSol the exact solution (found by eg. hand computation or googling).\n//! @param exactSol_grad the gradient of the exact solution.\nvoid convergenceAnalysis(const std::string &baseMeshName, int maxLevel, const std::function<double(double, double)> f, const std::function<double(double, double)> exactSol, const std::function<Eigen::Vector2d(double, double)> exactSol_grad) {\n\tstd::vector<double> differences_L2;\n\tstd::vector<double> differences_H1;\n\tstd::vector<int>    numberOfDegreesOfFreedom;\n\tfor (int i = 0; i <= maxLevel; i++) {\n\t\tVector          u;\n\t\tEigen::MatrixXd vertices;\n\t\tEigen::MatrixXi triangles;\n\t\tEigen::MatrixXi tetrahedra;\n\n\t\tstd::stringstream basenameSS;\n\t\tbasenameSS << baseMeshName << \"_\" << i;\n\t\tstd::string basename = basenameSS.str();\n\n\t\tigl::readMESH(std::string(NPDE_DATA_PATH)\n\t\t                  + basename\n\t\t                  + \".mesh\",\n\t\t              vertices,\n\t\t              tetrahedra,\n\t\t              triangles);\n\n\t\t// Initialize quadratic Dofs\n\t\tQDofs quadraticDofs(vertices, triangles);\n\t\t// get dofs\n\t\tEigen::MatrixXi dofs;\n\t\tquadraticDofs.get_dofs(dofs);\n\n\t\tstd::cout << \"Computing convergence. At: \" << basename << std::endl;\n\t\t// solve finite element system\n\t\t// (write your solution here)\n\t\tnumberOfDegreesOfFreedom.push_back(solveFiniteElement(u, quadraticDofs, f));\n\n\t\t//compute L2-error and save it in the corresponding vector\n\t\t// (write your solution here)\n\t\tdifferences_L2.push_back(computeL2Difference(vertices, dofs, u, exactSol));\n\n\t\t//compute H1-error and save it in the corresponding vector\n\t\t// (write your solution here)\n\t\tdifferences_H1.push_back(computeH1Difference(vertices, dofs, u, exactSol_grad));\n\n\t\t// store number of dofs in vector\n\t\t// (write your solution here)\n\n\t\twriteToFile(basename + \"_values.txt\", u);\n\t\twriteMatrixToFile(basename + \"_vertices.txt\", vertices);\n\t\twriteMatrixToFile(basename + \"_triangles.txt\", triangles);\n\t}\n\n\tstd::stringstream errorL2Filename;\n\terrorL2Filename << baseMeshName << \"_errors.txt\";\n\n\tstd::stringstream errorH1Filename;\n\terrorH1Filename << baseMeshName << \"_errorsH1.txt\";\n\n\twriteToFile(errorL2Filename.str(), differences_L2);\n\twriteToFile(errorH1Filename.str(), differences_H1);\n\twriteToFile(baseMeshName + \"_resolutions.txt\", numberOfDegreesOfFreedom);\n}\n//----------------convEnd----------------\n", "meta": {"hexsha": "d11ea568237ffe956d7749c1158ddf50a7a0f986", "size": 2974, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "series3/2d-poissonqFEM/convergence.hpp", "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": "series3/2d-poissonqFEM/convergence.hpp", "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": "series3/2d-poissonqFEM/convergence.hpp", "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": 35.8313253012, "max_line_length": 242, "alphanum_fraction": 0.6903160726, "num_tokens": 745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677430095496, "lm_q2_score": 0.8688267779364222, "lm_q1q2_score": 0.736737081953007}}
{"text": "/*\n * test.cpp\n\n *\n *  Created on: Oct 14, 2017\n *      Author: nmsutton\n */\n\n#include \"test.h\"\n//#include <iostream>\n#include <boost/numeric/odeint.hpp>\n\nusing namespace std;\nusing namespace boost::numeric::odeint;\n\n/*\n * uncomment out below lines to get plotting working\n#include \"matplotlibcpp.h\"\nnamespace plt = matplotlibcpp;\n */\n\ntest::test()\n{\n\n}\n\ntest::~test()\n{\n}\n\n/* we solve the simple ODE x' = 3/(2t^2) + x/(2t)\n * with initial condition x(1) = 0.\n * Analytic solution is x(t) = sqrt(t) - 1/t\n */\n\nvoid test::rhs( const double x , double &dxdt , const double t )\n{\n    dxdt = 3.0/(2.0*t*t) + x/(2.0*t);\n}\n\nvoid test::write_cout( const double &x , const double t )\n{\n    cout << t << '\\t' << x << endl;\n    //x_data.push_back(x[0]);\n}\n\n// state_type = double\ntypedef runge_kutta_dopri5< double > stepper_type;\n\nvoid test::run_test()\n{\n    double x = 0.0;\n    runge_kutta_dopri5< double > rk2;\n    //integrate_adaptive( make_controlled( 1E-12 , 1E-12 , stepper_type() ) , rhs , x , 1.0 , 10.0 , 0.1 , write_cout );\n\tdouble t = 1.0;\n\tconst double dt = 0.1;//0.0025;\n\tint time_span = 90;\n\n\t//integrate_const( rk2 , rhs , x , 1.0 , 10.0 , 0.1, write_cout );\n\tfor (int i = 0; i < time_span; i++) {\n\t\tt += dt;\n\t\tx_data.push_back(x);\n\t\t//y_data.push_back(0);\n\t\tintegrate_const( rk2 , rhs , x , t , (t+dt) , dt);//, write_cout );\n\t}\n\t/*\n\t * uncomment out below lines to get plotting working\n    plt::plot(x_data);\n    plt::show();\n    */\n}\n\n\n", "meta": {"hexsha": "dbd2686935cc44e78fa0cb2a10c39a47619149cd", "size": 1445, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "neural_engine/neural_engine/src/test.cpp", "max_stars_repo_name": "nmsutton/MazeRunner", "max_stars_repo_head_hexsha": "1d5fe36586fdcb3cc22cf339eef3cf14c29c7748", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-07-02T04:04:23.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-11T03:18:25.000Z", "max_issues_repo_path": "neural_engine/neural_engine/src/test.cpp", "max_issues_repo_name": "nmsutton/MazeRunner", "max_issues_repo_head_hexsha": "1d5fe36586fdcb3cc22cf339eef3cf14c29c7748", "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": "neural_engine/neural_engine/src/test.cpp", "max_forks_repo_name": "nmsutton/MazeRunner", "max_forks_repo_head_hexsha": "1d5fe36586fdcb3cc22cf339eef3cf14c29c7748", "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.527027027, "max_line_length": 120, "alphanum_fraction": 0.6048442907, "num_tokens": 494, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995483, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.7367266484000318}}
{"text": "\ufeff#include <cstdlib>\n#include <tuple>\n#include <iostream>\n#include <Eigen/Dense>\n#include <Eigen/LU>\n\nnamespace LinearRegression\n{\n\t//h(X\u2081,X\u2082)=\u03b8\u2081X\u2081+\u03b8\u2082X\u2082\n\t//\u03b8\u2081=10,\u03b8\u2082=150,X\u2082=1\n\tstd::tuple<Eigen::MatrixX2d, Eigen::VectorXd> RandomGenterateTrainSet(size_t counts)\n\t{\n\t\tEigen::MatrixX2d train_input(counts, 2);\n\t\tEigen::VectorXd train_output(counts);\n\t\tfor (size_t i = 0; i < counts; i++)\n\t\t{\n\t\t\tfloat X\u2081 = std::rand() % 100 + 20, X\u2082 = 1;\n\t\t\ttrain_input(i, 0) = X\u2081;\n\t\t\ttrain_input(i, 1) = X\u2082;\n\t\t\tfloat \u03b8\u2081 = 10, \u03b8\u2082 = 150;\n\t\t\tfloat error = std::rand() % 11 - 5;\n\t\t\tfloat hx = \u03b8\u2081 * X\u2081 + \u03b8\u2082 * X\u2082 + error;\n\t\t\ttrain_output[i] = hx;\n\t\t}\n\t\treturn { train_input/*.normalized()*/, train_output };\n\t}\n\n\t//              i      i\n\t//1/2m * \u2211(h(x) - y(x) )\u00b2\n\tdouble LossFunction(const Eigen::MatrixXd& model, const Eigen::MatrixXd& train_input, const Eigen::MatrixXd& train_output)\n\t{\n\t\tauto hx_sub_jx = train_output - train_input * model;\n\t\treturn hx_sub_jx.array().pow(2).sum() / (train_input.rows() * 2);\n\t}\n\n\t//                            i      i     i\n\t//\u03b8 = \u03b8 - \u03b1 * 1/m * \u2211(h(x) - y(x) ) * x\n\t// j    j                                  j\n\tvoid GradientDescent(Eigen::MatrixXd& model, const Eigen::MatrixXd& train_input, const Eigen::MatrixXd& train_output, const Eigen::VectorXd& learning_rate, double limit)\n\t{\n\t\tsize_t batch_size = 0;\n\t\tEigen::MatrixXd update = Eigen::MatrixXd::Zero(model.rows(), model.cols());\n\t\tdo\n\t\t{\n\t\t\tbatch_size++;\n\t\t\tEigen::MatrixXd last_update;\n\t\t\tfor (size_t train_index = 0; train_index < train_input.rows(); train_index++)\n\t\t\t{\n\t\t\t\tauto hx_sub_yx = train_input * model - train_output;\n\t\t\t\t//std::cout << hx_sub_yx << \"\\n\\n\";\n\t\t\t\tEigen::MatrixXd duplicate_line(model.cols(), train_input.cols());\n\t\t\t\tauto&& reference = duplicate_line << train_input.row(train_index);\n\t\t\t\tfor (size_t line = 0; line < model.cols() - 1; line++)\n\t\t\t\t{\n\t\t\t\t\treference, train_input.row(train_index);\n\t\t\t\t}\n\t\t\t\tlast_update = update;\n\t\t\t\tupdate = learning_rate.array() * (1.0 / train_input.rows() * hx_sub_yx.row(train_index) * duplicate_line).transpose().array();\n\t\t\t\t//std::cout << duplicate_line << \"\\n\\n\";\n\t\t\t\t//std::cout << update << \"\\n\\n\";\n\t\t\t\tmodel -= update;\n\t\t\t\tstd::cout << model << \"\\n\\n\";\n\t\t\t}\n\n\t\t\tif (last_update.minCoeff() != 0)\n\t\t\t{\n\t\t\t\t//non-convergence\n\t\t\t\tif ((update.array().abs() > last_update.array().abs()).sum())\n\t\t\t\t\tbreak;\n\t\t\t\t//convergence\n\t\t\t\tif ((update.array() / last_update.array()).abs().maxCoeff() < limit)\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t} while (true);\n\t\tstd::cout << \"batch_size:\" << batch_size << \"\\n\\n\";\n\t}\n\n\tvoid GradientDescent(Eigen::MatrixXd& model, const Eigen::MatrixXd& train_input, const Eigen::MatrixXd& train_output, const Eigen::VectorXd& learning_rate, size_t batch_size)\n\t{\n\t\tfor (size_t i = 0; i < batch_size; i++)\n\t\t{\n\t\t\tfor (size_t train_index = 0; train_index < train_input.rows(); train_index++)\n\t\t\t{\n\t\t\t\tauto hx_sub_yx = train_input * model - train_output;\n\t\t\t\t//std::cout << hx_sub_yx << \"\\n\\n\";\n\t\t\t\tEigen::MatrixXd duplicate_line(model.cols(), train_input.cols());\n\t\t\t\tauto&& reference = duplicate_line << train_input.row(train_index);\n\t\t\t\tfor (size_t line = 0; line < model.cols() - 1; line++)\n\t\t\t\t{\n\t\t\t\t\treference, train_input.row(train_index);\n\t\t\t\t}\n\t\t\t\tEigen::MatrixXd update = learning_rate.array() * (1.0 / train_input.rows() * hx_sub_yx.row(train_index) * duplicate_line).transpose().array();\n\t\t\t\t//std::cout << duplicate_line << \"\\n\\n\";\n\t\t\t\t//std::cout << update << \"\\n\\n\";\n\t\t\t\tmodel -= update;\n\t\t\t\tstd::cout << model << \"\\n\\n\";\n\t\t\t}\n\t\t}\n\t}\n\n\t//  T   -1    T\n\t//(X *X)   * X  * y\n\t//\\note This matrix must be invertible, otherwise the result is undefined.\n\tEigen::MatrixXd NormalEquation(const Eigen::MatrixXd& train_input, const Eigen::MatrixXd& train_output)\n\t{\n\t\tif ((train_input.transpose() * train_input).fullPivLu().isInvertible())\n\t\t{\n\t\t\treturn (train_input.transpose() * train_input).inverse() * train_input.transpose() * train_output;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::cout << \"Not invertible!\" << std::endl;\n\t\t\treturn {};\n\t\t}\n\t}\n}\n\nint main_()\n{\n\tstd::cout << std::boolalpha;\n\n\tauto [train_input, train_output] = LinearRegression::RandomGenterateTrainSet(100);\n\t//std::cout << train_input << std::endl;\n\t//std::cout << train_output << std::endl;\n\n\tEigen::MatrixXd model = Eigen::Vector2d(1, 200);\n\tEigen::Vector2d learning_rate(0.005, 1);\n\tdouble limit = 0.05;\n\tsize_t batch_size = 25;\n\tLinearRegression::GradientDescent(model, train_input, train_output, learning_rate, limit/*batch_size*/);\n\tstd::cout << LinearRegression::NormalEquation(train_input, train_output) << std::endl;\n\treturn 0;\n}", "meta": {"hexsha": "c88852a568875c05065cf7fec475ebfbe0afce17", "size": 4538, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "LinearRegression.cpp", "max_stars_repo_name": "yonghenghuanmie/MachineLearning", "max_stars_repo_head_hexsha": "bb37ffc8cac3641eff32e7e31e25e7692c5fcb74", "max_stars_repo_licenses": ["ECL-2.0", "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": "LinearRegression.cpp", "max_issues_repo_name": "yonghenghuanmie/MachineLearning", "max_issues_repo_head_hexsha": "bb37ffc8cac3641eff32e7e31e25e7692c5fcb74", "max_issues_repo_licenses": ["ECL-2.0", "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": "LinearRegression.cpp", "max_forks_repo_name": "yonghenghuanmie/MachineLearning", "max_forks_repo_head_hexsha": "bb37ffc8cac3641eff32e7e31e25e7692c5fcb74", "max_forks_repo_licenses": ["ECL-2.0", "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": 34.1203007519, "max_line_length": 175, "alphanum_fraction": 0.632437197, "num_tokens": 1366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240073565739, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.7367168282001902}}
{"text": "#ifndef GRAVITY_HPP\n# define GRAVITY_HPP\n\n#include <Eigen/Dense>\n\n#include <cmath>\n\n/** @brief Parameters for gravity model */\nclass GravBody {\nprotected:\n  double mu;         /* (m3/s2) gravitational constant of planet */\n  double eq_radius;  /* (m)     mean equatorial radius of planet */\npublic:\n  GravBody(const double& mu_, const double& r_eq)\n    : mu(mu_),\n      eq_radius(r_eq)\n  { }\n  \n\n  /** @brief Compute gravitational acceleration and gravity gradient\n   *         (change in acceleration with respect to change in position)\n   *\n   * This function treats the planet as a point mass.\n   *\n   * @param[in]  r_pcpf   position in planet-centered, planet-fixed\n   *                      coordinates; should have same units as\n   *                      params->mu (meters, usually)\n   * @param[out] a_pcpf   acceleration due to gravity in PCPF frame\n   * @param[out] da_dr    partial of change in acceleration with respect\n   *                      to change in position\n   */\n  void accel(const Eigen::Vector3d& r_pcpf,\n\t     Eigen::Vector3d& a_pcpf,\n\t     Eigen::Matrix3d& da_dr) const {\n    double r2 = r_pcpf.squaredNorm();\n    double r3 = r2 * sqrt(r2);\n    double mu_over_r3 = mu / r3;\n\n    // Compute acceleration vector\n    a_pcpf = r_pcpf * -mu_over_r3;\n\n    // Compute gravity gradient\n    da_dr = (r_pcpf * r_pcpf.transpose() * 3.0 / r2 - Eigen::Matrix3d::Identity()) * mu_over_r3;\n  }\n};\n\n#endif\n\n", "meta": {"hexsha": "053148267a5ac44befadb679ee556a6d1b9152b2", "size": 1417, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/gravity.hpp", "max_stars_repo_name": "openlunar/nav", "max_stars_repo_head_hexsha": "37240000c542f4d42979a83ac5bebb3ab2c01fe4", "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": "include/gravity.hpp", "max_issues_repo_name": "openlunar/nav", "max_issues_repo_head_hexsha": "37240000c542f4d42979a83ac5bebb3ab2c01fe4", "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": "include/gravity.hpp", "max_forks_repo_name": "openlunar/nav", "max_forks_repo_head_hexsha": "37240000c542f4d42979a83ac5bebb3ab2c01fe4", "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": 28.9183673469, "max_line_length": 96, "alphanum_fraction": 0.6323218066, "num_tokens": 377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122732859021, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.7367114033016893}}
{"text": "#pragma once\r\n\r\n#include <cstdio>\r\n#include <dlib/optimization.h>\r\n#include <cmath>\r\n#include <iostream>\r\n\r\n#define DIM 3\r\n\r\nusing namespace dlib;\r\n\r\nclass CovIntersection\r\n{\r\npublic:\r\n\tvoid loadData(matrix<double, DIM, DIM> covA, matrix<double, DIM, DIM> covB, matrix<double, DIM, 1> posA, matrix<double, DIM, 1> posB)\r\n\t{\r\n\t\tCA = covA;\r\n\t\tCB = covB;\r\n\r\n\t\tca = posA;\r\n\t\tcb = posB;\r\n\t}\r\n\r\n\tstatic double function(double x)\r\n\t{\r\n\t\t// double value = sum(diag(inv(inv(CA) + inv(CB) - inv(x*CA + (1-x)*CB))));\r\n\t\treturn sum(diag(inv(inv(CA) + inv(CB) - inv(x*CA + (1 - x)*CB))));\r\n\t\t// return value;\r\n\t}\r\n\r\n\tstatic matrix<double, DIM, DIM> CA, CB;\r\n\tstatic matrix<double, DIM, 1> ca, cb;\r\n\r\n\tvoid optimize()\r\n\t{\r\n\t\tminValue = find_min_single_variable(&CovIntersection::function, starting_point, begin, end, eps, max_iter, initial_search_radius);\r\n\t\tminX = starting_point;\r\n\t}\r\n\r\n\tvoid computeFusedValues()\r\n\t{\r\n\t\tcovFused = inv(inv(CA) + inv(CB) - inv(minX*CA + (1 - minX)*CB));\r\n\r\n\t\tmatrix <double, DIM, DIM> KICI, LICI;\r\n\t\tKICI = covFused * (inv(CA) - minX * inv(minX*CA + (1 - minX)*CB));\r\n\t\tLICI = covFused * (inv(CB) - (1 - minX) * inv(minX*CA + (1 - minX)*CB));\r\n\r\n\t\tposeFused = KICI * ca + LICI * cb;\r\n\t}\r\n\r\n\tdouble minValue;\r\n\tdouble minX;\r\n\r\n\tmatrix <double, DIM, DIM> covFused;\r\n\tmatrix <double, DIM, 1> poseFused;\r\n\r\nprivate:\r\n\tconst double begin = 0.0;\r\n\tconst double end = 1.0;\r\n\tdouble starting_point = 0.0;\r\n\tconst double eps = 1e-3;\r\n\tconst long max_iter = 100;\r\n\tconst double initial_search_radius = 0.01;\r\n\t// print variables\r\n};\r\n\r\nmatrix <double, DIM, DIM> CovIntersection::CA;\r\nmatrix <double, DIM, DIM> CovIntersection::CB;\r\nmatrix <double, DIM, 1> CovIntersection::ca;\r\nmatrix <double, DIM, 1> CovIntersection::cb;", "meta": {"hexsha": "3b84d730ca0bd3548f4cc58cbd652a380ddcdb05", "size": 1733, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/coloc/CovIntersection.hpp", "max_stars_repo_name": "saihv/coloc", "max_stars_repo_head_hexsha": "260e78eb34b1b86928ac0bd3ddf29072325c7a2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2018-10-24T05:12:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-28T08:08:17.000Z", "max_issues_repo_path": "include/coloc/CovIntersection.hpp", "max_issues_repo_name": "saihv/coloc", "max_issues_repo_head_hexsha": "260e78eb34b1b86928ac0bd3ddf29072325c7a2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-02-21T10:13:11.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-24T18:30:05.000Z", "max_forks_repo_path": "include/coloc/CovIntersection.hpp", "max_forks_repo_name": "saihv/coloc", "max_forks_repo_head_hexsha": "260e78eb34b1b86928ac0bd3ddf29072325c7a2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-10-31T04:02:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-23T07:41:16.000Z", "avg_line_length": 24.7571428571, "max_line_length": 135, "alphanum_fraction": 0.6330063474, "num_tokens": 545, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768588653856, "lm_q2_score": 0.7799928951399099, "lm_q1q2_score": 0.7364512416705182}}
{"text": "#include <Eigen/Dense>\r\n#include <cmath>\r\n#include \"nv_core.h\"\r\n#include \"nv_num.h\"\r\n#include \"nv_ml_gaussian.h\"\r\n\r\n\r\n// \u30ac\u30a6\u30b9\u5206\u5e03\r\n\r\nfloat nv_gaussian_log_predict(const nv_cov_t *cov, const nv_matrix_t *x, int xm)\r\n{\r\n\tEigen::VectorXf X = Eigen::Map<Eigen::VectorXf>(&x->v[xm*x->n], x->n) - Eigen::Map<Eigen::VectorXf>(cov->u->v, x->n);\r\n\tEigen::Map<Eigen::MatrixXf> Sigma(cov->cov->v, x->n, x->n);\r\n\treturn log(1 / sqrt(pow(2 * acos(-1), x->n) * Sigma.determinant())) - X.dot(Sigma.llt().solve(X)) / 2;\r\n}\r\n", "meta": {"hexsha": "520468fa7a7b0bfc9f0fc58f32e92d7850c5f5d4", "size": 505, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "nvxs/nv_ml/nv_gaussian.cpp", "max_stars_repo_name": "aliakseis/animeface-2009", "max_stars_repo_head_hexsha": "ca633bf3623c2aac1823657bb5004c5ec2b46723", "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": "nvxs/nv_ml/nv_gaussian.cpp", "max_issues_repo_name": "aliakseis/animeface-2009", "max_issues_repo_head_hexsha": "ca633bf3623c2aac1823657bb5004c5ec2b46723", "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": "nvxs/nv_ml/nv_gaussian.cpp", "max_forks_repo_name": "aliakseis/animeface-2009", "max_forks_repo_head_hexsha": "ca633bf3623c2aac1823657bb5004c5ec2b46723", "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.5625, "max_line_length": 119, "alphanum_fraction": 0.6316831683, "num_tokens": 181, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810525948927, "lm_q2_score": 0.7772998611746911, "lm_q1q2_score": 0.7363991606615428}}
{"text": "#include \"ode45.hpp\"\n#include <iostream>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n\nusing namespace Eigen;\nusing namespace std;\n\n// Compute the maps Phi and W at time T, for initial data given by u0 and v0.\npair<Vector2d,Matrix2d> PhiAndW(double u0, double v0, double T) {\n    \n    auto f = [] (const VectorXd & w) {\n        Eigen::VectorXd temp(6);\n        temp(0) = (2. - w(1))*w(0);\n        temp(1) = (w(0) - 1.)*w(1);\n        temp(2) = (2. - w(1))*w(2) - w(0)*w(3);\n        temp(3) = w(1)*w(2) + (w(0) - 1.)*w(3);\n        temp(4) = (2. - w(1))*w(4) - w(0)*w(5);\n        temp(5) = w(1)*w(4) + (w(0) - 1.)*w(5);\n        return temp;\n    };\n    \n    Eigen::VectorXd w0(6);\n    w0 << u0, v0, 1., 0, 0, 1.;\n    \n    ode45<Eigen::VectorXd> O(f);\n    O.options.rtol = 1e-14;\n    O.options.atol = 1e-12;\n    auto sol = O.solve(w0, T);\n    VectorXd wT = sol.back().first;\n\n    pair<Vector2d,Matrix2d> PaW;\n    PaW.first << wT(0), wT(1);\n    PaW.second << wT(2), wT(4), wT(3), wT(5);\n    return PaW;\n}\n\n// Apply the Newton method to find initial data giving solutions with period equal to 5.\nint main(){\n    Vector2d y;\n    y << 3, 2;\n    double T = 5;\n    pair<Vector2d,Matrix2d> PaW = PhiAndW(y(0), y(1), T);\n    Vector2d F = PaW.first - y;\n    Matrix2d DF;\n\n    while (F.norm() > 1e-5) {\n        PaW = PhiAndW(y(0), y(1), T);\n        F = PaW.first - y;\n        DF = PaW.second - MatrixXd::Identity(2,2);\n        y = y - DF.lu().solve(F);\n    }\n    \n    cout << \"The obtained initial condition is: \" << endl << y << endl;\n    PaW = PhiAndW(y(0), y(1), 100);\n    \n    cout << \"y(100) = \" << endl << PaW.first << endl;\n}\n", "meta": {"hexsha": "f2cefdc8ef8f8cc59da722077169ae1d6d7c078a", "size": 1620, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/PS13/solutions_ps13/LV.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/LV.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/LV.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": 27.4576271186, "max_line_length": 88, "alphanum_fraction": 0.5154320988, "num_tokens": 617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425333801888, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.7363504168909742}}
{"text": "//\n//  main.cpp\n//  Exercise 5\n//\n//  Created by Zhehao Li on 2020/4/17.\n//  Copyright \u00a9 2020 Zhehao Li. All rights reserved.\n//\n//  Exercise 5 Statistical Functions\n\n#include <boost/math/distributions/exponential.hpp>\n#include <boost/math/distributions/poisson.hpp>\n#include <boost/math/distributions.hpp>             // For non-member functions of distributions\n\n#include <vector>\n#include <iostream>\nusing namespace std;\n\nint main(int argc, const char * argv[]) {\n\n    using namespace boost::math;\n\n    // 1. Create exponential distribution object\n    double scaleParameter = 0.5;\n    exponential_distribution<> myExponential(scaleParameter);          // Default type is 'double'\n    cout << \"Mean: \" << mean(myExponential) << \", standard deviation: \" << standard_deviation(myExponential) << endl;\n\n    // 1.1 Distributional properties\n    double x = 3.6;\n    cout << \"pdf: \" << pdf(myExponential, x) << endl;\n    cout << \"cdf: \" << cdf(myExponential, x) << endl;\n\n    // 1.2 Choose precision\n    cout.precision(10); // Number of values behind the comma\n\n    // 1.3 Other properties\n    cout << \"\\n*** Poisson Distribution ***\\n\";\n    cout << \"mean: \"                    << mean(myExponential)              << endl;\n    cout << \"variance: \"                << variance(myExponential)          << endl;\n    cout << \"median: \"                  << median(myExponential)            << endl;\n    cout << \"mode: \"                    << mode(myExponential)              << endl;\n    cout << \"kurtosis excess: \"         << kurtosis_excess(myExponential)   << endl;\n    cout << \"kurtosis: \"                << kurtosis(myExponential)          << endl;\n\n\n    \n    // 2. Poisson distribution\n    double lmbda = 3.0;                                 // Mean\n    poisson_distribution<> myPoisson(lmbda);            // Default type is 'double'\n\n    double val = 13.0;\n    cout << \"Exponential pdf: \" << pdf(myPoisson, val) << endl;\n    cout << \"Exponential cdf: \" << cdf(myPoisson, val) << endl;\n\n    vector<double> pdfList;\n    vector<double> cdfList;\n\n    double start = 0.0;\n    double end = 10.0;\n    long   N = 30;        // Number of subdivisions\n\n    val = 0.0;\n    double h = (end - start) / double(N);\n    \n    // Push the pdf and cdf value into vectors\n    for (long j = 1; j <= N; ++j){\n        pdfList.push_back(pdf(myPoisson, val));\n        cdfList.push_back(cdf(myPoisson, val));\n\n        val += h;\n    }\n    \n    cout << \"\\n********\\n\" << endl;\n\n    // Print the vector of pdf\n    cout << \"Poisson pdf:\" << endl;\n    for (long j = 0; j < pdfList.size(); ++j){\n        cout << pdfList[j] << \", \";\n    }\n\n    cout << \"\\n********\\n\" << endl;\n\n    // Print the vector of cdf\n    cout << \"Poisson cdf:\" << endl;\n    for (long j = 0; j < cdfList.size(); ++j){\n        cout << cdfList[j] << \", \";\n    }\n    \n    return 0;\n}\n", "meta": {"hexsha": "4aa870764d1c2147f2da561061059fc8419aa64a", "size": 2818, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Level_8_HW/Exercise 5/Exercise 5/main.cpp", "max_stars_repo_name": "ZhehaoLi9705/QuantNet_CPP", "max_stars_repo_head_hexsha": "a889f4656e757842f4163b0cda7e098cc6ad1193", "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": "Level_8_HW/Exercise 5/Exercise 5/main.cpp", "max_issues_repo_name": "ZhehaoLi9705/QuantNet_CPP", "max_issues_repo_head_hexsha": "a889f4656e757842f4163b0cda7e098cc6ad1193", "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": "Level_8_HW/Exercise 5/Exercise 5/main.cpp", "max_forks_repo_name": "ZhehaoLi9705/QuantNet_CPP", "max_forks_repo_head_hexsha": "a889f4656e757842f4163b0cda7e098cc6ad1193", "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.3111111111, "max_line_length": 117, "alphanum_fraction": 0.5461320085, "num_tokens": 781, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554475, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.7363265493923614}}
{"text": "#ifndef LQR_CONTROLLER_HPP\n#define LQR_CONTROLLER_HPP\n\n#include <armadillo>\n#include <cmath>\nclass LQRController {\n\npublic:\n\n    arma::mat A;\n    arma::mat B;\n    arma::mat Q;\n    arma::mat R;\n    arma::mat P;\n    arma::mat Klqr;\n\n    int maxIter;\n    float eps = 1e-3;\n\n\n    LQRController(const arma::mat& _A, const arma::mat& _B,\n                const arma::mat& _Q, const arma::mat& _R,\n                int _maxIter = 2000, float _eps = 1e-3) {\n\n        maxIter = _maxIter;\n        eps = _eps;\n\n        compute_LQR_gain(_A, _B, _Q, _R);\n    }\n\n    void compute_LQR_gain(const arma::mat& _A, const arma::mat& _B, const arma::mat& _Q, const arma::mat& _R) {\n\n        A = _A;\n        B = _B;\n        Q = _Q;\n        R = _R;\n        P = _Q;\n\n        arma::mat Pold = P;\n        arma::mat delta;\n\n        for (int i = 0; i < maxIter; i++) {\n            P = A.t() * P * A - (A.t() * P * B) * arma::inv(R + B.t() * P * B) * B.t() * P * A + Q;\n            delta = Pold - P;\n            if (std::abs(delta.max()) < eps) {\n                break;\n            }\n            Pold = P;\n        }\n\n        Klqr = arma::inv(R + B.t() * P * B) * B.t() * P * A;\n    }\n\n    arma::vec get_control(const arma::vec & x) {\n        return -Klqr * x;\n    }\n\n};\n\n#endif\n", "meta": {"hexsha": "a5ffcce909e696cddf8d15e3628491460121accd", "size": 1247, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/model_based_shared_control/src/robotlib/lqr_controller.hpp", "max_stars_repo_name": "argallab/model_based_shared_control", "max_stars_repo_head_hexsha": "ff42226b6345266f35a32021c7d0b44cc5948ec1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-05-08T19:47:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T06:43:31.000Z", "max_issues_repo_path": "src/model_based_shared_control/src/robotlib/lqr_controller.hpp", "max_issues_repo_name": "argallab/model_based_shared_control", "max_issues_repo_head_hexsha": "ff42226b6345266f35a32021c7d0b44cc5948ec1", "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/model_based_shared_control/src/robotlib/lqr_controller.hpp", "max_forks_repo_name": "argallab/model_based_shared_control", "max_forks_repo_head_hexsha": "ff42226b6345266f35a32021c7d0b44cc5948ec1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-05-08T19:47:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-07T10:10:17.000Z", "avg_line_length": 20.4426229508, "max_line_length": 111, "alphanum_fraction": 0.4635124298, "num_tokens": 408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897492587141, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.7363208420976076}}
{"text": "/*\n * Copyright 2021 MusicScience37 (Kenta Kabashima)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/*!\n * \\file\n * \\brief Test of tikhonov class.\n */\n#include \"num_collect/regularization/tikhonov.h\"\n\n#include <Eigen/Core>\n#include <catch2/catch_test_macros.hpp>\n#include <catch2/matchers/catch_matchers_floating.hpp>\n\n#include \"eigen_approx.h\"\n#include \"num_prob_collect/regularization/blur_sine.h\"\n\nTEST_CASE(\"num_collect::regularization::tikhonov\") {\n    using coeff_type = Eigen::MatrixXd;\n    using data_type = Eigen::VectorXd;\n\n    SECTION(\"solve\") {\n        constexpr num_collect::index_type solution_size = 15;\n        constexpr num_collect::index_type data_size = 30;\n        const auto prob = num_prob_collect::regularization::blur_sine(\n            data_size, solution_size);\n\n        num_collect::regularization::tikhonov<coeff_type, data_type> tikhonov;\n        tikhonov.compute(prob.coeff(), prob.data());\n        Eigen::VectorXd solution;\n        tikhonov.solve(0.0, solution);\n\n        REQUIRE_THAT(solution, eigen_approx(prob.solution()));\n    }\n\n    SECTION(\"solve with different parameters\") {\n        constexpr num_collect::index_type solution_size = 15;\n        constexpr num_collect::index_type data_size = 30;\n        const auto prob = num_prob_collect::regularization::blur_sine(\n            data_size, solution_size);\n\n        num_collect::regularization::tikhonov<coeff_type, data_type> tikhonov;\n        tikhonov.compute(prob.coeff(), prob.data());\n\n        constexpr double param_small = 1e-2;\n        Eigen::VectorXd solution_small;\n        tikhonov.solve(param_small, solution_small);\n\n        constexpr double param_large = 1e+2;\n        Eigen::VectorXd solution_large;\n        tikhonov.solve(param_large, solution_large);\n\n        REQUIRE(solution_large.squaredNorm() < solution_small.squaredNorm());\n    }\n\n    SECTION(\"singular_values\") {\n        constexpr num_collect::index_type solution_size = 15;\n        constexpr num_collect::index_type data_size = 30;\n        const auto prob = num_prob_collect::regularization::blur_sine(\n            data_size, solution_size);\n\n        num_collect::regularization::tikhonov<coeff_type, data_type> tikhonov;\n        tikhonov.compute(prob.coeff(), prob.data());\n\n        REQUIRE(tikhonov.singular_values().size() == solution_size);\n        for (num_collect::index_type i = 0; i < solution_size; ++i) {\n            INFO(\"i = \" << i);\n            REQUIRE(tikhonov.singular_values()(i) > 0.0);\n        }\n    }\n\n    SECTION(\"calculate norms\") {\n        constexpr num_collect::index_type solution_size = 15;\n        constexpr num_collect::index_type data_size = 10;\n        const auto prob = num_prob_collect::regularization::blur_sine(\n            data_size, solution_size);\n\n        num_collect::regularization::tikhonov<coeff_type, data_type> tikhonov;\n        tikhonov.compute(prob.coeff(), prob.data());\n\n        constexpr double param = 1.0;\n        Eigen::VectorXd solution;\n        tikhonov.solve(param, solution);\n\n        constexpr double rel_tol = 1e-6;\n\n        SECTION(\"residual_norm\") {\n            const double expected =\n                (prob.coeff() * solution - prob.data()).squaredNorm();\n            REQUIRE_THAT(tikhonov.residual_norm(param),\n                Catch::Matchers::WithinRel(expected, rel_tol));\n        }\n\n        SECTION(\"regularization term\") {\n            const double expected = solution.squaredNorm();\n            REQUIRE_THAT(tikhonov.regularization_term(param),\n                Catch::Matchers::WithinRel(expected, rel_tol));\n        }\n    }\n\n    SECTION(\"calculate the first-order derivatives of norms\") {\n        constexpr num_collect::index_type solution_size = 15;\n        constexpr num_collect::index_type data_size = 10;\n        const auto prob = num_prob_collect::regularization::blur_sine(\n            data_size, solution_size);\n\n        num_collect::regularization::tikhonov<coeff_type, data_type> tikhonov;\n        tikhonov.compute(prob.coeff(), prob.data());\n\n        constexpr double param = 1.0;\n        Eigen::VectorXd solution;\n        tikhonov.solve(param, solution);\n\n        constexpr double param_diff = param * 1e-3;\n        constexpr double param_plus = param + param_diff;\n        Eigen::VectorXd solution_plus;\n        tikhonov.solve(param_plus, solution_plus);\n\n        constexpr double rel_tol = 1e-2;\n\n        SECTION(\"first_derivative_of_residual_norm\") {\n            const double expected =\n                ((prob.coeff() * solution_plus - prob.data()).squaredNorm() -\n                    (prob.coeff() * solution - prob.data()).squaredNorm()) /\n                param_diff;\n            REQUIRE_THAT(tikhonov.first_derivative_of_residual_norm(param),\n                Catch::Matchers::WithinRel(expected, rel_tol));\n        }\n\n        SECTION(\"first_derivative_of_regularization_term\") {\n            const double expected =\n                (solution_plus.squaredNorm() - solution.squaredNorm()) /\n                param_diff;\n            REQUIRE_THAT(\n                tikhonov.first_derivative_of_regularization_term(param),\n                Catch::Matchers::WithinRel(expected, rel_tol));\n        }\n    }\n\n    SECTION(\"calculate the second-order derivatives of norms\") {\n        constexpr num_collect::index_type solution_size = 15;\n        constexpr num_collect::index_type data_size = 10;\n        const auto prob = num_prob_collect::regularization::blur_sine(\n            data_size, solution_size);\n\n        num_collect::regularization::tikhonov<coeff_type, data_type> tikhonov;\n        tikhonov.compute(prob.coeff(), prob.data());\n\n        constexpr double param = 1.0;\n        Eigen::VectorXd solution;\n        tikhonov.solve(param, solution);\n\n        constexpr double param_diff = param * 1e-3;\n        constexpr double param_plus = param + param_diff;\n        Eigen::VectorXd solution_plus;\n        tikhonov.solve(param_plus, solution_plus);\n\n        constexpr double param_minus = param - param_diff;\n        Eigen::VectorXd solution_minus;\n        tikhonov.solve(param_minus, solution_minus);\n\n        constexpr double rel_tol = 1e-2;\n\n        SECTION(\"second_derivative_of_residual_norm\") {\n            const double expected =\n                ((prob.coeff() * solution_plus - prob.data()).squaredNorm() -\n                    2.0 *\n                        (prob.coeff() * solution - prob.data()).squaredNorm() +\n                    (prob.coeff() * solution_minus - prob.data())\n                        .squaredNorm()) /\n                (param_diff * param_diff);\n            REQUIRE_THAT(tikhonov.second_derivative_of_residual_norm(param),\n                Catch::Matchers::WithinRel(expected, rel_tol));\n        }\n\n        SECTION(\"second_derivative_of_regularization_term\") {\n            const double expected =\n                (solution_plus.squaredNorm() - 2.0 * solution.squaredNorm() +\n                    solution_minus.squaredNorm()) /\n                (param_diff * param_diff);\n            REQUIRE_THAT(\n                tikhonov.second_derivative_of_regularization_term(param),\n                Catch::Matchers::WithinRel(expected, rel_tol));\n        }\n    }\n\n    SECTION(\"sum_of_filter_factor\") {\n        constexpr num_collect::index_type solution_size = 15;\n        constexpr num_collect::index_type data_size = 10;\n        const auto prob = num_prob_collect::regularization::blur_sine(\n            data_size, solution_size);\n\n        num_collect::regularization::tikhonov<coeff_type, data_type> tikhonov;\n        tikhonov.compute(prob.coeff(), prob.data());\n\n        constexpr double param = 1.0;\n\n        const double expected = (tikhonov.singular_values().array().square() /\n            (tikhonov.singular_values().array().square() + param))\n                                    .sum();\n        REQUIRE_THAT(tikhonov.sum_of_filter_factor(param),\n            Catch::Matchers::WithinRel(expected));\n    }\n\n    SECTION(\"data_size\") {\n        constexpr num_collect::index_type solution_size = 15;\n        constexpr num_collect::index_type data_size = 10;\n        const auto prob = num_prob_collect::regularization::blur_sine(\n            data_size, solution_size);\n\n        num_collect::regularization::tikhonov<coeff_type, data_type> tikhonov;\n        tikhonov.compute(prob.coeff(), prob.data());\n\n        REQUIRE(tikhonov.data_size() == data_size);\n    }\n\n    SECTION(\"param_search_region\") {\n        constexpr num_collect::index_type solution_size = 15;\n        constexpr num_collect::index_type data_size = 10;\n        const auto prob = num_prob_collect::regularization::blur_sine(\n            data_size, solution_size);\n\n        num_collect::regularization::tikhonov<coeff_type, data_type> tikhonov;\n        tikhonov.compute(prob.coeff(), prob.data());\n\n        const double max_singular_value = tikhonov.singular_values().maxCoeff();\n        const double squared_max_singular_value =\n            max_singular_value * max_singular_value;\n        const auto [min_param, max_param] = tikhonov.param_search_region();\n        REQUIRE(min_param < squared_max_singular_value);\n        REQUIRE(max_param > squared_max_singular_value);\n    }\n}\n", "meta": {"hexsha": "fd864cca75a4e21e1e93e94f19d84f203fccc3cd", "size": 9607, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/units/regularization/tikhonov_test.cpp", "max_stars_repo_name": "MusicScience37/numerical-collection-cpp", "max_stars_repo_head_hexsha": "490c24aae735ba25f1060b2941cff39050a41f8f", "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": "test/units/regularization/tikhonov_test.cpp", "max_issues_repo_name": "MusicScience37/numerical-collection-cpp", "max_issues_repo_head_hexsha": "490c24aae735ba25f1060b2941cff39050a41f8f", "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": "test/units/regularization/tikhonov_test.cpp", "max_forks_repo_name": "MusicScience37/numerical-collection-cpp", "max_forks_repo_head_hexsha": "490c24aae735ba25f1060b2941cff39050a41f8f", "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": 39.212244898, "max_line_length": 80, "alphanum_fraction": 0.6485895701, "num_tokens": 2104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.890294223211224, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7360167383227857}}
{"text": "#include \"utils.hpp\"\n\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/multiprecision/integer.hpp>\nusing namespace std;\nusing Bint = boost::multiprecision::cpp_int;\n\n\nstring FermatFactorizer_cppfunc(string s){\n    Bint n(s);\n    if(n%2 == 0){\n        return \"2\";\n    }\n    Bint x = sqrt(n);\n    if(pow(x,2)==n){\n        return x.str();\n    }\n    x+=1;\n    Bint y = sqrt(pow(x,2)-n);\n    Bint w = pow(x,2)-n-pow(y,2);\n    for(;;){\n        if(w==0){\n            Bint retval = x-y;\n            return retval.str();\n        }\n        else if(w>0){\n            y+=1;\n        }\n        else{\n            x+=1;\n        }\n        w = pow(x,2)-n-pow(y,2);\n    }\n}\n", "meta": {"hexsha": "66e55aad0cd5f1d5173e6b927d68049de6f6475d", "size": 666, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/FermatFactorizer_cpp.cpp", "max_stars_repo_name": "FullteaR/factorizer", "max_stars_repo_head_hexsha": "f4beb7a14d6cda38d69b9ff6dbe673575b554288", "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/FermatFactorizer_cpp.cpp", "max_issues_repo_name": "FullteaR/factorizer", "max_issues_repo_head_hexsha": "f4beb7a14d6cda38d69b9ff6dbe673575b554288", "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/FermatFactorizer_cpp.cpp", "max_forks_repo_name": "FullteaR/factorizer", "max_forks_repo_head_hexsha": "f4beb7a14d6cda38d69b9ff6dbe673575b554288", "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.0285714286, "max_line_length": 44, "alphanum_fraction": 0.475975976, "num_tokens": 200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107931567176, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.7359996826757409}}
{"text": "#include <fstream>\n#include <cmath>\n#include <boost/config.hpp>\n#include <boost/version.hpp>\n\n// CGAL headers\n#include <CGAL/Cartesian.h>\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Min_circle_2.h>\n#include <CGAL/Min_circle_2_traits_2.h>\n#include <CGAL/Min_ellipse_2.h>\n#include <CGAL/Min_ellipse_2_traits_2.h>\n#include <CGAL/convex_hull_2.h>\n#include <CGAL/point_generators_2.h>\n#include <CGAL/Polygon_2.h>\n#include <CGAL/min_quadrilateral_2.h>\n#include <CGAL/rectangular_p_center_2.h>\n#if BOOST_VERSION >= 105600 && (! defined(BOOST_GCC) || BOOST_GCC >= 40500)\n#include <CGAL/IO/WKT.h>\n#endif\n\n// Qt headers\n#include <QtGui>\n#include <QString>\n#include <QActionGroup>\n#include <QFileDialog>\n#include <QInputDialog>\n#include <QGraphicsEllipseItem>\n#include <QGraphicsRectItem>\n\n// GraphicsView items and event filters (input classes)\n\n#include <CGAL/Qt/PointsGraphicsItem.h>\n#include <CGAL/Qt/PolygonGraphicsItem.h>\n\n// for viewportsBbox\n#include <CGAL/Qt/utility.h>\n  \n#include <CGAL/Qt/GraphicsViewPolylineInput.h>\n\n// the two base classes\n#include \"ui_Bounding_volumes.h\"\n#include <CGAL/Qt/DemosMainWindow.h>\n\n#include \"Ellipse.h\"\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\ntypedef K::Point_2 Point_2;\ntypedef K::Vector_2 Vector_2;\ntypedef K::Iso_rectangle_2 Iso_rectangle_2;\n\ntypedef CGAL::Polygon_2<K> Polygon_2;\n\ntypedef CGAL::Min_circle_2<CGAL::Min_circle_2_traits_2<K> > Min_circle;\ntypedef CGAL::Min_ellipse_2<CGAL::Min_ellipse_2_traits_2<K> > Min_ellipse;\n\nclass MainWindow :\n  public CGAL::Qt::DemosMainWindow,\n  public Ui::Bounding_volumes\n{\n  Q_OBJECT\n  \nprivate:  \n  Polygon_2 convex_hull, min_rectangle, min_parallelogram;\n  Min_circle mc; \n  Min_ellipse me;\n  QGraphicsScene scene;  \n\n  std::vector<Point_2> points; \n  CGAL::Qt::PointsGraphicsItem<std::vector<Point_2> > * pgi;\n  CGAL::Qt::PolygonGraphicsItem<Polygon_2> * convex_hull_gi;\n  CGAL::Qt::PolygonGraphicsItem<Polygon_2> * min_rectangle_gi;\n  CGAL::Qt::PolygonGraphicsItem<Polygon_2> * min_parallelogram_gi;\n  QGraphicsEllipseItem *cgi, *egi;\n\n  const std::size_t P;\n  QGraphicsRectItem *p_center[3];\n  Iso_rectangle_2 p_center_iso_rectangle[3];\n  CGAL::Qt::GraphicsViewPolylineInput<K> * pi;\n\npublic:\n  MainWindow();\n\npublic Q_SLOTS:\n\n  void update();\n\n  void update_from_points();\n\n  void processInput(CGAL::Object o);\n\n  void on_actionShowMinCircle_toggled(bool checked);\n\n  void on_actionShowMinEllipse_toggled(bool checked);\n\n  void on_actionShowMinRectangle_toggled(bool checked);\n\n  void on_actionShowMinParallelogram_toggled(bool checked);\n\n  void on_actionShowConvexHull_toggled(bool checked);\n\n  void on_actionShowPCenter_toggled(bool checked);\n\n  void on_actionInsertPoint_toggled(bool checked);\n  \n  void on_actionInsertRandomPoints_triggered();\n\n  void on_actionLoadPoints_triggered();\n\n  void on_actionSavePoints_triggered();\n\n  void on_actionClear_triggered();\n\n  void on_actionRecenter_triggered();\n\n  virtual void open(QString fileName);\n\nQ_SIGNALS:\n  void changed();\n};\n\n\nMainWindow::MainWindow()\n  : DemosMainWindow(), P(3)\n{\n  setupUi(this);\n\n  QObject::connect(this, SIGNAL(changed()), this, SLOT(update()));\n\n  // Add a GraphicItem for the Min_circle\n  cgi = new QGraphicsEllipseItem;\n  cgi->setPen(QPen(Qt::red, 0, Qt::SolidLine));\n  cgi->hide();\n  scene.addItem(cgi);\n  \n  egi = new QGraphicsEllipseItem;\n  egi->setPen(QPen(Qt::magenta, 0, Qt::SolidLine));\n  egi->hide();\n  scene.addItem(egi);\n  \n  for(std::size_t i =0; i < P; i++){\n    p_center[i] = new QGraphicsRectItem;\n    p_center[i]->setPen(QPen(Qt::cyan, 0, Qt::SolidLine));\n    p_center[i]->hide(); \n    scene.addItem(p_center[i]);\n  }\n\n  // Graphics Item for the input point set\n  pgi = new CGAL::Qt::PointsGraphicsItem<std::vector<Point_2> >(&points);\n\n  QObject::connect(this, SIGNAL(changed()),\n\t\t   pgi, SLOT(modelChanged()));\n  pgi->setVerticesPen(QPen(Qt::black, 3, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n  scene.addItem(pgi);\n\n\n  // Graphics Item for the convex hull\n  convex_hull_gi = new CGAL::Qt::PolygonGraphicsItem<Polygon_2>(&convex_hull);\n\n  QObject::connect(this, SIGNAL(changed()),\n\t\t   convex_hull_gi, SLOT(modelChanged()));\n  convex_hull_gi->setEdgesPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n  scene.addItem(convex_hull_gi);\n\n\n  // Graphics Item for the min rectangle\n  min_rectangle_gi = new CGAL::Qt::PolygonGraphicsItem<Polygon_2>(&min_rectangle);\n\n  QObject::connect(this, SIGNAL(changed()),\n\t\t   min_rectangle_gi, SLOT(modelChanged()));\n  min_rectangle_gi->setEdgesPen(QPen(Qt::green, 0, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n  scene.addItem(min_rectangle_gi);\n\n\n  // Graphics Item for the min parallelogram\n  min_parallelogram_gi = new CGAL::Qt::PolygonGraphicsItem<Polygon_2>(&min_parallelogram);\n\n  QObject::connect(this, SIGNAL(changed()),\n\t\t   min_parallelogram_gi, SLOT(modelChanged()));\n  min_parallelogram_gi->setEdgesPen(QPen(Qt::blue, 0, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n  scene.addItem(min_parallelogram_gi);\n\n\n  // Setup input handlers. They get events before the scene gets them\n  // and the input they generate is passed to the triangulation with \n  // the signal/slot mechanism    \n  pi = new CGAL::Qt::GraphicsViewPolylineInput<K>(this, &scene, 1);\n\n  scene.installEventFilter(pi);\n\n  QObject::connect(pi, SIGNAL(generate(CGAL::Object)),\n\t\t   this, SLOT(processInput(CGAL::Object)));\n\n\n  // \n  // Manual handling of actions\n  //\n\n  QObject::connect(this->actionQuit, SIGNAL(triggered()), \n\t\t   this, SLOT(close()));\n\n  //\n  // Setup the scene and the view\n  //\n  scene.setItemIndexMethod(QGraphicsScene::NoIndex);\n  scene.setSceneRect(-100, -100, 100, 100);\n  this->graphicsView->setScene(&scene);\n  this->graphicsView->setMouseTracking(true);\n\n  // Turn the vertical axis upside down\n  this->graphicsView->matrix().scale(1, -1);\n                                                      \n  // The navigation adds zooming and translation functionality to the\n  // QGraphicsView\n  this->addNavigation(this->graphicsView);\n\n  this->setupStatusBar();\n  this->setupOptionsMenu();\n  this->addAboutDemo(\":/cgal/help/about_Bounding_volumes.html\");\n  this->addAboutCGAL();\n\n  this->addRecentFiles(this->menuFile, this->actionQuit);\n  connect(this, SIGNAL(openRecentFile(QString)),\n\t  this, SLOT(open(QString)));\n}\n\nvoid\nMainWindow::update()\n{\n  if(this->actionShowConvexHull->isChecked()){\n    convex_hull_gi->show();\n  }else {\n    convex_hull_gi->hide();\n  }\n\n  if(this->actionShowMinRectangle->isChecked()){\n    min_rectangle_gi->show();\n  }else {\n    min_rectangle_gi->hide();\n  }\n\n\n  if(this->actionShowMinParallelogram->isChecked()){\n    min_parallelogram_gi->show();\n  }else {\n    min_parallelogram_gi->hide();\n  }\n\n  CGAL::Qt::Converter<K> convert;  \n\n  if(this->actionShowPCenter->isChecked() && convex_hull.size()>=3){\n    for(std::size_t i=0; i< P; i++){\n      p_center[i]->setRect(convert(p_center_iso_rectangle[i]));\n      p_center[i]->show();\n    }\n  }\n\n  if (mc.is_degenerate() || (! this->actionShowMinCircle->isChecked())){\n    cgi->hide();\n  } else {\n    K::Circle_2 c;\n    if (mc.number_of_support_points() == 2) \n      c = K::Circle_2(mc.support_point(0), mc.support_point(1));\n    else\n      c = K::Circle_2(mc.support_point(0), mc.support_point(1), mc.support_point(2));\n    \n\n    cgi->setRect(convert(c.bbox()));\n    cgi->show();\n  }\n\n  if (me.is_degenerate()  || (! this->actionShowMinEllipse->isChecked()) ){\n    egi->hide();\n  } else {\n    if (me.number_of_support_points() == 2) {\n    } else {\n      Ellipse_2<K> e(me);\n      double half_width = sqrt(e.va() * e.va());\n      double half_height = sqrt(e.vb() * e.vb());\n      double angle = std::atan2( e.va().y(), e.va().x() ) * 180.0/CGAL_PI;\n      Vector_2 wh(half_width, half_height);\n\n      Iso_rectangle_2 isor(e.center()+ wh, e.center()-wh);\n      egi->setRect(convert(isor));\n      // Rotate an item 45 degrees around (x, y).\n      double x = e.center().x();\n      double y = e.center().y();\n      egi->setTransform(QTransform().translate(x, y).rotate(angle).translate(-x, -y));\n      egi->show();\n    } \n  }\n}\n\n\nvoid\nMainWindow::update_from_points()\n{\n    convex_hull.clear();\n    CGAL::convex_hull_2(points.begin(), points.end(), std::back_inserter(convex_hull));\n   \n    min_rectangle.clear();\n    CGAL::min_rectangle_2(convex_hull.vertices_begin(), convex_hull.vertices_end(), std::back_inserter(min_rectangle));\n \n    min_parallelogram.clear();\n    CGAL::min_parallelogram_2(convex_hull.vertices_begin(), convex_hull.vertices_end(), std::back_inserter(min_parallelogram));\n\n    std::vector<Point_2> center;\n    double radius;\n\n    CGAL::rectangular_p_center_2 (points.begin(), points.end(), std::back_inserter(center), radius, static_cast<int>(P));\n    Vector_2 rvec(radius, radius);\n\n    for(std::size_t i = 0; i < center.size(); i++){\n      p_center_iso_rectangle[i] = Iso_rectangle_2(center[i]-rvec, center[i]+rvec);\n    }\n}\n\n\nvoid\nMainWindow::processInput(CGAL::Object o)\n{\n  std::list<Point_2> input;\n  if(CGAL::assign(input, o)){\n    Point_2 p = input.front();\n    \n    mc.insert(p);\n    me.insert(p);\n    points.push_back(p);\n\n    convex_hull.push_back(p);\n    Polygon_2 tmp;\n    CGAL::convex_hull_2(convex_hull.vertices_begin(), convex_hull.vertices_end(), std::back_inserter(tmp));\n    convex_hull = tmp;\n\n    min_rectangle.clear();\n    CGAL::min_rectangle_2(convex_hull.vertices_begin(), convex_hull.vertices_end(), std::back_inserter(min_rectangle));\n \n    min_parallelogram.clear();\n    CGAL::min_parallelogram_2(convex_hull.vertices_begin(), convex_hull.vertices_end(), std::back_inserter(min_parallelogram));\n    \n    std::vector<Point_2> center;\n    double radius;\n    if (points.size()>=P){\n      CGAL::rectangular_p_center_2 (points.begin(), points.end(), std::back_inserter(center), radius, static_cast<int>(P));\n      Vector_2 rvec(radius, radius);\n\n      for(std::size_t i=0; i < center.size(); i++){\n        p_center_iso_rectangle[i] = Iso_rectangle_2(center[i]-rvec, center[i]+rvec);\n      }\n    }\n  }\n  Q_EMIT( changed());\n}\n\n\n/* \n *  Qt Automatic Connections\n *  https://doc.qt.io/qt-5/designer-using-a-ui-file.html#automatic-connections\n * \n *  setupUi(this) generates connections to the slots named\n *  \"on_<action_name>_<signal_name>\"\n */\nvoid\nMainWindow::on_actionInsertPoint_toggled(bool checked)\n{\n  if(checked){\n    scene.installEventFilter(pi);\n  } else {\n    scene.removeEventFilter(pi);\n  }\n}\n\n\nvoid\nMainWindow::on_actionShowMinCircle_toggled(bool checked)\n{\n  cgi->setVisible(checked);\n  Q_EMIT( changed());\n}\n\nvoid\nMainWindow::on_actionShowMinEllipse_toggled(bool checked)\n{\n  egi->setVisible(checked);\n  Q_EMIT( changed());\n}\n\n\nvoid\nMainWindow::on_actionShowMinRectangle_toggled(bool checked)\n{\n  min_rectangle_gi->setVisible(checked);\n  Q_EMIT( changed());\n}\n\nvoid\nMainWindow::on_actionShowMinParallelogram_toggled(bool checked)\n{\n  min_parallelogram_gi->setVisible(checked);\n  Q_EMIT( changed());\n}\n\nvoid\nMainWindow::on_actionShowConvexHull_toggled(bool checked)\n{\n  convex_hull_gi->setVisible(checked);\n  Q_EMIT( changed());\n}\n\nvoid\nMainWindow::on_actionShowPCenter_toggled(bool checked)\n{\n  for(std::size_t i =0; i < P; i++){\n    p_center[i]->setVisible(checked);\n  }\n  Q_EMIT( changed());\n}\n\nvoid\nMainWindow::on_actionClear_triggered()\n{\n  mc.clear();\n  me.clear();\n  points.clear();\n  convex_hull.clear();\n  min_rectangle.clear();\n  min_parallelogram.clear();\n  for(std::size_t i=0; i < P;i++){\n    p_center[i]->hide();\n  }\n  Q_EMIT( changed());\n}\n\n\nvoid\nMainWindow::on_actionInsertRandomPoints_triggered()\n{\n  QRectF rect = CGAL::Qt::viewportsBbox(&scene);\n  CGAL::Qt::Converter<K> convert;  \n  Iso_rectangle_2 isor = convert(rect);\n  CGAL::Random_points_in_iso_rectangle_2<Point_2> pg((isor.min)(), (isor.max)());\n  bool ok = false;\n\n  const int number_of_points = \n    QInputDialog::getInt(this, \n                             tr(\"Number of random points\"),\n                             tr(\"Enter number of random points\"),\n\t\t\t     100,\n\t\t\t     0,\n\t\t\t     (std::numeric_limits<int>::max)(),\n\t\t\t     1,\n\t\t\t     &ok);\n\n  if(!ok) {\n    return;\n  }\n\n  // wait cursor\n  QApplication::setOverrideCursor(Qt::WaitCursor);\n  for(int i = 0; i < number_of_points; ++i){\n    Point_2 p = *pg++;\n    mc.insert(p);\n    me.insert(p);\n    points.push_back(p);\n  }\n\n  update_from_points();\n\n  // default cursor\n  QApplication::restoreOverrideCursor();\n  Q_EMIT( changed());\n}\n\n\nvoid\nMainWindow::on_actionLoadPoints_triggered()\n{\n  QString fileName = QFileDialog::getOpenFileName(this,\n\t\t\t\t\t\t  tr(\"Open Points file\"),\n                                                  \".\",\n                                                  tr(\"CGAL files (*.pts.cgal);;\"\n                                                   #if BOOST_VERSION >= 105600 && (! defined(BOOST_GCC) || BOOST_GCC >= 40500)\n                                                     \"WKT files (*.WKT *.wkt);;\"\n                                                   #endif\n                                                     \"All files (*)\"));\n  if(! fileName.isEmpty()){\n    open(fileName);\n  }\n}\n\n\nvoid\nMainWindow::open(QString fileName)\n{\n  // wait cursor\n  QApplication::setOverrideCursor(Qt::WaitCursor);\n  std::ifstream ifs(qPrintable(fileName));\n  if(fileName.endsWith(\".wkt\", Qt::CaseInsensitive))\n  {\n#if BOOST_VERSION >= 105600 && (! defined(BOOST_GCC) || BOOST_GCC >= 40500)\n    CGAL::read_multi_point_WKT(ifs, points);\n    for(K::Point_2 p : points)\n    {\n      mc.insert(p);\n      me.insert(p);\n    }\n#endif\n  }\n  else\n  {\n    K::Point_2 p;\n    while(ifs >> p) {\n      mc.insert(p);\n      me.insert(p);\n      points.push_back(p);\n    }\n  }\n  update_from_points();\n\n  // default cursor\n  QApplication::restoreOverrideCursor();\n  this->addToRecentFiles(fileName);\n  actionRecenter->trigger();\n  Q_EMIT( changed());\n    \n}\n\nvoid\nMainWindow::on_actionSavePoints_triggered()\n{\n  QString fileName = QFileDialog::getSaveFileName(this,\n\t\t\t\t\t\t  tr(\"Save points\"),\n                                                  \".\",\n                                                  tr(\"CGAL files (*.pts.cgal);;\"\n                                                   #if BOOST_VERSION >= 105600 && (! defined(BOOST_GCC) || BOOST_GCC >= 40500)\n                                                     \"WKT files (*.WKT *.wkt);;\"\n                                                   #endif\n                                                     \"All files (*)\"));\n  if(! fileName.isEmpty()){\n    std::ofstream ofs(qPrintable(fileName));\n    if(fileName.endsWith(\".wkt\", Qt::CaseInsensitive))\n    {\n#if BOOST_VERSION >= 105600 && (! defined(BOOST_GCC) || BOOST_GCC >= 40500)\n      std::vector<K::Point_2> out_pts;\n      out_pts.reserve(std::distance(mc.points_begin(),\n                                    mc.points_end()));\n      for(Min_circle::Point_iterator pit = mc.points_begin();\n          pit != mc.points_end(); ++pit)\n        out_pts.push_back(*pit);\n      CGAL::write_multi_point_WKT(ofs, out_pts);\n#endif\n    }\n    else\n    {\n      for(Min_circle::Point_iterator  \n          vit = mc.points_begin(),\n          end = mc.points_end();\n          vit!= end; ++vit)\n      {\n        ofs << *vit << std::endl;\n      }\n    }\n  }\n}\n\n\nvoid\nMainWindow::on_actionRecenter_triggered()\n{\n  this->graphicsView->setSceneRect(cgi->boundingRect());\n  this->graphicsView->fitInView(cgi->boundingRect(), Qt::KeepAspectRatio);  \n}\n\n\n#include \"Bounding_volumes.moc\"\n#include <CGAL/Qt/resources.h>\n\nint main(int argc, char **argv)\n{\n  QApplication app(argc, argv);\n\n  app.setOrganizationDomain(\"geometryfactory.com\");\n  app.setOrganizationName(\"GeometryFactory\");\n  app.setApplicationName(\"Bounding_volumes demo\");\n\n  // Import resources from libCGAL (Qt5).\n  // See https://doc.qt.io/qt-5/qdir.html#Q_INIT_RESOURCE\n  CGAL_QT_INIT_RESOURCES;\n\n  MainWindow mainWindow;\n  mainWindow.show();\n  return app.exec();\n}\n", "meta": {"hexsha": "9cd70810ec04d624bd50a9c576fa866e15e5200a", "size": 15840, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CoreSystem/lib/CGAL/demo/Bounding_volumes/Bounding_volumes.cpp", "max_stars_repo_name": "josuehfa/DAASystem", "max_stars_repo_head_hexsha": "a1fe61ffc19f0781eeeddcd589137eefde078a45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-17T01:13:02.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-17T01:13:02.000Z", "max_issues_repo_path": "CoreSystem/lib/CGAL/demo/Bounding_volumes/Bounding_volumes.cpp", "max_issues_repo_name": "josuehfa/DAASystem", "max_issues_repo_head_hexsha": "a1fe61ffc19f0781eeeddcd589137eefde078a45", "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": "CoreSystem/lib/CGAL/demo/Bounding_volumes/Bounding_volumes.cpp", "max_forks_repo_name": "josuehfa/DAASystem", "max_forks_repo_head_hexsha": "a1fe61ffc19f0781eeeddcd589137eefde078a45", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-02T11:11:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-02T11:11:36.000Z", "avg_line_length": 26.6666666667, "max_line_length": 127, "alphanum_fraction": 0.65625, "num_tokens": 4178, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.8354835330070838, "lm_q1q2_score": 0.735891449342733}}
{"text": "#ifndef QUADRATIC_FORM_HPP\n#define QUADRATIC_FORM_HPP\n\n#include <Eigen/Dense>\n\n// quadraticform in three variables\nstruct QuadraticForm{\n    // x1, x2, x3\n    // A*x1*x1 + B*x1*x2 + C*x2*x2 + D*x1*x3 + E*x2*x3 + F*x3*x3 = 0\n    double A, B, C, D, E, F;\n    Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> eigensolver;\n    Eigen::Matrix3d mat;\n\n    QuadraticForm(double a, double b, double c, double d, double e, double f) :\n        A(a), B(b), C(c), D(d), E(e), F(f) {\n        mat << A, B/2, D/2,\n               B/2, C, E/2,\n               D/2, E/2, F;\n        eigensolver = Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d>(mat);\n    }\n\n    QuadraticForm& operator*=(double k) {\n        A*=k; B*=k; C*=k; D*=k; E*=k; F*=k;\n        Eigen::Matrix3d _mat;\n        _mat << A, B/2, D/2,\n                B/2, C, E/2,\n                D/2, E/2, F;\n        mat = _mat;\n        eigensolver = Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d>(mat);\n        return *this;\n    }\n\n    double evaluate(const Eigen::Vector3d& vec) {\n        return vec.transpose()*mat*vec;\n    }\n\n};\n\n#endif // QUADRATIC_FORM_HPP\n", "meta": {"hexsha": "204191fd1e65e3612a8549efa41c8e34b19bcbe9", "size": 1091, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "geometry/QuadraticForm.hpp", "max_stars_repo_name": "myirci/3d_circle_estimation", "max_stars_repo_head_hexsha": "7161005ab14d510503310e0bb028fea5ad2a1389", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-07-16T18:59:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T01:25:54.000Z", "max_issues_repo_path": "geometry/QuadraticForm.hpp", "max_issues_repo_name": "myirci/3d_circle_estimation", "max_issues_repo_head_hexsha": "7161005ab14d510503310e0bb028fea5ad2a1389", "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": "geometry/QuadraticForm.hpp", "max_forks_repo_name": "myirci/3d_circle_estimation", "max_forks_repo_head_hexsha": "7161005ab14d510503310e0bb028fea5ad2a1389", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-08T13:49:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-08T13:49:32.000Z", "avg_line_length": 27.275, "max_line_length": 79, "alphanum_fraction": 0.5472043996, "num_tokens": 375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475683211323, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.7358044009379938}}
{"text": "// The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt\n/*\n\n    This is an example illustrating the use the general purpose non-linear\n    optimization routines from the dlib C++ Library.\n\n    The library provides implementations of many popular algorithms such as L-BFGS\n    and BOBYQA.  These algorithms allow you to find the minimum or maximum of a\n    function of many input variables.  This example walks though a few of the ways\n    you might put these routines to use.\n\n*/\n\n\n#include <dlib/optimization.h>\n#include <dlib/global_optimization.h>\n#include <iostream>\n\n\nusing namespace std;\nusing namespace dlib;\n\n// ----------------------------------------------------------------------------------------\n\n// In dlib, most of the general purpose solvers optimize functions that take a\n// column vector as input and return a double.  So here we make a typedef for a\n// variable length column vector of doubles.  This is the type we will use to\n// represent the input to our objective functions which we will be minimizing.\ntypedef matrix<double,0,1> column_vector;\n\n// ----------------------------------------------------------------------------------------\n// Below we create a few functions.  When you get down into main() you will see that\n// we can use the optimization algorithms to find the minimums of these functions.\n// ----------------------------------------------------------------------------------------\n\ndouble rosen (const column_vector& m)\n/*\n    This function computes what is known as Rosenbrock's function.  It is \n    a function of two input variables and has a global minimum at (1,1).\n    So when we use this function to test out the optimization algorithms\n    we will see that the minimum found is indeed at the point (1,1). \n*/\n{\n    const double x = m(0); \n    const double y = m(1);\n\n    // compute Rosenbrock's function and return the result\n    return 100.0*pow(y - x*x,2) + pow(1 - x,2);\n}\n\n// This is a helper function used while optimizing the rosen() function.  \nconst column_vector rosen_derivative (const column_vector& m)\n/*!\n    ensures\n        - returns the gradient vector for the rosen function\n!*/\n{\n    const double x = m(0);\n    const double y = m(1);\n\n    // make us a column vector of length 2\n    column_vector res(2);\n\n    // now compute the gradient vector\n    res(0) = -400*x*(y-x*x) - 2*(1-x); // derivative of rosen() with respect to x\n    res(1) = 200*(y-x*x);              // derivative of rosen() with respect to y\n    return res;\n}\n\n// This function computes the Hessian matrix for the rosen() fuction.  This is\n// the matrix of second derivatives.\nmatrix<double> rosen_hessian (const column_vector& m)\n{\n    const double x = m(0);\n    const double y = m(1);\n\n    matrix<double> res(2,2);\n\n    // now compute the second derivatives \n    res(0,0) = 1200*x*x - 400*y + 2; // second derivative with respect to x\n    res(1,0) = res(0,1) = -400*x;   // derivative with respect to x and y\n    res(1,1) = 200;                 // second derivative with respect to y\n    return res;\n}\n\n// ----------------------------------------------------------------------------------------\n\nclass rosen_model \n{\n    /*!\n        This object is a \"function model\" which can be used with the\n        find_min_trust_region() routine.  \n    !*/\n\npublic:\n    typedef ::column_vector column_vector;\n    typedef matrix<double> general_matrix;\n\n    double operator() (\n        const column_vector& x\n    ) const { return rosen(x); }\n\n    void get_derivative_and_hessian (\n        const column_vector& x,\n        column_vector& der,\n        general_matrix& hess\n    ) const\n    {\n        der = rosen_derivative(x);\n        hess = rosen_hessian(x);\n    }\n};\n\n// ----------------------------------------------------------------------------------------\n\n\n\n#if defined(BUILD_MONOLITHIC)\n#define main(cnt, arr)      dlib_optimization_ex_main(cnt, arr)\n#endif\n\nint main(int argc, const char** argv)\ntry\n{\n    // Set the starting point to (4,8).  This is the point the optimization algorithm\n    // will start out from and it will move it closer and closer to the function's \n    // minimum point.   So generally you want to try and compute a good guess that is\n    // somewhat near the actual optimum value.\n    column_vector starting_point = {4, 8};\n\n    // The first example below finds the minimum of the rosen() function and uses the\n    // analytical derivative computed by rosen_derivative().  Since it is very easy to\n    // make a mistake while coding a function like rosen_derivative() it is a good idea\n    // to compare your derivative function against a numerical approximation and see if\n    // the results are similar.  If they are very different then you probably made a \n    // mistake.  So the first thing we do is compare the results at a test point: \n    cout << \"Difference between analytic derivative and numerical approximation of derivative: \" \n         << length(derivative(rosen)(starting_point) - rosen_derivative(starting_point)) << endl;\n\n\n    cout << \"Find the minimum of the rosen function()\" << endl;\n    // Now we use the find_min() function to find the minimum point.  The first argument\n    // to this routine is the search strategy we want to use.  The second argument is the \n    // stopping strategy.  Below I'm using the objective_delta_stop_strategy which just \n    // says that the search should stop when the change in the function being optimized \n    // is small enough.\n\n    // The other arguments to find_min() are the function to be minimized, its derivative, \n    // then the starting point, and the last is an acceptable minimum value of the rosen() \n    // function.  That is, if the algorithm finds any inputs to rosen() that gives an output \n    // value <= -1 then it will stop immediately.  Usually you supply a number smaller than \n    // the actual global minimum.  So since the smallest output of the rosen function is 0 \n    // we just put -1 here which effectively causes this last argument to be disregarded.\n\n    find_min(bfgs_search_strategy(),  // Use BFGS search algorithm\n             objective_delta_stop_strategy(1e-7), // Stop when the change in rosen() is less than 1e-7\n             rosen, rosen_derivative, starting_point, -1);\n    // Once the function ends the starting_point vector will contain the optimum point \n    // of (1,1).\n    cout << \"rosen solution:\\n\" << starting_point << endl;\n\n\n    // Now let's try doing it again with a different starting point and the version\n    // of find_min() that doesn't require you to supply a derivative function.  \n    // This version will compute a numerical approximation of the derivative since \n    // we didn't supply one to it.\n    starting_point = {-94, 5.2};\n    find_min_using_approximate_derivatives(bfgs_search_strategy(),\n                                           objective_delta_stop_strategy(1e-7),\n                                           rosen, starting_point, -1);\n    // Again the correct minimum point is found and stored in starting_point\n    cout << \"rosen solution:\\n\" << starting_point << endl;\n\n\n    // Here we repeat the same thing as above but this time using the L-BFGS \n    // algorithm.  L-BFGS is very similar to the BFGS algorithm, however, BFGS \n    // uses O(N^2) memory where N is the size of the starting_point vector.  \n    // The L-BFGS algorithm however uses only O(N) memory.  So if you have a \n    // function of a huge number of variables the L-BFGS algorithm is probably \n    // a better choice.\n    starting_point = {0.8, 1.3};\n    find_min(lbfgs_search_strategy(10),  // The 10 here is basically a measure of how much memory L-BFGS will use.\n             objective_delta_stop_strategy(1e-7).be_verbose(),  // Adding be_verbose() causes a message to be \n                                                                // printed for each iteration of optimization.\n             rosen, rosen_derivative, starting_point, -1);\n\n    cout << endl << \"rosen solution: \\n\" << starting_point << endl;\n\n    starting_point = {-94, 5.2};\n    find_min_using_approximate_derivatives(lbfgs_search_strategy(10),\n                                           objective_delta_stop_strategy(1e-7),\n                                           rosen, starting_point, -1);\n    cout << \"rosen solution: \\n\"<< starting_point << endl;\n\n\n\n\n    // dlib also supports solving functions subject to bounds constraints on\n    // the variables.  So for example, if you wanted to find the minimizer\n    // of the rosen function where both input variables were in the range\n    // 0.1 to 0.8 you would do it like this:\n    starting_point = {0.1, 0.1}; // Start with a valid point inside the constraint box.\n    find_min_box_constrained(lbfgs_search_strategy(10),  \n                             objective_delta_stop_strategy(1e-9),  \n                             rosen, rosen_derivative, starting_point, 0.1, 0.8);\n    // Here we put the same [0.1 0.8] range constraint on each variable, however, you\n    // can put different bounds on each variable by passing in column vectors of\n    // constraints for the last two arguments rather than scalars.  \n\n    cout << endl << \"constrained rosen solution: \\n\" << starting_point << endl;\n\n    // You can also use an approximate derivative like so:\n    starting_point = {0.1, 0.1}; \n    find_min_box_constrained(bfgs_search_strategy(),  \n                             objective_delta_stop_strategy(1e-9),  \n                             rosen, derivative(rosen), starting_point, 0.1, 0.8);\n    cout << endl << \"constrained rosen solution: \\n\" << starting_point << endl;\n\n\n\n\n    // In many cases, it is useful if we also provide second derivative information\n    // to the optimizers.  Two examples of how we can do that are shown below.  \n    starting_point = {0.8, 1.3};\n    find_min(newton_search_strategy(rosen_hessian),\n             objective_delta_stop_strategy(1e-7),\n             rosen,\n             rosen_derivative,\n             starting_point,\n             -1);\n    cout << \"rosen solution: \\n\"<< starting_point << endl;\n\n    // We can also use find_min_trust_region(), which is also a method which uses\n    // second derivatives.  For some kinds of non-convex function it may be more\n    // reliable than using a newton_search_strategy with find_min().\n    starting_point = {0.8, 1.3};\n    find_min_trust_region(objective_delta_stop_strategy(1e-7),\n                          rosen_model(), \n                          starting_point, \n                          10 // initial trust region radius\n    );\n    cout << \"rosen solution: \\n\"<< starting_point << endl;\n\n\n\n\n\n    // Next, let's try the BOBYQA algorithm.  This is a technique specially\n    // designed to minimize a function in the absence of derivative information.  \n    // Generally speaking, it is the method of choice if derivatives are not available\n    // and the function you are optimizing is smooth and has only one local optima.  As\n    // an example, consider the be_like_target function defined below:\n    column_vector target = {3, 5, 1, 7};\n    auto be_like_target = [&](const column_vector& x) {\n        return mean(squared(x-target));\n    };\n    starting_point = {-4,5,99,3};\n    find_min_bobyqa(be_like_target, \n                    starting_point, \n                    9,    // number of interpolation points\n                    uniform_matrix<double>(4,1, -1e100),  // lower bound constraint\n                    uniform_matrix<double>(4,1, 1e100),   // upper bound constraint\n                    10,    // initial trust region radius\n                    1e-6,  // stopping trust region radius\n                    100    // max number of objective function evaluations\n    );\n    cout << \"be_like_target solution:\\n\" << starting_point << endl;\n\n\n\n\n\n    // Finally, let's try the find_min_global() routine.  Like find_min_bobyqa(),\n    // this technique is specially designed to minimize a function in the absence\n    // of derivative information.  However, it is also designed to handle\n    // functions with many local optima.  Where BOBYQA would get stuck at the\n    // nearest local optima, find_min_global() won't.  find_min_global() uses a\n    // global optimization method based on a combination of non-parametric global\n    // function modeling and BOBYQA style quadratic trust region modeling to\n    // efficiently find a global minimizer.  It usually does a good job with a\n    // relatively small number of calls to the function being optimized.  \n    // \n    // You also don't have to give it a starting point or set any parameters,\n    // other than defining bounds constraints.  This makes it the method of\n    // choice for derivative free optimization in the presence of multiple local\n    // optima.  Its API also allows you to define functions that take a\n    // column_vector as shown above or to explicitly use named doubles as\n    // arguments, which we do here.\n    auto complex_holder_table = [](double x0, double x1)\n    {\n        // This function is a version of the well known Holder table test\n        // function, which is a function containing a bunch of local optima.\n        // Here we make it even more difficult by adding more local optima\n        // and also a bunch of discontinuities. \n\n        // add discontinuities\n        double sign = 1;\n        for (double j = -4; j < 9; j += 0.5)\n        {\n            if (j < x0 && x0 < j+0.5) \n                x0 += sign*0.25;\n            sign *= -1;\n        }\n        // Holder table function tilted towards 10,10 and with additional\n        // high frequency terms to add more local optima.\n        return -( std::abs(sin(x0)*cos(x1)*exp(std::abs(1-std::sqrt(x0*x0+x1*x1)/pi))) -(x0+x1)/10 - sin(x0*10)*cos(x1*10));\n    };\n\n    // To optimize this difficult function all we need to do is call\n    // find_min_global()\n    auto result = find_min_global(complex_holder_table, \n                                  {-10,-10}, // lower bounds\n                                  {10,10}, // upper bounds\n                                  std::chrono::milliseconds(500) // run this long\n                                  );\n\n    cout.precision(9);\n    // These cout statements will show that find_min_global() found the\n    // globally optimal solution to 9 digits of precision:\n    cout << \"complex holder table function solution y (should be -21.9210397): \" << result.y << endl;\n    cout << \"complex holder table function solution x:\\n\" << result.x << endl;\n}\ncatch (std::exception& e)\n{\n    cout << e.what() << endl;\n}\n\n", "meta": {"hexsha": "fefe76f578a320836d50cf122bfc7bc70a49aef5", "size": 14498, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/optimization_ex.cpp", "max_stars_repo_name": "GerHobbelt/dlib", "max_stars_repo_head_hexsha": "d26e917abc626fb81f0b57ecf1f3be555bddf8de", "max_stars_repo_licenses": ["BSL-1.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": "examples/optimization_ex.cpp", "max_issues_repo_name": "GerHobbelt/dlib", "max_issues_repo_head_hexsha": "d26e917abc626fb81f0b57ecf1f3be555bddf8de", "max_issues_repo_licenses": ["BSL-1.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": "examples/optimization_ex.cpp", "max_forks_repo_name": "GerHobbelt/dlib", "max_forks_repo_head_hexsha": "d26e917abc626fb81f0b57ecf1f3be555bddf8de", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.2012195122, "max_line_length": 124, "alphanum_fraction": 0.6320182094, "num_tokens": 3358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412808, "lm_q2_score": 0.8539127492339909, "lm_q1q2_score": 0.7356784670569144}}
{"text": "#ifndef MLT_MODELS_CLASSIFIERS_PERCEPTRON_HPP\n#define MLT_MODELS_CLASSIFIERS_PERCEPTRON_HPP\n\n#include <algorithm>\n#include <Eigen/Core>\n\n#include \"linear_classifier.hpp\"\n#include \"../../utils/linear_algebra.hpp\"\n\nnamespace mlt {\nnamespace models {\nnamespace classifiers {\ntemplate <class Rng>\nclass Perceptron : public LinearClassifier<Perceptron<Rng>> {\npublic:\n\ttemplate <class R, class = enable_if<is_same<decay_t<R>, Rng>::value>>\n\tPerceptron(size_t epochs,  bool shuffle, double learning_rate, bool fit_intercept, R&& rng) : LinearClassifier(fit_intercept),\n\t\t_epochs(epochs), _shuffle(shuffle), _learning_rate(learning_rate), _rng(forward<R>(rng)) {}\n\n\tSelf& fit(Features input, Target classes, bool cold_start = true) {\n\t\tauto n_classes = classes.maxCoeff() + 1;\n\t\tauto n_features = input.rows();\n\t\tauto n_samples = input.cols();\n\n\t\tMatrixXd current_coeffs = _fitted && !cold_start && num_classes() == n_classes ?\n\t\t                                coefficients() :\n\t\t                                (MatrixXd::Zero(n_classes, n_features + (fit_intercept() ? 1 : 0)) * 0.005);\n\n\t\tMatrixXd input_prime(input.rows() + (fit_intercept() ? 1 : 0), n_samples);\n\t\tinput_prime.topRows(input.rows()) << input;\n\n\t\tif (fit_intercept()) {\n\t\t\tinput_prime.bottomRows<1>() = VectorXd::Ones(n_samples);\n\t\t}\n\n\t\tvector<int> idxs;\n\t\tif (_shuffle) {\n\t\t\tidxs = vector<int>(n_samples);\n\t\t\tfor (auto i = 0; i < n_samples; i++) {\n\t\t\t\tidxs[i] = i;\n\t\t\t}\n\t\t}\n\n\t\tfor (auto epoch = 0; epoch < _epochs; epoch++) {\n\t\t\tif (_shuffle) {\n\t\t\t\tshuffle(idxs.begin(), idxs.end(), _rng);\n\t\t\t}\n\n\t\t\tfor (auto i = 0; i < n_samples; i++) {\n\t\t\t\tauto idx = _shuffle ? idxs[i] : i;\n\n\t\t\t\tauto f = input.col(idx).eval();\n\t\t\t\tauto t = classes(idx);\n\t\t\t\tauto y = max_row(_apply_linear_transformation(f, current_coeffs));\n\n\t\t\t\tif (t != y) {\n\t\t\t\t\tauto f_t = f.transpose().eval();\n\t\t\t\t\tcurrent_coeffs.block(y, 0, 1, n_features) -= _learning_rate * f_t;\n\t\t\t\t\tcurrent_coeffs.block(t, 0, 1, n_features) += _learning_rate * f_t;\n\n\t\t\t\t\tif (fit_intercept()) {\n\t\t\t\t\t\tcurrent_coeffs(y, n_classes) -= 1;\n\t\t\t\t\t\tcurrent_coeffs(t, n_classes) += 1;\n\t\t\t\t\t}\t\t\t\t\t\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t_set_coefficients(current_coeffs);\n\n\t\treturn *this;\n\t}\n\nprotected:\n\tsize_t _epochs;\n\tbool _shuffle;\n\tdouble _learning_rate;\n\tRng& _rng;\n};\n\n\ttemplate <class R = default_random_engine>\n\tauto create_perceptron(size_t epoch = 100, bool shuffle = true, double learning_rate = 0.001, bool fit_intercept = true, R&& rng = default_random_engine()) {\n\t\treturn Perceptron<R>(epoch, shuffle, learning_rate, fit_intercept, forward<R>(rng));\n\t}\n}\n}\n}\n#endif", "meta": {"hexsha": "6d20dd34ecb46efe26916d4a410321766498ab4f", "size": 2563, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/mlt/models/classifiers/perceptron.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/models/classifiers/perceptron.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/models/classifiers/perceptron.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": 29.125, "max_line_length": 158, "alphanum_fraction": 0.6586031994, "num_tokens": 719, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582593509314, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.7355554688653623}}
{"text": "/***************************************************************************\r\n/* Javier Juan Albarracin - jajuaal1@ibime.upv.es                         */\r\n/* Universidad Politecnica de Valencia, Spain                             */\r\n/*                                                                        */\r\n/* Copyright (C) 2014 Javier Juan Albarracin                              */\r\n/*                                                                        */\r\n/***************************************************************************\r\n* Principal Component Analysis                                             *\r\n***************************************************************************/\r\n\r\n#ifndef PRINCIPALCOMPONENTANALYSIS_HPP\r\n#define PRINCIPALCOMPONENTANALYSIS_HPP\r\n\r\n#include <Eigen/Dense>\r\n#include <Eigen/Eigenvalues>\r\n#include <omp.h>\r\n\r\nusing namespace Eigen;\r\n\r\nclass PrincipalComponentAnalysis\r\n{\r\npublic:\r\n    PrincipalComponentAnalysis();\r\n    \r\n    template <class Derived>\r\n    void compute(const MatrixBase<Derived> &dataset, const bool zscores = false);\r\n    template <class Derived>\r\n    MatrixXd dimensionalityReductionComponents(const MatrixBase<Derived> &dataset, const unsigned int components);\r\n    template <class Derived>\r\n    MatrixXd dimensionalityReductionVarianceExplained(const MatrixBase<Derived> &dataset, const double varianceExplained, const unsigned int minComponents = 0, const unsigned int maxComponents = 0);\r\n    template <class Derived>\r\n    Matrix<typename Derived::Scalar, Dynamic, Dynamic> filteringComponents(const MatrixBase<Derived> &dataset, const unsigned int components);\r\n    template <class Derived>\r\n    Matrix<typename Derived::Scalar, Dynamic, Dynamic> filteringVarianceExplained(const MatrixBase<Derived> &dataset, const double varianceExplained, const unsigned int minComponents = 0, const unsigned int maxComponents = 0);\r\n    \r\n    MatrixXd scores() const { return m_scores; }\r\n    MatrixXd coefficients() const { return m_coefficients; }\r\n    VectorXd latent() const { return m_latent; }\r\n    VectorXd explained() const { return m_explained; }\r\n    RowVectorXd mu() const { return m_mu; } \r\n    unsigned int components() const { return m_components; }\r\n    \r\nprivate:\r\n    MatrixXd m_scores;\r\n    MatrixXd m_coefficients;\r\n    VectorXd m_latent;\r\n    VectorXd m_explained;\r\n    RowVectorXd m_mu;\r\n    unsigned int m_components;\r\n    SelfAdjointEigenSolver<MatrixXd> m_solver;\r\n};\r\n\r\n/***************************** Implementation *****************************/\r\n\r\nPrincipalComponentAnalysis::PrincipalComponentAnalysis()\r\n: m_scores(MatrixXd()), m_coefficients(MatrixXd()), m_latent(VectorXd()), m_explained(VectorXd()), m_mu(RowVectorXd()), m_components(0)\r\n{\r\n}\r\n\r\ntemplate<class Derived>\r\nvoid PrincipalComponentAnalysis::compute(const MatrixBase<Derived> &dataset, const bool zscores)\r\n{\r\n    // Check extreme case\r\n    if (dataset.rows() == 1)    \r\n    {\r\n        m_latent = VectorXd::Ones(1);\r\n        m_explained = m_latent / m_latent.sum();\r\n        m_coefficients = MatrixXd::Ones(dataset.cols(), 1);\r\n        m_scores = dataset.template cast<double>() * m_coefficients;\r\n        return;\r\n    }\r\n    \r\n    // Subtract mean of each variable\r\n    m_mu = dataset.template cast<double>().colwise().mean();\r\n    MatrixXd centered = dataset.template cast<double>().rowwise() - m_mu;\r\n    \r\n    // Standarize std if required\r\n    if (zscores)\r\n    {\r\n        RowVectorXd stdScaling = (centered.cwiseProduct(centered).colwise().sum() / (double) (dataset.rows() - 1)).cwiseSqrt();\r\n        #pragma omp parallel for\r\n        for (int i = 0; i < centered.rows(); ++i)\r\n            centered.row(i) = centered.row(i).cwiseQuotient(stdScaling);\r\n    }\r\n    \r\n    // Compute the covariance matrix.\r\n    MatrixXd covarianceMatrix = (centered.transpose() * centered) / (double)(dataset.rows() - 1);\r\n\r\n    // Compute Singular Value Decomposition\r\n    m_solver.compute(covarianceMatrix);\r\n    \r\n    // Store results\r\n    m_latent = m_solver.eigenvalues();\r\n    m_explained = m_latent / m_latent.sum();\r\n    m_coefficients = m_solver.eigenvectors();\r\n    m_scores = centered * m_coefficients;\r\n}\r\n\r\ntemplate<class Derived>\r\nMatrixXd PrincipalComponentAnalysis::dimensionalityReductionComponents(const MatrixBase<Derived> &dataset, const unsigned int components)\r\n{\r\n    // Compute PCA\r\n    compute(dataset);\r\n    \r\n    // Get the dataset in the new components dimensional space\r\n    m_components = components;\r\n    return m_scores.rightCols(components);\r\n}\r\n\r\ntemplate<typename  Derived>\r\nMatrixXd PrincipalComponentAnalysis::dimensionalityReductionVarianceExplained(const MatrixBase<Derived> &dataset, const double varianceExplained, const unsigned int minComponents, const unsigned int maxComponents)\r\n{\r\n    // Compute PCA\r\n    compute(dataset);\r\n    \r\n    // Get components to explain at least <varianceExplained>\r\n    m_components = 0;\r\n    double cumsum = 0;\r\n    for (int i = m_explained.size() - 1; i >= 0; --i)\r\n    {\r\n        m_components++;\r\n        cumsum += m_explained(i);\r\n        if (cumsum > varianceExplained)\r\n            break;\r\n    }\r\n    if (minComponents != 0)\r\n        m_components = m_components < minComponents ? minComponents : m_components;\r\n    if (maxComponents != 0)\r\n        m_components = m_components > maxComponents ? maxComponents : m_components;\r\n    \r\n    // Get the dataset in the new components dimensional space\r\n    return m_scores.rightCols(m_components);\r\n}\r\n\r\ntemplate <typename  Derived>\r\nMatrix<typename Derived::Scalar, Dynamic, Dynamic> PrincipalComponentAnalysis::filteringComponents(const MatrixBase<Derived> &dataset, const unsigned int components)\r\n{\r\n    // Compute PCA\r\n    compute(dataset);\r\n\r\n    // Rebuild dataset with components\r\n    m_components = components;\r\n    MatrixXd filteredDataset = (m_scores.rightCols(m_components) * m_coefficients.rightCols(m_components).transpose());\r\n    filteredDataset = filteredDataset.rowwise() + m_mu;\r\n\r\n    return filteredDataset.cast<Derived::Scalar>();\r\n}\r\n\r\ntemplate <typename  Derived>\r\nMatrix<typename Derived::Scalar, Dynamic, Dynamic> PrincipalComponentAnalysis::filteringVarianceExplained(const MatrixBase<Derived> &dataset, const double varianceExplained, const unsigned int minComponents, const unsigned int maxComponents)\r\n{\r\n    // Compute PCA\r\n    compute(dataset);\r\n\r\n    // Get components to explain at least <varianceExplained>\r\n    m_components = 0;\r\n    double cumsum = 0;\r\n    for (int i = m_explained.size() - 1; i >= 0; i--)\r\n    {\r\n        m_components++;\r\n        cumsum += m_explained(i);\r\n        if (cumsum > varianceExplained)\r\n            break;\r\n    }\r\n    if (minComponents != 0)\r\n        m_components = m_components < minComponents ? minComponents : m_components;\r\n    if (maxComponents != 0)\r\n        m_components = m_components > maxComponents ? maxComponents : m_components;\r\n\r\n    // Rebuild dataset with components\r\n    MatrixXd filteredDataset = m_scores.rightCols(m_components) * m_coefficients.rightCols(m_components).transpose();\r\n    filteredDataset = filteredDataset.rowwise() + m_mu;\r\n\r\n    return filteredDataset.cast<typename Derived::Scalar>();\r\n}\r\n\r\n#endif", "meta": {"hexsha": "c34a83fba5db3464bb3a0cea33f0785bd301b839", "size": 7164, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "PrincipalComponentAnalysis.hpp", "max_stars_repo_name": "javierjuan/decomposition", "max_stars_repo_head_hexsha": "cc9c1ed51e915847f4e7b5e26d3e130e89d88473", "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": "PrincipalComponentAnalysis.hpp", "max_issues_repo_name": "javierjuan/decomposition", "max_issues_repo_head_hexsha": "cc9c1ed51e915847f4e7b5e26d3e130e89d88473", "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": "PrincipalComponentAnalysis.hpp", "max_forks_repo_name": "javierjuan/decomposition", "max_forks_repo_head_hexsha": "cc9c1ed51e915847f4e7b5e26d3e130e89d88473", "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": 40.4745762712, "max_line_length": 242, "alphanum_fraction": 0.6411222781, "num_tokens": 1498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308165850442, "lm_q2_score": 0.7879311906630568, "lm_q1q2_score": 0.7354792547134433}}
{"text": "#include \"LinearRegression.h\"\n#include \"TrainingType.h\"\n#include <armadillo>\n#include <assert.h>\n#include <iostream>\n\nusing namespace arma;\n\nLinearRegression::LinearRegression(mat &x, vec &y, double regPara)\n    : x{x}, y{y}, trained{false}, regPara{regPara} {\n  assert(x.n_rows == y.n_rows);\n\n  // Create bias column and append at the end of  x\n  mat bias = ones<mat>(this->ExampleNumber(), 1);\n  this->x.insert_cols(0, bias);\n}\n\nLinearRegression::~LinearRegression() {}\n\nvoid LinearRegression::AddData(mat &extraX, vec &extraY) {\n  assert(extraX.n_rows == extraY.n_rows);\n  // Add 1 because x has a bias column\n  assert((extraX.n_cols + 1) == this->x.n_cols);\n\n  this->trained = false;\n  // Add Bias column to latest added input\n  mat bias = ones<mat>(extraX.n_rows, 1);\n  mat inputX = extraX;\n  inputX.insert_cols(0, bias);\n  this->x.insert_rows(this->x.n_rows, inputX);\n  this->y.insert_rows(this->y.n_rows, extraY);\n}\n\nvoid LinearRegression::Train(TrainingType Type, double alpha,\n                             unsigned int iters) {\n  if (Type == normalEquation) {\n    this->NormalEquation();\n  } else if (Type == gradientDescent) {\n    this->GradientDescent(alpha, iters);\n  } else {\n    std::cerr << \"Invalid training type\" << std::endl;\n  }\n}\n\nvoid LinearRegression::NormalEquation() {\n  mat xtx = (this->x.t() * this->x);\n  mat L = eye<mat>(xtx.n_rows, xtx.n_cols);\n  L[0] = 0;\n  // Check if xtx is full-rank matrix\n  if (rank(xtx) == xtx.n_rows || this->regPara > 0) {\n    this->theta = pinv(xtx - (this->regPara * L)) * this->x.t() * this->y;\n    this->trained = true;\n  } else {\n    std::cerr << \"you have to regularize your data set\" << std::endl;\n  }\n}\n\nuword LinearRegression::ExampleNumber() { return this->x.n_rows; }\n\ndouble LinearRegression::Predict(vec &x) {\n  if (!this->trained) {\n    std::cerr << \"This model hasn't been trained\" << std::endl;\n    return 0.0;\n  }\n  vec bias = vec(\"1\");\n  vec input = x;\n  input.insert_rows(0, bias);\n  return (input.t() * this->theta).eval()(0, 0);\n}\n\nvec LinearRegression::CostDerivative() {\n  vec deriv = (((this->x * this->theta) - this->y).t() * this->x).t();\n  vec thetaWithoutFirst = this->theta;\n  thetaWithoutFirst[0] = 0;\n  return 1 / (double)this->ExampleNumber() * deriv +\n         this->regPara / (double)this->ExampleNumber() * thetaWithoutFirst;\n}\n\ndouble LinearRegression::SelfCost() { return this->Cost(this->x); }\n\ndouble LinearRegression::Cost(mat &inputX) {\n  this->InitializeTheta();\n  //--J(Theta) = 1/2m * (X Theta - y)^T (X Theta - y) + lambda theta^2--//\n  assert(inputX.n_cols == this->theta.n_rows);\n  vec ve = (inputX * this->theta) - this->y;\n  vec thetaWithoutFirst = this->theta;\n  thetaWithoutFirst[0] = 0;\n  return (((float)1 / 2) * this->ExampleNumber() * ve.t() * ve +\n          this->regPara * thetaWithoutFirst.t() * thetaWithoutFirst)\n      .eval()(0, 0);\n}\n\nvoid LinearRegression::GradientDescent(double alpha, unsigned int iters) {\n  this->InitializeTheta();\n  for (unsigned int i = 0; i < iters; i++) {\n    this->theta = this->theta - (alpha * this->CostDerivative());\n  }\n\n  this->trained = true;\n}\n\nvoid LinearRegression::InitializeTheta() {\n  if (this->trained != true || this->theta.n_rows != this->x.n_cols) {\n    // Initialize Theta\n    this->theta = zeros<vec>(this->x.n_cols);\n  }\n}\n", "meta": {"hexsha": "5f8d1bd92f525100eb2a90b316ca1845c6d5b229", "size": 3287, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/LinearModel/LinearRegression.cc", "max_stars_repo_name": "Gh0u1L5/Cetus", "max_stars_repo_head_hexsha": "979a13db4f6837e845fd5f540f7a710d0256dd9a", "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/LinearModel/LinearRegression.cc", "max_issues_repo_name": "Gh0u1L5/Cetus", "max_issues_repo_head_hexsha": "979a13db4f6837e845fd5f540f7a710d0256dd9a", "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/LinearModel/LinearRegression.cc", "max_forks_repo_name": "Gh0u1L5/Cetus", "max_forks_repo_head_hexsha": "979a13db4f6837e845fd5f540f7a710d0256dd9a", "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.4351851852, "max_line_length": 75, "alphanum_fraction": 0.6394888956, "num_tokens": 982, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505453836383, "lm_q2_score": 0.8128673201042493, "lm_q1q2_score": 0.7353608644568457}}
{"text": "#include <Eigen/Core>\n#include <iostream>\n#include <LBFGS.h>\n\nusing Eigen::VectorXd;\nusing Eigen::MatrixXd;\nusing namespace LBFGSpp;\n\ndouble foo(const VectorXd& x, VectorXd& grad)\n{\n    const int n = x.size();\n    VectorXd d(n);\n    for(int i = 0; i < n; i++)\n        d[i] = i;\n\n    double f = (x - d).squaredNorm();\n    grad.noalias() = 2.0 * (x - d);\n    return f;\n}\n\nint main()\n{\n    const int n = 10;\n    LBFGSParam<double> param;\n    LBFGSSolver<double> solver(param);\n\n    VectorXd x = VectorXd::Zero(n);\n    double fx;\n    int niter = solver.minimize(foo, x, fx);\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": "ae98d8d9930381a30ebff3acb24c8f0ce57c9f99", "size": 747, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "third_party/lbfgs/example-quadratic.cpp", "max_stars_repo_name": "hcyang99/horovod", "max_stars_repo_head_hexsha": "825cc197468548da47dcd38872d5b4ba6e6a125b", "max_stars_repo_licenses": ["Apache-2.0"], "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": "third_party/lbfgs/example-quadratic.cpp", "max_issues_repo_name": "hcyang99/horovod", "max_issues_repo_head_hexsha": "825cc197468548da47dcd38872d5b4ba6e6a125b", "max_issues_repo_licenses": ["Apache-2.0"], "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": "third_party/lbfgs/example-quadratic.cpp", "max_forks_repo_name": "hcyang99/horovod", "max_forks_repo_head_hexsha": "825cc197468548da47dcd38872d5b4ba6e6a125b", "max_forks_repo_licenses": ["Apache-2.0"], "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": 20.1891891892, "max_line_length": 56, "alphanum_fraction": 0.5635876841, "num_tokens": 236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008904, "lm_q2_score": 0.8128673087708699, "lm_q1q2_score": 0.7353608458455881}}
{"text": "#include <mitsuba/core/quad.h>\n#include <boost/bind.hpp>\n\nMTS_NAMESPACE_BEGIN\n\nfloat legendreP(int l, float x_) {\n\tSAssert(l >= 0);\n\n\tif (l == 0) {\n\t\treturn (float) 1.0f;\n\t} else if (l == 1) {\n\t\treturn x_;\n\t} else {\n\t\t/* Evaluate the recurrence in double precision */\n\t\tdouble x = (double) x_;\n\t\tdouble Lppred = 1.0, Lpred = x, Lcur = 0.0;\n\n\t\tfor (int k = 2; k <= l; ++k) {\n\t\t\tLcur = ((2*k-1) * x * Lpred - (k - 1) * Lppred) / k;\n\t\t\tLppred = Lpred; Lpred = Lcur;\n\t\t}\n\n\t\treturn (float) Lcur;\n\t}\n}\n\ndouble legendreP(int l, double x) {\n\tSAssert(l >= 0);\n\n\tif (l == 0) {\n\t\treturn (double) 1.0f;\n\t} else if (l == 1) {\n\t\treturn x;\n\t} else {\n\t\tdouble Lppred = 1.0, Lpred = x, Lcur = 0.0;\n\n\t\tfor (int k = 2; k <= l; ++k) {\n\t\t\tLcur = ((2*k-1) * x * Lpred - (k - 1) * Lppred) / k;\n\t\t\tLppred = Lpred; Lpred = Lcur;\n\t\t}\n\n\t\treturn Lcur;\n\t}\n}\n\nstd::pair<float, float> legendrePD(int l, float x_) {\n\tSAssert(l >= 0);\n\n\tif (l == 0) {\n\t\treturn std::make_pair((float) 1.0f, (float) 0.0f);\n\t} else if (l == 1) {\n\t\treturn std::make_pair(x_, (float) 1.0f);\n\t} else {\n\t\t/* Evaluate the recurrence in double precision */\n\t\tdouble x = (double) x_;\n\t\tdouble Lppred = 1.0, Lpred = x, Lcur = 0.0,\n\t\t       Dppred = 0.0, Dpred = 1.0, Dcur = 0.0;\n\n\t\tfor (int k = 2; k <= l; ++k) {\n\t\t\tLcur = ((2*k-1) * x * Lpred - (k - 1) * Lppred) / k;\n\t\t\tDcur = Dppred + (2*k-1) * Lpred;\n\t\t\tLppred = Lpred; Lpred = Lcur;\n\t\t\tDppred = Dpred; Dpred = Dcur;\n\t\t}\n\n\t\treturn std::make_pair((float) Lcur, (float) Dcur);\n\t}\n}\n\nstd::pair<double, double> legendrePD(int l, double x) {\n\tSAssert(l >= 0);\n\n\tif (l == 0) {\n\t\treturn std::make_pair(1.0, 0.0);\n\t} else if (l == 1) {\n\t\treturn std::make_pair(x, 1.0);\n\t} else {\n\t\tdouble Lppred = 1.0, Lpred = x, Lcur = 0.0,\n\t\t       Dppred = 0.0, Dpred = 1.0, Dcur = 0.0;\n\n\t\tfor (int k = 2; k <= l; ++k) {\n\t\t\tLcur = ((2*k-1) * x * Lpred - (k - 1) * Lppred) / k;\n\t\t\tDcur = Dppred + (2*k-1) * Lpred;\n\t\t\tLppred = Lpred; Lpred = Lcur;\n\t\t\tDppred = Dpred; Dpred = Dcur;\n\t\t}\n\n\t\treturn std::make_pair(Lcur, Dcur);\n\t}\n}\n\n/// Evaluate the function legendrePD(l+1, x) - legendrePD(l-1, x)\nstatic std::pair<double, double> legendreQ(int l, double x) {\n\tSAssert(l >= 1);\n\n\tif (l == 1) {\n\t\treturn std::make_pair(0.5 * (3*x*x-1) - 1, 3*x);\n\t} else {\n\t\t/* Evaluate the recurrence in double precision */\n\t\tdouble Lppred = 1.0, Lpred = x, Lcur = 0.0,\n\t\t       Dppred = 0.0, Dpred = 1.0, Dcur = 0.0;\n\n\t\tfor (int k = 2; k <= l; ++k) {\n\t\t\tLcur = ((2*k-1) * x * Lpred - (k-1) * Lppred) / k;\n\t\t\tDcur = Dppred + (2*k-1) * Lpred;\n\t\t\tLppred = Lpred; Lpred = Lcur;\n\t\t\tDppred = Dpred; Dpred = Dcur;\n\t\t}\n\n\t\tdouble Lnext = ((2*l+1) * x * Lpred - l * Lppred) / (l+1);\n\t\tdouble Dnext = Dppred + (2*l+1) * Lpred;\n\n\t\treturn std::make_pair(Lnext - Lppred, Dnext - Dppred);\n\t}\n}\n\ndouble legendreP(int l, int m, double x) {\n\tdouble p_mm = 1;\n\n\tif (m > 0) {\n\t\tdouble somx2 = std::sqrt((1 - x) * (1 + x));\n\t\tdouble fact = 1;\n\t\tfor (int i=1; i<=m; i++) {\n\t\t\tp_mm *= (-fact) * somx2;\n\t\t\tfact += 2;\n\t\t}\n\t}\n\n\tif (l == m)\n\t\treturn p_mm;\n\n\tdouble p_mmp1 = x * (2*m + 1) * p_mm;\n\tif (l == m+1)\n\t\treturn p_mmp1;\n\n\tdouble p_ll = 0;\n\tfor (int ll=m+2; ll <= l; ++ll) {\n\t\tp_ll = ((2*ll-1)*x*p_mmp1 - (ll+m-1) * p_mm) / (ll-m);\n\t\tp_mm = p_mmp1;\n\t\tp_mmp1 = p_ll;\n\t}\n\n\treturn p_ll;\n}\n\nfloat legendreP(int l, int m, float x) {\n\t/* Evaluate the recurrence in double precision */\n\tdouble p_mm = 1;\n\n\tif (m > 0) {\n\t\tdouble somx2 = std::sqrt((1 - x) * (1 + x));\n\t\tdouble fact = 1;\n\t\tfor (int i=1; i<=m; i++) {\n\t\t\tp_mm *= (-fact) * somx2;\n\t\t\tfact += 2;\n\t\t}\n\t}\n\n\tif (l == m)\n\t\treturn (float) p_mm;\n\n\tdouble p_mmp1 = x * (2*m + 1) * p_mm;\n\tif (l == m+1)\n\t\treturn (float) p_mmp1;\n\n\tdouble p_ll = 0;\n\tfor (int ll=m+2; ll <= l; ++ll) {\n\t\tp_ll = ((2*ll-1)*x*p_mmp1 - (ll+m-1) * p_mm) / (ll-m);\n\t\tp_mm = p_mmp1;\n\t\tp_mmp1 = p_ll;\n\t}\n\n\treturn (float) p_ll;\n}\n\nvoid gaussLegendre(int n, Float *nodes, Float *weights) {\n\tif (n-- < 1)\n\t\tSLog(EError, \"gaussLegendre(): n must be >= 1\");\n\n\tif (n == 0) {\n\t\tnodes[0] = 0;\n\t\tweights[0] = 2;\n\t} else if (n == 1) {\n\t\tnodes[0] = (Float) -std::sqrt(1.0/3.0);\n\t\tnodes[1] = -nodes[0];\n\t\tweights[0] = weights[1] = 1;\n\t}\n\n\tint m = (n+1)/2;\n\tfor (int i=0; i<m; ++i) {\n\t\t/* Initial guess for this root using that of a Chebyshev polynomial */\n\n\t\tdouble x = -std::cos((double) (2*i + 1) / (double) (2*n + 2) * M_PI);\n\t\tint it = 0;\n\n\t\twhile (true) {\n\t\t\tif (++it > 20)\n\t\t\t\tSLog(EError, \"gaussLegendre(%i): did not converge after 20 iterations!\", n);\n\n\t\t\t/* Search for the interior roots of P_{n+1}(x) using Newton's method. */\n\t\t\tstd::pair<double, double> L = legendrePD(n+1, x);\n\t\t\tdouble step = L.first / L.second;\n\t\t\tx -= step;\n\n\t\t\tif (std::abs(step) <= 4 * std::abs(x) * std::numeric_limits<double>::epsilon())\n\t\t\t\tbreak;\n\t\t}\n\n\t\tstd::pair<double, double> L = legendrePD(n+1, x);\n\t\tweights[i] = weights[n-i] = (Float) (2.0 / ((1-x*x) * (L.second*L.second)));\n\t\tnodes[i] = (Float) x; nodes[n-i] = (Float) -x;\n\t\tSAssert(i == 0 || x > nodes[i-1]);\n\t}\n\n\tif ((n % 2) == 0) {\n\t\tstd::pair<double, double> L = legendrePD(n+1, 0.0);\n\t\tweights[n/2] = (Float) (2.0 / (L.second*L.second));\n\t\tnodes[n/2] = 0;\n\t}\n}\n\nvoid gaussLobatto(int n, Float *nodes, Float *weights) {\n\tif (n-- < 2)\n\t\tSLog(EError, \"gaussLobatto(): n must be >= 2\");\n\n\tnodes[0] = -1;\n\tnodes[n] =  1;\n\tweights[0] = weights[n] = (Float) 2 / (Float) (n * (n+1));\n\n\tint m = (n+1)/2;\n\tfor (int i=1; i<m; ++i) {\n\t\t/* Initial guess for this root -- see \"On the Legendre-Gauss-Lobatto Points\n\t\t   and Weights\" by Seymor V. Parter, Journal of Sci. Comp., Vol. 14, 4, 1999 */\n\n\t\tdouble x = -std::cos((i + 0.25) * M_PI / n - 3/(8*n*M_PI * (i + 0.25)));\n\t\tint it = 0;\n\n\t\twhile (true) {\n\t\t\tif (++it > 20)\n\t\t\t\tSLog(EError, \"gaussLobatto(%i): did not converge after 20 iterations!\", n);\n\n\t\t\t/* Search for the interior roots of P_n'(x) using Newton's method. The same\n\t\t\t   roots are also shared by P_{n+1}-P_{n-1}, which is nicer to evaluate. */\n\n\t\t\tstd::pair<double, double> Q = legendreQ(n, x);\n\t\t\tdouble step = Q.first / Q.second;\n\t\t\tx -= step;\n\n\t\t\tif (std::abs(step) <= 4 * std::abs(x) * std::numeric_limits<double>::epsilon())\n\t\t\t\tbreak;\n\t\t}\n\n\t\tdouble Ln = legendreP(n, x);\n\t\tweights[i] = weights[n-i] = (Float) (2.0 / ((n * (n+1)) * Ln * Ln));\n\t\tnodes[i] = (Float) x; nodes[n-i] = (Float) -x;\n\t\tSAssert(x > nodes[i-1]);\n\t}\n\n\tif ((n % 2) == 0) {\n\t\tdouble Ln = legendreP(n, 0.0);\n\t\tweights[n/2] = (Float) (2.0 / ((n * (n+1)) * Ln * Ln));\n\t\tnodes[n/2] = 0.0;\n\t}\n}\n\n\n/*!\n \\brief integral of a one-dimensional function using an adaptive\n Gauss-Lobatto integral\n\n Copyright (C) 2008 Klaus Spanderen\n\n This code is based on code in QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE. See the license for more details.\n*/\n\nconst Float GaussLobattoIntegrator::m_alpha = (Float) std::sqrt(2.0/3.0);\nconst Float GaussLobattoIntegrator::m_beta  = (Float) (1.0/std::sqrt(5.0));\nconst Float GaussLobattoIntegrator::m_x1\t= (Float) 0.94288241569547971906;\nconst Float GaussLobattoIntegrator::m_x2\t= (Float) 0.64185334234578130578;\nconst Float GaussLobattoIntegrator::m_x3\t= (Float) 0.23638319966214988028;\n\nGaussLobattoIntegrator::GaussLobattoIntegrator(size_t maxEvals,\n\tFloat absError, Float relError, bool useConvergenceEstimate, bool warn)\n\t: m_absError(absError),\n\t  m_relError(relError),\n\t  m_maxEvals(maxEvals),\n\t  m_useConvergenceEstimate(useConvergenceEstimate),\n      m_warn(warn) {\n\tif (m_absError == 0 && m_relError == 0)\n\t\tSLog(EError, \"GaussLobattoIntegrator:: Absolute and relative \"\n\t\t\t\"error requirements can't both be zero!\");\n}\n\nFloat GaussLobattoIntegrator::integrate(\n\t\tconst boost::function<Float (Float)>& f, Float a, Float b, size_t *_evals) const {\n\tFloat factor = 1;\n\tsize_t evals = 0;\n\tif (a == b) {\n\t\treturn 0;\n\t} else if (b < a) {\n\t\tstd::swap(a, b);\n\t\tfactor = -1;\n\t}\n\tconst Float absTolerance = calculateAbsTolerance(f, a, b, evals);\n\tevals += 2;\n\tFloat result = factor * adaptiveGaussLobattoStep(f, a, b, f(a), f(b), absTolerance, evals);\n\tif (evals >= m_maxEvals && m_warn)\n\t\tSLog(EWarn, \"GaussLobattoIntegrator: Maximum number of evaluations reached!\");\n\tif (_evals)\n\t\t*_evals = evals;\n\treturn result;\n}\n\nFloat GaussLobattoIntegrator::calculateAbsTolerance(\n\t\tconst boost::function<Float (Float)>& f, Float a, Float b, size_t &evals) const {\n\tconst Float m = (a+b)/2;\n\tconst Float h = (b-a)/2;\n\tconst Float y1 = f(a);\n\tconst Float y3 = f(m-m_alpha*h);\n\tconst Float y5 = f(m-m_beta*h);\n\tconst Float y7 = f(m);\n\tconst Float y9 = f(m+m_beta*h);\n\tconst Float y11= f(m+m_alpha*h);\n\tconst Float y13= f(b);\n\n\tFloat acc = h*((Float) 0.0158271919734801831*(y1+y13)\n\t\t\t\t + (Float) 0.0942738402188500455*(f(m-m_x1*h)+f(m+m_x1*h))\n\t\t\t\t + (Float) 0.1550719873365853963*(y3+y11)\n\t\t\t\t + (Float) 0.1888215739601824544*(f(m-m_x2*h)+ f(m+m_x2*h))\n\t\t\t\t + (Float) 0.1997734052268585268*(y5+y9)\n\t\t\t\t + (Float) 0.2249264653333395270*(f(m-m_x3*h)+f(m+m_x3*h))\n\t\t\t\t + (Float) 0.2426110719014077338*y7);\n\tevals += 13;\n\n\tFloat r = 1.0;\n\tif (m_useConvergenceEstimate) {\n\t\tconst Float integral2 = (h/6)*(y1+y13+5*(y5+y9));\n\t\tconst Float integral1 = (h/1470)*\n\t\t\t(77*(y1+y13) + 432*(y3+y11) + 625*(y5+y9) + 672*y7);\n\n\t\tif (std::abs(integral2-acc) != 0.0)\n\t\t\tr = std::abs(integral1-acc)/std::abs(integral2-acc);\n\t\tif (r == 0.0 || r > 1.0)\n\t\t\tr = 1.0;\n\t}\n\tFloat result = std::numeric_limits<Float>::infinity();\n\n\tif (m_relError != 0 && acc != 0)\n\t\tresult = acc * std::max(m_relError,\n\t\t\tstd::numeric_limits<Float>::epsilon())\n\t\t\t/ (r*std::numeric_limits<Float>::epsilon());\n\n\tif (m_absError != 0)\n\t\tresult = std::min(result, m_absError\n\t\t\t/ (r*std::numeric_limits<Float>::epsilon()));\n\n\treturn result;\n}\n\nFloat GaussLobattoIntegrator::adaptiveGaussLobattoStep(\n\t\t\t\t\t\t\t\t const boost::function<Float (Float)>& f,\n\t\t\t\t\t\t\t\t Float a, Float b, Float fa, Float fb,\n\t\t\t\t\t\t\t\t Float acc, size_t &evals) const {\n\tconst Float h=(b-a)/2;\n\tconst Float m=(a+b)/2;\n\n\tconst Float mll=m-m_alpha*h;\n\tconst Float ml =m-m_beta*h;\n\tconst Float mr =m+m_beta*h;\n\tconst Float mrr=m+m_alpha*h;\n\n\tconst Float fmll= f(mll);\n\tconst Float fml = f(ml);\n\tconst Float fm  = f(m);\n\tconst Float fmr = f(mr);\n\tconst Float fmrr= f(mrr);\n\n\tconst Float integral2=(h/6)*(fa+fb+5*(fml+fmr));\n\tconst Float integral1=(h/1470)*(77*(fa+fb)\n\t\t+ 432*(fmll+fmrr) + 625*(fml+fmr) + 672*fm);\n\n\tevals += 5;\n\n\tif (evals >= m_maxEvals)\n\t\treturn integral1;\n\n\tFloat dist = acc + (integral1-integral2);\n\tif (dist==acc || mll<=a || b<=mrr) {\n\t\treturn integral1;\n\t} else {\n\t\treturn  adaptiveGaussLobattoStep(f,a,mll,fa,fmll,acc,evals)\n\t\t\t  + adaptiveGaussLobattoStep(f,mll,ml,fmll,fml,acc,evals)\n\t\t\t  + adaptiveGaussLobattoStep(f,ml,m,fml,fm,acc,evals)\n\t\t\t  + adaptiveGaussLobattoStep(f,m,mr,fm,fmr,acc,evals)\n\t\t\t  + adaptiveGaussLobattoStep(f,mr,mrr,fmr,fmrr,acc,evals)\n\t\t\t  + adaptiveGaussLobattoStep(f,mrr,b,fmrr,fb,acc,evals);\n\t}\n}\n\n/* Adaptive multidimensional integration of a vector of const Integrand &s.\n *\n * Copyright (c) 2005-2010 Steven G. Johnson\n *\n * Portions (see comments) based on HIntLib (also distributed under\n * the GNU GPL, v2 or later), copyright (c) 2002-2005 Rudolf Schuerer.\n *     (http://www.cosy.sbg.ac.at/~rschuer/hintlib/)\n *\n * Portions (see comments) based on GNU GSL (also distributed under\n * the GNU GPL, v2 or later), copyright (c) 1996-2000 Brian Gough.\n *     (http://www.gnu.org/software/gsl/)\n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n *\n */\n\n/* Adaptive multidimensional integration on hypercubes (or, really,\n   hyper-rectangles) using cubature rules.\n\n   A cubature rule takes a function and a hypercube and evaluates\n   the function at a small number of points, returning an estimate\n   of the integral as well as an estimate of the error, and also\n   a suggested dimension of the hypercube to subdivide.\n\n   Given such a rule, the adaptive integration is simple:\n\n   1) Evaluate the cubature rule on the hypercube(s).\n      Stop if converged.\n\n   2) Pick the hypercube with the largest estimated error,\n      and divide it in two along the suggested dimension.\n\n   3) Goto (1).\n\n The basic algorithm is based on the adaptive cubature described in\n\n     A. C. Genz and A. A. Malik, \"An adaptive algorithm for numeric\n     integration over an N-dimensional rectangular region,\"\n     J. Comput. Appl. Math. 6 (4), 295-302 (1980).\n\n and subsequently extended to integrating a vector of const Integrand &s in\n\n     J. Berntsen, T. O. Espelid, and A. Genz, \"An adaptive algorithm\n     for the approximate calculation of multiple integrals,\"\n     ACM Trans. Math. Soft. 17 (4), 437-451 (1991).\n\n Note, however, that we do not use any of code from the above authors\n (in part because their code is Fortran 77, but mostly because it is\n under the restrictive ACM copyright license).  I did make use of some\n GPL code from Rudolf Schuerer's HIntLib and from the GNU Scientific\n Library as listed in the copyright notice above, on the other hand.\n\n I am also grateful to Dmitry Turbiner <dturbiner@alum.mit.edu>, who\n implemented an initial prototype of the \"vectorized\" functionality\n for evaluating multiple points in a single call (as opposed to\n multiple functions in a single call).  (Although Dmitry implemented\n a working version, I ended up re-implementing this feature from\n scratch as part of a larger code-cleanup, and in order to have\n a single code path for the vectorized and non-vectorized APIs.  I\n subsequently implemented the algorithm by Gladwell to extract\n even more parallelism by evalutating many hypercubes at once.)\n*/\n\n/***************************************************************************/\n/* Basic datatypes */\n\ntypedef NDIntegrator::VectorizedIntegrand VectorizedIntegrand;\n\ntypedef struct {\n\tFloat val, err;\n} esterr;\n\nstatic Float relError(esterr ee) {\n\treturn (ee.val == 0 ? std::numeric_limits<Float>::infinity() :\n\t\tstd::abs(ee.err / ee.val));\n}\n\nstatic Float errMax(unsigned int fdim, const esterr *ee) {\n\tFloat errmax = 0;\n\tunsigned int k;\n\tfor (k = 0; k < fdim; ++k)\n\t\tif (ee[k].err > errmax) errmax = ee[k].err;\n\treturn errmax;\n}\n\ntypedef struct {\n\tunsigned int dim;\n\tFloat *data;\t/* length 2*dim = center followed by half-widths */\n\tFloat vol;\t/* cache volume = product of widths */\n} hypercube;\n\nstatic Float compute_vol(const hypercube *h) {\n\tunsigned int i;\n\tFloat vol = 1;\n\tfor (i = 0; i < h->dim; ++i)\n\t\tvol *= 2 * h->data[i + h->dim];\n\treturn vol;\n}\n\nstatic hypercube make_hypercube(unsigned int dim, const Float *center, const Float *halfwidth) {\n\tunsigned int i;\n\thypercube h;\n\th.dim = dim;\n\th.data = (Float *) malloc(sizeof(Float) * dim * 2);\n\th.vol = 0;\n\tif (h.data) {\n\t\tfor (i = 0; i < dim; ++i) {\n\t\t\th.data[i] = center[i];\n\t\t\th.data[i + dim] = halfwidth[i];\n\t\t}\n\t\th.vol = compute_vol(&h);\n\t}\n\treturn h;\n}\n\nstatic hypercube make_hypercube_range(unsigned int dim, const Float *xmin, const Float *xmax) {\n\thypercube h = make_hypercube(dim, xmin, xmax);\n\tunsigned int i;\n\tif (h.data) {\n\t\tfor (i = 0; i < dim; ++i) {\n\t\t\th.data[i] = 0.5f * (xmin[i] + xmax[i]);\n\t\t\th.data[i + dim] = 0.5f * (xmax[i] - xmin[i]);\n\t\t}\n\t\th.vol = compute_vol(&h);\n\t}\n\treturn h;\n}\n\nstatic void destroy_hypercube(hypercube *h) {\n\tfree(h->data);\n\th->dim = 0;\n}\n\ntypedef struct {\n\thypercube h;\n\tunsigned int splitDim;\n\tunsigned int fdim; /* dimensionality of vector const Integrand & */\n\testerr *ee; /* array of length fdim */\n\tFloat errmax; /* max ee[k].err */\n} region;\n\nstatic region make_region(const hypercube *h, unsigned int fdim) {\n\tregion R;\n\tR.h = make_hypercube(h->dim, h->data, h->data + h->dim);\n\tR.splitDim = 0;\n\tR.fdim = fdim;\n\tR.ee = R.h.data ? (esterr *) malloc(sizeof(esterr) * fdim) : NULL;\n\treturn R;\n}\n\nstatic void destroy_region(region *R) {\n\tdestroy_hypercube(&R->h);\n\tfree(R->ee);\n\tR->ee = 0;\n}\n\nstatic bool cut_region(region *R, region *R2) {\n\tunsigned int d = R->splitDim, dim = R->h.dim;\n\t*R2 = *R;\n\tR->h.data[d + dim] *= 0.5f;\n\tR->h.vol *= 0.5f;\n\tR2->h = make_hypercube(dim, R->h.data, R->h.data + dim);\n\tif (!R2->h.data)\n\t\treturn NDIntegrator::EFailure;\n\tR->h.data[d] -= R->h.data[d + dim];\n\tR2->h.data[d] += R->h.data[d + dim];\n\tR2->ee = (esterr *) malloc(sizeof(esterr) * R2->fdim);\n\treturn R2->ee == NULL;\n}\n\nstruct rule_s; /* forward declaration */\n\ntypedef NDIntegrator::EResult (*evalError_func)(struct rule_s *r,\n\t\t\t      unsigned int fdim, const VectorizedIntegrand &f,\n\t\t\t      unsigned int nR, region *R);\ntypedef void (*destroy_func)(struct rule_s *r);\n\ntypedef struct rule_s {\n\tunsigned int dim, fdim;         /* the dimensionality & number of functions */\n\tunsigned int num_points;       /* number of evaluation points */\n\tunsigned int num_regions; /* max number of regions evaluated at once */\n\tFloat *pts; /* points to eval: num_regions * num_points * dim */\n\tFloat *vals; /* num_regions * num_points * fdim */\n\tevalError_func evalError;\n\tdestroy_func destroy;\n} rule;\n\nstatic void destroy_rule(rule *r) {\n\tif (r) {\n\t\tif (r->destroy)\n\t\t\tr->destroy(r);\n\t\tfree(r->pts);\n\t\tfree(r);\n\t}\n}\n\nstatic NDIntegrator::EResult alloc_rule_pts(rule *r, unsigned int num_regions) {\n\tif (num_regions > r->num_regions) {\n\t\tfree(r->pts);\n\t\tr->pts = r->vals = NULL;\n\t\tr->num_regions = 0;\n\t\t/* allocate extra so that repeatedly calling alloc_rule_pts with\n\t\t   growing num_regions only needs a logarithmic number of allocations */\n\t\tnum_regions *= 2;\n\t\tr->pts = (Float *) malloc(sizeof(Float) *\n\t\t\t     (num_regions * r->num_points * (r->dim + r->fdim)));\n\t\tif (r->fdim + r->dim > 0 && !r->pts)\n\t\t\treturn NDIntegrator::EFailure;\n\t\tr->vals = r->pts + num_regions * r->num_points * r->dim;\n\t\tr->num_regions = num_regions;\n\t}\n\treturn NDIntegrator::ESuccess;\n}\n\nstatic rule *make_rule(size_t sz, /* >= sizeof(rule) */\n\t\t       unsigned int dim, unsigned int fdim, unsigned int num_points,\n\t\t       evalError_func evalError, destroy_func destroy) {\n\trule *r;\n\n\tif (sz < sizeof(rule))\n\t\treturn NULL;\n\tr = (rule *) malloc(sz);\n\tif (!r)\n\t\treturn NULL;\n\tr->pts = r->vals = NULL;\n\tr->num_regions = 0;\n\tr->dim = dim; r->fdim = fdim;\n\tr->num_points = num_points;\n\tr->evalError = evalError;\n\tr->destroy = destroy;\n\treturn r;\n}\n\n/* note: all regions must have same fdim */\nstatic int eval_regions(unsigned int nR, region *R,\n\t\t\tconst VectorizedIntegrand & f, rule *r)\n{\n\tunsigned int iR;\n\tif (nR == 0)\n\t\treturn NDIntegrator::ESuccess; /* nothing to evaluate */\n\tif (r->evalError(r, R->fdim, f, nR, R))\n\t\treturn NDIntegrator::EFailure;\n\tfor (iR = 0; iR < nR; ++iR)\n\t\tR[iR].errmax = errMax(R->fdim, R[iR].ee);\n\treturn NDIntegrator::ESuccess;\n}\n\n/***************************************************************************/\n/* Functions to loop over points in a hypercube. */\n\n/* Based on orbitrule.cpp in HIntLib-0.0.10 */\n\n/* ls0 returns the least-significant 0 bit of n (e.g. it returns\n   0 if the LSB is 0, it returns 1 if the 2 LSBs are 01, etcetera). */\nstatic unsigned int ls0(unsigned int n)\n{\n#if defined(__GNUC__) && \\\n\t((__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || __GNUC__ > 3)\n\treturn __builtin_ctz(~n); /* gcc builtin for version >= 3.4 */\n#else\n\tconst unsigned int bits[256] = {\n\t\t0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4,\n\t\t0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 5,\n\t\t0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4,\n\t\t0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 6,\n\t\t0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4,\n\t\t0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 5,\n\t\t0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4,\n\t\t0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 7,\n\t\t0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4,\n\t\t0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 5,\n\t\t0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4,\n\t\t0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 6,\n\t\t0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4,\n\t\t0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 5,\n\t\t0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4,\n\t\t0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 8,\n\t};\n\tunsigned int bit = 0;\n\twhile ((n & 0xff) == 0xff) {\n\t\tn >>= 8;\n\t\tbit += 8;\n\t}\n\treturn bit + bits[n & 0xff];\n#endif\n}\n\n/**\n *  Evaluate the integration points for all 2^n points (+/-r,...+/-r)\n *\n *  A Gray-code ordering is used to minimize the number of coordinate updates\n *  in p, although this doesn't matter as much now that we are saving all pts.\n */\nstatic void evalR_Rfs(Float *pts, unsigned int dim, Float *p, const Float *c, const Float *r) {\n\tunsigned int signs = 0; /* 0/1 bit = +/- for corresponding element of r[] */\n\n\t/* We start with the point where r is ADDed in every coordinate\n\t   (this implies signs=0). */\n\tfor (unsigned int i = 0; i < dim; ++i)\n\t\tp[i] = c[i] + r[i];\n\n\t/* Loop through the points in Gray-code ordering */\n\tfor (unsigned i = 0;; ++i) {\n\t\tunsigned int mask, d;\n\t\tmemcpy(pts, p, sizeof(Float) * dim); pts += dim;\n\t\td = ls0(i);\t/* which coordinate to flip */\n\t\tif (d >= dim)\n\t\t\tbreak;\n\n\t\t/* flip the d-th bit and add/subtract r[d] */\n\t\tmask = 1U << d;\n\t\tsigns ^= mask;\n\t\tp[d] = (signs & mask) ? c[d] - r[d] : c[d] + r[d];\n\t}\n}\n\nstatic void evalRR0_0fs(Float *pts, unsigned int dim, Float *p, const Float *c, const Float *r) {\n\tfor (unsigned i = 0; i < dim - 1; ++i) {\n\t\tp[i] = c[i] - r[i];\n\t\tfor (unsigned j = i + 1; j < dim; ++j) {\n\t\t\tp[j] = c[j] - r[j];\n\t\t\tmemcpy(pts, p, sizeof(Float) * dim); pts += dim;\n\t\t\tp[i] = c[i] + r[i];\n\t\t\tmemcpy(pts, p, sizeof(Float) * dim); pts += dim;\n\t\t\tp[j] = c[j] + r[j];\n\t\t\tmemcpy(pts, p, sizeof(Float) * dim); pts += dim;\n\t\t\tp[i] = c[i] - r[i];\n\t\t\tmemcpy(pts, p, sizeof(Float) * dim); pts += dim;\n\t\t\tp[j] = c[j];\t/* Done with j -> Restore p[j] */\n\t\t}\n\t\tp[i] = c[i];\t\t/* Done with i -> Restore p[i] */\n\t}\n}\n\nstatic void evalR0_0fs4d(Float *pts, unsigned int dim, Float *p, const Float *c,\n\t\t\t const Float *r1, const Float *r2) {\n\tmemcpy(pts, p, sizeof(Float) * dim); pts += dim;\n\tfor (unsigned i = 0; i < dim; i++) {\n\t\tp[i] = c[i] - r1[i];\n\t\tmemcpy(pts, p, sizeof(Float) * dim); pts += dim;\n\t\tp[i] = c[i] + r1[i];\n\t\tmemcpy(pts, p, sizeof(Float) * dim); pts += dim;\n\t\tp[i] = c[i] - r2[i];\n\t\tmemcpy(pts, p, sizeof(Float) * dim); pts += dim;\n\t\tp[i] = c[i] + r2[i];\n\t\tmemcpy(pts, p, sizeof(Float) * dim); pts += dim;\n\t\tp[i] = c[i];\n\t}\n}\n\n#define num0_0(dim) (1U)\n#define numR0_0fs(dim) (2 * (dim))\n#define numRR0_0fs(dim) (2 * (dim) * (dim-1))\n#define numR_Rfs(dim) (1U << (dim))\n\n/***************************************************************************/\n/* Based on rule75genzmalik.cpp in HIntLib-0.0.10: An embedded\n   cubature rule of degree 7 (embedded rule degree 5) due to A. C. Genz\n   and A. A. Malik.  See:\n\n         A. C. Genz and A. A. Malik, \"An imbedded [sic] family of fully\n         symmetric numerical integration rules,\" SIAM\n         J. Numer. Anal. 20 (3), 580-588 (1983).\n*/\n\ntypedef struct {\n     rule parent;\n\n     /* temporary arrays of length dim */\n     Float *widthLambda, *widthLambda2, *p;\n\n     /* dimension-dependent constants */\n     Float weight1, weight3, weight5;\n     Float weightE1, weightE3;\n} rule75genzmalik;\n\n#define real(x) ((Float)(x))\n#define to_int(n) ((int)(n))\n\nstatic int isqr(int x)\n{\n     return x * x;\n}\n\nstatic void destroy_rule75genzmalik(rule *r_)\n{\n     rule75genzmalik *r = (rule75genzmalik *) r_;\n     free(r->p);\n}\n\nstatic NDIntegrator::EResult rule75genzmalik_evalError(rule *r_, unsigned int fdim, const VectorizedIntegrand &f, unsigned int nR, region *R) {\n\t/* lambda2 = sqrt(9/70), lambda4 = sqrt(9/10), lambda5 = sqrt(9/19) */\n\tconst Float lambda2 = (Float) 0.3585685828003180919906451539079374954541;\n\tconst Float lambda4 = (Float) 0.9486832980505137995996680633298155601160;\n\tconst Float lambda5 = (Float) 0.6882472016116852977216287342936235251269;\n\tconst Float weight2 = (Float) (980.0 / 6561.0);\n\tconst Float weight4 = (Float) (200.0 / 19683.0);\n\tconst Float weightE2 = (Float) (245.0 / 486.0);\n\tconst Float weightE4 = (Float) (25.0 / 729.0);\n\tconst Float ratio = (lambda2 * lambda2) / (lambda4 * lambda4);\n\n\trule75genzmalik *r = (rule75genzmalik *) r_;\n\tunsigned int i, j, dim = r_->dim, npts = 0;\n\tFloat *diff, *pts, *vals;\n\n\tif (alloc_rule_pts(r_, nR))\n\t\treturn NDIntegrator::EFailure;\n\tpts = r_->pts; vals = r_->vals;\n\n\tfor (unsigned int iR = 0; iR < nR; ++iR) {\n\t\tconst Float *center = R[iR].h.data;\n\t\tconst Float *halfwidth = R[iR].h.data + dim;\n\n\t\tfor (i = 0; i < dim; ++i)\n\t\t\tr->p[i] = center[i];\n\n\t\tfor (i = 0; i < dim; ++i)\n\t\t\tr->widthLambda2[i] = halfwidth[i] * lambda2;\n\t\tfor (i = 0; i < dim; ++i)\n\t\t\tr->widthLambda[i] = halfwidth[i] * lambda4;\n\n\t\t/* Evaluate points in the center, in (lambda2,0,...,0) and\n\t\t\t(lambda3=lambda4, 0,...,0).  */\n\t\tevalR0_0fs4d(pts + npts*dim, dim, r->p, center,\n\t\t\tr->widthLambda2, r->widthLambda);\n\t\tnpts += num0_0(dim) + 2 * numR0_0fs(dim);\n\n\t\t/* Calculate points for (lambda4, lambda4, 0, ...,0) */\n\t\tevalRR0_0fs(pts + npts*dim, dim, r->p, center, r->widthLambda);\n\t\tnpts += numRR0_0fs(dim);\n\n\t\t/* Calculate points for (lambda5, lambda5, ..., lambda5) */\n\t\tfor (i = 0; i < dim; ++i)\n\t\t\tr->widthLambda[i] = halfwidth[i] * lambda5;\n\t\tevalR_Rfs(pts + npts*dim, dim, r->p, center, r->widthLambda);\n\t\tnpts += numR_Rfs(dim);\n\t}\n\n\t/* Evaluate the const Integrand & function(s) at all the points */\n\tf((size_t) npts, pts, vals);\n\n\t/* we are done with the points, and so we can re-use the pts\n\t   array to store the maximum difference diff[i] in each dimension\n\t   for each hypercube */\n\tdiff = pts;\n\tfor (i = 0; i < dim * nR; ++i)\n\t\tdiff[i] = 0;\n\n\tfor (j = 0; j < fdim; ++j) {\n\t\tfor (unsigned int iR = 0; iR < nR; ++iR) {\n\t\t\tFloat result, res5th;\n\t\t\tFloat val0, sum2=0, sum3=0, sum4=0, sum5=0;\n\t\t\tunsigned int k, k0 = 0;\n\n\t\t\t/* accumulate j-th function values into j-th integrals\n\t\t\t   NOTE: this relies on the ordering of the eval functions\n\t\t\t   above, as well as on the internal structure of\n\t\t\t   the evalR0_0fs4d function */\n\n\t\t\tval0 = vals[0]; /* central point */\n\t\t\tk0 += 1;\n\n\t\t\tfor (k = 0; k < dim; ++k) {\n\t\t\t\tFloat v0 = vals[k0 + 4*k];\n\t\t\t\tFloat v1 = vals[(k0 + 4*k) + 1];\n\t\t\t\tFloat v2 = vals[(k0 + 4*k) + 2];\n\t\t\t\tFloat v3 = vals[(k0 + 4*k) + 3];\n\n\t\t\t\tsum2 += v0 + v1;\n\t\t\t\tsum3 += v2 + v3;\n\n\t\t\t\tdiff[iR * dim + k] +=\n\t\t\t\t\tstd::abs(v0 + v1 - 2*val0 - ratio * (v2 + v3 - 2*val0));\n\t\t\t}\n\t\t\tk0 += 4*k;\n\n\t\t\tfor (k = 0; k < numRR0_0fs(dim); ++k)\n\t\t\t\tsum4 += vals[k0 + k];\n\t\t\tk0 += k;\n\n\t\t\tfor (k = 0; k < numR_Rfs(dim); ++k)\n\t\t\t\tsum5 += vals[k0 + k];\n\n\t\t\t/* Calculate fifth and seventh order results */\n\t\t\tresult = R[iR].h.vol * (r->weight1 * val0 + weight2 * sum2 + r->weight3 * sum3 + weight4 * sum4 + r->weight5 * sum5);\n\t\t\tres5th = R[iR].h.vol * (r->weightE1 * val0 + weightE2 * sum2 + r->weightE3 * sum3 + weightE4 * sum4);\n\n\t\t\tR[iR].ee[j].val = result;\n\t\t\tR[iR].ee[j].err = std::abs(res5th - result);\n\n\t\t\tvals += r_->num_points;\n\t\t}\n\t}\n\n\t/* figure out dimension to split: */\n\tfor (unsigned int iR = 0; iR < nR; ++iR) {\n\t\tFloat maxdiff = 0;\n\t\tunsigned int dimDiffMax = 0;\n\n\t\tfor (i = 0; i < dim; ++i) {\n\t\t\tif (diff[iR*dim + i] > maxdiff) {\n\t\t\t\tmaxdiff = diff[iR*dim + i];\n\t\t\t\tdimDiffMax = i;\n\t    \t}\n\t\t}\n\t\tR[iR].splitDim = dimDiffMax;\n\t}\n\treturn NDIntegrator::ESuccess;\n}\n\nstatic rule *make_rule75genzmalik(unsigned int dim, unsigned int fdim) {\n\trule75genzmalik *r;\n\n\tif (dim < 2) return NULL; /* this rule does not support 1d integrals */\n\n\t/* Because of the use of a bit-field in evalR_Rfs, we are limited\n\t   to be < 32 dimensions (or however many bits are in unsigned).\n\t   This is not a practical limitation...long before you reach\n\t   32 dimensions, the Genz-Malik cubature becomes excruciatingly\n\t   slow and is superseded by other methods (e.g. Monte-Carlo). */\n\tif (dim >= sizeof(unsigned) * 8)\n\t\treturn NULL;\n\n\tr = (rule75genzmalik *) make_rule(sizeof(rule75genzmalik),\n\t\t\tdim, fdim, num0_0(dim) + 2 * numR0_0fs(dim)\n\t\t\t+ numRR0_0fs(dim) + numR_Rfs(dim),\n\t\t\trule75genzmalik_evalError,\n\t\t\tdestroy_rule75genzmalik);\n     if (!r)\n\t\t return NULL;\n\n\tr->weight1 = (real(12824 - 9120 * to_int(dim) + 400 * isqr(to_int(dim))) / real(19683));\n\tr->weight3 = real(1820 - 400 * to_int(dim)) / real(19683);\n\tr->weight5 = real(6859) / real(19683) / real(1U << dim);\n\tr->weightE1 = (real(729 - 950 * to_int(dim) + 50 * isqr(to_int(dim))) / real(729));\n\tr->weightE3 = real(265 - 100 * to_int(dim)) / real(1458);\n\tr->p = (Float *) malloc(sizeof(Float) * dim * 3);\n\tif (!r->p) {\n\t\tdestroy_rule((rule *) r);\n\t\treturn NULL;\n\t}\n\tr->widthLambda = r->p + dim;\n\tr->widthLambda2 = r->p + 2 * dim;\n\treturn (rule *) r;\n}\n\n/***************************************************************************/\n/* 1d 15-point Gaussian quadrature rule, based on qk15.c and qk.c in\n   GNU GSL (which in turn is based on QUADPACK). */\n\nstatic NDIntegrator::EResult rule15gauss_evalError(rule *r,\n\t\t\t\t unsigned int fdim, const VectorizedIntegrand & f,\n\t\t\t\t unsigned int nR, region *R) {\n     /* Gauss quadrature weights and kronrod quadrature abscissae and\n\t    weights as evaluated with 80 decimal digit arithmetic by\n\t    L. W. Fullerton, Bell Labs, Nov. 1981. */\n\tconst unsigned int n = 8;\n\tconst Float xgk[8] = {  /* abscissae of the 15-point kronrod rule */\n\t\t(Float) 0.991455371120812639206854697526329,\n\t\t(Float) 0.949107912342758524526189684047851,\n\t\t(Float) 0.864864423359769072789712788640926,\n\t\t(Float) 0.741531185599394439863864773280788,\n\t\t(Float) 0.586087235467691130294144838258730,\n\t\t(Float) 0.405845151377397166906606412076961,\n\t\t(Float) 0.207784955007898467600689403773245,\n\t\t(Float) 0.000000000000000000000000000000000\n\t\t/* xgk[1], xgk[3], ... abscissae of the 7-point gauss rule.\n\t\t   xgk[0], xgk[2], ... to optimally extend the 7-point gauss rule */\n\t};\n\tstatic const Float wg[4] = {  /* weights of the 7-point gauss rule */\n\t\t(Float) 0.129484966168869693270611432679082,\n\t\t(Float) 0.279705391489276667901467771423780,\n\t\t(Float) 0.381830050505118944950369775488975,\n\t\t(Float) 0.417959183673469387755102040816327\n\t};\n\tstatic const Float wgk[8] = { /* weights of the 15-point kronrod rule */\n\t\t(Float) 0.022935322010529224963732008058970,\n\t\t(Float) 0.063092092629978553290700663189204,\n\t\t(Float) 0.104790010322250183839876322541518,\n\t\t(Float) 0.140653259715525918745189590510238,\n\t\t(Float) 0.169004726639267902826583426598550,\n\t\t(Float) 0.190350578064785409913256402421014,\n\t\t(Float) 0.204432940075298892414161999234649,\n\t\t(Float) 0.209482141084727828012999174891714\n\t};\n\tunsigned int j, npts = 0;\n\tFloat *pts, *vals;\n\n\tif (alloc_rule_pts(r, nR))\n\t\treturn NDIntegrator::EFailure;\n\n\tpts = r->pts; vals = r->vals;\n\n\tfor (unsigned int iR = 0; iR < nR; ++iR) {\n\t\tconst Float center = R[iR].h.data[0];\n\t\tconst Float halfwidth = R[iR].h.data[1];\n\n\t\tpts[npts++] = center;\n\n\t\tfor (j = 0; j < (n - 1) / 2; ++j) {\n\t\t\tint j2 = 2*j + 1;\n\t\t\tFloat w = halfwidth * xgk[j2];\n\t\t\tpts[npts++] = center - w;\n\t\t\tpts[npts++] = center + w;\n\t\t}\n\t\tfor (j = 0; j < n/2; ++j) {\n\t\t\tint j2 = 2*j;\n\t\t\tFloat w = halfwidth * xgk[j2];\n\t\t\tpts[npts++] = center - w;\n\t\t\tpts[npts++] = center + w;\n\t\t}\n\n\t\tR[iR].splitDim = 0; /* no choice but to divide 0th dimension */\n\t}\n\n\tf((size_t) npts, pts, vals);\n\n\tfor (unsigned int k = 0; k < fdim; ++k) {\n\t\tfor (unsigned int iR = 0; iR < nR; ++iR) {\n\t\t\tconst Float halfwidth = R[iR].h.data[1];\n\t\t\tFloat result_gauss = vals[0] * wg[n/2 - 1];\n\t\t\tFloat result_kronrod = vals[0] * wgk[n - 1];\n\t\t\tFloat result_abs = std::abs(result_kronrod);\n\t\t\tFloat result_asc, mean, err;\n\n\t\t\t/* accumulate integrals */\n\t\t\tnpts = 1;\n\t\t\tfor (j = 0; j < (n - 1) / 2; ++j) {\n\t\t\t\tint j2 = 2*j + 1;\n\t\t\t\tFloat v = vals[npts] + vals[npts+1];\n\t\t\t\tresult_gauss += wg[j] * v;\n\t\t\t\tresult_kronrod += wgk[j2] * v;\n\t\t\t\tresult_abs += wgk[j2] * (std::abs(vals[npts]) + std::abs(vals[npts+1]));\n\t\t\t\tnpts += 2;\n\t\t\t}\n\t\t\tfor (j = 0; j < n/2; ++j) {\n\t\t\t\tint j2 = 2*j;\n\t\t\t\tresult_kronrod += wgk[j2] * (vals[npts] + vals[npts+1]);\n\t\t\t\tresult_abs += wgk[j2] * (std::abs(vals[npts]) + std::abs(vals[npts+1]));\n\t\t\t\tnpts += 2;\n\t\t\t}\n\n\t\t\t/* integration result */\n\t\t\tR[iR].ee[k].val = result_kronrod * halfwidth;\n\n\t\t\t/* error estimate (from GSL, probably dates back to QUADPACK\n\t\t\t... not completely clear to me why we don't just use\n\t\t\tstd::abs(result_kronrod - result_gauss) * halfwidth */\n\t\t\tmean = result_kronrod * 0.5f;\n\t\t\tresult_asc = wgk[n - 1] * std::abs(vals[0] - mean);\n\t\t\tnpts = 1;\n\t\t\tfor (j = 0; j < (n - 1) / 2; ++j) {\n\t\t\t\tint j2 = 2*j + 1;\n\t\t\t\tresult_asc += wgk[j2] * (std::abs(vals[npts]-mean)\n\t\t\t\t\t     + std::abs(vals[npts+1]-mean));\n\t\t\t\tnpts += 2;\n\t\t\t}\n\t\t\tfor (j = 0; j < n/2; ++j) {\n\t\t\t\tint j2 = 2*j;\n\t\t\t\tresult_asc += wgk[j2] * (std::abs(vals[npts]-mean)\n\t\t\t\t\t     + std::abs(vals[npts+1]-mean));\n\t\t\t\tnpts += 2;\n\t\t\t}\n\t\t\terr = std::abs(result_kronrod - result_gauss) * halfwidth;\n\t\t\tresult_abs *= halfwidth;\n\t\t\tresult_asc *= halfwidth;\n\t\t\tif (result_asc != 0 && err != 0) {\n\t\t\t\t/* Recommended error estimate for the 7-15 G-K rule */\n\t\t\t\tFloat scale = std::pow((200 * err / result_asc), (Float) 1.5);\n\t\t\t\terr = (scale < 1) ? result_asc * scale : result_asc;\n\t\t\t}\n\t\t\t#if 0\n\t\t\t\t/* This seems a bit excessive (and creates problems for single\n\t\t\t\t   precision code) */\n\t\t\t\tif (result_abs > std::numeric_limits<Float>::min() / (50 * std::numeric_limits<Float>::epsilon())) {\n\t\t\t\t\tFloat min_err = 50 * std::numeric_limits<Float>::epsilon() * result_abs;\n\t\t\t\t\tif (min_err > err)\n\t\t\t\t\t\terr = min_err;\n\t\t\t\t}\n\t\t\t#endif\n\t\t\tR[iR].ee[k].err = err;\n\n\t\t\t/* increment vals to point to next batch of results */\n\t\t\tvals += 15;\n\t\t}\n\t}\n\treturn NDIntegrator::ESuccess;\n}\n\nstatic rule *make_rule15gauss(unsigned int dim, unsigned int fdim) {\n     if (dim != 1) return NULL; /* this rule is only for 1d integrals */\n\n     return make_rule(sizeof(rule), dim, fdim, 15, rule15gauss_evalError, 0);\n}\n\n/***************************************************************************/\n/* binary heap implementation (ala _Introduction to Algorithms_ by\n   Cormen, Leiserson, and Rivest), for use as a priority queue of\n   regions to integrate. */\n\ntypedef region heap_item;\n#define KEY(hi) ((hi).errmax)\n\ntypedef struct {\n\tunsigned int n, nalloc;\n\theap_item *items;\n\tunsigned int fdim;\n\testerr *ee; /* array of length fdim of the total const Integrand & & error */\n} heap;\n\nstatic void heap_resize(heap *h, unsigned int nalloc) {\n\th->nalloc = nalloc;\n\th->items = (heap_item *) realloc(h->items, sizeof(heap_item) * nalloc);\n}\n\nstatic heap heap_alloc(unsigned int nalloc, unsigned int fdim) {\n\theap h;\n\tunsigned int i;\n\th.n = 0;\n\th.nalloc = 0;\n\th.items = 0;\n\th.fdim = fdim;\n\th.ee = (esterr *) malloc(sizeof(esterr) * fdim);\n\tif (h.ee) {\n\t\tfor (i = 0; i < fdim; ++i)\n\t\t\th.ee[i].val = h.ee[i].err = 0;\n\t\theap_resize(&h, nalloc);\n\t}\n\treturn h;\n}\n\n/* note that heap_free does not deallocate anything referenced by the items */\nstatic void heap_free(heap *h) {\n\th->n = 0;\n\theap_resize(h, 0);\n\th->fdim = 0;\n\tfree(h->ee);\n}\n\nstatic NDIntegrator::EResult heap_push(heap *h, heap_item hi) {\n\tint insert;\n\tunsigned int fdim = h->fdim;\n\n\tfor (unsigned int i = 0; i < fdim; ++i) {\n\t\th->ee[i].val += hi.ee[i].val;\n\t\th->ee[i].err += hi.ee[i].err;\n\t}\n\tinsert = h->n;\n\tif (++(h->n) > h->nalloc) {\n\t\theap_resize(h, h->n * 2);\n\t\tif (!h->items)\n\t\t\treturn NDIntegrator::EFailure;\n\t}\n\twhile (insert) {\n\t\tint parent = (insert - 1) / 2;\n\t\tif (KEY(hi) <= KEY(h->items[parent]))\n\t\t\tbreak;\n\t\th->items[insert] = h->items[parent];\n\t\tinsert = parent;\n\t}\n\th->items[insert] = hi;\n\treturn NDIntegrator::ESuccess;\n}\n\nstatic NDIntegrator::EResult heap_push_many(heap *h, unsigned int ni, heap_item *hi) {\n     unsigned int i;\n     for (i = 0; i < ni; ++i)\n\t  if (heap_push(h, hi[i])) return NDIntegrator::EFailure;\n     return NDIntegrator::ESuccess;\n}\n\nstatic heap_item heap_pop(heap *h) {\n\theap_item ret;\n\tint i, n, child;\n\tif (!(h->n))\n\t\tSLog(EError, \"attempted to pop an empty heap\\n\");\n\n\tret = h->items[0];\n\th->items[i = 0] = h->items[n = --(h->n)];\n\twhile ((child = i * 2 + 1) < n) {\n\t\tint largest;\n\t\theap_item swap;\n\n\t\tif (KEY(h->items[child]) <= KEY(h->items[i]))\n\t\t\tlargest = i;\n\t\telse\n\t\t\tlargest = child;\n\t\tif (++child < n && KEY(h->items[largest]) < KEY(h->items[child]))\n\t\t\tlargest = child;\n\t\tif (largest == i)\n\t\t\tbreak;\n\t\tswap = h->items[i];\n\t\th->items[i] = h->items[largest];\n\t\th->items[i = largest] = swap;\n\t}\n\tunsigned int fdim = h->fdim;\n\tfor (unsigned int j = 0; j < fdim; ++j) {\n\t\th->ee[j].val -= ret.ee[j].val;\n\t\th->ee[j].err -= ret.ee[j].err;\n\t}\n\treturn ret;\n}\n\n/***************************************************************************/\n\n/* adaptive integration, analogous to adaptintegrator.cpp in HIntLib */\n\nstatic NDIntegrator::EResult ruleadapt_integrate(rule *r, unsigned int fdim,\n\t\tconst VectorizedIntegrand & f, const hypercube *h, size_t maxEval,\n\t\tFloat reqAbsError, Float reqRelError, Float *val, Float *err, size_t &numEval, int parallel) {\n\theap regions;\n\tunsigned int i, j;\n\tregion *R = NULL; /* array of regions to evaluate */\n\tunsigned int nR_alloc = 0;\n\testerr *ee = NULL;\n\n\tregions = heap_alloc(1, fdim);\n\tif (!regions.ee || !regions.items)\n\t\tgoto bad;\n\n\tee = (esterr *) malloc(sizeof(esterr) * fdim);\n\tif (!ee)\n\t\tgoto bad;\n\n\tnR_alloc = 2;\n\tR = (region *) malloc(sizeof(region) * nR_alloc);\n\tif (!R)\n\t\tgoto bad;\n\tR[0] = make_region(h, fdim);\n\tif (!R[0].ee || eval_regions(1, R, f, r) || heap_push(&regions, R[0]))\n\t\tgoto bad;\n\tnumEval += r->num_points;\n\n\twhile (numEval < maxEval || !maxEval) {\n\t\tfor (j = 0; j < fdim && (regions.ee[j].err <= reqAbsError ||\n\t\t\trelError(regions.ee[j]) <= reqRelError); ++j)\n\t\t\t;\n\t\tif (j == fdim)\n\t\t\tbreak; /* convergence */\n\n\t\tif (parallel) {\n\t\t\t/* Maximize potential parallelism\n\n\t\t\t   adapted from I. Gladwell, \"Vectorization of one dimensional\n\t\t\t   quadrature codes,\" pp. 230--238 in _Numerical Integration. Recent\n\t\t\t   Developments, Software and Applications_, G. Fairweather and\n\t\t\t   P. M. Keast, eds., NATO ASI Series C203, Dordrecht (1987), as\n\t\t\t   described in J. M. Bull and T. L. Freeman, \"Parallel Globally\n\t\t\t   Adaptive Algorithms for Multi-dimensional Integration,\"\n\t\t\t   http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.42.6638\n\n\t\t\t   Basically, this evaluates in one shot all regions\n\t\t\t   that *must* be evaluated in order to reduce the\n\t\t\t   error to the requested bound: the minimum set of\n\t\t\t   largest-error regions whose errors push the total\n\t\t\t   error over the bound.\n\n\t\t\t   [Note: Bull and Freeman claim that the Gladwell\n\t\t\t   approach is intrinsically inefficent because it\n\t\t\t   \"requires sorting\", and propose an alternative\n\t\t\t   algorithm that \"only\" requires three passes over the\n\t\t\t   entire set of regions.  Apparently, they didn't\n\t\t\t   realize that one could use a heap data structure, in\n\t\t\t   which case the time to pop K biggest-error regions\n\t\t\t   out of N is only O(K log N), much better than the\n\t\t\t   O(N) cost of the Bull and Freeman algorithm if\n\t\t\t   K << N, and it is also much simpler.] */\n\t\t\tunsigned int nR = 0;\n\t\t\tfor (j = 0; j < fdim; ++j)\n\t\t\t\tee[j] = regions.ee[j];\n\t\t\tdo {\n\t\t\t\tif (nR + 2 > nR_alloc) {\n\t\t\t\t\tnR_alloc = (nR + 2) * 2;\n\t\t\t\t\tR = (region *) realloc(R, nR_alloc * sizeof(region));\n\t\t\t\t\tif (!R)\n\t\t\t\t\t\tgoto bad;\n\t\t\t\t}\n\t\t\t\tR[nR] = heap_pop(&regions);\n\t\t\t\tfor (j = 0; j < fdim; ++j)\n\t\t\t\t\tee[j].err -= R[nR].ee[j].err;\n\t\t\t\tif (cut_region(R+nR, R+nR+1))\n\t\t\t\t\tgoto bad;\n\t\t\t\tnumEval += r->num_points * 2;\n\t\t\t\tnR += 2;\n\t\t\t\tfor (j = 0; j < fdim && (ee[j].err <= reqAbsError\n\t\t\t\t\t|| relError(ee[j]) <= reqRelError); ++j)\n\t\t\t\t\t;\n\t\t\t\tif (j == fdim)\n\t\t\t\t\tbreak; /* other regions have small errs */\n\t\t\t} while (regions.n > 0 && (numEval < maxEval || !maxEval));\n\t\t\tif (eval_regions(nR, R, f, r) || heap_push_many(&regions, nR, R))\n\t\t\t\tgoto bad;\n\t\t} else { /* minimize number of function evaluations */\n\t\t\tR[0] = heap_pop(&regions); /* get worst region */\n\t\t\tif (cut_region(R, R+1) || eval_regions(2, R, f, r)\n\t\t\t\t|| heap_push_many(&regions, 2, R))\n\t\t\t\tgoto bad;\n\t\t\tnumEval += r->num_points * 2;\n\t\t}\n\t}\n\n     /* re-sum integral and errors */\n\tfor (j = 0; j < fdim; ++j)\n\t\tval[j] = err[j] = 0;\n\tfor (i = 0; i < regions.n; ++i) {\n\t\tfor (j = 0; j < fdim; ++j) {\n\t\t\tval[j] += regions.items[i].ee[j].val;\n\t\t\terr[j] += regions.items[i].ee[j].err;\n\t\t}\n\t\tdestroy_region(&regions.items[i]);\n\t}\n\n\t/* printf(\"regions.nalloc = %d\\n\", regions.nalloc); */\n\tfree(ee);\n\theap_free(&regions);\n\tfree(R);\n\treturn NDIntegrator::ESuccess;\n\nbad:\n\tfree(ee);\n\theap_free(&regions);\n\tfree(R);\n\treturn NDIntegrator::EFailure;\n}\n\nstatic NDIntegrator::EResult integrate(unsigned fdim, const VectorizedIntegrand & f,\n\t\t     unsigned dim, const Float *xmin, const Float *xmax,\n\t\t     size_t maxEval, Float reqAbsError, Float reqRelError,\n\t\t     Float *val, Float *err, size_t &numEval, int parallel) {\n\tNDIntegrator::EResult status;\n\n\tnumEval = 0;\n\tif (fdim == 0) /* nothing to do */\n\t\treturn NDIntegrator::ESuccess;\n\tif (dim == 0) { /* trivial integration */\n\t\tf(1, xmin, val);\n\t\tfor (unsigned int i = 0; i < fdim; ++i)\n\t\t\terr[i] = 0;\n\t\treturn NDIntegrator::ESuccess;\n\t}\n\trule *r = dim == 1 ? make_rule15gauss(dim, fdim)\n\t\t: make_rule75genzmalik(dim, fdim);\n\tif (!r) {\n\t\tfor (unsigned int i = 0; i < fdim; ++i) {\n\t\t\tval[i] = 0;\n\t\t\terr[i] = std::numeric_limits<Float>::infinity();\n\t\t}\n\t\treturn NDIntegrator::EFailure;\n\t}\n\thypercube h = make_hypercube_range(dim, xmin, xmax);\n\tstatus = !h.data ? NDIntegrator::EFailure\n\t\t: ruleadapt_integrate(r, fdim, f, &h,\n\t\t\tmaxEval, reqAbsError, reqRelError,\n\t\t\tval, err, numEval, parallel);\n\tdestroy_hypercube(&h);\n\tdestroy_rule(r);\n\treturn status;\n}\n\nclass VectorizationAdapter {\npublic:\n\tVectorizationAdapter(const NDIntegrator::Integrand &integrand, size_t fdim,\n\t\t\tsize_t dim) : m_integrand(integrand), m_fdim(fdim), m_dim(dim) {\n\t\tm_temp = new Float[m_fdim];\n\t}\n\n\t~VectorizationAdapter() {\n\t\tdelete[] m_temp;\n\t}\n\n\tvoid f(size_t nPt, const Float *in, Float *out) {\n\t\tfor (size_t i = 0; i < nPt; ++i) {\n\t\t\tm_integrand(in + i*m_dim, m_temp);\n\t  \t\tfor (size_t k = 0; k < m_fdim; ++k)\n\t\t\t\tout[k*nPt + i] = m_temp[k];\n\t\t}\n\t}\nprivate:\n\tconst NDIntegrator::Integrand &m_integrand;\n\tsize_t m_fdim, m_dim;\n\tFloat *m_temp;\n};\n\nNDIntegrator::NDIntegrator(size_t fDim, size_t dim,\n\t\t\tsize_t maxEvals, Float absError, Float relError)\n : m_fdim(fDim), m_dim(dim), m_maxEvals(maxEvals), m_absError(absError),\n  m_relError(relError) { }\n\nNDIntegrator::EResult NDIntegrator::integrate(const Integrand &f, const Float *min,\n\t\tconst Float *max, Float *result, Float *error, size_t *_evals) const {\n\tVectorizationAdapter adapter(f, m_fdim, m_dim);\n\tsize_t evals = 0;\n\tEResult retval = mitsuba::integrate((unsigned int) m_fdim, boost::bind(\n\t\t&VectorizationAdapter::f, &adapter, _1, _2, _3), (unsigned int) m_dim,\n\t\tmin, max, m_maxEvals, m_absError, m_relError, result, error, evals, false);\n\tif (_evals)\n\t\t*_evals = evals;\n\treturn retval;\n}\n\nNDIntegrator::EResult NDIntegrator::integrateVectorized(const VectorizedIntegrand &f, const Float *min,\n\t\tconst Float *max, Float *result, Float *error, size_t *_evals) const {\n\tsize_t evals = 0;\n\tEResult retval = mitsuba::integrate((unsigned int) m_fdim, f, (unsigned int) m_dim,\n\t\tmin, max, m_maxEvals, m_absError, m_relError, result, error, evals, true);\n\tif (_evals)\n\t\t*_evals = evals;\n\treturn retval;\n}\n\nMTS_NAMESPACE_END\n", "meta": {"hexsha": "e958e1b86dc460fabe7ca709340267a64c3655aa", "size": 43696, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mitsuba-af602c6fd98a/src/libcore/quad.cpp", "max_stars_repo_name": "NTForked-ML/pbrs", "max_stars_repo_head_hexsha": "0b405d92c12d257e2581366542762c9f0c3facce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 139.0, "max_stars_repo_stars_event_min_datetime": "2017-04-21T00:22:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T20:33:10.000Z", "max_issues_repo_path": "mitsuba-af602c6fd98a/src/libcore/quad.cpp", "max_issues_repo_name": "NTForked-ML/pbrs", "max_issues_repo_head_hexsha": "0b405d92c12d257e2581366542762c9f0c3facce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2017-08-15T18:22:59.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-01T05:44:41.000Z", "max_forks_repo_path": "mitsuba-af602c6fd98a/src/libcore/quad.cpp", "max_forks_repo_name": "NTForked-ML/pbrs", "max_forks_repo_head_hexsha": "0b405d92c12d257e2581366542762c9f0c3facce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 30.0, "max_forks_repo_forks_event_min_datetime": "2017-07-21T03:56:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T06:55:34.000Z", "avg_line_length": 30.4714086471, "max_line_length": 143, "alphanum_fraction": 0.6179055291, "num_tokens": 15372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122288794595, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.7353574209320394}}
{"text": "#include <fstream>\n#include <cstring>\n#include <cmath>\n#include <stdlib.h>\n#include <assert.h>\n#include <iomanip>\n\n#include <armadillo>\n\n#include \"math_utility.hh\"\n#include \"matrix/utility.hh\"\n\n#include \"cad_utility.hh\"\n#include \"global_constants.hh\"\n\n/**\n * @return great circle distance between two point on a spherical Earth\n * @brief Refrence: Bate et al. \"Fundamentals of Astrodynamics\", Dover 1971, p. 310\n *\n * @param[in] lon1 longitude of first  point - rad\n * @param[in] lat1 latitude  of first  point - rad\n * @param[in] lon2 longitude of second point - rad\n * @param[in] lat2 latitude  of second point - rad\n *\n * @author 030414 Created from FORTRAN by Peter H Zipfel\n */\ndouble cad::distance(const double &lon1,\n                const double &lat1,\n                const double &lon2,\n                const double &lat2) {\n    double dum =\n        sin(lat2) * sin(lat1) + cos(lat2) * cos(lat1) * cos(lon2 - lon1);\n    if (fabs(dum) > 1.)\n        dum = 1. * sign(dum);\n    double distancex = REARTH * acos(dum) * 1.e-3;\n\n    return distancex;\n}\n\n\n/**\n * @brief Calculates geodetic longitude, latitude, and altitude from inertial\n *        displacement vector\n *        using the WGS 84 reference ellipsoid\n *        Reference: Britting,K.R.\"Inertial Navigation Systems Analysis\", Wiley. 1971\n *\n * @return std::tuple(lon, lat, alt)\n *                    lon geodetic longitude - rad\n *                    lat geodetic latitude - rad\n *                    alt altitude above ellipsoid - m\n *\n * @param[in] SBII(3x1) = Inertial position - m\n * @param[in] TEI = T.M from Inertia coordinate to ECEF coordinate\n *\n * @author 030414 Created from FORTRAN by Peter H Zipfel\n * @author 170121 Create Armadillo Version by soncyang\n */\nstd::tuple<double, double, double> cad::geo84_in(arma::vec3 SBII,\n                                                 arma::mat33 TEI) {\n    int count(0);\n    double lat0(0);\n    double alamda(0);\n\n    /* tuple */\n    double lon(0);\n    double lat(0);\n    double alt(0);\n\n    arma::vec3 SBEE;\n    SBEE = TEI * SBII;\n    /** initializing geodetic latitude using geocentric latitude */\n    double dbi = norm(SBEE);\n    double latg = asin(SBEE(2, 0) / dbi);\n    // double latg = atan2(SBEE(2), sqrt(SBEE(0) * SBEE(0) + SBEE(1) * SBEE(1)));\n    lat = latg;\n\n    /** iterating to calculate geodetic latitude and altitude */\n    do {\n        lat0 = lat;\n        double r0 =\n            SMAJOR_AXIS *\n            (1. - FLATTENING * (1. - cos(2. * lat0)) / 2. +\n             5. * pow(FLATTENING, 2) * (1. - cos(4. * lat0)) / 16.);  /** eq 4-21 */\n        alt = dbi - r0;\n        double dd = FLATTENING * sin(2. * lat0) *\n                    (1. - FLATTENING / 2. - alt / r0);  /** eq 4-15 */\n        lat = latg + dd;\n        count++;\n        assert(count <= 100 &&\n               \" *** Stop: Geodetic latitude does not \"\n               \"converge,'cad_geo84_in()' *** \");\n    }while (fabs(lat - lat0) > SMALL);\n\n    /** longitude */\n    double sbee1 = SBEE(0, 0);\n    double sbee2 = SBEE(1, 0);\n    double dum4 = asin(sbee2 / sqrt(sbee1 * sbee1 + sbee2 * sbee2));\n    // double dum4 = atan2(sbee2, sbee1);\n    /** Resolving the multi-valued arcsin function */\n    if ((sbee1 >= 0.0) && (sbee2 >= 0.0))\n        alamda = dum4;  /** quadrant I */\n    if ((sbee1 < 0.0) && (sbee2 >= 0.0))\n        alamda = (180. * RAD) - dum4;  /** quadrant II */\n    if ((sbee1 < 0.0) && (sbee2 < 0.0))\n        alamda = (180. * RAD) - dum4;  /** quadrant III */\n    if ((sbee1 > 0.0) && (sbee2 < 0.0))\n        alamda = (360. * RAD) + dum4;  /** quadrant IV */\n    lon = alamda;  /** - WEII3 * time - GW_CLONG; */\n    if ((lon) > (180. * RAD))\n        lon = -((360. * RAD) - lon);  /** east positive, west negative */\n\n    return std::make_tuple(lon, lat, alt);\n}\n\n/**\n * @return geodetic velocity vector information from inertial postion and\n * velocity\n * using the WGS 84 reference ellipsoid\n *\n * @brief Calls utilities\n *    geo84_in(...), tdi84(...)\n *\n * @param[out] dvbe geodetic velocity - m/s\n * @param[out] psivdx geodetic heading angle - deg\n * @param[out] thtvdx geodetic flight path angle - deg\n *\n * @param[in] SBII(3x1) Inertial position - m\n * @param[in] VBII(3x1) Inertial velocity - m\n *\n * @author 040710 created by Peter H Zipfel\n */\nstd::tuple<double, double, double> cad::geo84vel_in(arma::vec3 SBII,\n                                                    arma::vec3 VBII,\n                                                    arma::mat33 TEI) {\n    double lon(0);\n    double lat(0);\n    double alt(0);\n\n    /* tuple */\n    double dvbe(0);\n    double psivdx(0);\n    double thtvdx(0);\n\n    /** geodetic longitude, latitude and altitude */\n    std::tie(lon, lat, alt) = geo84_in(SBII, TEI);\n    arma::mat33 TDI = tdi84(lon, lat, alt, TEI);\n\n    /** Earth's angular velocity skew-symmetric matrix (3x3) */\n    arma::mat33 WEII(arma::fill::zeros);\n    WEII(0, 1) = -WEII3;\n    WEII(1, 0) = WEII3;\n\n    /** geographic velocity in geodetic axes VBED(3x1) and flight path angles */\n    arma::vec3 VBED = TDI * (VBII - WEII * SBII);\n    arma::vec3 POLAR = pol_from_cart(VBED);\n\n    dvbe   = POLAR[0];\n    psivdx = DEG * POLAR[1];\n    thtvdx = DEG * POLAR[2];\n\n    return std::make_tuple(dvbe, psivdx, thtvdx);\n}\n\n/**\n * @return geocentric lon, lat, alt from inertial displacement vector\n * for spherical Earth\n *\n * @param[out] lonc = geocentric longitude - rad\n * @param[out] latc = geocentric latitude - rad\n * @param[out] altc = geocentric latitude - m\n *\n * @param[in] SBII = Inertial position - m\n * @param[in] time = simulation time - sec\n *\n * @author 010628 Created by Peter H Zipfel\n * @author 030416 Modified for SBII (not SBIE) input, PZi\n */\n\nstd::tuple<double, double, double> cad::geoc_in(arma::vec3 SBII,\n                                                const double &time) {\n    double lon_cel(0);\n    double sbii1 = SBII(0);\n    double sbii2 = SBII(1);\n    double sbii3 = SBII(2);\n    arma::vec3 RESULT;\n\n    /* tuple returns */\n    double lonc(0);\n    double latc(0);\n    double altc(0);\n\n    /** latitude */\n    double dbi = sqrt(sbii1 * sbii1 + sbii2 * sbii2 + sbii3 * sbii3);\n    latc = asin((sbii3) / dbi);\n\n    /** altitude */\n    altc = dbi - REARTH;\n\n    /** longitude */\n    double dum4 = asin(sbii2 / sqrt(sbii1 * sbii1 + sbii2 * sbii2));\n    /** Resolving the multi-valued arcsin function */\n    if ((sbii1 >= 0.0) && (sbii2 >= 0.0))\n        lon_cel = dum4;  /** quadrant I */\n    if ((sbii1 < 0.0) && (sbii2 >= 0.0))\n        lon_cel = (180. * RAD) - dum4;  /** quadrant II */\n    if ((sbii1 < 0.0) && (sbii2 < 0.0))\n        lon_cel = (180. * RAD) - dum4;  /** quadrant III */\n    if ((sbii1 > 0.0) && (sbii2 < 0.0))\n        lon_cel = (360. * RAD) + dum4;  /** quadrant IV */\n    lonc = lon_cel - WEII3 * time - GW_CLONG;\n    if ((lonc) > (180. * RAD))\n        lonc = -((360. * RAD) - lonc);  /** east positive, west negative */\n\n    return std::make_tuple(lonc, latc, altc);\n}\n\n/**\n * @return lon, lat, alt from displacement vector in Earth coord for spherical\n * earth\n * RETURN[0]=lon\n * RETURN[1]=lat\n * RETURN[2]=alt\n *\n * @param[in] SBIE = displacement of vehicle wrt Earth center in Earth coordinates\n *\n * @author 010628 Created by Peter H Zipfel\n */\nstd::tuple<double, double, double> cad::geoc_ine(arma::vec3 SBIE) {\n    double dum4(0);\n    double alamda(0);\n    double x(0), y(0), z(0);\n    double dbi(0);\n    double alt(0);\n    double lat(0);\n    double lon(0);\n\n    /** downloading inertial components */\n    x = SBIE(0);\n    y = SBIE(1);\n    z = SBIE(2);\n    /** Latitude */\n    // dbi = sqrt(x * x + y * y + z * z);\n    dbi = norm(SBIE);\n    lat = asin((z) / dbi);\n\n    /** Altitude */\n    alt = dbi - REARTH;\n\n    /** Longitude */\n    dum4 = asin(y / sqrt(x * x + y * y));\n\n    // Resolving the multi-valued arcsin function\n    if ((x >= 0.0) && (y >= 0.0)) {\n        alamda = dum4;  // quadrant I\n    }\n    if ((x < 0.0) && (y >= 0.0)) {\n        alamda = (180.0 * RAD) - dum4;  // quadrant II\n    }\n    if ((x < 0.0) && (y < 0.0)) {\n        alamda = (180.0 * RAD) - dum4;  // quadrant III\n    }\n    if ((x >= 0.0) && (y < 0.0)) {\n        alamda = (360.0 * RAD) + dum4;  // quadrant IV\n    }\n\n    lon = alamda;\n    if ((lon) > (180.0 * RAD)) {\n        lon = -((360.0 * RAD) - lon);  // east positive, west negative\n    }\n\n    return std::make_tuple(lon, lat, alt);\n}\n/**\n * @brief Earth gravitational acceleration, using the WGS 84 ellipsoid\n *      Ref: Chatfield, A.B.,\"Fundamentals of High Accuracy Inertial\n *      Navigation\",p.10, Prog.Astro and Aeronautics, Vol 174, AIAA, 1997.\n *\n * @return GRAVG(3x1) = gravitational acceleration in geocentric coord - m/s^2\n *\n * @param[in] SBII = inertial displacement vector - m\n * @param[in] time = simulation time - sec\n *\n * @author 030417 Created from FORTRAN by Peter H Zipfel\n */\narma::vec3 cad::grav84(arma::vec3 SBII, const double &time) {\n    double lonc(0), latc(0), altc(0);\n\n    std::tie(lonc, latc, altc) = geoc_in(SBII, time);\n    double dbi = norm(SBII);\n    double dum1 = GM / (dbi * dbi);\n    double dum2 = 3 * sqrt(5.);\n    double dum3 = pow((SMAJOR_AXIS / dbi), 2);\n    double gravg1 = -dum1 * dum2 * C20 * dum3 * sin(latc) * cos(latc);\n    double gravg2 = 0;\n    double gravg3 =\n        dum1 * (1. + dum2 / 2. * C20 * dum3 * (3. * pow(sin(latc), 2) - 1.));\n    return arma::vec3({gravg1, gravg2, gravg3});\n}\n\n/**\n * @brief Returns the inertial displacement vector from longitude, latitude and\n *      altitude\n *      using the WGS 84 reference ellipsoid\n *      Reference: \n *      1. Britting,K.R.\"Inertial Navigation Systems Analysis\"\n *         pp.45-49, Wiley, 1971\n *      2. Geodetic_Coordinate_Conversion.pdf James R. Clynch February 2006 p.3\n *\n * @return SBII(3x1) = Inertial vehicle position - m\n *\n * @param[in] lon = geodetic longitude - rad\n * @param[in] lat = geodetic latitude - rad\n * @param[in] alt = altitude above ellipsoid - m\n * @param[in] TEI = T.M from Inertia coordinate to ECEF coordinate\n *\n * @author 030411 Created from FORTRAN by Peter H Zipfel\n * @author 170121 Create Armadillo Version by soncyanga\n */\narma::vec3 cad::in_geo84(const double lon,\n                         const double lat,\n                         const double alt,\n                         arma::mat33 TEI) {\n    arma::vec3 SBIE;\n    arma::vec3 SBII;\n\n    // deflection of the normal, dd, and length of earth's radius to ellipse\n    // surface, R0\n\n    double r0 = SMAJOR_AXIS/sqrt(1 - FLATTENING * (2 - FLATTENING) * sin(lat) * sin(lat));\n\n    double e = sqrt(2 * FLATTENING - FLATTENING * FLATTENING);\n\n    // vehicle's displacement vector from earth's center SBID(3x1) in geodetic\n    // coord.\n    double dbi = r0 + alt;\n    SBIE(0, 0) = dbi * cos(lat)* cos(lon);\n    SBIE(1, 0) = dbi * cos(lat) * sin(lon);\n    SBIE(2, 0) = ((1. - e * e) * r0 + alt) * sin(lat);\n\n    SBII = trans(TEI) * SBIE;\n    // double dum = (1.0 - FLATTENING) * (1.0 - FLATTENING);\n    // double lamdas = atan(dum * tan(lat));\n    // double rs = sqrt(SMAJOR_AXIS * SMAJOR_AXIS / (1.0 + ((1.0 / dum) - 1.0) * sin(lamdas) * sin(lamdas)));\n\n    // SBIE(0, 0) = rs * cos(lamdas) * cos(lon) + alt * cos(lat) * cos(lon);\n    // SBIE(1, 0) = rs * cos(lamdas) * sin(lon) + alt * cos(lat) * sin(lon);\n    // SBIE(2, 0) = rs * sin(lamdas) + alt * sin(lat);\n\n    // SBII = trans(TEI) * SBIE;\n    return SBII;\n}\n\n/**\n * @brief Returns the inertial displacement vector from geocentric longitude, latitude\n *      and altitude\n *      for spherical Earth\n *\n * @return SBII = position of vehicle wrt center of Earth, in inertial coord\n *\n * @param[in] lon = geographic longitude - rad\n * @param[in] lat = geocentric latitude - rad\n * @param[in] alt = altitude above spherical Earth = m\n *\n * @author 010405 Created by Peter H Zipfel\n */\narma::vec3 cad::in_geoc(const double &lon,\n                   const double &lat,\n                   const double &alt,\n                   const double &time) {\n    arma::vec3 VEC;\n\n    double dbi = alt + REARTH;\n    double cel_lon = lon + WEII3 * time + GW_CLONG;\n    double clat = cos(lat);\n    double slat = sin(lat);\n    double clon = cos(cel_lon);\n    double slon = sin(cel_lon);\n\n    VEC(0) = dbi * clat * clon;\n    VEC(1) = dbi * clat * slon;\n    VEC(2) = dbi * slat;\n\n    return VEC;\n}\n\n/**\n * @brief Calculates inertial displacement and velocity vectors from orbital elements\n *      Reference: Bate et al. \"Fundamentals of Astrodynamics\", Dover 1971, p.71\n *\n * @return parabola_flag = 0 ok\n *                       = 1 not suitable (divide by zero), because parabolic\n *                           trajectory\n *\n * @param[out] SBII = Inertial position - m\n * @param[out] SBII = Inertial velocity - m/s\n *\n * @param[in] semi = semi-major axis of orbital ellipsoid - m\n * @param[in] ecc = eccentricity of elliptical orbit - ND\n * @param[in] inclx = inclination of orbital wrt equatorial plane - deg\n * @param[in] lon_anodex = celestial longitude of the ascending node - deg\n * @param[in] arg_perix = argument of periapsis (ascending node to periapsis) - deg\n * @param[in] true_anomx = true anomaly (periapsis to satellite) - deg\n *\n * @author 040510 Created by Peter H Zipfel\n */\nint cad::in_orb(arma::vec3 &SBII,\n           arma::vec3 &VBII,\n           const double &semi,\n           const double &ecc,\n           const double &inclx,\n           const double &lon_anodex,\n           const double &arg_perix,\n           const double &true_anomx) {\n    // local variable\n    int parabola_flag(0);\n    arma::vec3 SBIP;\n    arma::vec3 VBIP;\n    arma::mat33 TIP;\n\n    // semi-latus rectum from semi-major axis and eccentricity\n    double pp = semi * (1 - ecc * ecc);\n\n    // angles\n    double c_true_anom = cos(true_anomx * RAD);\n    double s_true_anom = sin(true_anomx * RAD);\n\n    // inertial distance in perifocal coordinates\n    double dbi = pp / (1 + ecc * c_true_anom);\n\n    // inertial position vector\n    SBIP[0] = dbi * c_true_anom;\n    SBIP[1] = dbi * s_true_anom;\n    SBIP[2] = 0;\n\n    // pypass calculation if parabola\n    if (pp == 0) {\n        parabola_flag = 1;\n    } else {\n        // inertial velocity\n        double dum = sqrt(GM / pp);\n        VBIP[0] = -dum * s_true_anom;\n        VBIP[1] = dum * (ecc + c_true_anom);\n        VBIP[2] = 0;\n    }\n\n    // transforming to inertial coordinates\n    TIP = tip(inclx * RAD, lon_anodex * RAD, arg_perix * RAD);\n    SBII = TIP * SBIP;\n    VBII = TIP * VBIP;\n\n    return parabola_flag;\n}\n\n/**\n * @brief Projects initial state through 'tgo' to final state along a Keplerian\n *      trajectory\n *      Based on Ray Morth, unpublished utility\n *\n * @return kepler_flan = 0: good Kepler projection;\n *                     = 1: bad (# of iterations>20, or neg. sqrt), no new proj cal,\n *                          use prev value;  - ND\n * @param[out] SPII = projected inertial position after tgo - m\n * @param[out] VPII = projected inertial velocity after tgo - m/s\n *\n * @param[in] SBII = current inertial position - m\n * @param[in] VBII = current inertial velocity - m/s\n * @param[in] tgo = time-to-go to projected point - sec\n *\n * @author 040319 Created from FORTRAN by Peter H Zipfel\n */\nint cad::kepler(arma::vec3 &SPII,\n           arma::vec3 &VPII,\n           arma::vec3 SBII,\n           arma::vec3 VBII,\n           const double &tgo) {\n    // local variables\n    double sde(0);\n    double cde(0);\n    int kepler_flag(0);\n\n    double sqrt_GM = sqrt(GM);\n    double ro = norm(SBII);\n    double vo = norm(VBII);\n    double rvo = dot(SBII, VBII);\n    double a1 = vo * vo / GM;\n    double sa = ro / (2 - ro * a1);\n    if (sa < 0) {\n        // return without re-calculating SPII, VPII\n        kepler_flag = 1;\n        return kepler_flag;\n    }\n    double smua = sqrt_GM * sqrt(sa);\n    double mdot = smua / (sa * sa);\n\n    // calculating 'de'iteratively\n    double dm = mdot * tgo;\n    double de = dm;  // initialize eccentricity\n    double a11 = rvo / smua;\n    double a21 = (sa - ro) / sa;\n    int count20 = 0;\n    double adm(0);\n    do {\n        cde = 1 - cos(de);\n        sde = sin(de);\n        double dmn = de + a11 * cde - a21 * sde;\n        double dmerr = dm - dmn;\n\n        adm = fabs(dmerr) / mdot;\n        double dmde = 1 + a11 * sde - a21 * (1 - cde);\n        de = de + dmerr / dmde;\n        count20++;\n        if (count20 > 20) {\n            // return without re-calculating SPII, VPII\n            kepler_flag = 1;\n            return kepler_flag;\n        }\n    }while (adm > SMALL);\n\n    // projected position\n    double fk = (ro - sa * cde) / ro;\n    double gk = (dm + sde - de) / mdot;\n    SPII = SBII * fk + VBII * gk;\n\n    // projected velocity\n    double rp = norm(SPII);\n    double fdk = -smua * sde / ro;\n    double gdk = rp - sa * cde;\n    VPII = SBII * (fdk / rp) + VBII * (gdk / rp);\n\n    return kepler_flag;\n}\n\n/**\n * @brief Projects initial state through 'tgo' to final state along a Keplerian\n *      trajectory\n *      Based on: Bate, Mueller, White, \"Fundamentals of Astrodynamics\", Dover 1971\n *\n * @return iter_flan = 0: # of iterations < 20;\n *                   = 1: # of iterations > 20;  - ND\n *\n * @param[out] SPII = projected inertial position after tgo - m\n * @param[out] VPII = projected inertial velocity after tgo - m/s\n *\n * @param[in] SBII = current inertial position - m\n * @param[in] VBII = current inertial velocity - m/s\n * @param[in] tgo = time-to-go to projected point - sec\n *\n * @author 040318 Created from ASTRO_KEP by Peter H Zipfel\n */\nint cad::kepler1(arma::vec3 &SPII,\n            arma::vec3 &VPII,\n            arma::vec3 SBII,\n            arma::vec3 VBII,\n            const double &tgo) {\n    double c(0);\n    double s(0);\n    double z(0);\n    double dt(0);\n    int iter_flag(0);\n\n    double ro = norm(SBII);\n    double vo = norm(VBII);\n    double al = (2 * GM / ro - vo * vo) / GM;\n    /*\n     * double en = -GM * al / 2;  // specific mechanical energy - J/kg\n     * Unused variable.\n     */\n    arma::vec3 AM = skew_sym(SBII) * VBII;\n    /*\n     * double h = norm(AM);  // angular momentum - m^2/s\n     * Unused variable.\n     */\n    double dum = dot(SBII, VBII);\n    double sqrt_GM = sqrt(GM);\n\n    // initial guaess of x\n    double x = 0;\n    int count20 = 0;\n\n    // calculating x using newton iteration\n    do {\n        count20++;\n        z = x * x * al;\n        std::tie(c, s) = kepler1_ucs(z);\n        dt =\n            (x * x * x * s + dum * x * x * c / sqrt_GM + ro * x * (1 - z * s)) /\n            sqrt_GM;\n        double dtx =\n            (x * x * c + dum * x * (1 - z * s) / sqrt_GM + ro * (1 - z * c)) /\n            sqrt_GM;\n        x = x + (tgo - dt) / dtx;\n    }while (fabs((tgo - dt) / tgo) > SMALL);\n\n    // projected inertial position\n    double f = 1 - x * x * c / ro;\n    double g = tgo - x * x * s / sqrt_GM;\n    SPII = SBII * f + VBII * g;\n\n    // projecting inertial velocity\n    double rx = norm(SPII);\n    double fd = sqrt_GM * x * (z * s - 1) / (ro * rx);\n    double gd = 1 - x * x * c / rx;\n    VPII = SBII * fd + VBII * gd;\n\n    // diagnostic: bad iteration if count20 > 20\n    if (count20 > 20)\n        iter_flag = 1;\n    return iter_flag;\n}\n\n/**\n * @brief Calculates utility functions c(z) and s(z) for kepler(...)\n *      Reference: Bate, Mueller, White, \"Fundamentals of Astrodynamics\", Dover 1971,\n *      p.196\n * \n * @param[out] c = c(z) utility function\n * @param[out] s = s(z) utility function\n *\n * @param[in] z = z-variable\n * \n * @author 040318 Created from ASTRO_UCS by Peter H Zipfel\n */\nstd::tuple<double, double> cad::kepler1_ucs(const double &z) {\n    double sd(0);\n    double cd(0);\n\n    /* tuple */\n    double c(0);\n    double s(0);\n\n    if (z > 0.1) {\n        c = (1 - cos(sqrt(z))) / z;\n        s = (sqrt(z) - sin(sqrt(z))) / sqrt(z * z * z);\n    }\n    if (z < -0.1) {\n        c = (1 - cosh(sqrt(-z))) / z;\n        s = (sinh(sqrt(-z)) - sqrt(-z)) / sqrt(-z * z * z);\n    }\n    if (fabs(z) <= 0.1) {\n        double dc = 2;\n        c = 1 / dc;\n        double dcd = -24;\n        cd = 1 / dcd;\n        double ds = 6;\n        s = 1 / ds;\n        double dsd = -120;\n        sd = 1 / dsd;\n\n        for (int k = 1; k < 7; k++) {\n            double z_pow_k = pow(-z, k);\n            int n = 2 * k + 1;\n            dc = dc * n * (n + 1);\n            c = c + z_pow_k / dc;\n            dcd = dcd * (n + 2) * (n + 3);\n            cd = cd - (k + 1) * z_pow_k / dcd;\n            ds = ds * (n + 1) * (n + 2);\n            s = s + z_pow_k / ds;\n            dsd = dsd * (n + 3) * (n + 4);\n            sd = sd - (k + 1) * z_pow_k / dsd;\n        }\n    }\n\n    return std::make_tuple(c, s);\n}\n\n/**\n * @brief Calculates the orbital elements from inertial displacement and velocity\n *      Reference: Bate et al. \"Fundamentals of Astrodynamics\", Dover 1971, p.58\n * \n * @return cadorbin_flag = 0 ok\n *                         1 'true_anomx' not calculated, because of circular orbit\n *                         2 'semi' not calculated, because parabolic orbit\n *                         3 'lon_anodex' not calculated, because equatorial orbit\n *                         13 'arg_perix' not calculated, because equatorialand/or\n *                            circular orbit\n * @param[out] semi = semi-major axis of orbital ellipsoid - m\n * @param[out] ecc = eccentricity of elliptical orbit - ND\n * @param[out] inclx = inclination of orbital wrt equatorial plane - deg\n * @param[out] lon_anodex = celestial longitude of the ascending node - deg\n * @param[out] arg_perix = argument of periapsis (ascending node to periapsis) - deg\n * @param[out] true_anomx = true anomaly (periapsis to satellite) - deg\n * \n * @param[in] SBII = Inertial position - m\n * @param[in] VBII = Inertial velocity - m/s\n * \n * @author 040510 Created by Peter H Zipfel\n * @author 170121 Create Armadillo Version by soncyang\n */\nint cad::orb_in(double &semi,\n                   double &ecc,\n                   double &inclx,\n                   double &lon_anodex,\n                   double &arg_perix,\n                   double &true_anomx,\n                   arma::vec3 &SBII,\n                   arma::vec3 &VBII) {\n    // local variable\n    int cadorbin_flag(0);\n    arma::vec3 NODE_I;\n    double lon_anode(0);\n    double arg_peri(0);\n    double true_anom(0);\n\n    // angular momentum vector of orbit\n    arma::mat ANGL_MOM_I = skew_sym(SBII) * VBII;\n    double angl_mom = norm(ANGL_MOM_I);\n\n    // vector of the ascending node (undefined if inclx=0)\n    NODE_I(0) = -ANGL_MOM_I(1);\n    NODE_I(1) = ANGL_MOM_I(0);\n    double node = norm(NODE_I);\n\n    // orbit eccentricity vector and magnitude\n    double dbi = norm(SBII);\n    double dvbi = norm(VBII);\n    arma::vec3 EI;\n    EI = (SBII * (dvbi * dvbi - GM / dbi) - VBII * dot(SBII, VBII)) * (1 / GM);\n    ecc = norm(EI);\n\n    // semi latus rectum\n    double pp = angl_mom * angl_mom / GM;\n\n    // semi-major axis of orbit\n    if (pp == 1)\n        cadorbin_flag = 2;\n    else\n        semi = pp / (1 - ecc * ecc);\n\n    // orbit inclination\n    double arg = ANGL_MOM_I(2) * (1 / angl_mom);\n    if (fabs(arg) > 1)\n        arg = 1;\n    inclx = acos(arg) * DEG;\n\n    // bypass calculations if equatorial orbit\n    if (node < SMALL) {\n        cadorbin_flag = 3;\n    } else {\n        // longitude of the ascending node\n        arg = NODE_I(0) / node;\n        if (fabs(arg) > 1)\n            arg = 1;\n        lon_anode = acos(arg);\n    }\n\n    // bypass calculations if circular and/or equatorial orbit\n    if (ecc < SMALL || node < SMALL) {\n        cadorbin_flag = 13;\n    } else {\n        // argument of periapsis\n        arg = dot(NODE_I, EI) * (1 / (node * ecc));\n        if (fabs(arg) > 1)\n            arg = 1;\n        arg_peri = acos(arg);\n    }\n\n    // bypass calculations if circular orbit\n    if (ecc < SMALL) {\n        cadorbin_flag = 1;\n    } else {\n        // true anomaly\n        arg = dot(SBII, EI) * (1 / (dbi * ecc));\n        if (fabs(arg) > 1)\n            arg = 1;\n        true_anom = acos(arg);\n    }\n\n    // quadrant resolution\n    double quadrant = dot(SBII, VBII);\n    if (quadrant >= 0)\n        true_anomx = true_anom * DEG;\n    else\n        true_anomx = (2 * PI - true_anom) * DEG;\n\n    if (EI(2) >= 0)\n        arg_perix = arg_peri * DEG;\n    else\n        arg_perix = (2 * PI - arg_peri) * DEG;\n\n    if (NODE_I(1) > 0)\n        lon_anodex = lon_anode * DEG;\n    else\n        lon_anodex = (2 * PI - lon_anode) * DEG;\n\n    return cadorbin_flag;\n}\n\n/**\n * @brief Returns the T.M. of geodetic wrt inertial coordinates\n *        using the WGS 84 reference ellipsoid\n *\n * @return TDI(3x3) = T.M.of geosetic wrt inertial coord - ND\n *\n * @param[in] lon = geodetic longitude - rad\n * @param[in] lat = geodetic latitude - rad\n * @param[in] alt = altitude above ellipsoid - m\n * @param[in] TEI = T.M from Inertia coordinate to ECEF coordinate\n *\n * @author 030424 Created by Peter H Zipfel\n * @author 170121 Create Armadillo Version by sonicyang\n */\narma::mat33 cad::tdi84(const double &lon,\n                           const double &lat,\n                           const double &alt,\n                           arma::mat33 TEI) {\n    arma::mat33 TDE;\n\n    // celestial longitude of vehicle at simulation 'time'\n    // double lon_cel = GW_CLONG + WEII3 * time + lon;\n\n    // T.M. of geodetic coord wrt ECEF coord., TDE(3x3)\n    double tdi13 = cos(lat);\n    double tdi33 = -sin(lat);\n    double tdi22 = cos(lon);\n    double tdi21 = -sin(lon);\n    TDE(0, 0) = tdi33 * tdi22;\n    TDE(0, 1) = -tdi33 * tdi21;\n    TDE(0, 2) = tdi13;\n    TDE(1, 0) = tdi21;\n    TDE(1, 1) = tdi22;\n    TDE(1, 2) = 0;\n    TDE(2, 0) = -tdi13 * tdi22;\n    TDE(2, 1) = tdi13 * tdi21;\n    TDE(2, 2) = tdi33;\n\n    return TDE * TEI;\n}\n\narma::mat33 cad::tde84(const double &lon,\n                           const double &lat,\n                           const double &alt) {\n    arma::mat33 TGE;\n    arma::mat33 TGD;\n\n    double r0 = SMAJOR_AXIS * (1. - FLATTENING * (1. - cos(2. * lat)) / 2. +\n                               5. * pow(FLATTENING, 2) * (1. - cos(4. * lat)) /\n                                   16.);  // eq 4-21\n    double dd = FLATTENING * sin(2. * lat) *\n                (1. - FLATTENING / 2. - alt / r0);  // eq 4-15\n\n    TGE = tge(lon, lat - dd);\n\n    // T.M. of geographic (geocentric) wrt geodetic coord., TGD(3x3)\n    TGD(0, 0) = cos(dd);\n    TGD(2, 2) = cos(dd);\n    TGD(1, 1) = 1;\n    TGD(2, 0) = sin(dd);\n    TGD(0, 2) = -sin(dd);\n\n\n    // T.M. of geodetic coord wrt inertial coord., TDI(3x3)\n    // double tdi13 = cos(lat);\n    // double tdi33 = -sin(lat);\n    // double tdi22 = cos(lon);\n    // double tdi21 = -sin(lon);\n    // TDE(0, 0) = tdi33 * tdi22;\n    // TDE(0, 1) = -tdi33 * tdi21;\n    // TDE(0, 2) = tdi13;\n    // TDE(1, 0) = tdi21;\n    // TDE(1, 1) = tdi22;\n    // TDE(1, 2) = 0;\n    // TDE(2, 0) = -tdi13 * tdi22;\n    // TDE(2, 1) = tdi13 * tdi21;\n    // TDE(2, 2) = tdi33;\n\n    return trans(TGD) * TGE;\n}\n\n/**\n * @brief Returns the T.M. of earth wrt inertial coordinates\n *\n * @return TEI = T.M. of Earthy wrt inertial coordinates\n *\n * @param[in] = time since start of simulation - s\n *\n * @author 010628 Created by Peter H Zipfel\n */\narma::mat33 cad::tei(const double &time) {\n    arma::mat33 TEI(arma::fill::eye);\n\n    double xi = WEII3 * time + GW_CLONG;\n    double sxi = sin(xi);\n    double cxi = cos(xi);\n\n    TEI(0, 0) = cxi;\n    TEI(0, 1) = sxi;\n    TEI(1, 0) = -sxi;\n    TEI(1, 1) = cxi;\n\n    return TEI;\n}\n\n/**\n * @return TGE = the T.M. of geographic wrt earth coordinates, TGE\n *               spherical Earth only\n *\n * @param[in] lon = geographic longitude - rad\n * @param[in] lat = geographic latitude - rad\n *\n * @author 010628 Created by Peter H Zipfel\n */\narma::mat33 cad::tge(const double &lon, const double &lat) {\n    arma::mat33 TGE(arma::fill::zeros);\n\n    double clon = cos(lon);\n    double slon = sin(lon);\n    double clat = cos(lat);\n    double slat = sin(lat);\n\n    TGE(0, 0) = (-slat * clon);\n    TGE(0, 1) = (-slat * slon);\n    TGE(0, 2) = clat;\n    TGE(1, 0) = -slon;\n    TGE(1, 1) = clon;\n    TGE(1, 2) = 0.0;\n    TGE(2, 0) = (-clat * clon);\n    TGE(2, 1) = (-clat * slon);\n    TGE(2, 2) = -slat;\n\n    return TGE;\n}\n\n/**\n * @brief Returns the T.M. of geographic (geocentric) wrt inertial\n *        using the WGS 84 reference ellipsoid\n *        Reference: Britting,K.R.\"Inertial Navigation Systems Analysis\",\n *        pp.45-49, Wiley, 1971\n *\n * @return TGI(3x3) = T.M.of geographic wrt inertial coord - ND\n * \n * @param[in] lon = geodetic longitude - rad\n * @param[in] lat = geodetic latitude - rad\n * @param[in] alt = altitude above ellipsoid - m\n *\n * @author 030414 Created from FORTRAN by Peter H Zipfel\n * @author 170121 Create Armadillo Version by soncyang\n */\narma::mat33 cad::tgi84(const double &lon,\n                  const double &lat,\n                  const double &alt,\n                  arma::mat33 TEI) {\n    arma::mat33 TDI = tdi84(lon, lat, alt, TEI);\n    arma::mat33 TGD(arma::fill::zeros);\n\n    // deflection of the normal, dd, and length of earth's radius to ellipse\n    // surface, R0\n    double r0 = SMAJOR_AXIS * (1. - FLATTENING * (1. - cos(2. * lat)) / 2. +\n                               5. * pow(FLATTENING, 2) * (1. - cos(4. * lat)) /\n                                   16.);  // eq 4-21\n    double dd = FLATTENING * sin(2. * lat) *\n                (1. - FLATTENING / 2. - alt / r0);  // eq 4-15\n\n    // T.M. of geographic (geocentric) wrt geodetic coord., TGD(3x3)\n    TGD(0, 0) = cos(dd);\n    TGD(2, 2) = cos(dd);\n    TGD(1, 1) = 1;\n    TGD(2, 0) = sin(dd);\n    TGD(0, 2) = -sin(dd);\n\n    // T.M. of geographic (geocentric) wrt inertial coord., TGI(3x3)\n    arma::mat33 TGI = TGD * TDI;\n\n    return TGI;\n}\n/**\n * @brief Returns the transformation matrix of inertial wrt perifocal coordinates\n *\n * @return TIP = TM of inertial wrt perifocal\n *\n * @param[in] incl = inclination of orbital wrt equatorial plane - rad\n * @param[in] lon_anode = celestial longitude of the ascending node - rad\n * @param[in] arg_peri = argument of periapsis (ascending node to periapsis) - rad\n *\n * @author 040510 Created by Peter H Zipfel\n */\narma::mat33 cad::tip(const double &incl,\n                const double &lon_anode,\n                const double &arg_peri) {\n    // local variable\n    arma::mat33 TIP(arma::fill::zeros);\n\n    double clon_anode = cos(lon_anode);\n    double carg_peri = cos(arg_peri);\n    double cincl = cos(incl);\n    double slon_anode = sin(lon_anode);\n    double sarg_peri = sin(arg_peri);\n    double sincl = sin(incl);\n\n    TIP(0, 0) = clon_anode * carg_peri - slon_anode * sarg_peri * cincl;\n    TIP(0, 1) = -clon_anode * sarg_peri - slon_anode * carg_peri * cincl;\n    TIP(0, 2) = slon_anode * sincl;\n    TIP(1, 0) = slon_anode * carg_peri + clon_anode * sarg_peri * cincl;\n    TIP(1, 1) = -slon_anode * sarg_peri + clon_anode * carg_peri * cincl;\n    TIP(1, 2) = -clon_anode * sincl;\n    TIP(2, 0) = sarg_peri * sincl;\n    TIP(2, 1) = carg_peri * sincl;\n    TIP(2, 2) = cincl;\n\n    return TIP;\n}\n", "meta": {"hexsha": "9f53347301faa39f92c4443e9e59039d7e88fcaf", "size": 30754, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "models/cad/src/cad_utility.cpp", "max_stars_repo_name": "cihuang123/Next-simulation", "max_stars_repo_head_hexsha": "e8552a5804184b30022d103d47c8728fb242b5bc", "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": "models/cad/src/cad_utility.cpp", "max_issues_repo_name": "cihuang123/Next-simulation", "max_issues_repo_head_hexsha": "e8552a5804184b30022d103d47c8728fb242b5bc", "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": "models/cad/src/cad_utility.cpp", "max_forks_repo_name": "cihuang123/Next-simulation", "max_forks_repo_head_hexsha": "e8552a5804184b30022d103d47c8728fb242b5bc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-05-05T14:59:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-17T03:19:45.000Z", "avg_line_length": 30.7232767233, "max_line_length": 109, "alphanum_fraction": 0.5560902647, "num_tokens": 10085, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850110816423, "lm_q2_score": 0.7853085808877581, "lm_q1q2_score": 0.7352726533590034}}
{"text": "static bool eigen_did_assert = false;\n#define eigen_assert(X) if(!eigen_did_assert && !(X)){ std::cout << \"### Assertion raised in \" << __FILE__ << \":\" << __LINE__ << \":\\n\" #X << \"\\n### The following would happen without assertions:\\n\"; eigen_did_assert = true;}\n\n#include <iostream>\n#include <Eigen/Eigen>\n\n#ifndef M_PI\n#define M_PI 3.1415926535897932384626433832795\n#endif\n\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  Matrix3f A(3,3);\nA << 1,2,3,  4,5,6,  7,8,10;\nMatrix<float,3,2> B;\nB << 3,1, 3,1, 4,1;\nMatrix<float,3,2> X;\nX = A.fullPivLu().solve(B);\ncout << \"The solution with right-hand side (3,3,4) is:\" << endl;\ncout << X.col(0) << endl;\ncout << \"The solution with right-hand side (1,1,1) is:\" << endl;\ncout << X.col(1) << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "36178944613664e3e451a84f8099be99d72677be", "size": 802, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/snippets/compile_Tutorial_solve_multiple_rhs.cpp", "max_stars_repo_name": "mousepawmedia/libdeps", "max_stars_repo_head_hexsha": "b004d58d5b395ceaf9fdc993cfb00e91334a5d36", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2021-02-27T11:00:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T10:31:46.000Z", "max_issues_repo_path": "doc/snippets/compile_Tutorial_solve_multiple_rhs.cpp", "max_issues_repo_name": "mousepawmedia/libdeps", "max_issues_repo_head_hexsha": "b004d58d5b395ceaf9fdc993cfb00e91334a5d36", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-11-14T23:14:58.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-14T23:14:58.000Z", "max_forks_repo_path": "doc/snippets/compile_Tutorial_solve_multiple_rhs.cpp", "max_forks_repo_name": "mousepawmedia/libdeps", "max_forks_repo_head_hexsha": "b004d58d5b395ceaf9fdc993cfb00e91334a5d36", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-03-13T13:28:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-05T02:26:02.000Z", "avg_line_length": 25.8709677419, "max_line_length": 224, "alphanum_fraction": 0.6421446384, "num_tokens": 277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769413, "lm_q2_score": 0.8056321959813275, "lm_q1q2_score": 0.7350879476578092}}
{"text": "#include <Eigen/Dense>\n#include \"../include/numerical_gradient.h\"\n\nnamespace MyDL\n{\n\n    using namespace Eigen;\n\n    MatrixXd numerical_gradient(double (*f)(MatrixXd&), MatrixXd& x)\n    {\n        double h = 1e-4;\n        int size_x = x.rows() * x.cols();\n        MatrixXd grad(x.rows(), x.cols());\n\n        for (int i = 0; i < size_x; i++)\n        {\n            double tmp_val = x(i);\n            double f_plus_h;\n            double f_minus_h;\n\n            // f(x + h)\n            x(i) = tmp_val + h;\n            f_plus_h = f(x);\n\n            // f(x - h)\n            x(i) = tmp_val - h;\n            f_minus_h = f(x);\n\n            grad(i) = (f_plus_h - f_minus_h) / (2 * h);\n\n            x(i) = tmp_val;\n        }\n\n        return grad;\n    }\n\n    // TwoLayerNet\u306a\u3069\u3067\u7528\u3044\u308b\u3082\u306e(\u30e9\u30e0\u30c0\u5f0f\u4f7f\u7528\u30fbDNN\u306e\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u306b\u542b\u307e\u308c\u308b\u30d1\u30e9\u30e1\u30fc\u30bf\u3092\u53c2\u7167\u3057\u3066\u4f7f\u7528\u3059\u308b\u5834\u5408)\n    MatrixXd numerical_gradient(const std::function<double(MatrixXd)> &f, MatrixXd &x)\n    {\n        double h = 1e-4;\n        int size_x = x.rows() * x.cols();\n        MatrixXd grad(x.rows(), x.cols());\n\n        for (int i = 0; i < size_x; i++)\n        {\n            double tmp_val = x(i);\n            double f_plus_h;\n            double f_minus_h;\n\n            // f(x + h)\n            x(i) = tmp_val + h;\n            f_plus_h = f(x);\n\n            // f(x - h)\n            x(i) = tmp_val - h;\n            f_minus_h = f(x);\n\n            grad(i) = (f_plus_h - f_minus_h) / (2 * h);\n\n            x(i) = tmp_val;\n        }\n\n        return grad;\n    }\n\n    MatrixXd numerical_gradient(const std::function<vector<MatrixXd>(MatrixXd)> &f, MatrixXd &X)\n    {\n        double h = 1e-4;\n        int size_X = X.rows() * X.cols();\n        MatrixXd grad(X.rows(), X.cols());\n        double f_plus_h, f_minus_h;\n\n        for (int i = 0; i < size_X; i++)\n        {\n            double tmp_val = X(i);\n\n            // f(x + h)\n            X(i) = tmp_val + h;\n            f_plus_h = f(X)[0].sum();\n\n            // f(x - h)\n            X(i) = tmp_val - h;\n            f_minus_h = f(X)[0].sum();\n\n            grad(i) = (f_plus_h - f_minus_h) / (2 * h);\n\n            X(i) = tmp_val;\n        }\n\n        return grad;\n    }\n\n    MatrixXd numerical_gradient(const std::function<vector<MatrixXd>(VectorXd)> &f, VectorXd &X)\n    {\n        double h = 1e-4;\n        int size_X = X.rows();\n        VectorXd grad(X.rows());\n        double f_plus_h, f_minus_h;\n\n        for (int i = 0; i < size_X; i++)\n        {\n            double tmp_val = X(i);\n\n            // f(x + h)\n            X(i) = tmp_val + h;\n            f_plus_h = f(X)[0].sum();\n\n            // f(x - h)\n            X(i) = tmp_val - h;\n            f_minus_h = f(X)[0].sum();\n\n            grad(i) = (f_plus_h - f_minus_h) / (2 * h);\n\n            X(i) = tmp_val;\n        }\n\n        return grad;\n    }\n}", "meta": {"hexsha": "fa96429a385939fcba6b73c54c15ab4821c2d8d8", "size": 2739, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/numerical_gradient.cpp", "max_stars_repo_name": "potedo/zeroDL_cpp", "max_stars_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-22T15:26:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-22T15:26:20.000Z", "max_issues_repo_path": "src/numerical_gradient.cpp", "max_issues_repo_name": "potedo/zeroDL_cpp", "max_issues_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "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/numerical_gradient.cpp", "max_forks_repo_name": "potedo/zeroDL_cpp", "max_forks_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "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.0168067227, "max_line_length": 96, "alphanum_fraction": 0.4381161008, "num_tokens": 795, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769413, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.7350879433997298}}
{"text": "/* \n   Oscar Efrain RAMOS PONCE, LAAS-CNRS\n   Date: 28/10/2014\n   Object to estimate a polynomial that fits some data.\n*/\n\n#ifndef _POLY_ESTIMATOR_HH_\n#define _POLY_ESTIMATOR_HH_\n\n#include <Eigen/Dense>\n#include <vector>\n\n\n/**\n * Compute the pseudo-inverse using Eigen\n * @param [in] matrix_in is the input matrix.\n * @param [out] pseudo_inv is the pseudo-inverse of the input matrix.\n * @param [in] pinvtoler is the tolerance in the SVD decomposition\n */ \nvoid pinv(const Eigen::MatrixXd& matrix_in, \n          Eigen::MatrixXd& pseudo_inv, \n          const double& pinvtoler = 1.0e-6);\n\n/**\n * Object to fit a polynomial of a given order. It provides a generic fitting\n * polynomial of any order. However, it cannot be used by itself since the\n * proper coefficient of the polynomial (which represents the estimation) needs\n * to be specified. Moreover, the derived classes implement a faster computation\n * based on the specific case.\n *\n */\nclass PolyEstimator\n{\n\npublic:\n\n  /**\n   * Create a polynomial estimator on a window of length N\n   * @param order is the order of the polynomial estimator.\n   * @param N is the window length.\n   * @param dt is the control (sampling) time\n   */ \n  PolyEstimator(const unsigned int& order, \n                const unsigned int& N,\n                const double& dt);\n  \n  /**\n   * Estimate the generic polynomial given a new element. The order of the\n   * polynomial is specified in the constructor. Note that this function can be\n   * slow if no specialization of fit() has been done, since the generic\n   * algorithm would be used.\n   * @param [out] estimee is the calculated estimation\n   * @param [in] data_element is the new data vector.\n   * @param [in] time is the time stamp corresponding to the new data.\n   */\n  void estimate(std::vector<double>& estimee,\n                const std::vector<double>& data_element, \n                const double& time);\n  \n  /**\n   * Estimate the polynomial given a new element assuming a constant time\n   * difference. This constant time difference between consecutive samples is\n   * given by dt (specified in the constructor). <br>Note: This function will\n   * only work if dt is different to zero.\n   * @param [out] estimee is the calculated estimation.\n   * @param [in] data_element is the new data vector.\n   */\n  virtual void estimate(std::vector<double>& estimee,\n                        const std::vector<double>& data_element) = 0;\n  \n  /**\n   * Estimate the polynomial given a new element using a recursive\n   * algorithm. This method is faster. However, it takes the time as it is (it\n   * does not set the lowest time to zero), which can create \"ill-conditions\".\n   * @param [out] estimee is the calculated estimation\n   * @param [in] data_element is the new data.\n   * @param [in] time is the time stamp corresponding to the new data.\n   */\n  virtual void estimateRecursive(std::vector<double>& estimee,\n                                 const std::vector<double>& data_element, \n                                 const double& time) = 0;\n\n  /**\n   * Get the time derivative of the estimated polynomial.\n   * @param [out] estimeeDerivative is the calculated time derivative.\n   * @param [in] order The order of the derivative (e.g. 1 means the first derivative).\n   */\n  virtual void getEstimateDerivative(std::vector<double>& estimeeDerivative,\n                                     const unsigned int order) = 0;\n  \n  /**\n   * Set the size of the filter window.\n   * @param [in] N size\n   */\n  void setWindowLength(const unsigned int& N);\n\n  /**\n   * Get the size of the filter window.\n   * @return Size\n   */\n  unsigned int getWindowLength();\n\nprotected:\n\n  /**\n   * Find the regressor which best fits in least square sense the last N data\n   * sample couples. The order of the regressor is given in the constructor.\n   */ \n  virtual void fit();\n  \n  /**\n   * Get the estimation when using the generic fit function (in poly-estimator)\n   */\n  virtual double getEsteeme() = 0;\n\n  /// Order of the polynomial estimator\n  unsigned int order_;\n\n  /// Window length \n  unsigned int N_;\n\n  /// Sampling (control) time \n  double dt_;\n\n  /// Indicate that dt is zero (dt is invalid)\n  bool dt_zero_;\n\n  /// Indicate that there are not enough elements to compute. The reason is that\n  /// it is one of the first runs, and the estimate will be zero.\n  bool first_run_;\n\n  /// All the data (N elements of size dim)\n  std::vector< std::vector<double> > elem_list_;\n\n  /// Time vector corresponding to each element in elem_list_\n  std::vector< double > time_list_;\n\n  /// Circular index to each data and time element\n  unsigned int pt_;\n\n  /// Coefficients for the least squares solution\n  Eigen::VectorXd coeff_;\n \n  /// Time vector setting the lowest time to zero (for numerical stability).\n  std::vector<double> t_;\n\n  /// Data vector for a single dimension (a single dof). It is only one 'column'\n  /// of the elem_list_ 'matrix'\n  std::vector<double> x_;\n\n  /// Matrix containing time components. It is only used for the generic fit\n  /// computation, such that the estimation is \\f$c = R^{\\#} x\\f$, where \\f$x\\f$\n  /// is the data vector.\n  Eigen::MatrixXd R_; \n\n};\n\n\n#endif \n", "meta": {"hexsha": "a39d4fcc532326796f7ac88d27aa9a58f93251d8", "size": 5165, "ext": "hh", "lang": "C++", "max_stars_repo_path": "include/sot/torque_control/utils/poly-estimator.hh", "max_stars_repo_name": "jviereck/sot-torque-control", "max_stars_repo_head_hexsha": "90409a656e5b5be4dd4ff937724154579861c20f", "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": "include/sot/torque_control/utils/poly-estimator.hh", "max_issues_repo_name": "jviereck/sot-torque-control", "max_issues_repo_head_hexsha": "90409a656e5b5be4dd4ff937724154579861c20f", "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": "include/sot/torque_control/utils/poly-estimator.hh", "max_forks_repo_name": "jviereck/sot-torque-control", "max_forks_repo_head_hexsha": "90409a656e5b5be4dd4ff937724154579861c20f", "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": 32.28125, "max_line_length": 87, "alphanum_fraction": 0.6726040658, "num_tokens": 1248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767938900121, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7349920799239641}}
{"text": "/********************************************************************************\n * Copyright 2009 The Robotics Group, The Maersk Mc-Kinney Moller Institute,\n * Faculty of Engineering, University of Southern Denmark\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n ********************************************************************************/\n\n#include \"LinearAlgebra.hpp\"\n\n#include <rw/core/macros.hpp>\n\n#include <Eigen/SVD>\n\nusing namespace rw::math;\n\nEigen::MatrixXd LinearAlgebra::pseudoInverse (const Eigen::MatrixXd& am, double precision)\n{\n    if (am.rows () < am.cols ()) {\n        // RW_THROW(\"pseudoInverse require rows >= to cols!\");\n        Eigen::MatrixXd a = am.transpose ();\n        Eigen::JacobiSVD< Eigen::MatrixXd > svd =\n            a.jacobiSvd (Eigen::ComputeThinU | Eigen::ComputeThinV);\n        double tolerance = precision * std::max (a.cols (), a.rows ()) *\n                           svd.singularValues ().array ().abs ().maxCoeff ();\n        return (svd.matrixV () *\n                Eigen::MatrixXd ((svd.singularValues ().array ().abs () > tolerance)\n                                     .select (svd.singularValues ().array ().inverse (), 0))\n                    .asDiagonal () *\n                svd.matrixU ().adjoint ())\n            .transpose ();\n    }\n    else {\n        Eigen::JacobiSVD< Eigen::MatrixXd > svd =\n            am.jacobiSvd (Eigen::ComputeThinU | Eigen::ComputeThinV);\n        double tolerance = precision * std::max (am.cols (), am.rows ()) *\n                           svd.singularValues ().array ().abs ().maxCoeff ();\n        return svd.matrixV () *\n               Eigen::MatrixXd ((svd.singularValues ().array ().abs () > tolerance)\n                                    .select (svd.singularValues ().array ().inverse (), 0))\n                   .asDiagonal () *\n               svd.matrixU ().adjoint ();\n    }\n}\n\nvoid LinearAlgebra::svd (const Eigen::MatrixXd& M, Eigen::MatrixXd& U, Eigen::VectorXd& sigma,\n                         Eigen::MatrixXd& V)\n{\n    const Eigen::JacobiSVD< Eigen::MatrixXd > svd =\n        M.jacobiSvd (Eigen::ComputeFullU | Eigen::ComputeFullV);\n    U     = svd.matrixU ();\n    sigma = svd.singularValues ();\n    V     = svd.matrixV ();\n}\n\nbool LinearAlgebra::checkPenroseConditions (const Eigen::MatrixXd& A, const Eigen::MatrixXd& X,\n                                            double prec)\n{\n    const Eigen::MatrixXd AX = A * X;\n    const Eigen::MatrixXd XA = X * A;\n\n    if (((AX * A) - A).lpNorm< Eigen::Infinity > () > prec)\n        return false;\n    if (((XA * X) - X).lpNorm< Eigen::Infinity > () > prec)\n        return false;\n    if ((AX.transpose () - AX).lpNorm< Eigen::Infinity > () > prec)\n        return false;\n    if ((XA.transpose () - XA).lpNorm< Eigen::Infinity > () > prec)\n        return false;\n    return true;\n}\n\ntemplate<>\nstd::pair< LinearAlgebra::EigenMatrix< double >::type, LinearAlgebra::EigenVector< double >::type >\nLinearAlgebra::eigenDecompositionSymmetric< double > (const Eigen::MatrixXd& Am1)\n{\n    Eigen::SelfAdjointEigenSolver< Eigen::MatrixXd > eigenSolver;\n    eigenSolver.compute (Am1);\n    return std::make_pair (eigenSolver.eigenvectors (), eigenSolver.eigenvalues ());\n}\n\ntemplate<>\nstd::pair< LinearAlgebra::EigenMatrix< std::complex< double > >::type,\n           LinearAlgebra::EigenVector< std::complex< double > >::type >\nLinearAlgebra::eigenDecomposition< double > (const Eigen::MatrixXd& Am1)\n{\n    Eigen::EigenSolver< Eigen::MatrixXd > eigenSolver;\n    eigenSolver.compute (Am1);\n    return std::make_pair (eigenSolver.eigenvectors (), eigenSolver.eigenvalues ());\n}\n", "meta": {"hexsha": "96ca35d3fb9b8f0b0fa144b384da5b705241b8b4", "size": 4109, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RobWork/src/rw/math/LinearAlgebra.cpp", "max_stars_repo_name": "ZLW07/RobWork", "max_stars_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-29T14:16:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T14:16:27.000Z", "max_issues_repo_path": "RobWork/src/rw/math/LinearAlgebra.cpp", "max_issues_repo_name": "ZLW07/RobWork", "max_issues_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "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": "RobWork/src/rw/math/LinearAlgebra.cpp", "max_forks_repo_name": "ZLW07/RobWork", "max_forks_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "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": 41.09, "max_line_length": 99, "alphanum_fraction": 0.5874908737, "num_tokens": 956, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248242542284, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.7349395015094836}}
{"text": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE MatrixTests\n#include <boost/test/unit_test.hpp>\n#include <stdlib.h>\n#include <algorithm>\n#include <array>\n#include <stdlib.h>\n\n#include \"graph/PBQPGraph.hpp\"\n#include \"graph/Matrix.hpp\"\n#include \"graph/PBQPNode.hpp\"\n#include \"graph/PBQPEdge.hpp\"\n\nnamespace pbqppapa {\n\n/**\n * Generates a n x n matrix filled with only 1\n */\ntemplate<typename T>\nMatrix<T> genMatrix(int n, int value) {\n\tT* data = new T[n * n];\n\tMatrix<T> mat = Matrix<T>(n, n, data);\n\tdelete data;\n\tfor (int i = 0; i < n * n; i++) {\n\t\tmat.getRaw(i) = value;\n\t}\n\treturn mat;\n}\n\ntemplate<typename T>\nMatrix<T> genMatrixAscending(int n, int value) {\n\tT* data = new T[n * n];\n\tMatrix<T> matrix = Matrix<T>(n, n, data);\n\tdelete data;\n\tfor (int i = 0; i < n * n; i++) {\n\t\tmatrix.getRaw(i) = value++;\n\t}\n\treturn matrix;\n}\n\nMatrix<int> genMatrixRandom(int maxLength) {\n\tsrand(time(NULL));\n\tint rows = rand() % maxLength + 1;\n\tint columns = rand() % maxLength + 1;\n\tMatrix<int> matrix = Matrix<int>(rows, columns);\n\tfor (int row = 0; row < rows; row++) {\n\t\tfor (int column = 0; column < columns; column++) {\n\t\t\tmatrix.get(row, column) = rand();\n\t\t}\n\t}\n\treturn matrix;\n}\n\n//Not used anywhere at the moment, but intentionally left here, because it massively eases debugging\nvoid printMatrix(Matrix<int>& matrix) {\n\tBOOST_TEST_MESSAGE(\"---------\");\n\tBOOST_TEST_MESSAGE(\"Rows\" << matrix.getRowCount());\n\tBOOST_TEST_MESSAGE(\"Columns\" << matrix.getColumnCount());\n\tfor (int row = 0; row < matrix.getRowCount(); row++) {\n\t\tfor (int column = 0; column < matrix.getColumnCount(); column++) {\n\t\t\tBOOST_TEST_MESSAGE(\n\t\t\t\t\t\"Column: \" << column << \" ; \" << \"Row: \" << row << \"  \" << matrix.get(row, column));\n\t\t}\n\t\tBOOST_TEST_MESSAGE(\"---\");\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(basicMatrixGeneration) {\n\tfor (int i = 0; i <= 15; i++) {\n\t\tMatrix<int> matrix = genMatrix<int>(i, i);\n\t\tBOOST_CHECK_EQUAL(matrix.getColumnCount(), i);\n\t\tBOOST_CHECK_EQUAL(matrix.getRowCount(), i);\n\t\tBOOST_CHECK_EQUAL(matrix.getElementCount(), i * i);\n\t\tint count = 0;\n\t\tfor (int row = 0; row < i; row++) {\n\t\t\tfor (int column = 0; column < i; column++) {\n\t\t\t\tBOOST_CHECK_EQUAL(matrix.get(row, column), i);\n\t\t\t\tBOOST_CHECK_EQUAL(matrix.getRaw(count++), i);\n\t\t\t}\n\t\t}\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(matrixPlus) {\n\tint size = 15;\n\tint firstValue = 2358;\n\tint secondValue = 2734;\n\tMatrix<int> matrix = genMatrixAscending<int>(size, firstValue);\n\tMatrix<int> matrix2 = genMatrixAscending<int>(size, secondValue);\n\tmatrix += matrix2;\n\tint counter = 0;\n\tfor (int row = 0; row < size; row++) {\n\t\tfor (int column = 0; column < size; column++) {\n\t\t\tBOOST_CHECK_EQUAL(matrix.get(row, column),\n\t\t\t\t\tfirstValue + secondValue + (counter++ * 2));\n\t\t}\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(matrixMinus) {\n\tint size = 15;\n\tint firstValue = 473235;\n\tint secondValue = 9284736;\n\tMatrix<int> matrix = genMatrixAscending<int>(size, firstValue);\n\tMatrix<int> matrix2 = genMatrixAscending<int>(size, secondValue);\n\tmatrix -= matrix2;\n\tfor (int row = 0; row < size; row++) {\n\t\tfor (int column = 0; column < size; column++) {\n\t\t\tBOOST_CHECK_EQUAL(matrix.get(row, column),\n\t\t\t\t\tfirstValue - secondValue);\n\t\t}\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(matrixMultiply) {\n\tint size = 15;\n\tint value = 425327;\n\tint factor = 18;\n\tMatrix<int> matrix = genMatrixAscending<int>(size, value);\n\tmatrix *= factor;\n\tint counter = 0;\n\tfor (int row = 0; row < size; row++) {\n\t\tfor (int column = 0; column < size; column++) {\n\t\t\tBOOST_CHECK_EQUAL(matrix.get(row, column),\n\t\t\t\t\t(value + counter++) * factor);\n\t\t}\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(matrixDivide) {\n\tint size = 15;\n\tint value = 38482;\n\tint divisor = 3;\n\tMatrix<int> matrix = genMatrixAscending<int>(size, value);\n\tmatrix /= divisor;\n\tint counter = 0;\n\tfor (int row = 0; row < size; row++) {\n\t\tfor (int column = 0; column < size; column++) {\n\t\t\tBOOST_CHECK_EQUAL(matrix.get(row, column),\n\t\t\t\t\t(value + counter++) / divisor);\n\t\t}\n\t}\n}\n\ntemplate<typename T>\nvoid checkMatrixTranspose(Matrix<T>& m1, Matrix<T>& m2) {\n\tBOOST_CHECK_EQUAL(m1.getColumnCount(), m2.getRowCount());\n\tBOOST_CHECK_EQUAL(m1.getRowCount(), m2.getColumnCount());\n\tfor (int row = 0; row < m1.getRowCount(); row++) {\n\t\tfor (int column = 0; column < m1.getColumnCount(); column++) {\n\t\t\tBOOST_CHECK_EQUAL(m1.get(row, column), m2.get(column, row));\n\t\t}\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(matrixTranspose) {\n\tfor (int i = 0; i < 20; i++) {\n\t\tMatrix<int> matrix = genMatrixRandom(20);\n\t\tMatrix<int> transposed = matrix.transpose();\n\t\tcheckMatrixTranspose<int>(matrix, transposed);\n\t}\n}\n\n}\n\n", "meta": {"hexsha": "5f1f31db7fdce824ebe9479d995a9d0ac4e4b64e", "size": 4494, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/graph/MatrixTests.cpp", "max_stars_repo_name": "sgraf812/pbqp-papa", "max_stars_repo_head_hexsha": "b5ae6fcb0842cb66956cccc4663f6fd9e6f6ae07", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-08-10T04:18:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-10T04:18:11.000Z", "max_issues_repo_path": "test/graph/MatrixTests.cpp", "max_issues_repo_name": "sgraf812/pbqp-papa", "max_issues_repo_head_hexsha": "b5ae6fcb0842cb66956cccc4663f6fd9e6f6ae07", "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/graph/MatrixTests.cpp", "max_forks_repo_name": "sgraf812/pbqp-papa", "max_forks_repo_head_hexsha": "b5ae6fcb0842cb66956cccc4663f6fd9e6f6ae07", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-03-07T10:20:50.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-07T10:20:50.000Z", "avg_line_length": 27.0722891566, "max_line_length": 100, "alphanum_fraction": 0.6577659101, "num_tokens": 1264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.896251378675949, "lm_q2_score": 0.8198933315126792, "lm_q1q2_score": 0.7348305287354556}}
{"text": "// Barrier functions that grow to infinity as x -> 0+. Includes gradient and\n// hessian functions, too. These barrier functions can be used to impose\n// inequlity constraints on a function.\n\n#pragma once\n\n#include <Eigen/Core>\n\nnamespace ipc {\n\n/// @brief Function that grows to infinity as x approaches 0 from the right.\n///\n/// \\f$b(d) = -(d-\\hat{d})^2\\ln\\left(\\frac{d}{\\hat{d}}\\right)\\f$\n///\n/// @param d The distance.\n/// @param dhat Activation distance of the barrier.\n/// @return The value of the barrier function at d.\ntemplate <typename T> T barrier(const T& d, double dhat);\n\n/// @brief Derivative of the barrier function.\n///\n/// \\f$b'(d) = (\\hat{d}-d) \\left( 2\\ln\\left( \\frac{d}{\\hat{d}} \\right) -\n/// \\frac{\\hat{d}}{d} + 1\\right)\\f$\n///\n/// @param d The distance.\n/// @param dhat Activation distance of the barrier.\n/// @return The derivative of the barrier wrt d.\ndouble barrier_gradient(double d, double dhat);\n\n/// @brief Second derivative of the barrier function.\n///\n/// \\f$b''(d) = \\left( \\frac{\\hat{d}}{d} + 2 \\right) \\frac{\\hat{d}}{d} -\n/// 2\\ln\\left( \\frac{d}{\\hat{d}} \\right) - 3\\f$\n///\n/// @param d The distance.\n/// @param dhat Activation distance of the barrier.\n/// @return The second derivative of the barrier wrt d.\ndouble barrier_hessian(double d, double dhat);\n\n} // namespace ipc\n\n#include \"barrier.tpp\"\n", "meta": {"hexsha": "8619dbab2970353f8af312e796fdea2ed11ead66", "size": 1335, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/barrier/barrier.hpp", "max_stars_repo_name": "ipc-sim/ipc-toolk", "max_stars_repo_head_hexsha": "81873d0288810e30166d871419da4104329860e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2020-08-04T21:08:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T02:24:31.000Z", "max_issues_repo_path": "src/barrier/barrier.hpp", "max_issues_repo_name": "dbelgrod/ipc-toolkit", "max_issues_repo_head_hexsha": "0b7ca9b5f867db63bd68dd02ce54a9d00b0fc337", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-10-12T05:54:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-10T18:39:30.000Z", "max_forks_repo_path": "src/barrier/barrier.hpp", "max_forks_repo_name": "dbelgrod/ipc-toolkit", "max_forks_repo_head_hexsha": "0b7ca9b5f867db63bd68dd02ce54a9d00b0fc337", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2020-11-26T12:47:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T04:55:49.000Z", "avg_line_length": 31.0465116279, "max_line_length": 76, "alphanum_fraction": 0.6584269663, "num_tokens": 395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929799, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.734824471157071}}
{"text": "#include \"problemes.h\"\n#include \"arithmetique.h\"\n\n#include <fstream>\n#include <boost/algorithm/string.hpp>\n\ntypedef unsigned long long nombre;\ntypedef std::vector<nombre> vecteur;\ntypedef std::vector<vecteur> matrice;\n\nENREGISTRER_PROBLEME(82, \"Path sum: three ways\") {\n    // The minimal path sum in the 5 by 5 matrix below, by starting in any cell in the left column and finishing in any\n    // cell in the right column, and only moving up, down, and right, is indicated in red and bold; the sum is equal to\n    // 994.\n    //\n    // Find the minimal path sum, in matrix.txt (right click and \"Save Link/Target As...\"), a 31K text file containing\n    // a 80 by 80 matrix, from the left column to the right column.\n    matrice graphe;\n    std::ifstream ifs(\"data/p082_matrix.txt\");\n    std::string ligne;\n    while (ifs >> ligne) {\n        std::vector<std::string> v;\n        boost::split(v, ligne, boost::is_any_of(\",\"));\n        vecteur l;\n        for (const auto &s: v) {\n            l.push_back(std::stoull(s));\n        }\n        graphe.push_back(std::move(l));\n    }\n\n    const nombre taille = graphe.size();\n    matrice chemin(taille, vecteur(taille, 0));\n    for (size_t i = 0; i < taille; ++i) {\n        vecteur chemin_bas(taille, 0);\n        for (size_t j = 0; j < taille; ++j) {\n            if (i == 0)\n                chemin_bas[j] = graphe[j][i];\n            else if (j == 0)\n                chemin_bas[j] = chemin[j][i - 1] + graphe[j][i];\n            else\n                chemin_bas[j] = std::min(chemin[j][i - 1], chemin_bas[j - 1]) + graphe[j][i];\n        }\n\n        vecteur chemin_haut(taille, 0);\n        for (size_t jj = 0; jj < taille; ++jj) {\n            const size_t j = taille - jj - 1;\n            if (i == 0)\n                chemin_haut[j] = graphe[j][i];\n            else if (j == taille - 1)\n                chemin_haut[j] = chemin[j][i - 1] + graphe[j][i];\n            else\n                chemin_haut[j] = std::min(chemin[j][i - 1], chemin_haut[j + 1]) + graphe[j][i];\n        }\n\n        for (size_t j = 0; j < taille; ++j)\n            chemin[j][i] = std::min(chemin_haut[j], chemin_bas[j]);\n    }\n\n    nombre resultat = std::numeric_limits<nombre>::max();\n    for (const auto &c: chemin) {\n        resultat = std::min(resultat, c.back());\n    }\n\n\n    return std::to_string(resultat);\n}\n", "meta": {"hexsha": "9844868bc38d021fd318bd502bb0f24f038518ba", "size": 2317, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problemes/probleme0xx/probleme082.cpp", "max_stars_repo_name": "ZongoForSpeed/ProjectEuler", "max_stars_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-10-13T17:07:21.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-08T11:50:22.000Z", "max_issues_repo_path": "problemes/probleme0xx/probleme082.cpp", "max_issues_repo_name": "ZongoForSpeed/ProjectEuler", "max_issues_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "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": "problemes/probleme0xx/probleme082.cpp", "max_forks_repo_name": "ZongoForSpeed/ProjectEuler", "max_forks_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "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.5820895522, "max_line_length": 119, "alphanum_fraction": 0.5541648684, "num_tokens": 677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.888758793492457, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.7347473709724521}}
{"text": "#include <iostream>\n#include <Eigen/Geometry>\n#include <Eigen/Dense>\n#include <math.h>\nusing Eigen::MatrixXd;\nusing Eigen::Matrix3d;\nusing Eigen::Matrix4d;\nusing namespace std;\n\nstruct Coordinate\n{\n\tdouble x, y, z;\n\n\tCoordinate(double x, double y, double z)\n\t{\n\t\tthis->x = x;\n\t\tthis->y = y;\n\t\tthis->z = z;\n\t}\n};\n\nstruct Rotation\n{\n\tdouble r, p, y;\n\n\tRotation(double roll, double pitch, double yall)\n\t{\n\t\tr = roll;\n\t\tp = pitch;\n\t\ty = yall;\n\t}\n};\n\n#define D 3\n\nMatrix3d RotationMatrix(float, float, float);\nMatrix4d HomogeneousTransformationMatrix(Coordinate, Rotation);\nMatrix4d TranslationMatrix(Coordinate);\n\nint main()\n{\n\tMatrix3d R;\n\tMatrix4d T;\n\n\tT = HomogeneousTransformationMatrix(Coordinate(4,5,6), Rotation(0, 0, 0));\n\n\tcout << T << endl;\n}\n\nMatrix3d RotationX(float thetax)\n{\n\tMatrix3d Rx;\n\n\tRx << 1, 0, 0,\n\t\t  0, cos(thetax), -sin(thetax),\n\t\t  0, sin(thetax), sin(thetax);\n\t\n\treturn Rx;\n}\n\nMatrix3d RotationY(float thetay)\n{\n\tMatrix3d Ry;\n\n\tRy << cos(thetay), 0, sin(thetay),\n\t\t  0, 1, 0,\n\t\t  -sin(thetay), 0, cos(thetay);\n\t\n\treturn Ry;\n}\n\nMatrix3d RotationZ(float thetaz)\n{\n\tMatrix3d Rz;\n\n\tRz << cos(thetaz), -sin(thetaz), 0,\n\t\t  sin(thetaz), cos(thetaz), 0,\n\t\t  0, 0, 1;\n\t\n\treturn Rz;\n}\n\nMatrix3d RotationMatrix(float thetaz1, float thetay, float thetaz2) // Angle in degrees\n{\n\treturn RotationZ(thetaz1)*RotationY(thetay)*RotationZ(thetaz2);\n}\n\nMatrix4d HomogeneousTransformationMatrix(Coordinate origin, Rotation rot)\n{\n\tMatrix4d T;\n\n\tT.block(0, 0, 3, 3) << RotationMatrix(rot.r, rot.p, rot.y);\n\tT.block(0, 3, 3, 1) << origin.x, origin.y, origin.z;\n\tT.block(3, 0, 1, 3) << MatrixXd::Zero(1,3);\n\tT.block(3, 3, 1, 1) << MatrixXd::Identity(1,1);\n\n\treturn T;\n}\n\nMatrix4d TranslationMatrix(Coordinate origin)\n{\n\treturn HomogeneousTransformationMatrix(origin, Rotation(0,0,0));\n}", "meta": {"hexsha": "9c78de4b854bcf6ee3562e88dfe500de6a624a01", "size": 1787, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CorkeCpp.cpp", "max_stars_repo_name": "luccosta/RoboticsCorkeCpp", "max_stars_repo_head_hexsha": "cfb02b36710316bffcfbb58ab2f7e2687934cb4f", "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": "CorkeCpp.cpp", "max_issues_repo_name": "luccosta/RoboticsCorkeCpp", "max_issues_repo_head_hexsha": "cfb02b36710316bffcfbb58ab2f7e2687934cb4f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-05-05T18:37:01.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-05T19:19:47.000Z", "max_forks_repo_path": "CorkeCpp.cpp", "max_forks_repo_name": "luccosta/RoboticsCorkeCpp", "max_forks_repo_head_hexsha": "cfb02b36710316bffcfbb58ab2f7e2687934cb4f", "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": 17.3495145631, "max_line_length": 87, "alphanum_fraction": 0.6720761052, "num_tokens": 609, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632261523028, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.7346894419377796}}
{"text": "// Arguments: Ints, Doubles, Doubles\n#include <stan/math/prim/scal.hpp>\n#include <boost/math/special_functions/binomial.hpp>\n\nusing std::vector;\nusing std::numeric_limits;\nusing stan::math::var;\n\nclass AgradCdfNegBinomial2 : public AgradCdfTest {\npublic:\n  void valid_values(vector<vector<double> >& parameters,\n                    vector<double>& cdf) {\n    vector<double> param(3);\n\n    param[0] = 3;          // n\n    param[1] = 10;          // mu\n    param[2] = 20;           // phi\n    parameters.push_back(param);\n    cdf.push_back(0.0264752601628231235); // expected cdf\n    \n    param[0] = 7;          // n\n    param[1] = 15;          // mu\n    param[2] = 10;           // phi\n    parameters.push_back(param);\n    cdf.push_back(0.091899254171238523026); // expected cdf\n    \n    param[0] = 0;          // n\n    param[1] = 15;          // mu\n    param[2] = 10;           // phi\n    parameters.push_back(param);\n    cdf.push_back(0.0001048576000000001529); // expected cdf\n    \n    param[0] = 1;          // n\n    param[1] = 15;          // mu\n    param[2] = 10;           // phi\n    parameters.push_back(param);\n    cdf.push_back(0.00073400320000000126002); // expected cdf\n    \n    param[0] = 0;          // n\n    param[1] = 10;          // mu\n    param[2] = 1;           // phi\n    parameters.push_back(param);\n    cdf.push_back(0.090909090909090897736); // expected cdf\n    \n    param[0] = -1;          // n\n    param[1] = 10;          // mu\n    param[2] = 1;           // phi\n    parameters.push_back(param);\n    cdf.push_back(0); // expected cdf\n    \n    param[0] = -89;          // n\n    param[1] = 10;          // mu\n    param[2] = 1;           // phi\n    parameters.push_back(param);\n    cdf.push_back(0); // expected cdf\n  }\n  \n  void invalid_values(vector<size_t>& index, \n                      vector<double>& value) {\n\n    // mu\n    index.push_back(1U);\n    value.push_back(-1);\n      \n    // phi\n    index.push_back(2U);\n    value.push_back(-1);\n      \n  }\n  \n  bool has_lower_bound() {\n    return false;\n  }\n    \n  bool has_upper_bound() {\n    return false;\n  }\n  \n  template <typename T_n, typename T_location, typename T_precision,\n            typename T3, typename T4, typename T5>\n  typename stan::return_type<T_location, T_precision>::type\n  cdf(const T_n& n, const T_location& alpha, const T_precision& beta,\n      const T3&, const T4&, const T5&) {\n    return stan::math::neg_binomial_2_cdf(n, alpha, beta);\n  }\n\n\n  template <typename T_n, typename T_location, typename T_precision,\n            typename T3, typename T4, typename T5>\n  typename stan::return_type<T_location, T_precision>::type\n  cdf_function(const T_n& nn, const T_location& mu, const T_precision& phi,\n               const T3&, const T4&, const T5&) {\n\n    using std::log;\n    using std::exp;\n    using stan::math::binomial_coefficient_log;\n    using stan::math::multiply_log;\n    \n    typename stan::return_type<T_location, T_precision>::type cdf(0);\n    \n    for (int n = 0; n <= nn; n++) {\n      typename stan::return_type<T_location, T_precision>::type lp(0);\n      if (n != 0)\n        lp += binomial_coefficient_log<typename stan::scalar_type<T_precision>::type>\n          (n + phi - 1.0, n);\n      lp +=  multiply_log(n, mu) + multiply_log(phi, phi) - (n+phi)*log(mu + phi);\n      cdf += exp(lp);\n    }\n      \n    return cdf;\n      \n  }\n};\n", "meta": {"hexsha": "81dfde89dcab5660d92306794f19ae69b4242bd9", "size": 3342, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/prob/neg_binomial_2/neg_binomial_2_cdf_test.hpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "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": "cmdstan/stan/lib/stan_math/test/prob/neg_binomial_2/neg_binomial_2_cdf_test.hpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "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": "cmdstan/stan/lib/stan_math/test/prob/neg_binomial_2/neg_binomial_2_cdf_test.hpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "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": 29.3157894737, "max_line_length": 85, "alphanum_fraction": 0.5676241771, "num_tokens": 985, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037363973295, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.7346570014109622}}
{"text": "#include <math.h>\n#include \"config.h\"\n#include \"matrix.h\"\n#include \"util.h\"\n#include <armadillo>\n\nvoid normalize(float *x, float *y, float *z) {\n    float d = sqrtf((*x) * (*x) + (*y) * (*y) + (*z) * (*z));\n    *x /= d; *y /= d; *z /= d;\n}\n\nvoid copy_matrix(float *dst, const arma::mat& src){\n\tfor(int i = 0; i < 4; i++){\n\t\tfor(int j = 0; j < 4; j++){\n\t\t\tdst[i * 4 + j] = src(i,j);\n\t\t}\n\t}\n}\n\narma::mat copy_from_array(float *src){\n\tarma::mat dst(4,4);\n\tfor(int i = 0; i < 4; i++){\n\t\tfor(int j = 0; j < 4; j++){\n\t\t\tdst(i,j) = src[i * 4 + j];\n\t\t}\n\t}\n\treturn dst;\n}\n\narma::mat mat_translate(float dx, float dy, float dz) {\n    arma::mat translate(4,4, arma::fill::zeros);\n    translate.eye();\n    translate(3,0) = dx;\n    translate(3,1) = dy;\n    translate(3,2) = dz;\n    return translate;\n}\n\narma::mat mat_rotate(float x, float y, float z, float t) {\n    float ux = x;\n    float uy = y;\n    float uz = z;\n    normalize(&ux, &uy, &uz);\n    return arma::mat {\n            { cos(t)+(ux*ux)*(1-cos(t)), (ux*uy)*(1-cos(t))-uz*sin(t), ux*uz*(1-cos(t)) + uy*sin(t), 0 },\n            { uy*uz*(1-cos(t))+uz*sin(t), cos(t)+(uy*uy)*(1-cos(t)), uy*uz*(1-cos(t)) - ux*sin(t), 0},\n            { uz*ux*(1-cos(t))-uy*sin(t), uz*uy*(1-cos(t)) + ux*sin(t), cos(t) + uz*uz*(1 - cos(t)), 0 },\n            { 0, 0, 0, 1}\n    };\n}\n\nvoid mat_apply(std::vector<float>& d, arma::mat &ma, int count, int offset, int stride) {\n\tarma::mat vec = {0,0,0,1};\n\tfor (int i = 0; i < count; i++) {\n        int cursor = offset + stride * i;\n\t\tvec(0,0) = d.at(cursor++);\n\t\tvec(0,1) = d.at(cursor++);\n\t\tvec(0,2) = d.at(cursor++);\n\n\t\tvec = vec * ma;\n\n\t\tcursor = offset + stride * i;\n\t\td.at(cursor++) = vec(0,0);\n\t\td.at(cursor++) = vec(0,1);\n\t\td.at(cursor++) = vec(0,2);\n\t}\n}\n\narma::mat frustum_planes(int radius, float *matrix) {\n    arma::mat planes(6,4);\n    float znear = 0.125;\n    float zfar = radius * 32 + 64;\n    float *m = matrix;\n    planes(0,0) = m[3] + m[0];\n    planes(0,1) = m[7] + m[4];\n    planes(0,2) = m[11] + m[8];\n    planes(0,3) = m[15] + m[12];\n    planes(1,0) = m[3] - m[0];\n    planes(1,1) = m[7] - m[4];\n    planes(1,2) = m[11] - m[8];\n    planes(1,3) = m[15] - m[12];\n    planes(2,0) = m[3] + m[1];\n    planes(2,1) = m[7] + m[5];\n    planes(2,2) = m[11] + m[9];\n    planes(2,3) = m[15] + m[13];\n    planes(3,0) = m[3] - m[1];\n    planes(3,1) = m[7] - m[5];\n    planes(3,2) = m[11] - m[9];\n    planes(3,3) = m[15] - m[13];\n    planes(4,0) = znear * m[3] + m[2];\n    planes(4,1) = znear * m[7] + m[6];\n    planes(4,2) = znear * m[11] + m[10];\n    planes(4,3) = znear * m[15] + m[14];\n    planes(5,0) = zfar * m[3] - m[2];\n    planes(5,1) = zfar * m[7] - m[6];\n    planes(5,2) = zfar * m[11] - m[10];\n    planes(5,3) = zfar * m[15] - m[14];\n    return planes;\n}\n\narma::mat mat_frustum(float left, float right, float bottom, float top, float znear, float zfar)\n{\n    float temp, temp2, temp3, temp4;\n    temp = 2.0 * znear;\n    temp2 = right - left;\n    temp3 = top - bottom;\n    temp4 = zfar - znear;\n    return arma::mat {\n        {temp / temp2, 0.0, 0.0, 0.0},\n        {0.0, temp / temp3, 0.0, 0.0},\n        {(right + left) / temp2, (top + bottom) / temp3, (-zfar - znear) / temp4, -1.0},\n        {0.0, 0.0, (-temp * zfar) / temp4, 0.0}\n    };\n}\n\n\narma::mat mat_perspective(float fov, float aspect, float znear, float zfar) {\n    float ymax, xmax;\n    ymax = znear * tanf(fov * PI / 360.0);\n    xmax = ymax * aspect;\n    return mat_frustum(-xmax, xmax, -ymax, ymax, znear, zfar);\n}\n\narma::mat mat_ortho(float left, float right, float bottom, float top, float near, float far) {\n    return arma::mat {\n        {2 / (right - left), 0, 0, 0},\n        {0, 2 / (top - bottom), 0, 0},\n        {0, 0, -2 / (far - near), 0},\n        {-(right + left) / (right - left), -(top + bottom) / (top - bottom), -(far + near) / (far - near), 1}\n    };\n}\n\narma::mat set_matrix_2d(int width, int height) {\n    return mat_ortho(0, width, 0, height, -1, 1);\n}\n\narma::mat set_matrix_3d(int width, int height,\n        float x, float y, float z, float rx, float ry,\n        float fov, int ortho, int radius){\n\n    arma::mat a(4,4);\n    arma::mat b(4,4);\n    float aspect = (float)width / height;\n    float znear = 0.125;\n    float zfar = radius * 32 + 64;\n    a.eye();\n    b = mat_translate(-x, -y, -z);\n    a = a * b;\n    b = mat_rotate(cosf(rx), 0, sinf(rx), ry);\n    a = a * b;\n    b = mat_rotate(0, 1, 0, -rx);\n    a = a * b;\n    if (ortho) {\n        int size = ortho;\n        b = mat_ortho(-size * aspect, size * aspect, -size, size, -zfar, zfar);\n    }\n    else {\n        b = mat_perspective(fov, aspect, znear, zfar);\n    }\n    a = a * b;\n    arma::mat m(4,4);\n    m.eye();\n    m = m* a;\n    return m;\n}\n\narma::mat set_matrix_item(int width, int height, int scale) {\n    arma::mat a(4,4);\n    arma::mat b(4,4);\n    float aspect = (float)width / height;\n    float size = 64 * scale;\n    float box = height / size / 2;\n    float xoffset = 1 - size / width * 2;\n    float yoffset = 1 - size / height * 2;\n    a.eye();\n    b = mat_rotate(0, 1, 0, -PI / 4);\n    a = a * b;\n    b = mat_rotate(1, 0, 0, -PI / 10);\n    a = a * b;\n    b = mat_ortho(-box * aspect, box * aspect, -box, box, -1, 1);\n    a = a * b;\n    b = mat_translate(-xoffset, -yoffset, 0);\n    a = a * b;\n    arma::mat m(4,4);\n    m.eye();\n    m = m * a;\n    return m;\n}\n", "meta": {"hexsha": "9cb57b1572a61f46efae531faaf2ef93399d6227", "size": 5295, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/matrix.cpp", "max_stars_repo_name": "nathanial/Craft", "max_stars_repo_head_hexsha": "63ac73aa2a266562a5e8a66a15ea2c1232e38df0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-03-23T23:08:51.000Z", "max_stars_repo_stars_event_max_datetime": "2017-08-05T01:10:38.000Z", "max_issues_repo_path": "src/matrix.cpp", "max_issues_repo_name": "nathanial/Craft", "max_issues_repo_head_hexsha": "63ac73aa2a266562a5e8a66a15ea2c1232e38df0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-03-23T22:21:39.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-22T23:00:33.000Z", "max_forks_repo_path": "src/matrix.cpp", "max_forks_repo_name": "nathanial/VGK", "max_forks_repo_head_hexsha": "63ac73aa2a266562a5e8a66a15ea2c1232e38df0", "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.0158730159, "max_line_length": 109, "alphanum_fraction": 0.5034938621, "num_tokens": 2077, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075701109193, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.7345535085723599}}
{"text": "//\n// Created by chen-tian on 17-7-4.\n//\n#include <iostream>\n#include <cmath>\nusing namespace std;\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\nint main(int argc, char** argv)\n{\n    Eigen::Matrix3d rotation_matrix = Eigen::Matrix3d::Identity();\n    Eigen::AngleAxisd rotation_vector (M_PI/4, Eigen::Vector3d(0,0,1));//\u6cbfz\u8f74\u65cb\u8f6c45\u5ea6\n    cout .precision(3);\n    cout<<\"rotation matrix =\\n\"<<rotation_vector.matrix()<<endl;\n    rotation_matrix = rotation_vector.toRotationMatrix();\n    Eigen::Vector3d v(1,0,0);\n    Eigen::Vector3d v_rotated = rotation_vector*v;\n    cout<<\"(1,0,0) after rotation = \"<<v_rotated.transpose()<<endl;\n    v_rotated=rotation_matrix*v;\n    cout<<\"(1,0,0) after rotation = \"<<v_rotated.transpose()<<endl;\n\n    //euler Isometry\n    Eigen::Isometry3d T=Eigen::Isometry3d::Identity();//although it is called 3d, this matrix is defeined by 4*4\n    T.rotate(rotation_vector);\n    T.pretranslate(Eigen::Vector3d(1,3,4));\n    cout<<\"Transform matrix = \\n\"<<T.matrix()<<endl;\n\n    Eigen::Vector3d v_transformed = T*v;\n    cout<<\"v transformed = \\n\"<<v_transformed.transpose()<<endl;\n\n    //quaterniond\n    Eigen::Quaterniond q = Eigen::Quaterniond ( rotation_vector);\n    cout<<\"quaternion = \\n\"<<q.coeffs()<<endl;\n    q=Eigen::Quaterniond (rotation_matrix);\n    cout<<\"quaternion = \\n\"<<q.coeffs()<<endl;\n    v_rotated = q*v;\n    cout<<\"(1,0,0) after rotation = \"<<v_rotated.transpose()<<endl;\n\n    return 0;\n};", "meta": {"hexsha": "1359ba823caa58b3175bbc28b8af08cdea922a14", "size": 1428, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch3_Eigen/useGeometry.cpp", "max_stars_repo_name": "ClovisChen/slam14", "max_stars_repo_head_hexsha": "35fad23a491f2dd7666edab55ae849ac937d44c2", "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_Eigen/useGeometry.cpp", "max_issues_repo_name": "ClovisChen/slam14", "max_issues_repo_head_hexsha": "35fad23a491f2dd7666edab55ae849ac937d44c2", "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_Eigen/useGeometry.cpp", "max_forks_repo_name": "ClovisChen/slam14", "max_forks_repo_head_hexsha": "35fad23a491f2dd7666edab55ae849ac937d44c2", "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.0, "max_line_length": 112, "alphanum_fraction": 0.6673669468, "num_tokens": 422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947055100817, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.7345442485286481}}
{"text": "#include <iostream>\n#include <iomanip>\n#include <stdexcept>\n#include <math.h>\n#include <set>\n#include <boost/multiprecision/gmp.hpp>\n#include <boost/multiprecision/number.hpp>\n\nusing namespace std;\nusing namespace boost::multiprecision;\n\nint target = 5;\n\nunsigned long long power(int n, int k) {\n  unsigned long long sum = 1;\n  for (int i = 0; i < k; i++) {\n    sum *= n;\n  }\n  return sum;\n}\n\nunsigned long long digits_power_sum(int n) {\n  unsigned long long sum = 0;\n  int digit;\n  while (n) {\n    digit = n % 10;\n    n /= 10;\n\n    sum += power(digit, target);\n  }\n  return sum;\n}\n\nint main(int argc, char** argv) {\n  int max = power(10, target + 1) - 1;\n  unsigned long long sum = 0;\n  for (int i = 2; i < max; i++) {\n    if (digits_power_sum(i) == i) {\n      cout << i << \" can be written as the sum of its \" << target << \"th power sums \" << endl;\n      sum += i;\n    }\n  }\n  cout << \"Sum of all \" << target << \"th-powerable integers is: \" << sum << endl;\n  return 0;\n}\n", "meta": {"hexsha": "a25260c3b81626c82ea36a33fc4eb450781c3535", "size": 973, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "30.cpp", "max_stars_repo_name": "DouglasSherk/project-euler", "max_stars_repo_head_hexsha": "f3b188b199ff31671c6d7683b15675be7484c5b8", "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": "30.cpp", "max_issues_repo_name": "DouglasSherk/project-euler", "max_issues_repo_head_hexsha": "f3b188b199ff31671c6d7683b15675be7484c5b8", "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": "30.cpp", "max_forks_repo_name": "DouglasSherk/project-euler", "max_forks_repo_head_hexsha": "f3b188b199ff31671c6d7683b15675be7484c5b8", "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.152173913, "max_line_length": 94, "alphanum_fraction": 0.5960945529, "num_tokens": 294, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465152482723, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.7345356398281488}}
{"text": "#include \"utils.hpp\"\n#include <cmath>\n#include <ctime>\n#include <fstream>\n#include <boost/range/numeric.hpp>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/median.hpp>\n\nusing namespace std;\n\nnamespace delphi::utils {\n\n/**\n * Returns the value rounded to n places past the decimal\n */\ndouble round_n(double x, int places) {\n  double n = pow(10.0, places);\n  return (double)((int)(x * n + 0.5))/n; \n}\n\n/**\n * Returns the square of a number.\n */\ndouble sqr(double x) { return x * x; }\n\n/**\n * Returns the sum of a vector of doubles.\n */\ndouble sum(const std::vector<double> &v) { return boost::accumulate(v, 0.0); }\n\n/**\n * Returns the arithmetic mean of a vector of doubles.\n * Updated based on:\n * https://codereview.stackexchange.com/questions/185450/compute-mean-variance-and-standard-deviation-of-csv-number-file\n */\ndouble mean(const std::vector<double> &v) {\n    if (v.empty()) {\n        return std::numeric_limits<double>::quiet_NaN();\n    }\n\n    return sum(v) / v.size();\n}\n\n/**\n * Returns the sample standard deviation of a vector of doubles.\n * Based on:\n * https://codereview.stackexchange.com/questions/185450/compute-mean-variance-and-standard-deviation-of-csv-number-file\n */\ndouble standard_deviation(const double mean, const std::vector<double>& v)\n{\n    if (v.size() <= 1u)\n        return std::numeric_limits<double>::quiet_NaN();\n\n    auto const add_square = [mean](double sum, int i) {\n        auto d = i - mean;\n        return sum + d*d;\n    };\n    double total = std::accumulate(v.begin(), v.end(), 0.0, add_square);\n    return sqrt(total / (v.size() - 1));\n}\n\n/**\n * Returns the median of a vector of doubles.\n */\ndouble median(const std::vector<double> &xs) {\n    if (xs.size() > 100) {\n        using namespace boost::accumulators;\n        accumulator_set<double, features<tag::median>> acc;\n        //  accumulator_set<double,\n        //      features<tag::median(with_p_square_cumulative_distribution) >>\n        //      acc ( p_square_cumulative_distribution_num_cells = xs.size() );\n\n        for (auto x : xs) {\n          acc(x);\n        }\n\n        return boost::accumulators::median(acc);\n    } else {\n        vector<double> x_copy(xs);\n        sort(x_copy.begin(), x_copy.end());\n        int num_els = x_copy.size();\n        int mid = num_els / 2;\n        if (num_els % 2 == 0) {\n            return (x_copy[mid - 1] +  x_copy[mid]) / 2;\n        }\n        else {\n            return x_copy[mid];\n        }\n    }\n}\n\n/**\n * Returns the center absolute deviation of a vector of doubles.\n * Based on:\n * https://en.wikipedia.org/wiki/Median_absolute_deviation\n */\ndouble median_absolute_deviation(const double center, const std::vector<double>& v)\n{\n  std::vector<double> abs_diff = std::vector<double>(v.size());\n\n  transform(v.begin(), v.end(),\n            abs_diff.begin(),\n            [&](double val){return abs(center - val);});\n\n  return median(abs_diff);\n}\n\ndouble log_normpdf(double x, double mean, double sd) {\n  double var = pow(sd, 2);\n  double log_denom = -0.5 * log(2 * M_PI) - log(sd);\n  double log_nume = pow(x - mean, 2) / (2 * var);\n\n  return log_denom - log_nume;\n}\n\nnlohmann::json load_json(string filename) {\n  ifstream i(filename);\n  nlohmann::json j = nlohmann::json::parse(i);\n  return j;\n}\n\n/** Compute the number of months between two dates **/\nint months_between(tuple<int, int, int> earlier_date, tuple<int, int, int> latter_date) {\n  int earlier_year = get<0>(earlier_date);\n  int earlier_month = get<1>(earlier_date);\n  int latter_year = get<0>(latter_date);\n  int latter_month = get<1>(latter_date);\n\n  return 12 * (latter_year - earlier_year) + (latter_month - earlier_month);\n}\n\nstd::string get_timestamp() {\n  time_t now = time(0);\n\n  struct tm *ptm = localtime(&now);\n  int year = 1900 + ptm->tm_year;\n  int month = 1 + ptm->tm_mon;\n  int date = ptm->tm_mday;\n  int hour = ptm->tm_hour;\n  int minute = ptm->tm_min;\n  int second = ptm->tm_sec;\n\n  return to_string(year) + \"-\" +\n         to_string(month) + \"-\" +\n         to_string(date) + \"_\" +\n         to_string(hour) + \".\" +\n         to_string(minute) + \".\" +\n         to_string(second);\n}\n} // namespace delphi::utils\n", "meta": {"hexsha": "b4ce70489719d3dc21ccf6a77f5f99e1570023c4", "size": 4166, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/utils.cpp", "max_stars_repo_name": "ml4ai/delphi", "max_stars_repo_head_hexsha": "9294d2d491f10c297c84f1cd5fdc9b55b6f866d9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2018-03-03T11:57:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-16T21:19:54.000Z", "max_issues_repo_path": "lib/utils.cpp", "max_issues_repo_name": "ml4ai/delphi", "max_issues_repo_head_hexsha": "9294d2d491f10c297c84f1cd5fdc9b55b6f866d9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 385.0, "max_issues_repo_issues_event_min_datetime": "2018-02-21T16:52:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-17T07:44:56.000Z", "max_forks_repo_path": "lib/utils.cpp", "max_forks_repo_name": "ml4ai/delphi", "max_forks_repo_head_hexsha": "9294d2d491f10c297c84f1cd5fdc9b55b6f866d9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2018-03-20T01:08:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-29T01:04:49.000Z", "avg_line_length": 27.5894039735, "max_line_length": 120, "alphanum_fraction": 0.6315410466, "num_tokens": 1102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600903, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.734285638784256}}
{"text": "#include <iostream>\n#include <chrono>\n#include <vector>\n#include <numeric>\n#include <algorithm>\n#include <boost/iterator/counting_iterator.hpp>\n\n//bad style do-while and wrong for Factorial1(0LL) -> 0 !!!\nlong long int Factorial1(long long int m_nValue)\n{\n   long long int result=m_nValue;\n   long long int result_next;\n   long long int pc = m_nValue;\n   do\n   {\n       result_next = result*(pc-1);\n       result = result_next;\n       pc--;\n   }while(pc>2);\n   m_nValue = result;\n   return m_nValue;\n}\n\n//iteration with while\nlong long int Factorial2(long long int n)\n{\n   long long int r = 1;\n   while(1<n)\n       r *= n--;\n   return r;\n}\n\n//recrusive\nlong long int Factorial3(long long int n)\n{\n   return n<2 ? 1 : n*Factorial3(n-1);\n}\n\n//tail recursive\ninline long long int _fac_aux(long long int n, long long int acc) {\n    return n < 1 ? acc : _fac_aux(n - 1, acc * n);\n}\nlong long int Factorial4(long long int n)\n{\n   return _fac_aux(n,1);\n}\n\n//accumulate with functor\nlong long int Factorial5(long long int n)\n{\n  // last is one-past-end\n  return std::accumulate(boost::counting_iterator<long long int>(1LL),\n                         boost::counting_iterator<long long int>(n+1LL), 1LL,\n                         std::multiplies<long long int>() );\n}\n\n//accumulate with lamda\nlong long int Factorial6(long long int n)\n{\n  // last is one-past-end\n  return std::accumulate(boost::counting_iterator<long long int>(1LL),\n                         boost::counting_iterator<long long int>(n+1LL), 1LL,\n                         [](long long int a, long long int b) { return a*b; } );\n}\n\nint main()\n{\n    int v = 55;\n    {\n        auto t1 = std::chrono::high_resolution_clock::now();\n        auto result = Factorial1(v);\n        auto t2 = std::chrono::high_resolution_clock::now();\n        std::chrono::duration<double, std::milli> ms = t2 - t1;\n        std::cout << std::fixed << \"do-while(1)              result \" << result\n                  << \" took \" << ms.count() << \" ms\\n\";\n    }\n\n    {\n        auto t1 = std::chrono::high_resolution_clock::now();\n        auto result = Factorial2(v);\n        auto t2 = std::chrono::high_resolution_clock::now();\n        std::chrono::duration<double, std::milli> ms = t2 - t1;\n        std::cout << std::fixed << \"while(2)                 result \" << result\n                  << \" took \" << ms.count() << \" ms\\n\";\n    }\n\n    {\n        auto t1 = std::chrono::high_resolution_clock::now();\n        auto result = Factorial3(v);\n        auto t2 = std::chrono::high_resolution_clock::now();\n        std::chrono::duration<double, std::milli> ms = t2 - t1;\n        std::cout << std::fixed << \"recusive(3)              result \" << result\n                  << \" took \" << ms.count() << \" ms\\n\";\n    }\n\n    {\n        auto t1 = std::chrono::high_resolution_clock::now();\n        auto result = Factorial3(v);\n        auto t2 = std::chrono::high_resolution_clock::now();\n        std::chrono::duration<double, std::milli> ms = t2 - t1;\n        std::cout << std::fixed << \"tail recusive(4)         result \" << result\n                  << \" took \" << ms.count() << \" ms\\n\";\n    }\n\n    {\n        auto t1 = std::chrono::high_resolution_clock::now();\n        auto result = Factorial5(v);\n        auto t2 = std::chrono::high_resolution_clock::now();\n        std::chrono::duration<double, std::milli> ms = t2 - t1;\n        std::cout << std::fixed << \"std::accumulate(5)       result \" << result\n                  << \" took \" << ms.count() << \" ms\\n\";\n    }\n\n    {\n        auto t1 = std::chrono::high_resolution_clock::now();\n        auto result = Factorial6(v);\n        auto t2 = std::chrono::high_resolution_clock::now();\n        std::chrono::duration<double, std::milli> ms = t2 - t1;\n        std::cout << std::fixed << \"std::accumulate lamda(6) result \" << result\n                  << \" took \" << ms.count() << \" ms\\n\";\n    }\n}\n", "meta": {"hexsha": "16318c0d8690396b5d7ea4d6f930c9cfd3743a1d", "size": 3847, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lang/C++/factorial-4.cpp", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-05T13:42:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-05T13:42:20.000Z", "max_issues_repo_path": "lang/C++/factorial-4.cpp", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "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": "lang/C++/factorial-4.cpp", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "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.2764227642, "max_line_length": 80, "alphanum_fraction": 0.5578372758, "num_tokens": 1046, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942145139149, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.7342583433226485}}
{"text": "\ufeff#include \"tut/ch3.hpp\"\n\n#include <math.h>\n#include <cmath>\n#include <random>\n#include <ctime>\n#include <iostream>\n#include <chrono>\n\n#include \"boost/date_time/gregorian/gregorian.hpp\"\n#include <boost/log/trivial.hpp>\n\nusing namespace boost::gregorian;\n\nnamespace tut {\n  namespace ch3 {\n    double exe_3_01(double a, double b, double c);\n\n    double FirstRoot(double a, double b, double c)\n    {\n      double r1 {(-b + sqrt(exe_3_01(a,b,c))) / (2 * a) };\n      BOOST_LOG_TRIVIAL(debug) << \"The first root: \" << r1;\n      return std::round( (r1 / 100000) * 10000000000 ) / 100000 ;\n    }\n    double SecondRoot(double a, double b, double c) {\n      double r2 { (-b - sqrt(exe_3_01(a,b,c))) / (2 * a)};\n      BOOST_LOG_TRIVIAL(debug) << \"The second root: \" << r2;\n      return std::round( (r2 / 100000) * 10000000000 ) / 100000;\n    }\n\n    double exe_3_01(double a, double b, double c) {\n      double discriminant { pow(b, 2) - (4 * a * c)};\n      discriminant = std::round( (discriminant / 100000) * 10000000000 ) / 100000;\n      if (discriminant > 0 ) {\n          BOOST_LOG_TRIVIAL(debug) << \"The equation has 2 real roots\\n\";\n          return discriminant;\n        }\n      if (discriminant == 0) {\n          BOOST_LOG_TRIVIAL(debug) << \"The equation has one root\\n\";\n          return discriminant;\n        }\n      if (discriminant < 0) {\n          BOOST_LOG_TRIVIAL(debug) << \"The equation has no real roots\\n\";\n          return discriminant;\n        }\n      return discriminant;\n    }\n\n    void exe_3_02() {\n      // Initialize our mersenne twister with a random seed based on the clock\n      std::mt19937 mersenne{ static_cast<std::mt19937::result_type>(std::time(nullptr)) };\n      // Create a reusable random number generator that generates uniform numbers between 1 and 6\n      std::uniform_int_distribution random_number{ 1, 10 };\n      int num1 {random_number(mersenne)};\n      int num2 {random_number(mersenne)};\n      int num3 {random_number(mersenne)};\n      std::cout << \"what is : \" << num1 << \" + \" << num2 << \" + \" << num3 <<\"\\n\";\n      std::cout << \"Enter your answer: \";\n      int answer{0};\n      std::cin >> answer;\n      int sum{ num1 + num2 + num3 };\n      if (answer == sum ) {\n          std::cout << \"Correct , the answer is: \"<< sum <<\"\\n\";\n        } else {\n          std::cout << \"Incorrect , the answer is: \" << sum << \"\\n\";\n        }\n    }\n\n    std::vector<double> exe_3_03(double x1, double y1, double z1, double x2, double y2,double z2) {\n      double x {( ((z1*y2) - (y1*z2)) / ((x1*y2) - (y1*x2)) )};\n      x = std::round( (x / 10) * 100 ) / 10;\n      double y { ( ((x1*z2) - (z1*x2)) / ((x1*y2) - (y1*x1)) ) };\n      y = std::round( (y / 10) * 100 ) / 10;\n      std::vector<double> sol;\n      double exp {x1*y2 - y1*x2};\n      if (exp == 0) {\n          BOOST_LOG_TRIVIAL(debug) << \"The equation has no solution \\n\";\n          BOOST_LOG_TRIVIAL(debug) << \"x is : \" << x << \" and y is: \" << y << \"\\n\";\n          sol.push_back(x);\n          sol.push_back(y);\n          return sol;\n        } else {\n          BOOST_LOG_TRIVIAL(debug) << \"x is : \" << x << \" and y is: \" << y << \"\\n\";\n          sol.push_back(x);\n          sol.push_back(y);\n          return sol;\n        }\n      return sol;\n    }\n\n    void exe_3_04() {\n      // Initialize our mersenne twister with a random seed based on the clock\n      std::mt19937 mersenne{ static_cast<std::mt19937::result_type>(std::time(nullptr)) };\n      // Create a reusable random number generator that generates uniform numbers between 1 and 6\n      std::uniform_int_distribution random_number{ 1, 12 };\n      BOOST_LOG_TRIVIAL(debug) << \"The english month name: \" << greg_month(random_number(mersenne));\n    }\n\n    void exe_3_05() {\n      std::cout << \"Enter today's day[ 0 - 6]: \";\n      int today;\n      std::cin >> today;\n      if (today > 6) {\n          std::cout << \"Incorrect date, enter again: \";\n          std::cin >> today;\n        }\n      std::cout << \"Enter the number of days elapsed since today[1 - 31]: \";\n      int elapsed_days;\n      std::cin >> elapsed_days;\n      if (elapsed_days > 31) {\n          std::cout << \"Incorrect date, enter again: \";\n          std::cin >> elapsed_days;\n        }\n      days future_day{ days{today} + days {elapsed_days} };\n      /// todo:: solution incomplete.\n      std::cout << \"Today is \" << greg_weekday(today) << \" and the future day is: \"<< future_day.days() <<std::endl;\n      BOOST_LOG_TRIVIAL(warning) << \" The furture date is incorrect.\\n\";\n    }\n\n    void exe_3_06() {\n      std::cout << \"Enter the weight in pounds: \";\n      double weight{0.0};\n      std::cin >> weight;\n      std::cout << \"Enter feet: \";\n      double feet{0.0};\n      std::cin >> feet;\n      std::cout << \"Enter inches: \";\n      double height{0.0};\n      std::cin >> height;\n\n      constexpr double KILOGRAMS_PER_POUND = 0.45359237; // Constant\n      constexpr double METERS_PER_INCH = 0.0254;\n\n      double weightInKilograms = weight * KILOGRAMS_PER_POUND;\n      double heightInMeters = height * METERS_PER_INCH;\n      double bmi = weightInKilograms /\n          (heightInMeters * heightInMeters);\n\n      std::cout << \"BMI is : \" << bmi << std::endl;\n      if (bmi < 18.5) {\n          std::cout << \"Underweight\\n\";\n        } else if(bmi < 25) {\n          std::cout << \"Normal\\n\";\n        } else if(bmi < 30) {\n          std::cout << \"Overweight\\n\";\n        } else {\n          std::cout << \"Obese\\n\";\n        }\n    }\n\n    void exe_3_07() {\n      std::cout << \"Enter an amount, for example 11.56:\";\n      double ammount;\n      std::cin >> ammount;\n      int remainingAmmount{ static_cast<int>(ammount * 100)};\n      int numberOfDollars { static_cast<int>(remainingAmmount / 100) };\n      remainingAmmount = remainingAmmount % 100;\n      int numberOfQuarters = remainingAmmount / 25;\n      remainingAmmount = remainingAmmount % 25;\n      int numberOfDimes = remainingAmmount / 10;\n      remainingAmmount = remainingAmmount % 10;\n      int numberOfNickels = remainingAmmount / 5;\n      remainingAmmount = remainingAmmount % 5;\n      int numberOfPenies = remainingAmmount;\n      std::cout << \"The ammount \" << ammount << std::endl;\n\n      if (numberOfDollars > 0) {\n          std::cout << \"Number of dollars: \" << numberOfDollars << \"s\\n\";\n        } else {\n          std::cout << \"Number of dollar: \" << numberOfDollars << std::endl;\n        }\n      if (numberOfQuarters > 0) {\n          std::cout << \"Number of quarters: \" << numberOfQuarters << \"s\\n\";\n        } else {\n          std::cout << \"Number of quarter: \" << numberOfQuarters << std::endl;\n        }\n      if (numberOfDimes > 0) {\n          std::cout << \"Number of dimes: \" << numberOfDimes << \"s\\n\";\n        } else {\n          std::cout << \"Number of dime: \" << numberOfDimes << std::endl;\n        }\n      if (numberOfNickels > 0) {\n          std::cout << \"Number of nickels: \" << numberOfNickels << \"s\\n\";\n        } else {\n          std::cout << \"Number of nickel: \" << numberOfNickels << std::endl;\n        }\n      if (numberOfPenies > 0) {\n          std::cout << \"Number of penies: \" << numberOfPenies << \"s\\n\";\n        } else {\n          std::cout << \"Number of penies: \" << numberOfPenies << std::endl;\n        }\n\n    }\n\n    void exe_3_08() {\n      int numbers, thousands, hundreds, tens;\n      std::cout << \"Enter the 3 numbers: \";\n      std::cin >> numbers; // 432\n\n      tens = numbers % 10; // 2\n      int hundredsAndThousands = numbers / 10; // 43\n      hundreds = hundredsAndThousands % 10; // 3\n      thousands = hundredsAndThousands / 10;\n      BOOST_LOG_TRIVIAL(debug) << \"Thousands: \" << thousands << \" hundreds: \" << hundreds << \" tens: \" << tens <<\"\\n\";\n      if (thousands == hundreds && hundreds == tens\n          && thousands == tens) {\n          std::cout << \"Numbers already sorted\\n\";\n        }\n      std::vector<int> sort; // 345 435\n      int temp;\n      if (hundreds < thousands || tens < thousands) // 259\n        {\n          if (hundreds < thousands)\n            {\n              temp = thousands;\n              thousands = hundreds;\n              hundreds = temp;\n            }\n          if (tens < thousands)\n            {\n              temp = thousands;\n              thousands = tens;\n              tens = temp;\n            }\n        }\n      if (tens < hundreds)\n        {\n          temp = hundreds;\n          hundreds = tens;\n          tens = temp;\n        }\n      std::cout << \"Sort : \" << tens << \" \" << hundreds << \" \" << thousands << std::endl;\n    }\n\n    void exe_3_09()\n    {\n      std::cout << \"Enter the first 9 digits of an ISBN: \";\n      int isbn{0};\n      std::cin >> isbn;\n      int d9{ isbn % 10 };\n      int rem {isbn / 10};\n      int d8{ rem % 10 };\n      rem = rem / 10;\n      int d7{ rem % 10 };\n      rem =rem / 10;\n      int d6{rem % 10};\n      rem = rem / 10;\n      int d5{rem % 10};\n      rem = rem / 10;\n      int d4{rem % 10};\n      rem = rem / 10;\n      int d3{rem % 10};\n      rem = rem / 10;\n      int d2{ rem % 10};\n      rem = rem /10;\n      int d1{ rem };\n      int d10{ (d1*1) + (d2*2) + (d3*3) + (d4*4) + (d5*5) + (d6*6) + (d7*7) + (d8*8) + (d9*9) };\n      d10 = d10 % 11;\n\n      std::string s{ std::to_string(isbn)};\n\n      if (d10 == 10) {\n          s.append(\"X\");\n          std::cout << \"The ISBN-10 number is: \"<< s << std::endl;\n        } else {\n          s.append(std::to_string(d10));\n          std::cout << \"The ISBN-10 number is: \"<< s << std::endl;\n        }\n    }\n\n    void exe_3_10() {\n      auto seed = std::chrono::system_clock::now().time_since_epoch().count();\n      auto mtgen = std::mt19937{static_cast<unsigned int>(seed) };\n      auto ud = std::uniform_int_distribution<>{1, 100};\n      auto number1 = ud(mtgen);\n      auto number2 = ud(mtgen);\n      std::cout << \"What is \" << number1 << \" + \" << number2 << \"? \";\n      int answer{0};\n      std::cin >> answer;\n      if (number1+number2 == answer) {\n          std::cout << \"You are correct !\\n\";\n        } else {\n          std::cout << \"Your answer is wrong, \"<< number1 << \" + \" << number2 << \" should be \" << number1 + number2 << std::endl;\n\n        }\n    }\n\n    void exe_3_11() {\n      std::cout << \"Enter a month [1 -12]: \";\n      int month{0};\n      std::cin >> month;\n      std::cout << \"Enter a year, i,e 2022: \";\n      int year;\n      std::cin >> year;\n      using namespace boost::gregorian;\n      auto end_of_month_day = gregorian_calendar::end_of_month_day(year, month);\n      std::cout << \" \"<< greg_month(month) << \" had \" << end_of_month_day << \" days.\" << std::endl;\n    }\n\n    void exe_3_12() {\n      std::cout << \"Enter a three digit integer: \";\n      int number;\n      std::cin >> number;\n      int number3 { number % 10 } ;\n      int rem { rem / 10 };\n      int number2{ rem % 10 };\n      rem =rem / 10;\n      int number1{ rem % 10 };\n      if (number1 == number3) {\n          std::cout << \" \" << number << \" is a palindrome\\n\";\n        } else {\n          std::cout << number << \" is not a palindrome\\n\";\n        }\n\n    }\n\n    void exe_3_13() {\n\n\n      // Prompt the user to enter filing status\n      std::cout << \"(0-single filter, 1-married jointly or \" <<\n                   \"qualifying widow(er), 2-married separately, 3-head of \" <<\n                   \"houshold) Enter the filing status: \";\n      int status{0};\n      std::cin >> status;\n\n      // Prompt the user to enter taxable income\n      std::cout << \"Enter the taxable income: \";\n      double income{0};\n      std::cin >> income;\n\n      // Compute tax\n      double tax = 0;\n      switch (status)\n        {\n        case 0 : // Compute tax for single filers\n          tax += (income <= 8350) ? income * 0.10 : 8350 * 0.10;\n          if (income > 8350)\n            tax += (income <= 33950) ? (income - 8350) * 0.15 :\n                                       25600 * 0.15;\n          if (income > 33950)\n            tax += (income <= 82250) ? (income - 33950) * 0.25 :\n                                       48300 * 0.25;\n          if (income > 82250)\n            tax += (income <= 171550) ? (income - 82250) * 0.28 :\n                                        89300 * 0.28;\n          if (income > 171550)\n            tax += (income <= 372950) ? (income - 171550) * 0.33 :\n                                        201400 * 0.33;\n          if (income > 372950)\n            tax += (income - 372950) * 0.35;\n          break;\n        case 1 : // Compute tax for married file jointly or qualifying widow(er)\n          tax += (income <= 16700) ? income * 0.10 : 16700 * 0.10;\n          if (income > 16700)\n            tax += (income <= 67900) ? (income - 16700) * 0.15 :\n                                       (67900 - 16700) * 0.15;\n          if (income > 67900)\n            tax += (income <= 137050) ? (income - 67900) * 0.25 :\n                                        (137050 - 67900) * 0.25;\n          if (income > 137050)\n            tax += (income <= 208850) ? (income - 137050) * 0.28 :\n                                        (208850 - 137050) * 0.28;\n          if (income > 208850)\n            tax += (income <= 372950) ? (income - 208850) * 0.33 :\n                                        (372950 - 208850) * 0.33;\n          if (income > 372950)\n            tax += (income - 372950) * 0.35;\n          break;\n        case 2 : // Compute tax for married separately\n          tax += (income <= 8350) ? income * 0.10 : 8350 * 0.10;\n          if (income > 8350)\n            tax += (income <= 33950) ? (income - 8350) * 0.15 :\n                                       (33950 - 8350) * 0.15;\n          if (income > 33950)\n            tax += (income <= 68525) ? (income - 33950) * 0.25 :\n                                       (68525 - 33950) * 0.25;\n          if (income > 68525)\n            tax += (income <= 104425) ? (income - 68525) * 0.28 :\n                                        (104425 - 68525) * 0.28;\n          if (income > 104425)\n            tax += (income <= 186475) ? (income - 104425) * 0.33 :\n                                        (186475 - 104425) * 0.33;\n          if (income > 186475)\n            tax += (income - 186475) * 0.35;\n          break;\n        case 3 : // Compute tax for head of household\n          tax += (income <= 11950) ? income * 0.10 : 11950 * 0.10;\n          if (income > 11950)\n            tax += (income <= 45500) ? (income - 11950) * 0.15 :\n                                       (45500 - 11950) * 0.15;\n          if (income > 45500)\n            tax += (income <= 117450) ? (income - 45500) * 0.25 :\n                                        (117450 - 45500) * 0.25;\n          if (income > 117450)\n            tax += (income <= 190200) ? (income - 117450) * 0.28 :\n                                        (190200 - 117450) * 0.28;\n          if (income > 190200)\n            tax += (income <= 372950) ? (income - 190200) * 0.33 :\n                                        (372950 - 190200) * 0.33;\n          if (income > 372950)\n            tax += (income - 372950) * 0.35;\n          break;\n        default : std::cout << \"Error: invalid status\\n\";\n          quick_exit(1);\n        }\n      // Display the result\n      std::cout << \"Tax is \" << (int)(tax * 100) / 100.0 << std::endl;\n    }\n\n    void exe_3_14() {\n      auto seed = std::chrono::system_clock::now().time_since_epoch().count();\n      auto mtgen = std::mt19937{static_cast<unsigned int>(seed)};\n      auto ud = std::uniform_int_distribution<>{0, 1};\n      auto coin_side { ud(mtgen) };\n      std::cout << \"Guess the coin flip [ 0= heads, 1=Tails ]: \";\n      int guess{0};\n      std::cin >> guess;\n\n      if (guess == 0 && coin_side == 0) {\n          std::cout << \"Correct guess, Heads\\n\";\n        } else {\n          std::cout << \"Incorrect guess, Tails\\n\";\n        }\n    }\n\n    std::string exe_3_15(int digits) {\n      auto seed {std::chrono::steady_clock::now().time_since_epoch().count()};\n      auto mtgen {std::mt19937{static_cast<unsigned int >(seed)}};\n      auto ud {std::uniform_int_distribution<>(100, 999)};\n\n      std::string response1{\"Exact match: you win $10,000\"};\n      std::string response2{\"Match all digits: you win $3,000\"};\n      std::string response3{\"Match one digit: you win $1,000\"};\n      std::string response4{\"Sorry, no match\"};\n\n      int lottery { ud(mtgen) }; // genereate the lottery number\n      int lottery1{}, lottery2{}, lottery3{}, lrem{};\n      lottery3 = lottery % 10;\n      lrem = lottery / 10;\n      lottery2 = lrem % 10;\n      lottery3 = lrem / 10;\n\n\n      int guess1{}, guess2{}, guess3{}, rem{};\n      guess3 = digits % 10;\n      rem = digits / 10;\n      guess2 = rem % 10;\n      guess1 = rem / 10;\n\n      if (guess1 == lottery1 && guess2 == lottery2 && guess3 == lottery3) {\n          BOOST_LOG_TRIVIAL(debug) << \"Lottery: \"<< lottery << \" guess: \"<< response1;\n          return response1;\n        } else if(digits == lottery) {\n          BOOST_LOG_TRIVIAL(debug) << \"Lottery: \"<< lottery << \" guess: \"<< response2;\n          return response2;\n        } else if(guess1 == lottery1 || guess2 == lottery2 || guess3 == lottery3) {\n          BOOST_LOG_TRIVIAL(debug) << \"Lottery: \"<< lottery << \" guess: \"<< response3;\n          return response3;\n        } else {\n          BOOST_LOG_TRIVIAL(debug) << \"Lottery: \"<< lottery << \" guess: \"<< response4;\n          return response4;\n        }\n\n      return response4;\n    }\n\n    void exe_3_16() {\n      auto seed = std::chrono::system_clock::now().time_since_epoch().count();\n      auto mtgen = std::mt19937{ static_cast<unsigned int >(seed)};\n      auto ud = std::uniform_int_distribution<>(0, 100);\n      auto ud1 = std::uniform_int_distribution<>(0, 200);\n      int x{ ud(mtgen) }, y{ ud1(mtgen) };\n      std::cout << \"The random coordinate of the recatangle start: x1=\" << x << \" y1=\" << y << std::endl;\n    }\n\n    void exe_3_17() {\n      auto seed = std::chrono::system_clock::now().time_since_epoch().count();\n      auto mtgen = std::mt19937{static_cast<unsigned int >(seed)};\n      auto ud = std::uniform_int_distribution(1,2);\n      int guess = ud(mtgen);\n\n      std::cout << \"scissor (0), rock (1), paper (2): \";\n      int ans{};\n      std::cin >> ans;\n\n      if (ans == 1 && guess == 0) {\n          std::cout << \"The computer is scissor. You are rock. You won\\n\";\n        }\n      if (ans == 1 && guess == 1) {\n          std::cout << \"The computer is rock. You are rock too. It is a draw\\n\";\n        }\n      if (ans == 0 && guess == 2){\n          std::cout << \"The computer is paper. You are scissor. You won\\n\";\n        }\n      if(ans == 0 && guess == 0) {\n          std::cout << \"The computer is scissor. You are scissor too. It is a draw.\\n\";\n        }\n      if (ans == 2 && guess == 1) {\n          std::cout << \"The computer is rock. You are paper. You win\\n.\";\n        }\n      if (ans == 2 && guess == 2) {\n          std::cout << \"The computer is paper. You are paper. It is a draw\\n\";\n        }\n    }\n\n    double exe_3_18(int x1, int y1, int x2, int y2, int x3, int y3)\n    {\n      if (x1 + y1 > x3 && x3 + y3 > x2 + y2 ||\n          (x1 + y1 > x2 + y2 && x3 + y3 > x2 + y2) ||\n          (x3 + y3 > x1 + y1 && x2 + y2 > x1 + y1)) {\n          std::cout << \"The input is valid \\n\";\n        } else {\n          std::cout << \"The inputs are invalid!\\n\";\n          std::exit(0);\n        }\n      double perimeter{0.0};\n      double l1 = sqrt(pow((x2-x1), 2) + pow(y2-y1, 2));\n      double l2 = sqrt(pow(x3 - x2, 2) + pow(y3 -y2, 2));\n      double l3 = sqrt(pow(x3 - x1, 2) + pow(y3 -y1, 2));\n      std::cout << \" The perimeter is: \" << l1 + l2 + l3;\n      perimeter = l1 + l2 + l3;\n      return std::round(perimeter * 1000) / 1000.0;\n    }\n\n    void exe_3_20()\n    {\n      // Prompt the user to enter a temperature and a wind speed\n      std::cout << \"Enter the temperature in Fahrenheit \"\n                   \"between -58F and 41F: \";\n      double temperature{0.0};\n      std::cin >> temperature;\n      std::cout << \"Enter the wind speed (>= 2) in miles per hour: \";\n      double speed{0.0};\n      std::cin >> speed;\n\n      if (temperature <= -58 || temperature >= 41 || speed < 2)\n        {\n          std::cout << \"The \";\n          if (temperature <= -58 || temperature >= 41)\n            std::cout << \"temperature \";\n          if ((temperature <= -58 || temperature >= 41) && speed < 2)\n            std::cout << \"and \";\n          if (speed < 2)\n            std::cout << \"wind speed \";\n          std::cout << \"is invalid\";\n          std::exit(1);\n        }\n\n      // Compute the wind chill index\n      double windChill = 35.74 + 0.6215 * temperature -\n          35.75 * pow(speed, 0.16) +\n          0.4275 * temperature * pow(speed, 0.16);\n\n      // Display result\n      std::cout << \"The wind chill index is \" << windChill;\n    }\n\n    int exe_3_21(int k, int m, int q)\n    {\n      int h{0};\n      int j = (k / 100 );\n      k = k % 100;\n\n      if (m <= 0 || m > 12) {\n          std::cerr << \"Month is out of range [ 1 - 12]\\n\";\n          std::exit(EXIT_FAILURE);\n        }\n      if(q <=0 || q > 31) {\n          std::cerr << \"Day of the month is out of range[ 1 - 31]\\n\";\n          std::exit(EXIT_FAILURE);\n        }\n\n      if (m == 1 || m == 2)\n        {\n          m = (m == 1) ? 13 : 14;\n          k--;\n        }\n\n      h = ( q + ( (26 * (m + 1)) / 10 ) + k +  (k / 4) + (j / 4) + 5 * j ) % 7;\n      return h;\n    }\n\n    bool exe_3_22(double x, double y)\n    {\n      double d{ sqrt(pow(x - 0.0, 2) + pow(y - 0.0, 2) ) };\n      if ( d <= 10.0)\n        return true; /// the point is in the circle\n      return false;\n    }\n\n    bool exe_3_23(double x, double y)\n    {\n      if (sqrt(pow(x, 2) + pow(y, 2)) <= (10 / 5) || sqrt(pow(y, 2)) <=(5.0 / 2) )\n        return true;\n      return false;\n    }\n\n    void exe_3_24()\n    {\n      long seed = std::chrono::system_clock::now().time_since_epoch().count();\n      auto mtgen = std::mt19937{ static_cast<unsigned int>(seed) };\n      auto ud = std::uniform_int_distribution(1, 13);\n      int rank = ud(mtgen);\n      auto ud_1_4 = std::uniform_int_distribution(1, 4);\n      int suit = ud_1_4(mtgen);\n\n      std::cout << \"The card picked from 52 card deck \";\n      switch (rank) {\n        case 1:\n          std::cout << \"Ace\";\n          break;\n        case 2:\n          std::cout << rank;\n          break;\n        case 3:\n          std::cout << rank;\n          break;\n        case 4:\n          std::cout << rank;\n          break;\n        case 5:\n          std::cout << rank;\n          break;\n        case 6:\n          std::cout << rank;\n          break;\n        case 7:\n          std::cout << rank;\n          break;\n        case 8:\n          std::cout << rank;\n          break;\n        case 9:\n          std::cout << rank;\n          break;\n        case 10:\n          std::cout << rank;\n          break;\n        case 11:\n          std::cout << \"Jack\";\n          break;\n        case 12:\n          std::cout << \"Queen\";\n          break;\n        case 13:\n          std::cout << \"King\";\n          break;\n\n        }\n\n      std::cout << \" of \";\n      switch(suit) {\n        case 0:\n          std::cout << \"clubs\\n\";\n          break;\n        case 1:\n          std::cout << \"diamonds\\n\";\n          break;\n        case 2:\n          std::cout << \"hearts\\n\";\n          break;\n        case 3:\n          std::cout << \"spades\\n\";\n          break;\n\n        }\n    }\n\n    void exe_3_25(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4)\n    {\n      // Calculate the intersecting point\n      // Get a, b, c, d, e, f\n      double a = y1 - y2;\n      double b = -1 * (x1 - x2);\n      double c = y3 - y4;\n      double d = -1 * (x3 - x4);\n      double e = (y1 - y2) * x1 - (x1 - x2) * y1;\n      double f = (y3 - y4) * x3 - (x3 - x4) * y3;\n\n      // Display results\n      if (a * d - b * c == 0)\n        {\n          std::cout << \"The two lines are parallel.\\n\";\n        }\n      else\n        {\n          double x = (e * d - b * f) / (a * d - b * c);\n          double y = (a * f - e * c) / (a * d - b * c);\n          std::cout << \"The intersecting point is at (\" << x << \", \" << y << \") \\n\";\n        }\n    }\n\n    void exe_3_26()\n    {\n      std::cout << \"Enter an interger: \";\n      int number{};\n      std::cin >> number;\n      // Determine whether it is divisible by 5 and 6\n      // Display results\n      std::cout << \"Is 10 divisible by 5 and 6? \" <<\n                   ((number % 5 == 0) && (number % 6 == 0)) << std::endl;\n      std::cout << \"Is 10 divisible by 5 or 6? \" <<\n                   ((number % 5 == 0) || (number % 6 == 0)) << std::endl;\n      std::cout << \"Is 10 divisible by 5 of 6, but not both? \" <<\n                   ((number % 5 == 0) ^ (number % 6 == 0)) << std::endl;\n    }\n\n    void exe_3_27()\n    {\n      std::cout << \"Enter a point's x- and y- coordinates: \";\n      double x{}, y{};\n      std::cin >> x >> y;\n      // Determine whether the point is inside the triangle\n      // getting the point of ina line that starts at point\n\n      // Get the intersecting point with the hypotenuse side of the triangle\n      // of a line that starts and points (0, 0) and touches the user points\n      double intersectx = (-x * (200 * 100)) / (-y * 200 - x * 100);\n      double intersecty = (-y * (200 * 100)) / (-y * 200 - x * 100);\n\n      // Display results\n      std::cout << \"The point \" << ((x > intersectx || y > intersecty)\n                                    ? \"is not \" : \"is \" ) << \" in the triangle. \" << std::endl;\n    }\n\n\n  }\n}\n", "meta": {"hexsha": "83155252c5055e2fec9e160b674de476f595121a", "size": 25230, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tut_lib/ch3.cpp", "max_stars_repo_name": "Igwanya/cpp-bit2203-tutorial", "max_stars_repo_head_hexsha": "0602a0cc929feae7223178cb868545ff0300bc22", "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/tut_lib/ch3.cpp", "max_issues_repo_name": "Igwanya/cpp-bit2203-tutorial", "max_issues_repo_head_hexsha": "0602a0cc929feae7223178cb868545ff0300bc22", "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/tut_lib/ch3.cpp", "max_forks_repo_name": "Igwanya/cpp-bit2203-tutorial", "max_forks_repo_head_hexsha": "0602a0cc929feae7223178cb868545ff0300bc22", "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.5616438356, "max_line_length": 129, "alphanum_fraction": 0.4885850178, "num_tokens": 7478, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240211961401, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.7342344767504253}}
{"text": "#pragma once\n\n#include <random>\n#include <math.h>\n\n#include <dtl/dtl.hpp>\n\n#include <boost/math/distributions/poisson.hpp>\n\n//TODO merge into fpr.hpp\n\nnamespace dtl {\nnamespace bloomfilter {\n\n/// Computes an approximation of the false positive probability for standard Bloom filter.\n/// Assuming independence for the probabilities of each bit being set.\nstatic f64\nfpr(u64 m,\n    u64 n,\n    f64 k) {\n  return std::pow(1.0 - std::pow(1.0 - (1.0 / m), k * n), k);\n}\n\n\n/// Computes an approximation of the false positive probability for Blocked Bloom filter as\n/// defined by Putze et al.\n/// Note: The formula of Putze does not take self collisions into account and thus leads\n///       to a significant error for small block sizes (i.e., register blocks).\n///       Therefore, for small block sizes, the 'self collision' flag should be set to true.\nstatic f64\nfpr_blocked(u64 m,\n            u64 n,\n            f64 k,\n            u64 B, /* block size in bits */\n            u1 self_collisions = false,\n            f64 epsilon = 0.000001) {\n  $f64 f = 0;\n  $f64 c = (m * 1.0) / n;\n  $f64 lambda = B / c;\n  boost::math::poisson_distribution<> poisson(lambda);\n\n  $f64 k_act = k;\n  if (self_collisions) {\n    k_act = B * (1.0 - std::pow(1.0-1.0/B, k_act));\n  }\n\n  $f64 d_sum = 0.0;\n  $u64 i = 0;\n  while ((d_sum + epsilon) < 1.0) {\n    auto d = boost::math::pdf(poisson, i);\n    d_sum += d;\n    f += d * fpr(B, i, k_act);\n    i++;\n  }\n  return f;\n}\n\n\n/// Computes an approximation of the false positive probability for\n/// Sectorized Blocked Bloom filter.\nstatic f64\nfpr_blocked_sectorized(u64 m,\n                       u64 n,\n                       f64 k,\n                       u64 B, /* block size in bits */\n                       u64 S, /* sector size in bits */\n                       u1 self_collisions = false,\n                       f64 epsilon = 0.000001) {\n  $f64 f = 0;\n  $f64 c = (m * 1.0) / n;\n  $f64 lambda = (B * 1.0) / c;\n  $f64 s = (B * 1.0) / S;\n  boost::math::poisson_distribution<> poisson(lambda);\n\n  $f64 d_sum = 0.0;\n  $u64 i = 0;\n  $f64 k_per_s = (k * 1.0)/s;\n  if (self_collisions) {\n    k_per_s = S * (1.0 - std::pow(1.0-1.0/S, k_per_s));\n  }\n  while ((d_sum + epsilon) < 1.0) {\n    auto d = boost::math::pdf(poisson, i);\n    d_sum += d;\n    f += d * std::pow(fpr(S, i, k_per_s), s);\n    i++;\n  }\n  return f;\n}\n\n\nstatic __forceinline__ f64\np_load(f64 v, u64 i) {\n  f64 lambda = v;\n  boost::math::poisson_distribution<> poisson(lambda);\n  return boost::math::pdf(poisson, i);\n}\n\n\nstatic __forceinline__ f64\np_cache(u64 s, u64 S, u64 B, f64 k, u64 i) {\n//  boost::math::binomial_distribution binomial();\n\n  f64 k_per_s = (k * 1.0)/s;\n  $f64 sum = 0.0;\n  for (std::size_t j = 1; j <= i; j++) {\n    auto ev = (i*s*S*1.0)/B;\n    auto p_l = p_load(ev, j);\n    auto f_mini = fpr(S, j, k_per_s);\n    sum += p_l * f_mini;\n  }\n  auto r = std::pow(sum, s);\n  return r;\n}\n\n/// Computes an approximation of the false positive probability for\n/// Sectorized Blocked Bloom filter.\nstatic f64\nfpr_zoned(u64 m,\n          u64 n,\n          f64 k,\n          u64 B, /* block size in bits */\n          u64 S, /* sector size in bits */\n          f64 z, /* the number of zones */\n          u1 self_collisions = false,\n          f64 epsilon = 0.000001) {\n  $f64 f = 0;\n  $f64 c = (m * 1.0) / n;\n  $f64 lambda = (B * 1.0) / c;\n  $f64 s = (B * 1.0) / S;\n  boost::math::poisson_distribution<> poisson(lambda);\n\n  $f64 d_sum = 0.0;\n  $u64 i = 0;\n  $f64 k_per_s = (k * 1.0) / s;\n  if (self_collisions) {\n    k_per_s = S * (1.0 - std::pow(1.0 - 1.0 / S, k_per_s));\n  }\n  while ((d_sum + epsilon) < 1.0) {\n    auto d = boost::math::pdf(poisson, i);\n    d_sum += d;\n    f += d * p_cache(z, S, B, k, i);\n    i++;\n  }\n  return f;\n}\n\n\nstatic __forceinline__ f64\n_p_cache(u64 s, u64 S, u64 B, f64 k, u64 i) {\n  f64 k_per_s = (k * 1.0)/s;\n  $f64 sum = 0.0;\n  for (std::size_t j = 1; j <= i; j++) {\n    auto ev = (i*s*S*1.0)/B;\n    auto p_l = p_load(ev, j);\n    auto f_mini = fpr(S, j, k_per_s);\n    sum += p_l * f_mini;\n  }\n  auto r = std::pow(sum, s);\n  return r;\n}\n\n\nstatic f64\nfpr_blocked_sectorized_zoned(u64 m,\n                             u64 n,\n                             u64 k,\n                             u64 z, /* the number of zones */\n                             u64 B, /* block size in bits */\n                             u64 S, /* sector size in bits */\n                             u1 self_collisions = false,\n                             f64 epsilon = 0.000001) {\n  $f64 f = 0;\n//  f64 c = (m * 1.0) / n;\n//  f64 v = (B * 1.0) / c; // aka 'Poisson lambda'\n  f64 s = z;\n\n  $f64 d_sum = 0.0;\n  $u64 i = 0;\n  $f64 k_per_s = (k * 1.0)/s;\n  if (self_collisions) {\n    k_per_s = S * (1.0 - std::pow(1.0-1.0/S, k_per_s));\n  }\n  while ((d_sum + epsilon) < 1.0) {\n    auto ev = (n*B*1.0)/m;\n    auto d = p_load(ev, i);\n    d_sum += d;\n    f += d * p_cache(z, S, B, k, i);\n    i++;\n  }\n  return f;\n}\n\n} // namespace filter\n\nnamespace cuckoofilter {\n\n//// TODO\nstatic f64\nfpr(u64 associativity,\n    u64 tag_bitlength,\n    f64 load_factor) {\n//  return (2.0 /*k=2*/ * associativity * load_factor) / (std::pow(2, tag_bitlength) - 1); // no duplicates\n  return 1 - std::pow(1.0 - 1 / (std::pow(2.0, tag_bitlength) - 1), 2.0 * associativity * load_factor); // counting - with duplicates\n//  return 1 - std::pow(1.0 - 1 / (std::pow(2.0, tag_bitlength)), 2.0 * associativity * load_factor); // counting - with duplicates\n}\n\n\n} // namespace cuckoofilter\n} // namespace dtl\n\n\n\n//f64\n//fpr_k_partitioned(u64 m,\n//                  u64 n,\n//                  u64 k) {\n//  f64 c = (m * 1.0) / n;\n//  return fpr((m * 1.0)/k, n, 1);\n//}\n//f64\n//fpr_k_partitioned(u64 m,\n//                  u64 n,\n//                  u64 k) {\n//  f64 c = (m * 1.0) / n;\n//  return std::pow(1.0 - std::exp(-(k*1.0) / c), k);\n//}\n\n//f64\n//fpr_zoned(u64 m,\n//          u64 n,\n//          u64 k,\n//          u64 B, /* block size in bits */\n//          u64 z, /* number of zones */\n//          f64 epsilon = 0.000001) {\n//  return std::pow(fpr_blocked(m/z,n,k/z,64), z);\n//}\n\n//f64\n//fpr_blocked_k_partitioned(u64 m,\n//                          u64 n,\n//                          u64 k,\n//                          u64 B, /* block size in bits */\n//                          f64 epsilon = 0.000001) {\n//  $f64 f = 0;\n//  $f64 c = (m * 1.0) / n;\n//  $f64 lambda = (B * 1.0) / c;\n//  boost::math::poisson_distribution<> poisson(lambda);\n//\n//  std::random_device rd;\n//  std::mt19937 gen(rd());\n//\n//  $f64 d_sum = 0.0;\n//  $u64 i = 0;\n//  while ((d_sum + epsilon) < 1.0) {\n//    auto d = boost::math::pdf(poisson, i);\n//    d_sum += d;\n//    f += d * fpr_k_partitioned(B, i, k);\n//    i++;\n//  }\n//  return f;\n//}\n\n//f64\n//fpr_blocked_sectorized(u64 m,\n//                       u64 n,\n//                       u64 k,\n//                       u64 B, /* block size in bits */\n//                       u64 S, /* sector size in bits */\n//                       f64 epsilon = 0.000001) {\n//  $f64 f = 0;\n//  $f64 c = (m * 1.0) / n;\n//  $f64 lambda = (B * 1.0) / c;\n//  $f64 s = (B * 1.0) / S;\n//  boost::math::poisson_distribution<> poisson(lambda);\n//\n//  std::random_device rd;\n//  std::mt19937 gen(rd());\n//\n//  $f64 d_sum = 0.0;\n//  $u64 i = 0;\n//  while ((d_sum + epsilon) < 1.0) {\n//    auto d = boost::math::pdf(poisson, i);\n//    d_sum += d;\n//    f += d * std::pow(fpr(S, i, (k * 1.0)/s), s);\n//    i++;\n//  }\n//  return f;\n//}\n", "meta": {"hexsha": "06592d56cc1f65d89e5360d71c0328cca2d57d99", "size": 7390, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/dtl/filter/blocked_bloomfilter/math.hpp", "max_stars_repo_name": "peterboncz/bloomfilter-bsd", "max_stars_repo_head_hexsha": "bae83545a091555e48b5495669c7adcb99fd2047", "max_stars_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2018-08-26T15:31:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-28T06:28:33.000Z", "max_issues_repo_path": "src/dtl/filter/blocked_bloomfilter/math.hpp", "max_issues_repo_name": "peterboncz/bloomfilter-bsd", "max_issues_repo_head_hexsha": "bae83545a091555e48b5495669c7adcb99fd2047", "max_issues_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-12-20T22:56:22.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-20T22:56:22.000Z", "max_forks_repo_path": "src/dtl/filter/blocked_bloomfilter/math.hpp", "max_forks_repo_name": "peterboncz/bloomfilter-bsd", "max_forks_repo_head_hexsha": "bae83545a091555e48b5495669c7adcb99fd2047", "max_forks_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2018-10-02T09:15:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-29T15:45:42.000Z", "avg_line_length": 25.5709342561, "max_line_length": 133, "alphanum_fraction": 0.5086603518, "num_tokens": 2585, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240142763573, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.7342344713345709}}
{"text": "#include \"numeric_tools.h\"\r\n\r\n#include <boost/math/quadrature/tanh_sinh.hpp>\r\n#include <boost/math/constants/constants.hpp>\r\n#include <unsupported/Eigen/Polynomials>\r\n#include <iostream>\r\n\r\nnamespace Numerics\r\n{\r\n\tdouble bickley3f(double x)\r\n\t{\r\n\t   auto f = [&x](double t) {return exp(-x / sin(t)) * sin(t) * sin(t);};\r\n\t   boost::math::quadrature::tanh_sinh<double> integrator;\r\n\t   return integrator.integrate(f, 0.0, boost::math::constants::half_pi<double>());\r\n\t}\r\n\r\n\tdouble delk(int a, int b)\r\n\t{\r\n\t\treturn a == b ? 1.0 : 0.0;\r\n\t} \r\n\r\n\tvoid diagonalDominanceCheck(Eigen::MatrixXd &matrix)\r\n\t{\r\n\t\tEigen::VectorXd rowSum = Eigen::VectorXd::Zero(matrix.rows());\r\n\r\n\t\tbool isWarningPrinted = false;\r\n\t\r\n\t\tfor(unsigned i = 0; i < rowSum.size(); i++)\r\n\t\t{\r\n\t\t\tfor(unsigned j = 0; j < rowSum.size(); j++)\r\n\t\t    {\r\n\t\t\t    rowSum(i) += fabs(matrix(i, j));\r\n\t\t\t}\r\n\t\t}\r\n\t\r\n\t\tfor(unsigned i = 0; i < rowSum.size(); i++)\r\n\t\t{\r\n\t\t\tif((is_lower(matrix(i, i), (rowSum(i) - matrix(i, i)))) && !isWarningPrinted)\r\n\t\t\t{\r\n\t\t\t\tisWarningPrinted = true;\r\n\t\t\t\tout.print(TraceLevel::CRITICAL, \"The convergence is not guaranteed, the matrix is not strictly diagonally dominant\");\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tdouble bickley3f_old(const double x)\r\n\t{\r\n\t\tdouble intValue = 0.0;\r\n\t\tint N = 200;\r\n\r\n    \tif(is_lower_equal(x, 0.0)) \r\n\t\t{\r\n\t\t\tintValue = M_PI / 4.0;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tfor(int i = -N; i < N; i++)\r\n\t\t\t{\r\n\t\t\t\tdouble step = 1.0 / 100.0;\r\n\t\t\t\tdouble abscissa = 1.0 - 0.25 * pow((tanh(0.5 * M_PI * sinh(i * step)) + 1.0), 2);\r\n\t\t\t\tdouble func = exp(-x / sqrt(abscissa)) * sqrt(abscissa);\r\n\t\t\t\tdouble weight = 0.5 * step * M_PI * cosh(i * step) / pow(cosh(0.5 * M_PI * sinh(i * step)), 2);\r\n\t\t\t\tintValue = weight * func / 2.0 + intValue;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn intValue;\r\n\t}\r\n\r\n\t// https://www.geeksforgeeks.org/multiply-two-polynomials-2/\r\n\tstd::vector<double> multiply_poly(std::vector<double> &a, \r\n\t                                  std::vector<double> &b)\r\n\t{\r\n\t   size_t m = a.size();\r\n\t   size_t n = b.size();\r\n\r\n\t   std::vector<double> result(m + n - 1, 0.0);\r\n  \r\n\t   for (size_t i = 0; i < m; i++) \r\n\t     for (size_t j = 0; j < n; j++) \r\n\t           result[i + j] += a[i] * b[j];\r\n\r\n\t   return result; \r\n\t}\r\n\r\n\t// product of (a1 + x)(a2 + x)(a3 + x)... \r\n\tstd::vector<double> prod_poly(std::vector<double> &a)\r\n\t{\r\n\t    std::vector<double> result = {1.0};\r\n\r\n\t\tfor(auto & a_i : a)\r\n\t\t{\r\n\t        std::vector<double> temp = {a_i, 1.0};\r\n\t\t\tresult = multiply_poly(result, temp);\r\n\t\t}\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tstd::vector<double> prod_poly_i(std::vector<double> &a, size_t i)\r\n\t{\r\n\t    std::vector<double> result = {1.0};\r\n\r\n\t\tfor(size_t j = 0; j < a.size(); j++)\r\n\t\t{\r\n\t\t\tif (j == i) continue;\r\n\t        std::vector<double> temp = {a[j], 1.0};\r\n\t\t\tresult = multiply_poly(result, temp);\r\n\t\t}\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\t// http://www.ce.unipr.it/people/medici/eigen-poly.html\r\n\tstd::vector<double> poly_roots(std::vector<double> &p)\r\n\t{\r\n\t\tstd::vector<double> result;\r\n\t\r\n\t\tEigen::PolynomialSolver<double, Eigen::Dynamic> solver;\r\n\t\tEigen::VectorXd coeff = Eigen::VectorXd::Zero(p.size());\r\n\t\r\n\t\tfor(size_t i = 0; i < p.size(); i++)\r\n\t    \tcoeff[i] = p[i];\r\n\t\r\n\t\tsolver.compute(coeff);\r\n\t\r\n\t\tconst Eigen::PolynomialSolver<double, Eigen::Dynamic>::RootsType & r = solver.roots();\r\n\r\n\t\tfor(unsigned i = 0; i < r.rows(); i++)\r\n\t\t\tresult.push_back(r[i].real());\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tEigen::VectorXd tridiag_solver(const Eigen::VectorXd &a, \r\n\t                               const Eigen::VectorXd &b, \r\n\t              \t               const Eigen::VectorXd &c, \r\n\t\t\t\t\t\t\t\t   const Eigen::VectorXd &d)\r\n\t{\r\n\t   int n = d.size();\r\n\t   Eigen::VectorXd result = Eigen::VectorXd::Zero(n); \r\n\t   Eigen::VectorXd P = Eigen::VectorXd::Zero(n);   \r\n\t   Eigen::VectorXd Q = Eigen::VectorXd::Zero(n);   \r\n\t   result = P;\r\n\r\n\t   // Forward pass\r\n\t   P(0) = -c(0) / b(0);\r\n\t   Q(0) =  d(0) / b(0);\r\n\r\n\t   for (int i = 1; i < n; i++)\r\n\t   {\r\n\t      double denominator = b(i) + a(i - 1) * P(i - 1);\r\n\t      P(i) = -c(i - 1)                    / denominator;\r\n\t      Q(i) = (d(i) - a(i - 1) * Q(i - 1)) / denominator;\r\n\t   }\r\n\r\n\t   // Backward pass\r\n\t   result(n - 1) = Q(n - 1);\r\n\t   for (int i = n - 2; i >= 0; i--) \r\n\t      result(i) = P(i) * result(i + 1) + Q(i);\r\n\r\n\t    return result;\r\n\t}\r\n\r\n\tEigen::VectorXd ConcatenateEigenVectors(Eigen::VectorXd a, Eigen::VectorXd b)\r\n\t{\r\n\t\tEigen::VectorXd result(a.size() + b.size());\r\n\t\tresult << a, b;\r\n\t\treturn result;\r\n\t}\r\n\r\n\tSourceIterResults sourceIteration(Eigen::MatrixXd &Mmatrix, Eigen::MatrixXd &Fmatrix, \r\n                                      SolverData &solverData, Eigen::VectorXd volumes)\r\n\t{\r\n\t\tdiagonalDominanceCheck(Mmatrix);\r\n\t\r\n\t\tif(Mmatrix.size() != Fmatrix.size())\r\n\t\t{\r\n\t\t\tout.print(TraceLevel::CRITICAL, \" MMatrix has a different number of elements than FMatrix!\");\r\n\t\t\texit(-1);\r\n\t\t}\r\n\t\r\n\t\tunsigned size = sqrt(Mmatrix.size());\r\n\t\r\n\t\tEigen::VectorXd source1      = Eigen::VectorXd::Zero(size);\r\n\t\tEigen::VectorXd source2      = Eigen::VectorXd::Ones(size);\t\r\n\t\tEigen::VectorXd neutronFlux1 = Eigen::VectorXd::Ones(size);\r\n\t\tEigen::VectorXd neutronFlux2 = Eigen::VectorXd::Zero(size);\r\n\r\n\t\tEigen::VectorXd volumesVec = volumes;\r\n\r\n\t\tint energyGroups = double(size) / volumes.size();\r\n\r\n\t\tfor(auto i = 0; i < energyGroups - 1; i++)\r\n\t\t\tvolumesVec = ConcatenateEigenVectors(volumesVec, volumes);\r\n\r\n\t\tdouble kFactor1 = 1.0;\r\n\t\tdouble kFactor2 = 0.0;\r\n\r\n\t\tint max_iter_number = solverData.getMaxIterNumber();\r\n\t\tdouble accuracy = solverData.getAccuracy();\r\n\t\tstd::string title = get_name(solverData.getKind());\r\n\t\r\n\t\tint h;\r\n\t\r\n\t\tEigen::ColPivHouseholderQR<Eigen::MatrixXd> CPHQR;\r\n\t\tCPHQR.compute(Mmatrix);\r\n\t\r\n\t\tfor(h = 0; h < max_iter_number; h++)\r\n\t\t{\r\n\t\t\tneutronFlux2 = CPHQR.solve(source2);\r\n\t\t\r\n\t\t\tsource1 = Fmatrix * neutronFlux1;\r\n\t\t\tsource2 = Fmatrix * neutronFlux2;\r\n\t\t\r\n\t\t\tdouble sum1 = std::inner_product(source1.begin(), source1.end(), source2.begin(), 0.0);\r\n\t\t\tdouble sum2 = std::inner_product(source2.begin(), source2.end(), source2.begin(), 0.0);\r\n\t\t\r\n\t\t\tkFactor2 = kFactor1 * (sum2 / sum1);\r\n\r\n\t\t\tif(solverData.getKind() == SolverKind::DIFFUSION)\r\n\t\t\t{\r\n\t\t\t\tsource2 = source2.cwiseProduct(volumesVec);\t\r\n\t\t\t}\r\n\r\n\t\t\tsource2 /= kFactor2;\r\n\t\t\r\n\t\t\t// exit condition\r\n\t\t\tif (fabs((kFactor2 - kFactor1) / kFactor2) < accuracy) break;\r\n\t\t\r\n\t\t\tkFactor1     = kFactor2;\r\n\t\t\tneutronFlux1 = neutronFlux2;\r\n\t\t}\r\n\r\n\t\tout.print(TraceLevel::DEBUG, \"Number of {} iteration: {}\", title, h + 1);\r\n\r\n\t\tif(h + 1 > max_iter_number)\r\n\t\t{\r\n\t\t\tout.print(TraceLevel::CRITICAL, \"Number of {} iteration: {}\", title, h + 1);\r\n\t\t\tout.print(TraceLevel::CRITICAL, \"The {} calculation did not converge!\", title);\r\n\t\t\texit(-1);\r\n\t\t}\r\n\r\n\t\tEigen::VectorXd neutronFlux = neutronFlux2 / neutronFlux2.sum(); \r\n\t\tdouble kFactor = kFactor2;\r\n\r\n\t\tSourceIterResults result(neutronFlux, kFactor);\r\n\t\treturn result;\r\n\t}\r\n}", "meta": {"hexsha": "f09fcf738055c9f987cd8a85b763f4297eef35fb", "size": 6835, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Utilities/numeric_tools.cpp", "max_stars_repo_name": "FrancisKhan/ALMOST", "max_stars_repo_head_hexsha": "06e36666ca18aa06167baac3123dbbe913f74b5d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-12-20T15:37:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-18T18:11:17.000Z", "max_issues_repo_path": "Utilities/numeric_tools.cpp", "max_issues_repo_name": "FrancisKhan/ALMOST", "max_issues_repo_head_hexsha": "06e36666ca18aa06167baac3123dbbe913f74b5d", "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": "Utilities/numeric_tools.cpp", "max_forks_repo_name": "FrancisKhan/ALMOST", "max_forks_repo_head_hexsha": "06e36666ca18aa06167baac3123dbbe913f74b5d", "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.4497991968, "max_line_length": 122, "alphanum_fraction": 0.5762984638, "num_tokens": 2085, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178969328287, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.734224327958888}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\nusing namespace std;\nint main() {\n  //\u968f\u673a\u521d\u59cb\u5316\u4e00\u4e2a 3x3 \u6d6e\u70b9\u6570\u77e9\u9635[-1,1]\u4e4b\u95f4\u5747\u5300\u5206\u5e03\n  Eigen::Matrix3f matrix = Eigen::MatrixXf::Random(3, 3);\n  // \u521d\u59cb\u5316 3x3 \u7684 double \u77e9\u9635\u4e3a\u5168 1.2\n  Eigen::Matrix3d matrix_c = Eigen::MatrixXd::Constant(3, 3, 1.2);\n  Eigen::Vector3d v1(1., 2., 3.);\n  Eigen::VectorXd v2(3);\n  v2 << 1., 2., 3;\n  cout << matrix << \"\\n\"\n       << matrix_c << \"\\n\"\n       << \"vec1 = \\n\"\n       << v1 << \"\\n\"\n       << \"vec2 = \\n\"\n       << v2 << \"\\n\";\n}\n", "meta": {"hexsha": "3d6c898431d647ab911343d8cc775f611030003e", "size": 486, "ext": "cc", "lang": "C++", "max_stars_repo_path": "code/matrix_demo1.cc", "max_stars_repo_name": "bleedingfight/eigen-docs", "max_stars_repo_head_hexsha": "c74d91e935eb0afbb2fc1ed6f191b9817ad2b424", "max_stars_repo_licenses": ["LPPL-1.3c"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/matrix_demo1.cc", "max_issues_repo_name": "bleedingfight/eigen-docs", "max_issues_repo_head_hexsha": "c74d91e935eb0afbb2fc1ed6f191b9817ad2b424", "max_issues_repo_licenses": ["LPPL-1.3c"], "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/matrix_demo1.cc", "max_forks_repo_name": "bleedingfight/eigen-docs", "max_forks_repo_head_hexsha": "c74d91e935eb0afbb2fc1ed6f191b9817ad2b424", "max_forks_repo_licenses": ["LPPL-1.3c"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5789473684, "max_line_length": 66, "alphanum_fraction": 0.5329218107, "num_tokens": 209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760038, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.7340757027549374}}
{"text": "#include <iostream>\n#include <cmath>\nusing namespace std;\n\n#include <Eigen/Core>\n// Eigen \u51e0\u4f55\u6a21\u5757\n#include <Eigen/Geometry>\n\n/****************************\n* \u672c\u7a0b\u5e8f\u6f14\u793a\u4e86 Eigen \u51e0\u4f55\u6a21\u5757\u7684\u4f7f\u7528\u65b9\u6cd5\n****************************/\n\nint main ( int argc, char** argv )\n{\n    // Eigen/Geometry \u6a21\u5757\u63d0\u4f9b\u4e86\u5404\u79cd\u65cb\u8f6c\u548c\u5e73\u79fb\u7684\u8868\u793a\n    // 3D \u65cb\u8f6c\u77e9\u9635\u76f4\u63a5\u4f7f\u7528 Matrix3d \u6216 Matrix3f\n    Eigen::Matrix3d rotation_matrix = Eigen::Matrix3d::Identity();\n    // \u65cb\u8f6c\u5411\u91cf\u4f7f\u7528 AngleAxis, \u5b83\u5e95\u5c42\u4e0d\u76f4\u63a5\u662fMatrix\uff0c\u4f46\u8fd0\u7b97\u53ef\u4ee5\u5f53\u4f5c\u77e9\u9635\uff08\u56e0\u4e3a\u91cd\u8f7d\u4e86\u8fd0\u7b97\u7b26\uff09\n    Eigen::AngleAxisd rotation_vector ( M_PI/2, Eigen::Vector3d ( 0,0,1 ) );     //\u6cbf Z \u8f74\u65cb\u8f6c 45 \u5ea6\n    cout .precision(3);\n    cout<<\"rotation matrix =\\n\"<<rotation_vector.matrix() <<endl;                //\u7528matrix()\u8f6c\u6362\u6210\u77e9\u9635\n    // \u4e5f\u53ef\u4ee5\u76f4\u63a5\u8d4b\u503c\n    rotation_matrix = rotation_vector.toRotationMatrix();\n    // \u7528 AngleAxis \u53ef\u4ee5\u8fdb\u884c\u5750\u6807\u53d8\u6362\n    Eigen::Vector3d v ( 1,0,0 );\n    Eigen::Vector3d v_rotated = rotation_vector * v;\n    cout<<\"(1,0,0) after rotation = \"<<v_rotated.transpose()<<endl;\n    // \u6216\u8005\u7528\u65cb\u8f6c\u77e9\u9635\n    v_rotated = rotation_matrix * v;\n    cout<<\"(1,0,0) after rotation = \"<<v_rotated.transpose()<<endl;\n\n    // \u6b27\u62c9\u89d2: \u53ef\u4ee5\u5c06\u65cb\u8f6c\u77e9\u9635\u76f4\u63a5\u8f6c\u6362\u6210\u6b27\u62c9\u89d2\n    Eigen::Vector3d euler_angles = rotation_matrix.eulerAngles ( 2,1,0 ); // ZYX\u987a\u5e8f\uff0c\u5373roll pitch yaw\u987a\u5e8f\n    cout<<\"yaw pitch roll = \"<<euler_angles.transpose()<<endl;\n\n    // \u6b27\u6c0f\u53d8\u6362\u77e9\u9635\u4f7f\u7528 Eigen::Isometry\n    Eigen::Isometry3d T=Eigen::Isometry3d::Identity();                // \u867d\u7136\u79f0\u4e3a3d\uff0c\u5b9e\u8d28\u4e0a\u662f4\uff0a4\u7684\u77e9\u9635\n    T.rotate ( rotation_vector );                                     // \u6309\u7167rotation_vector\u8fdb\u884c\u65cb\u8f6c\n    T.pretranslate ( Eigen::Vector3d ( 1,3,4 ) );                     // \u628a\u5e73\u79fb\u5411\u91cf\u8bbe\u6210(1,3,4)\n    cout << \"Transform matrix = \\n\" << T.matrix() <<endl;\n\n    // \u7528\u53d8\u6362\u77e9\u9635\u8fdb\u884c\u5750\u6807\u53d8\u6362\n    Eigen::Vector3d v_transformed = T*v;                              // \u76f8\u5f53\u4e8eR*v+t\n    cout<<\"v tranformed = \"<<v_transformed.transpose()<<endl;\n\n    // \u5bf9\u4e8e\u4eff\u5c04\u548c\u5c04\u5f71\u53d8\u6362\uff0c\u4f7f\u7528 Eigen::Affine3d \u548c Eigen::Projective3d \u5373\u53ef\uff0c\u7565\n\n    // \u56db\u5143\u6570\n    // \u53ef\u4ee5\u76f4\u63a5\u628aAngleAxis\u8d4b\u503c\u7ed9\u56db\u5143\u6570\uff0c\u53cd\u4e4b\u4ea6\u7136\n    Eigen::Quaterniond q = Eigen::Quaterniond ( rotation_vector );\n    cout<<\"quaternion = \\n\"<<q.coeffs() <<endl;   // \u8bf7\u6ce8\u610fcoeffs\u7684\u987a\u5e8f\u662f(x,y,z,w),w\u4e3a\u5b9e\u90e8\uff0c\u524d\u4e09\u8005\u4e3a\u865a\u90e8\n    // \u4e5f\u53ef\u4ee5\u628a\u65cb\u8f6c\u77e9\u9635\u8d4b\u7ed9\u5b83\n    q = Eigen::Quaterniond ( rotation_matrix );\n    cout<<\"quaternion = \\n\"<<q.coeffs() <<endl;\n    // \u4f7f\u7528\u56db\u5143\u6570\u65cb\u8f6c\u4e00\u4e2a\u5411\u91cf\uff0c\u4f7f\u7528\u91cd\u8f7d\u7684\u4e58\u6cd5\u5373\u53ef\n    v_rotated = q*v; // \u6ce8\u610f\u6570\u5b66\u4e0a\u662fqvq^{-1}\n    cout<<\"(1,0,0) after rotation = \"<<v_rotated.transpose()<<endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "05988c87d0d1f4496e5a36bdccba1e7fc06885f2", "size": 2295, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch3/useGeometry/eigenGeometry.cpp", "max_stars_repo_name": "hujun1413/slambook_hj", "max_stars_repo_head_hexsha": "3362bbb165e4c0699e644234437ec59be3d3ac22", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-04-19T12:53:08.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-19T12:53:08.000Z", "max_issues_repo_path": "ch3/useGeometry/eigenGeometry.cpp", "max_issues_repo_name": "hujun1413/slambook_hj", "max_issues_repo_head_hexsha": "3362bbb165e4c0699e644234437ec59be3d3ac22", "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/useGeometry/eigenGeometry.cpp", "max_forks_repo_name": "hujun1413/slambook_hj", "max_forks_repo_head_hexsha": "3362bbb165e4c0699e644234437ec59be3d3ac22", "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.6229508197, "max_line_length": 100, "alphanum_fraction": 0.605664488, "num_tokens": 914, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425223682085, "lm_q2_score": 0.7981867753392728, "lm_q1q2_score": 0.7340464993939555}}
{"text": "#include <iostream>\r\n#include <Eigen/Dense>\r\n\r\nusing namespace Eigen;\r\n\r\nint main()\r\n{\r\n  Matrix2d a;\r\n  a << 1, 2,\r\n       3, 4;\r\n  Vector3d v(1,2,3);\r\n  std::cout << \"a * 2.5 =\\n\" << a * 2.5 << std::endl;\r\n  std::cout << \"0.1 * v =\\n\" << 0.1 * v << std::endl;\r\n  std::cout << \"Doing v *= 2;\" << std::endl;\r\n  v *= 2;\r\n  std::cout << \"Now v =\\n\" << v << std::endl;\r\n}\r\n", "meta": {"hexsha": "cb8f1e1ef8778cd503d6eafb6251c16ab9369c32", "size": 370, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/eigen-eigen-323c052e1731/doc/examples/tut_arithmetic_scalar_mul_div.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_scalar_mul_div.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_scalar_mul_div.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": 20.5555555556, "max_line_length": 54, "alphanum_fraction": 0.4567567568, "num_tokens": 150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.7339923357221682}}
{"text": "#include \"ptEngine.hpp\"\n#include <Eigen/Dense>\n\nnamespace tapl {\n\tnamespace pte {\n\t\t// constructor \n\t\ttemplate <typename PointT>\n\t\tLine<PointT>::Line() {}\n\n\t\t// de-constructor \n\t\ttemplate <typename PointT>\n\t\tLine<PointT>::~Line() {}\n\n\t\ttemplate <typename PointT>\n\t\tstd::vector<float> Line<PointT>::fitSVD(std::vector<float> &x, std::vector<float> &y)\n\t\t{\n\t\t\t/*\n\t\t\tSystem of linear equations of the form Ax = 0\n\t\t\t\n\t\t\tSVD method solves the equation Ax = 0 by performing\n\t\t\tsingular-value decomposition of matrix A\n\t\t\t*/\n\n\t\t\t// Form Matrix A\n\t\t\tEigen::MatrixXd A(x.size(), 3);\n\t\t\tfor(int i = 0; i < x.size(); ++i)\n\t\t\t{\n\t\t\t\tA(i, 0) = x[i];\n\t\t\t\tA(i, 1) = y[i];\n\t\t\t\tA(i, 2) = 1.0;\n\t\t\t}\n\t\t\t\t\n\t\t\t// Take SVD of A\n\t\t\tEigen::JacobiSVD<Eigen::MatrixXd> svd(A, Eigen::DecompositionOptions::ComputeThinU | Eigen::DecompositionOptions::ComputeThinV);\n\t\t\tEigen::MatrixXd V = svd.matrixV();\n\t\t\t\n\t\t\t// store in vector\n\t\t\tstd::vector<float> line_coeffs;\n\t\t\tfor(auto i = 0; i < V.rows(); ++i)\n\t\t\t{\n\t\t\t\tline_coeffs.push_back(V(i, (V.cols() - 1)));\n\t\t\t}\n\t\t\t\n\t\t\t// Return coeffs\n\t\t\treturn line_coeffs;\n\t\t}\n\n\t\ttemplate <typename PointT>\n\t\tstd::vector<float> Line<PointT>::fitLS(std::vector<float> &x, std::vector<float> &y)\n\t\t{\n\t\t\t/*\n\t\t\tSystem of linear equations of the form Y = Hx\n\t\t\t\n\t\t\tleast-squares method attempts to minimize\n\t\t\tthe energy of error, J(x) = ( ||Y - Hx|| )^2\n\t\t\twhere, ||Y - Hx|| is the Euclidian length of vector (Y - Hx)\n\t\t\t*/\n\t\t\t\n\t\t\t// Form Matrix H\n\t\t\tEigen::MatrixXd H(x.size(), 2);\n\t\t\tfor(int i = 0; i < x.size(); ++i)\n\t\t\t{\n\t\t\t\tH(i, 0) = x[i];\n\t\t\t\tH(i, 1) = 1.0;\n\t\t\t}\n\n\t\t\t// Form Matrix Y\n\t\t\tEigen::MatrixXd Y(y.size(), 1);\n\t\t\tfor(int i = 0; i < y.size(); ++i)\n\t\t\t{\n\t\t\t\tY(i, 0) = y[i];\n\t\t\t}\n\n\t\t\t// Transpose of H\n\t\t\tauto H_transpose = H.transpose();\n\n\t\t\t// get line coefficients\n\t\t\tauto coeffs = ((H_transpose*H).inverse()) * (H_transpose*Y);\n\n\t\t\t// Line equation is of the form y = a'x + b'\n\t\t\t// let's convert it to the form ax + by + c = 0\n\t\t\t// a = a'; b = -1; c = b'\n\t\t\tstd::vector<float> line_coeffs;\n\t\t\tline_coeffs.push_back(coeffs(0, 0));\n\t\t\tline_coeffs.push_back(-1.0);\n\t\t\tline_coeffs.push_back(coeffs(1, 0));\n\n\t\t\t// Return coefficients\n\t\t\treturn line_coeffs;\n\t\t}\n\n\t\ttemplate <typename PointT>\n\t\tfloat Line<PointT>::distToPoint(std::vector<float> line_coeffs, PointT point)\n\t\t{\n\t\t\tfloat dist = fabs(line_coeffs[0] * point.x + line_coeffs[1] * point.y + line_coeffs[2]) /\n\t\t\t\t\t\t\tsqrt(pow(line_coeffs[0], 2) + pow(line_coeffs[1], 2));\n\t\t\t\n\t\t\treturn dist;\n\t\t}\n\n\t\ttemplate <typename PointT>\n\t\tstd::unordered_set<int> Line<PointT>::Ransac(typename pcl::PointCloud<PointT>::Ptr cloud, int maxIterations, float distTolerance)\n\t\t{\n\t\t\t// random number seed\n\t\t\tsrand(time(NULL));\n\t\t\t// get the start timestamp\n\t\t\tauto t_start = std::chrono::high_resolution_clock::now();\n\n\t\t\tstd::unordered_set<int> inliersResult;\n\t\t\t\n\t\t\t// number of random samples to select per iteration\n\t\t\tconst int n_random_samples = 2;\n\t\t\t\n\t\t\t// number of inliers for each iteration\n\t\t\tstd::vector<int> n_inliers(maxIterations, 0);\n\t\t\t// coefficients for each line\n\t\t\tstd::vector<std::vector<float>> coeffs(maxIterations);\n\n\t\t\t// iterate 'maxIterations' number of times\n\t\t\tfor(int i = 0; i < maxIterations; ++i)\n\t\t\t{\n\t\t\t\t// x, y, and z points as a vector\n\t\t\t\tstd::vector<float> x, y, z;\n\t\t\t\t// select random samples\n\t\t\t\tfor(int j = 0; j < n_random_samples; ++j)\n\t\t\t\t{\n\t\t\t\t\tint idx = rand()%cloud->size();\n\t\t\t\t\tx.push_back(cloud->at(idx).x);\n\t\t\t\t\ty.push_back(cloud->at(idx).y);\n\t\t\t\t\tz.push_back(cloud->at(idx).z);\n\t\t\t\t}\n\t\t\t\t// fit a line\n\t\t\t\tcoeffs[i] = this->fitSVD(x, y);\n\n\t\t\t\tfor(typename pcl::PointCloud<PointT>::iterator it = cloud->begin(); it != cloud->end(); ++it)\n\t\t\t\t{\n\t\t\t\t\tif(this->distToPoint(coeffs[i], *it) <= distTolerance)\n\t\t\t\t\t{\n\t\t\t\t\t\tn_inliers[i]++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// find the index for number of inliers\n\t\t\tauto inliers_it = std::max_element(n_inliers.begin(), n_inliers.end());\n\t\t\tint index_max_n_inlier = std::distance(n_inliers.begin(), inliers_it);\n\n\t\t\t// find inliers with the best fit\n\t\t\tint index = 0;\n\t\t\tfor(typename pcl::PointCloud<PointT>::iterator it = cloud->begin(); it != cloud->end(); ++it)\n\t\t\t{\n\t\t\t\tif(this->distToPoint(coeffs[index_max_n_inlier], *it) <= distTolerance)\n\t\t\t\t{\n\t\t\t\t\tinliersResult.insert(index);\n\t\t\t\t}\n\t\t\t\tindex++;\n\t\t\t}\n\n\t\t\t// get the end timestamp\n\t\t\tauto t_end = std::chrono::high_resolution_clock::now();\n\n\t\t\t// measure execution time\n\t\t\tauto t_duration = std::chrono::duration_cast<std::chrono::milliseconds>(t_end - t_start);\n\t\t\tTLOG_INFO << \"Time taken by RANSAC: \"\n\t\t\t\t<< t_duration.count() << \" milliseconds\" ; \n\n\t\t\t// Return indicies of inliers from fitted line with most inliers\n\t\t\treturn inliersResult;\n\t\t}\n\n\t\t// constructor \n\t\ttemplate <typename PointT>\n\t\tPlane<PointT>::Plane() {}\n\n\t\t// de-constructor \n\t\ttemplate <typename PointT>\n\t\tPlane<PointT>::~Plane() {}\n\n\t\ttemplate <typename PointT>\n\t\tstd::vector<float> Plane<PointT>::fitSVD(std::vector<float> &x, std::vector<float> &y, std::vector<float> &z)\n\t\t{\n\t\t\t/*\n\t\t\tSystem of linear equations of the form Ax = 0\n\t\t\t\n\t\t\tSVD method solves the equation Ax = 0 by performing\n\t\t\tsingular-value decomposition of matrix A\n\t\t\t*/\n\t\t\t\n\t\t\t// Form Matrix A\n\t\t\tEigen::MatrixXd A(x.size(), 4);\n\t\t\tfor(int i = 0; i < x.size(); ++i)\n\t\t\t{\n\t\t\t\tA(i, 0) = x[i];\n\t\t\t\tA(i, 1) = y[i];\n\t\t\t\tA(i, 2) = z[i];\n\t\t\t\tA(i, 3) = 1.0;\n\t\t\t}\n\t\t\t\t\n\t\t\t// Take SVD of A\n\t\t\tEigen::JacobiSVD<Eigen::MatrixXd> svd(A, Eigen::DecompositionOptions::ComputeThinU | Eigen::DecompositionOptions::ComputeThinV);\n\t\t\tEigen::MatrixXd V = svd.matrixV();\n\n\t\t\t// Plane equation is of the form ax + by + cz + d = 0\n\t\t\tstd::vector<float> plane_coeffs;\n\t\t\tfor(auto i = 0; i < V.rows(); ++i)\n\t\t\t{\n\t\t\t\tplane_coeffs.push_back(V(i, (V.cols() - 1)));\n\t\t\t}\n\t\t\t\n\t\t\t// Return coeffs\n\t\t\treturn plane_coeffs;\n\t\t}\n\n\t\ttemplate <typename PointT>\n\t\tstd::vector<float> Plane<PointT>::fitLS(std::vector<float> &x, std::vector<float> &y, std::vector<float> &z)\n\t\t{\n\t\t\t/*\n\t\t\tSystem of linear equations of the form Y = Hx\n\t\t\t\n\t\t\tleast-squares method attempts to minimize\n\t\t\tthe energy of error, J(x) = ( ||Y - Hx|| )^2\n\t\t\twhere, ||Y - Hx|| is the Euclidian length of vector (Y - Hx)\n\t\t\t*/\n\t\t\t\n\t\t\t// Form Matrix H\n\t\t\tEigen::MatrixXd H(x.size(), 3);\n\t\t\tfor(int i = 0; i < x.size(); ++i)\n\t\t\t{\n\t\t\t\tH(i, 0) = x[i];\n\t\t\t\tH(i, 1) = y[i];\n\t\t\t\tH(i, 2) = 1.0;\n\t\t\t}\n\n\t\t\t// Form Matrix Y\n\t\t\tEigen::MatrixXd Y(z.size(), 1);\n\t\t\tfor(int i = 0; i < z.size(); ++i)\n\t\t\t{\n\t\t\t\tY(i, 0) = z[i];\n\t\t\t}\n\n\t\t\t// Transpose of H\n\t\t\tauto H_transpose = H.transpose();\n\n\t\t\t// get plane coefficients\n\t\t\tauto coeffs = ((H_transpose*H).inverse()) * (H_transpose*Y);\n\n\t\t\t// Plane equation is of the form z = a'x + b'y + c'\n\t\t\t// let's convert it to the form ax + by + cz + d = 0\n\t\t\t// a = a'; b = b'; c = -1; d = c'\n\t\t\tstd::vector<float> plane_coeffs;\n\t\t\tplane_coeffs.push_back(coeffs(0, 0));\n\t\t\tplane_coeffs.push_back(coeffs(1, 0));\n\t\t\tplane_coeffs.push_back(-1.0);\n\t\t\tplane_coeffs.push_back(coeffs(2, 0));\n\n\t\t\t// Return coefficients\n\t\t\treturn plane_coeffs;\n\t\t}\n\n\t\ttemplate <typename PointT>\n\t\tfloat Plane<PointT>::distToPoint(std::vector<float> plane_coeffs, PointT point)\n\t\t{\n\t\t\tfloat dist = fabs(plane_coeffs[0] * point.x + plane_coeffs[1] * point.y + plane_coeffs[2] * point.z + plane_coeffs[3]) /\n\t\t\t\t\t\t\tsqrt(pow(plane_coeffs[0], 2) + pow(plane_coeffs[1], 2) + pow(plane_coeffs[2], 2));\n\t\t\t\n\t\t\treturn dist;\n\t\t}\n\n\t\ttemplate <typename PointT>\n\t\tstd::unordered_set<int> Plane<PointT>::Ransac(typename pcl::PointCloud<PointT>::Ptr cloud, int maxIterations, float distanceToPlane)\n\t\t{\n\t\t\t// random number seed\n\t\t\tsrand(time(NULL));\n\t\t\t// get the start timestamp\n\t\t\tauto t_start = std::chrono::high_resolution_clock::now();\n\n\t\t\tstd::unordered_set<int> inliersResult;\n\t\t\t\n\t\t\t// number of random samples to select per iteration\n\t\t\tconst int n_random_samples = 3;\n\t\t\t\n\t\t\t// number of inliers for each iteration\n\t\t\tstd::vector<int> n_inliers(maxIterations, 0);\n\t\t\t// coefficients for each plane\n\t\t\tstd::vector<std::vector<float>> coeffs(maxIterations);\n\n\t\t\t// iterate 'maxIterations' number of times\n\t\t\tfor(int i = 0; i < maxIterations; ++i)\n\t\t\t{\n\t\t\t\t// x, y, and z points as a vector\n\t\t\t\tstd::vector<float> x, y, z;\n\t\t\t\t// select random samples\n\t\t\t\tfor(int j = 0; j < n_random_samples; ++j)\n\t\t\t\t{\n\t\t\t\t\tint idx = rand()%(cloud->size());\n\t\t\t\t\tx.push_back(cloud->at(idx).x);\n\t\t\t\t\ty.push_back(cloud->at(idx).y);\n\t\t\t\t\tz.push_back(cloud->at(idx).z);\n\t\t\t\t}\n\t\t\t\t// fit a plane\n\t\t\t\tcoeffs[i] = this->fitLS(x, y, z);\n\n\t\t\t\tfor(typename pcl::PointCloud<PointT>::iterator it = cloud->begin(); it != cloud->end(); ++it)\n\t\t\t\t{\n\t\t\t\t\t// TLOG_INFO << \"dist = \" << this->distToPoint(coeffs[i], *it) ;\n\t\t\t\t\tif(this->distToPoint(coeffs[i], *it) <= distanceToPlane)\n\t\t\t\t\t{\n\t\t\t\t\t\tn_inliers[i]++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// find the index for number of inliers\n\t\t\tauto inliers_it = std::max_element(n_inliers.begin(), n_inliers.end());\n\t\t\tint index_max_n_inlier = std::distance(n_inliers.begin(), inliers_it);\n\n\t\t\t// find inliers with the best fit\n\t\t\tint index = 0;\n\t\t\tfor(typename pcl::PointCloud<PointT>::iterator it = cloud->begin(); it != cloud->end(); ++it)\n\t\t\t{\n\t\t\t\tif(this->distToPoint(coeffs[index_max_n_inlier], *it) <= distanceToPlane)\n\t\t\t\t{\n\t\t\t\t\tinliersResult.insert(index);\n\t\t\t\t}\n\t\t\t\tindex++;\n\t\t\t}\n\n\t\t\t// get the end timestamp\n\t\t\tauto t_end = std::chrono::high_resolution_clock::now();\n\n\t\t\t// measure execution time\n\t\t\tauto t_duration = std::chrono::duration_cast<std::chrono::milliseconds>(t_end - t_start);\n\n\t\t\t// Return indicies of inliers from fitted line with most inliers\n\t\t\treturn inliersResult;\n\t\t}\n\n\t\tvoid KdTree::insertHelper(Node ** node, unsigned depth, std::vector<float> point, int id)\n\t\t{\n\t\t\tif(*node != NULL) {\n\t\t\t\t// x split when (depth % 3) = 0; y split when (depth % 3) = 1; z split when (depth % 3) = 2\n\t\t\t\t// index for accessing point.x is 0; index for accessing point.y is 1; index for accessing point.z is 2\n\t\t\t\tif(point[(depth % 3)] < ((*node)->point[(depth % 3)])) {\n\t\t\t\t\tnode = &((*node)->left);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tnode = &((*node)->right);\n\t\t\t\t}\n\n\t\t\t\t// call this function recursively until a NULL is hit\n\t\t\t\tinsertHelper(node, depth+1, point, id);\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// create a node and insert the point\n\t\t\t\t*node = new Node(point, id);\n\t\t\t}\n\t\t}\n\n\t\tvoid KdTree::insert(std::vector<float> point, int id)\n\t\t{\n\t\t\t// This function inserts a new point into the tree\n\t\t\t// the function creates a new node and places correctly with in the root \n\t\t\tinsertHelper(&this->root, 0, point, id);\t\t\n\t\t}\n\n\t\t// this function returns euclidian distance between two points\n\t\tfloat KdTree::dist(std::vector<float> point_a, std::vector<float> point_b)\n\t\t{\n\t\t\t// compute distance\n\t\t\tfloat dist = sqrt(pow((point_a[0] - point_b[0]), 2) \n\t\t\t\t\t\t\t+ pow((point_a[1] - point_b[1]), 2)\n\t\t\t\t\t\t\t+ pow((point_a[2] - point_b[2]), 2));\n\n\t\t\t// Return the euclidian distance between points\n\t\t\treturn dist;\n\t\t}\n\n\t\tvoid KdTree::searchHelper(Node * node, std::vector<float> target, float distTolerance, int depth, std::vector<int>& ids)\n\t\t{\n\t\t\tif(node != NULL) {\n\t\t\t\t// add this node id to the list if its distance from target is less than distTolerance\n\t\t\t\tif(dist(node->point, target) <= distTolerance) \n\t\t\t\t\tids.push_back(node->id);\t\n\n\t\t\t\t// x split when (depth % 3) = 0; y split when (depth % 3) = 1; z split when (depth % 3) = 2\n\t\t\t\t// index for accessing point.x is 0; index for accessing point.y is 1; index for accessing point.z is 2\n\t\t\t\tif((target[depth % 3] - distTolerance) < node->point[(depth % 3)])\n\t\t\t\t\tsearchHelper(node->left, target, distTolerance, depth+1, ids);\n\t\t\t\tif((target[depth % 3] + distTolerance) > node->point[(depth % 3)])\n\t\t\t\t\tsearchHelper(node->right, target, distTolerance, depth+1, ids);\n\t\t\t}\n\t\t}\n\t\t// return a list of point ids in the tree that are within distance of target\n\t\tstd::vector<int> KdTree::search(std::vector<float> target, float distTolerance)\n\t\t{\n\t\t\tstd::vector<int> ids;\n\t\t\tsearchHelper(this->root, target, distTolerance, 0, ids);\n\t\t\treturn ids;\n\t\t}\n\n\t\tvoid EuclideanCluster::proximityPoints( int pointIndex,\n\t\t\t\t\t\t\t\tstd::vector<bool>& checked,\n\t\t\t\t\t\t\t\tfloat distTolerance, \n\t\t\t\t\t\t\t\tstd::vector<int>& cluster) \n\t\t{\n\t\t\tstd::vector<int> nearby = this->tree->search(this->points[pointIndex], distTolerance);\n\t\t\tfor(auto it = nearby.begin(); it != nearby.end(); ++it) {\n\t\t\t\tif(! checked[*it]) {\n\t\t\t\t\tchecked[*it] = true;\n\t\t\t\t\tcluster.push_back(*it);\n\t\t\t\t\t// call this function recursively to find all the points within proximity (i.e. points within proximity of proximity)\n\t\t\t\t\tproximityPoints(*it, checked, distTolerance, cluster);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tstd::vector<std::vector<int>> EuclideanCluster::clustering(float distTolerance)\n\t\t{\n\t\t\tstd::vector<std::vector<int>> clusters;\n\n\t\t\t// vector to keep track of checked points\n\t\t\tstd::vector<bool> checked(points.size(), false);\n\t\t\tfor(int i = 0; i < this->points.size(); ++i) {\n\t\t\t\t// create a new cluster if this point was not processed already\n\t\t\t\tif(! checked[i]) {\n\t\t\t\t\tstd::vector<int> cluster;\n\t\t\t\t\tchecked[i] = true;\n\t\t\t\t\tcluster.push_back(i);\n\t\t\t\t\t// find points within the proximity\n\t\t\t\t\tproximityPoints(i, checked, distTolerance, cluster);\n\t\t\t\t\t// add this cluster to the vector of clusters\n\t\t\t\t\tclusters.push_back(cluster);\n\t\t\t\t}\n\t\t\t}\n\t\t\n\t\t\treturn clusters;\n\t\t}\n\n\t\t/** \n         * @brief returns world to camera rotation matrix \n         * \n         *   Camera Coordinate System:\n         *       X -> To the right\n         *       Y -> Down\n         *       Z -> Forward - Direction where the camera is pointing\n         *\n         *   World Coordinate System:\n         *       X -> Forward - Direction where the camera is pointing\n         *       Y -> To the left\n         *       Z -> Up\n         * @return rotation matrix\n         */\n        cv::Mat world2CamRotation() {\n            // camera coordinate to world coordinate rotation matrix\n            cv::Mat R = cv::Mat::zeros(3, 3, CV_32F);\n            // Camera rotation\n            float Rx = degreesToRadians(-90);\n            float Ry = degreesToRadians(0);\n            float Rz = degreesToRadians(-90);\n            \n            // Rz\n            cv::Mat R_z = cv::Mat::eye(3, 3, CV_32F);\n            R_z.at<float>(0, 0) = cos(Rz);\n            R_z.at<float>(0, 1) = -sin(Rz);\n            R_z.at<float>(1, 0) = sin(Rz);\n            R_z.at<float>(1, 1) = cos(Rz);\n            // Ry\n            cv::Mat R_y = cv::Mat::eye(3, 3, CV_32F);\n            R_y.at<float>(0, 0) = cos(Ry);\n            R_y.at<float>(0, 2) = sin(Ry);\n            R_y.at<float>(2, 0) = -sin(Ry);\n            R_y.at<float>(2, 2) = cos(Ry);\n            // Rx\n            cv::Mat R_x = cv::Mat::eye(3, 3, CV_32F);\n            R_y.at<float>(1, 1) = cos(Rx);\n            R_y.at<float>(1, 2) = -sin(Rx);\n            R_y.at<float>(2, 1) = sin(Rx);\n            R_y.at<float>(2, 2) = cos(Rx);\n\n                            \n            // Camera Rotation Correction Matrix\n            R = R_z * R_y * R_x;\n            \n\t\t\t// return rotation matrix\n            return R;\n        }\n\n        /** \n         * @brief affine transform on a point \n         * \n         * Apply affine transforms on point given in world coordinate\n         *\n         *\n         *   Camera Coordinate System:\n         *       X -> To the right\n         *       Y -> Down\n         *       Z -> Forward - Direction where the camera is pointing\n         *\n         *   World Coordinate System:\n         *       X -> Forward - Direction where the camera is pointing\n         *       Y -> To the left\n         *       Z -> Up\n         * \n         * @param[in] point point in world coordinate\n         * \n         * @return point in camera coordinate\n         */\n        template <typename PointT>\n        void world2CamCoordinate(PointT &point) {\n            // Camera Rotation Correction Matrix\n            cv::Mat R = world2CamRotation();\n            \n            cv::Mat xyz = cv::Mat(3, 1, CV_32F);\n            xyz.at<float>(0, 0) = point.x;\n            xyz.at<float>(1, 0) = point.y;\n            xyz.at<float>(2, 0) = point.z;\n\n            cv::Mat xyz_w = cv::Mat(3, 1, CV_32F);\n\n            xyz_w = R * xyz;\n            point.x = xyz_w.at<float>(0, 0);\n            point.y = xyz_w.at<float>(1, 0);\n            point.z = xyz_w.at<float>(2, 0);\n        }\n\t}\n}\n\n// explicit instantiation to avoid linker error\ntemplate class tapl::pte::Line<tapl::Point3d>;\ntemplate class tapl::pte::Line<pcl::PointXYZ>;\ntemplate class tapl::pte::Line<pcl::PointXYZI>;\ntemplate class tapl::pte::Line<pcl::PointXYZRGB>;\ntemplate class tapl::pte::Plane<tapl::Point3d>;\ntemplate class tapl::pte::Plane<pcl::PointXYZ>;\ntemplate class tapl::pte::Plane<pcl::PointXYZI>;\ntemplate class tapl::pte::Plane<pcl::PointXYZRGB>;", "meta": {"hexsha": "bd93d26bc58de49e118b5143263668978b4028ab", "size": 16552, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tapl/pte/ptEngine.cpp", "max_stars_repo_name": "towardsautonomy/TAPL", "max_stars_repo_head_hexsha": "4d065b2250483bf2ea118bafa312ca893a25ca87", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-05T12:53:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-05T12:53:17.000Z", "max_issues_repo_path": "tapl/pte/ptEngine.cpp", "max_issues_repo_name": "towardsautonomy/TAPL", "max_issues_repo_head_hexsha": "4d065b2250483bf2ea118bafa312ca893a25ca87", "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": "tapl/pte/ptEngine.cpp", "max_forks_repo_name": "towardsautonomy/TAPL", "max_forks_repo_head_hexsha": "4d065b2250483bf2ea118bafa312ca893a25ca87", "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.8805970149, "max_line_length": 134, "alphanum_fraction": 0.5920734654, "num_tokens": 4980, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.931462503162843, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.7339283638136225}}
{"text": "// VMD\u30e2\u30fc\u30b7\u30e7\u30f3\u306e\u88dc\u9593\u3092\u884c\u3046\n#include \"interpolate.h\"\n\n#include <Eigen/Core>\n#include <unsupported/Eigen/NonLinearOptimization>\n#include <unsupported/Eigen/NumericalDiff>\n#include \"VMD.h\"\n\nusing namespace Eigen;\n\n// x\u5ea7\u6a19\u5024\u304cx_arg\u3068\u306a\u308b\u70b9\u3092\u30d9\u30b8\u30a7\u66f2\u7dda\u4e0a\u304b\u3089\u63a2\u3057\u3001\u305d\u306e\u70b9\u306ey\u5ea7\u6a19\u5024\u3092\u8fd4\u3059\n// \u30d9\u30b8\u30a7\u66f2\u7dda\u306e\u5236\u5fa1\u70b9\u306f(0,0), p1, p2, (1,1)\u3068\u3059\u308b\n// 0 < x_arg < 1 \u3068\u3059\u308b\nfloat bezier_y(Vector2f p1, Vector2f p2, float x_arg)\n{\n  // \u4e8c\u5206\u6cd5\u3067t\u3092\u63a2\u3059\n  float epsilon = 1.0e-5;\n  float lower = 0.0;\n  float upper = 1.0;\n  float t;\n  float x;\n  float x1 = p1.x();\n  float x2 = p2.x();\n  const int max_iteration = 20;\n  for (int i = 0; i < max_iteration; i++) {\n    t = (lower + upper) / 2;\n    x = bezier3(x1, x2, t);\n    if (abs(x - x_arg) < epsilon) {\n      // x == x_arg \u3068\u306a\u308b t \u304c\u898b\u3064\u304b\u3063\u305f\n      break;\n    }\n    if (x < x_arg) {\n      // x(t)\u306f\u5358\u8abf\u5897\u52a0\u3059\u308b\u306e\u3067\u3001\n      // \u771f\u306ex\u304c\u3082\u3063\u3068\u5927\u304d\u3044\u3068\u3044\u3046\u3053\u3068\u306f\u3001\u771f\u306et\u306f\u3082\u3063\u3068\u5927\u304d\u3044\u306e\u3067\u3001\n      // \u63a2\u7d22\u7bc4\u56f2\u3092\u4e0a\u534a\u5206\u306b\u7d5e\u308b\n      lower = t;\n    } else {\n      upper = t;\n    }\n  }\n  return bezier3(p1.y(), p2.y(), t);\n}\n\nfloat bezier_y_vmd(uint8_t ipx1, uint8_t ipy1, uint8_t ipx2, uint8_t ipy2, float x)\n{\n  return bezier_y(Vector2f(float(ipx1)/127, float(ipy1)/127), Vector2f(float(ipx2)/127, float(ipy2)/127), x);\n}\n\nVMD_Frame make_intermediate_frame(const VMD_Frame& head_frame, const VMD_Frame& tail_frame, float ratio, bool bezier)\n{\n  VMD_Frame f;\n  memcpy(f.bonename, head_frame.bonename, f.bonename_len);\n  if (bezier) {\n    // \u30d9\u30b8\u30a7\u66f2\u7dda\u88dc\u9593\n    const uint8_t* ip = tail_frame.interpolation;\n    float y;\n\n    // X\u5ea7\u6a19\u5024\u306e\u88dc\u9593\n    y = bezier_y_vmd(ip[0], ip[4], ip[8], ip[12], ratio);\n    f.position.x() = head_frame.position.x() * (1-y) + tail_frame.position.x() * y;\n\n    // Y\u5ea7\u6a19\u5024\u306e\u88dc\u9593\n    y = bezier_y_vmd(ip[16], ip[20], ip[24], ip[28], ratio);\n    f.position.y() = head_frame.position.y() * (1-y) + tail_frame.position.y() * y;\n\n    // Z\u5ea7\u6a19\u5024\u306e\u88dc\u9593\n    y = bezier_y_vmd(ip[32], ip[36], ip[40], ip[44], ratio);\n    f.position.z() = head_frame.position.z() * (1-y) + tail_frame.position.z() * y;\n\n    // \u56de\u8ee2\u306e\u88dc\u9593\n    y = bezier_y_vmd(ip[48], ip[52], ip[56], ip[60], ratio);\n    f.rotation = head_frame.rotation.slerp(y, tail_frame.rotation);\n  } else {\n    // \u7dda\u5f62\u88dc\u9593\n    f.position = head_frame.position + (tail_frame.position - head_frame.position) * ratio;\n    f.rotation = head_frame.rotation.slerp(ratio, tail_frame.rotation);\n  }\n  return f;\n}\n\n// head_frame\u3068tail_frame\u3092\u5143\u306b\u3001\u88dc\u9593\u3067frame_num\u756a\u76ee\u306e\u30dc\u30fc\u30f3\u30d5\u30ec\u30fc\u30e0\u3092\u4f5c\u308b\nVMD_Frame interpolate_frame(const VMD_Frame& head_frame, const VMD_Frame& tail_frame, int frame_num, bool bezier)\n{\n  int total = tail_frame.number - head_frame.number;\n  float ratio = float(frame_num - head_frame.number) / total;\n  VMD_Frame f = make_intermediate_frame(head_frame, tail_frame, ratio, bezier);\n  f.number = frame_num;\n  return f;\n}\n\nVMD_Morph make_intermediate_morph(const VMD_Morph& head_frame, const VMD_Morph& tail_frame, float ratio)\n{\n  VMD_Morph m = head_frame;\n  m.weight = head_frame.weight + (tail_frame.weight - head_frame.weight) * ratio;\n  return m;\n}\n\n// head_frame\u3068tail_frame\u3092\u5143\u306b\u3001\u88dc\u9593\u3067frame_num\u756a\u76ee\u306e\u8868\u60c5\u30d5\u30ec\u30fc\u30e0\u3092\u4f5c\u308b\nVMD_Morph interpolate_morph(const VMD_Morph& head_frame, const VMD_Morph& tail_frame, int frame_num)\n{\n  int total = tail_frame.frame - head_frame.frame;\n  float ratio = float(frame_num - head_frame.frame) / total;\n  VMD_Morph m = make_intermediate_morph(head_frame, tail_frame, ratio);\n  m.frame = frame_num;\n  return m;\n}\n\nvector<VMD_Frame> fill_bone_frame(const vector<VMD_Frame>& fv, bool bezier)\n{\n  vector<VMD_Frame> fv_new;\n  VMD_Frame f_old = fv[0];\n  f_old.number = 0;\n  fv_new.push_back(f_old);\n  for (VMD_Frame f : fv) {\n    // \u3082\u3057\u30d5\u30ec\u30fc\u30e0\u756a\u53f7\u304c\u91cd\u8907\u3057\u3066\u3044\u305f\u3089\u3001\u91cd\u8907\u3057\u305f\u30d5\u30ec\u30fc\u30e0\u306f\u6d88\u3059\n    if (f.number == f_old.number) {\n      continue;\n    }\n    // \u30d5\u30ec\u30fc\u30e0\u756a\u53f7\u304c\u9023\u7d9a\u3057\u3066\u3044\u306a\u3044\u5834\u5408\u3001\u9014\u4e2d\u306e\u30d5\u30ec\u30fc\u30e0\u3092\u88dc\u9593\u3059\u308b\n    for (uint32_t i = f_old.number + 1; i < f.number; i++) {\n      VMD_Frame interpolated = interpolate_frame(f_old, f, i, bezier);\n      fv_new.push_back(interpolated);\n    }\n    fv_new.push_back(f);\n    f_old = f;\n  }\n  return fv_new;\n}\n\nvector<VMD_Morph> fill_morph_frame(vector<VMD_Morph>& mv)\n{\n  vector<VMD_Morph> mv_new;\n  VMD_Morph m_old = mv[0];\n  m_old.frame = 0;\n  mv_new.push_back(m_old);\n  for (VMD_Morph m : mv) {\n    // \u3082\u3057\u30d5\u30ec\u30fc\u30e0\u756a\u53f7\u304c\u91cd\u8907\u3057\u3066\u3044\u305f\u3089\u3001\u91cd\u8907\u3057\u305f\u30d5\u30ec\u30fc\u30e0\u306f\u6d88\u3059\n    if (m.frame == m_old.frame) {\n      continue;\n    }\n    // \u30d5\u30ec\u30fc\u30e0\u756a\u53f7\u304c\u9023\u7d9a\u3057\u3066\u3044\u306a\u3044\u5834\u5408\u3001\u9014\u4e2d\u306e\u30d5\u30ec\u30fc\u30e0\u3092\u88dc\u9593\u3059\u308b\n    for (uint32_t i = m_old.frame + 1; i < m.frame; i++) {\n      VMD_Morph interpolated = interpolate_morph(m_old, m, i);\n      mv_new.push_back(interpolated);\n    }\n    mv_new.push_back(m);\n    m_old = m;\n  }\n  return mv_new;\n}\n\n// Eigen::LevenbergMarquardt \u3067\u975e\u7dda\u5f62\u6700\u5c0f\u4e8c\u4e57\u6cd5\u30d5\u30a3\u30c3\u30c6\u30a3\u30f3\u30b0\u306b\u4f7f\u3046\u69cb\u9020\u4f53\ntemplate<typename _Scalar, int NX=Eigen::Dynamic, int NY=Eigen::Dynamic>\nstruct Functor\n{\n    typedef _Scalar Scalar;\n    enum {\n        InputsAtCompileTime = NX,\n        ValuesAtCompileTime = NY\n    };\n    typedef Matrix<Scalar, InputsAtCompileTime, 1> InputType;\n    typedef Matrix<Scalar, ValuesAtCompileTime, 1> ValueType;\n    typedef Matrix<Scalar, ValuesAtCompileTime, InputsAtCompileTime> JacobianType;\n\n    const int m_inputs, m_values;\n\n    Functor() : m_inputs(InputsAtCompileTime), m_values(ValuesAtCompileTime) {}\n    Functor(int inputs, int values) : m_inputs(inputs), m_values(values) {}\n\n    int inputs() const { return m_inputs; }\n    int values() const { return m_values; }\n};\n\nstruct position_functor : Functor<float>\n{\n  position_functor(int nparam, int nvalue, const vector<float>& x, const vector<float>& y)\n  : Functor<float>(nparam, nvalue), x(x), y(y) {}\n\n  const vector<float>& x;\n  const vector<float>& y;\n\n  // \u5404\u30c7\u30fc\u30bf\u70b9(x[i], y[i])\u306b\u304a\u3051\u308b\u8aa4\u5dee\u3092f[i]\u306b\u683c\u7d0d\u3059\u308b\n  // \u30d1\u30e9\u30e1\u30fc\u30bfp\u306f\u30d9\u30b8\u30a7\u66f2\u7dda\u306e\u5236\u5fa1\u70b9\u306e\u5ea7\u6a19\u5024\n  // \u30d9\u30b8\u30a7\u66f2\u7dda\u306e\u5236\u5fa1\u70b9 = (0, 0), (p[0], p[1]), (p[2], p[3]), (1, 1) \u3068\u306a\u308b\n  int operator() (const VectorXf& p, VectorXf& f) const\n  {\n    Vector2f cp1(p[0], p[1]);\n    Vector2f cp2(p[2], p[3]);\n    for (int i = 0; i < m_values; i++) {\n      float by = bezier_y(cp1, cp2, x[i]);\n      f[i] = y[0]*(1.0-by) + y[m_values - 1]*by - y[i];\n    }\n    return 0;\n  }\n};\n\nstruct rotation_functor : Functor<float>\n{\n  rotation_functor(int nparam, int nvalue, const vector<float>& x, const vector<Eigen::Quaternionf>& y)\n  : Functor<float>(nparam, nvalue), x(x), y(y) {}\n\n  const vector<float>& x;\n  const vector<Eigen::Quaternionf>& y;\n\n  // \u5404\u30c7\u30fc\u30bf\u70b9\u306b\u304a\u3051\u308b\u8aa4\u5dee\u3092f[i]\u306b\u683c\u7d0d\u3059\u308b\n  // \u30d1\u30e9\u30e1\u30fc\u30bfp\u306f\u30d9\u30b8\u30a7\u66f2\u7dda\u306e\u5236\u5fa1\u70b9\u306e\u5ea7\u6a19\u5024\n  // \u30d9\u30b8\u30a7\u66f2\u7dda\u306e\u5236\u5fa1\u70b9 = (0, 0), (p[0], p[1]), (p[2], p[3]), (1, 1) \u3068\u306a\u308b\n  int operator() (const VectorXf& p, VectorXf& f) const\n  {\n    Vector2f cp1(p[0], p[1]);\n    Vector2f cp2(p[2], p[3]);\n    for (int i = 0; i < m_values; i++) {\n      float by = bezier_y(cp1, cp2, x[i]);\n      Eigen::Quaternionf rot = y[0].slerp(by, y[m_values - 1]);\n      f[i] = rot.angularDistance(y[i]);\n    }\n    return 0;\n  }\n};\n\n// head\u756a\u3081\u304b\u3089tail\u756a\u76ee\u307e\u3067\u306e\u8aa4\u5dee\u304c\u6700\u5c0f\u306b\u306a\u308b\u3088\u3046\u306a\u88dc\u9593\u66f2\u7dda\u30d1\u30e9\u30e1\u30fc\u30bf\u3092\u63a2\u3059\nVectorXf find_bezier_parameter_pos(const vector<VMD_Frame>& v, int head, int tail, int axis)\n{\n  vector<float> x;\n  vector<float> y;\n  for (int i = head; i <= tail; i++) {\n    int current = v[i].number;\n    x.push_back(float(current - head)/(tail - head));\n    y.push_back(v[i].position(axis));\n  }\n  // \u30d1\u30e9\u30e1\u30fc\u30bf\u306e\u521d\u671f\u5024\u3092\u4e0e\u3048\u308b\n  // \u30d9\u30b8\u30a7\u66f2\u7dda\u306e\u5236\u5fa1\u70b9 = (0, 0), (p[0], p[1]), (p[2], p[3]), (1, 1) \u3068\u306a\u308b\n  VectorXf p(4);\n  p << 20.0/127, 20.0/127, 107.0/127, 107.0/127;\n  position_functor functor(4, (tail - head + 1), x, y);\n  NumericalDiff<position_functor> nd(functor);\n  LevenbergMarquardt<NumericalDiff<position_functor>, float> lm(nd);\n  lm.parameters.maxfev = 10;\n  lm.minimize(p);\n  return p;\n}\n\n// head\u756a\u3081\u304b\u3089tail\u756a\u76ee\u307e\u3067\u306e\u8aa4\u5dee\u304c\u6700\u5c0f\u306b\u306a\u308b\u3088\u3046\u306a\u88dc\u9593\u66f2\u7dda\u30d1\u30e9\u30e1\u30fc\u30bf\u3092\u63a2\u3059\nVectorXf find_bezier_parameter_rot(const vector<VMD_Frame>& v, int head, int tail)\n{\n  vector<float> x;\n  vector<Eigen::Quaternionf> y;\n  for (int i = head; i <= tail; i++) {\n    int current = v[i].number;\n    x.push_back(float(current - head)/(tail - head));\n    y.push_back(v[i].rotation);\n  }\n  // \u30d1\u30e9\u30e1\u30fc\u30bf\u306e\u521d\u671f\u5024\u3092\u4e0e\u3048\u308b\n  // \u30d9\u30b8\u30a7\u66f2\u7dda\u306e\u5236\u5fa1\u70b9 = (0, 0), (p[0], p[1]), (p[2], p[3]), (1, 1) \u3068\u306a\u308b\n  VectorXf p(4);\n  p << 20.0/127, 20.0/127, 107.0/127, 107.0/127;\n  // \u30d1\u30e9\u30e1\u30fc\u30bfp\u306e\u6700\u9069\u5316\u3092\u884c\u3046\n  rotation_functor functor(4, (tail - head + 1), x, y);\n  NumericalDiff<rotation_functor> nd(functor);\n  LevenbergMarquardt<NumericalDiff<rotation_functor>, float> lm(nd);\n  lm.parameters.maxfev = 10;\n  lm.minimize(p);\n  return p;\n}\n\nvoid convert_interpolation(uint8_t* ip, const VectorXf p)\n{\n  for (int i = 0; i < 4; i++) {\n    int k = int(p[i] * 127);\n    if (k > 127) {\n      ip[i] = 127;\n    } else if (k < 0) {\n      ip[i] = 0;\n    } else {\n      ip[i] = uint8_t(k);\n    }\n  }\n}\n\n// head\u756a\u3081\u304b\u3089tail\u756a\u76ee\u307e\u3067\u306e\u8aa4\u5dee\u304c\u6700\u5c0f\u306b\u306a\u308b\u3088\u3046tail_frame\u306e\u88dc\u9593\u66f2\u7dda\u30d1\u30e9\u30e1\u30fc\u30bf\u3092\u8abf\u6574\u3059\u308b\nvoid optimize_bezier_parameter(VMD_Frame& tail_frame, const vector<VMD_Frame>& v,\n                               int head, int tail)\n{\n  uint8_t ip[4];\n  VectorXf p;\n\n  // X\u306e\u88dc\u9593\u30d1\u30e9\u30e1\u30fc\u30bf\u306e\u6700\u9069\u5316\n  p = find_bezier_parameter_pos(v, head, tail, 0);\n  convert_interpolation(ip, p);\n  tail_frame.set_interpolation_x(ip[0], ip[1], ip[2], ip[3]);\n\n  // Y\u306e\u88dc\u9593\u30d1\u30e9\u30e1\u30fc\u30bf\u306e\u6700\u9069\u5316\n  p = find_bezier_parameter_pos(v, head, tail, 1);\n  convert_interpolation(ip, p);\n  tail_frame.set_interpolation_y(ip[0], ip[1], ip[2], ip[3]);\n\n  // Z\u306e\u88dc\u9593\u30d1\u30e9\u30e1\u30fc\u30bf\u306e\u6700\u9069\u5316\n  p = find_bezier_parameter_pos(v, head, tail, 2);\n  convert_interpolation(ip, p);\n  tail_frame.set_interpolation_z(ip[0], ip[1], ip[2], ip[3]);\n\n  // \u56de\u8ee2\u306e\u88dc\u9593\u30d1\u30e9\u30e1\u30fc\u30bf\u306e\u6700\u9069\u5316\n  p = find_bezier_parameter_rot(v, head, tail);\n  convert_interpolation(ip, p);\n  tail_frame.set_interpolation_r(ip[0], ip[1], ip[2], ip[3]);\n}\n", "meta": {"hexsha": "312b51bced5a2a4ff4c73b9e4ac5590f091fc927", "size": 9103, "ext": "cc", "lang": "C++", "max_stars_repo_path": "interpolate.cc", "max_stars_repo_name": "ikeno-ikeo/readfacevmd", "max_stars_repo_head_hexsha": "854354812cbe27531afe8681c1b5b1df7207a42b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 49.0, "max_stars_repo_stars_event_min_datetime": "2018-05-19T07:28:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-21T07:16:06.000Z", "max_issues_repo_path": "interpolate.cc", "max_issues_repo_name": "ikeno-ikeo/readfacevmd", "max_issues_repo_head_hexsha": "854354812cbe27531afe8681c1b5b1df7207a42b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2018-05-29T10:10:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-10T00:42:49.000Z", "max_forks_repo_path": "interpolate.cc", "max_forks_repo_name": "ikeno-ikeo/readfacevmd", "max_forks_repo_head_hexsha": "854354812cbe27531afe8681c1b5b1df7207a42b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-03-03T20:58:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-15T09:06:47.000Z", "avg_line_length": 29.651465798, "max_line_length": 117, "alphanum_fraction": 0.6529715478, "num_tokens": 3595, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625012602593, "lm_q2_score": 0.7879311956428946, "lm_q1q2_score": 0.7339283623145173}}
{"text": "/*\n * Copyright Nick Thompson, John Maddock 2020\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 <numeric>\n#include <utility>\n#include <iomanip>\n#include <iostream>\n#include <random>\n#include <boost/core/demangle.hpp>\n#include <boost/hana/for_each.hpp>\n#include <boost/hana/ext/std/integer_sequence.hpp>\n#include <boost/math/tools/condition_numbers.hpp>\n#include <boost/math/differentiation/finite_difference.hpp>\n#include <boost/math/special_functions/daubechies_scaling.hpp>\n#include <boost/math/filters/daubechies.hpp>\n#include <boost/math/special_functions/detail/daubechies_scaling_integer_grid.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/quadrature/trapezoidal.hpp>\n#include <boost/math/special_functions/next.hpp>\n\n#ifdef BOOST_HAS_FLOAT128\n#include <boost/multiprecision/float128.hpp>\nusing boost::multiprecision::float128;\n#endif\n\n\nusing boost::math::constants::pi;\nusing boost::math::constants::root_two;\n\n// Mallat, Theorem 7.4, characterization number 3:\n// A conjugate mirror filter has p vanishing moments iff h^{(n)}(pi) = 0 for 0 <= n < p.\ntemplate<class Real, unsigned p>\nvoid test_daubechies_filters()\n{\n    std::cout << \"Testing Daubechies filters with \" << p << \" vanishing moments on type \" << boost::core::demangle(typeid(Real).name()) << \"\\n\";\n    Real tol = 3*std::numeric_limits<Real>::epsilon();\n    using boost::math::filters::daubechies_scaling_filter;\n    using boost::math::filters::daubechies_wavelet_filter;\n\n    auto h = daubechies_scaling_filter<Real, p>();\n    auto g = daubechies_wavelet_filter<Real, p>();\n\n    auto inner = std::inner_product(h.begin(), h.end(), g.begin(), Real(0));\n    CHECK_MOLLIFIED_CLOSE(0, inner, tol);\n\n    // This is implied by Fourier transform of the two-scale dilatation equation;\n    // If this doesn't hold, the infinite product for m_0 diverges.\n    Real H0 = 0;\n    for (size_t j = 0; j < h.size(); ++j)\n    {\n        H0 += h[j];\n    }\n    CHECK_MOLLIFIED_CLOSE(root_two<Real>(), H0, tol);\n\n    // This is implied if we choose the scaling function to be an orthonormal basis of V0.\n    Real scaling = 0;\n    for (size_t j = 0; j < h.size(); ++j) {\n      scaling += h[j]*h[j];\n    }\n    CHECK_MOLLIFIED_CLOSE(1, scaling, tol);\n\n    using std::pow;\n    // Daubechies wavelet of order p has p vanishing moments.\n    // Unfortunately, the condition number of the sum is infinite.\n    // Hence we must scale the tolerance by the summation condition number to ensure that we don't get spurious test failures.\n    for (size_t k = 1; k < p && k < 9; ++k)\n    {\n        Real hk = 0;\n        Real abs_hk = 0;\n        for (size_t n = 0; n < h.size(); ++n)\n        {\n            Real t = static_cast<Real>(pow(n, k)*h[n]);\n            if (n & 1)\n            {\n                hk -= t;\n            }\n            else\n            {\n                hk += t;\n            }\n            abs_hk += abs(t);\n        }\n        // Multiply the tolerance by the condition number:\n        Real cond = abs(hk) > 0 ? abs_hk/abs(hk) : 1/std::numeric_limits<Real>::epsilon();\n        if (!CHECK_MOLLIFIED_CLOSE(0, hk, 2*cond*tol))\n        {\n            std::cerr << \"  The \" << k << \"th moment of the p = \" << p << \" filter did not vanish\\n\";\n            std::cerr << \"  Condition number = \" << abs_hk/abs(hk) << \"\\n\";\n        }\n    }\n\n    // For the scaling function to be orthonormal to its integer translates,\n    // sum h_k h_{k-2l} = \\delta_{0,l}.\n    // See Theoretical Numerical Analysis, Atkinson, Exercise 4.5.2.\n    // This is the last condition we could test to ensure that the filters are correct,\n    // but I'm not gonna bother because it's painful!\n}\n\n// Test that the filters agree with Daubechies, Ten Lenctures on Wavelets, Table 6.1:\nvoid test_agreement_with_ten_lectures()\n{\n    std::cout << \"Testing agreement with Ten Lectures\\n\";\n    std::array<double, 4> h2 = {0.4829629131445341, 0.8365163037378077, 0.2241438680420134, -0.1294095225512603};\n    auto h2_ = boost::math::filters::daubechies_scaling_filter<double, 2>();\n    for (size_t i = 0; i < h2.size(); ++i)\n    {\n        CHECK_ULP_CLOSE(h2[i], h2_[i], 3);\n    }\n\n    std::array<double, 6> h3 = {0.3326705529500825, 0.8068915093110924, 0.4598775021184914, -0.1350110200102546, -0.0854412738820267, 0.0352262918857095};\n    auto h3_ = boost::math::filters::daubechies_scaling_filter<double, 3>();\n    for (size_t i = 0; i < h3.size(); ++i)\n    {\n        CHECK_ULP_CLOSE(h3[i], h3_[i], 5);\n    }\n\n    std::array<double, 8> h4 = {0.2303778133088964, 0.7148465705529154, 0.6308807679298587, -0.0279837694168599, -0.1870348117190931, 0.0308413818355607, 0.0328830116668852 , -0.010597401785069};\n    auto h4_ = boost::math::filters::daubechies_scaling_filter<double, 4>();\n    for (size_t i = 0; i < h4.size(); ++i)\n    {\n        if(!CHECK_ULP_CLOSE(h4[i], h4_[i], 18))\n        {\n            std::cerr << \"  Index \" << i << \" incorrect.\\n\";\n        }\n    }\n\n}\n\ntemplate<class Real1, class Real2, size_t p>\nvoid test_filter_ulp_distance()\n{\n    std::cout << \"Testing filters ULP distance between types \"\n              << boost::core::demangle(typeid(Real1).name()) << \"and\"\n              << boost::core::demangle(typeid(Real2).name()) << \"\\n\";\n    using boost::math::filters::daubechies_scaling_filter;\n    auto h1 = daubechies_scaling_filter<Real1, p>();\n    auto h2 = daubechies_scaling_filter<Real2, p>();\n\n    for (size_t i = 0; i < h1.size(); ++i)\n    {\n        if(!CHECK_ULP_CLOSE(h1[i], h2[i], 0))\n        {\n            std::cerr << \"  Index \" << i << \" at order \" << p << \" failed tolerance check\\n\";\n        }\n    }\n}\n\n\ntemplate<class Real, unsigned p, unsigned order>\nvoid test_integer_grid()\n{\n    std::cout << \"Testing integer grid with \" << p << \" vanishing moments and \" << order << \" derivative on type \" << boost::core::demangle(typeid(Real).name()) << \"\\n\";\n    using boost::math::detail::daubechies_scaling_integer_grid;\n    using boost::math::tools::summation_condition_number;\n    Real unit_roundoff = std::numeric_limits<Real>::epsilon()/2;\n    auto grid = daubechies_scaling_integer_grid<Real, p, order>();\n\n    if constexpr (order == 0)\n    {\n        auto cond = summation_condition_number<Real>(0);\n        for (auto & x : grid)\n        {\n            cond += x;\n        }\n        CHECK_MOLLIFIED_CLOSE(1, cond.sum(), 6*cond.l1_norm()*unit_roundoff);\n    }\n\n    if constexpr (order == 1)\n    {\n        auto cond = summation_condition_number<Real>(0);\n        for (size_t i = 0; i < grid.size(); ++i) {\n            cond += i*grid[i];\n        }\n        CHECK_MOLLIFIED_CLOSE(Real(-1), cond.sum(), 2*cond.l1_norm()*unit_roundoff);\n\n        // Differentiate \\sum_{k} \\phi(x-k) = 1 to get this:\n        cond = summation_condition_number<Real>(0);\n        for (size_t i = 0; i < grid.size(); ++i) {\n            cond += grid[i];\n        }\n        CHECK_MOLLIFIED_CLOSE(Real(0), cond.sum(), 2*cond.l1_norm()*unit_roundoff);\n    }\n\n    if constexpr (order == 2)\n    {\n        auto cond = summation_condition_number<Real>(0);\n        for (size_t i = 0; i < grid.size(); ++i)\n        {\n            cond += i*i*grid[i];\n        }\n        CHECK_MOLLIFIED_CLOSE(Real(2), cond.sum(), 2*cond.l1_norm()*unit_roundoff);\n\n        // Differentiate \\sum_{k} \\phi(x-k) = 1 to get this:\n        cond = summation_condition_number<Real>(0);\n        for (size_t i = 0; i < grid.size(); ++i)\n        {\n            cond += grid[i];\n        }\n        CHECK_MOLLIFIED_CLOSE(Real(0), cond.sum(), 2*cond.l1_norm()*unit_roundoff);\n    }\n\n    if constexpr (order == 3)\n    {\n        auto cond = summation_condition_number<Real>(0);\n        for (size_t i = 0; i < grid.size(); ++i)\n        {\n            cond += i*i*i*grid[i];\n        }\n        CHECK_MOLLIFIED_CLOSE(Real(-6), cond.sum(), 2*cond.l1_norm()*unit_roundoff);\n\n        // Differentiate \\sum_{k} \\phi(x-k) = 1 to get this:\n        cond = summation_condition_number<Real>(0);\n        for (size_t i = 0; i < grid.size(); ++i)\n        {\n            cond += grid[i];\n        }\n        CHECK_MOLLIFIED_CLOSE(Real(0), cond.sum(), 2*cond.l1_norm()*unit_roundoff);\n    }\n\n    if constexpr (order == 4)\n    {\n        auto cond = summation_condition_number<Real>(0);\n        for (size_t i = 0; i < grid.size(); ++i)\n        {\n            cond += i*i*i*i*grid[i];\n        }\n        CHECK_MOLLIFIED_CLOSE(24, cond.sum(), 2*cond.l1_norm()*unit_roundoff);\n\n        // Differentiate \\sum_{k} \\phi(x-k) = 1 to get this:\n        cond = summation_condition_number<Real>(0);\n        for (size_t i = 0; i < grid.size(); ++i)\n        {\n            cond += grid[i];\n        }\n        CHECK_MOLLIFIED_CLOSE(Real(0), cond.sum(), 2*cond.l1_norm()*unit_roundoff);\n    }\n}\n\ntemplate<class Real>\nvoid test_dyadic_grid()\n{\n    std::cout << \"Testing dyadic grid on type \" << boost::core::demangle(typeid(Real).name()) << \"\\n\";\n    auto f = [&](auto i)\n    {\n        auto phijk = boost::math::daubechies_scaling_dyadic_grid<Real, i+2, 0>(0);\n        auto phik = boost::math::detail::daubechies_scaling_integer_grid<Real, i+2, 0>();\n        assert(phik.size() == phijk.size());\n\n        for (size_t k = 0; k < phik.size(); ++k)\n        {\n            CHECK_ULP_CLOSE(phik[k], phijk[k], 0);\n        }\n\n        for (uint64_t j = 1; j < 10; ++j)\n        {\n            phijk = boost::math::daubechies_scaling_dyadic_grid<Real, i+2, 0>(j);\n            phik = boost::math::detail::daubechies_scaling_integer_grid<Real, i+2, 0>();\n            for (uint64_t l = 0; l < static_cast<uint64_t>(phik.size()); ++l)\n            {\n                CHECK_ULP_CLOSE(phik[l], phijk[l*(uint64_t(1)<<j)], 0);\n            }\n\n            // This test is from Daubechies, Ten Lectures on Wavelets, Ch 7 \"More About Compactly Supported Wavelets\",\n            // page 245: \\forall y \\in \\mathbb{R}, \\sum_{n \\in \\mathbb{Z}} \\phi(y+n) = 1\n            for (size_t k = 1; k < j; ++k)\n            {\n                auto cond = boost::math::tools::summation_condition_number<Real>(0);\n                for (uint64_t l = 0; l < static_cast<uint64_t>(phik.size()); ++l)\n                {\n                    uint64_t idx = l*(uint64_t(1)<<j) + k;\n                    if (idx < phijk.size())\n                    {\n                        cond += phijk[idx];\n                    }\n                }\n                CHECK_MOLLIFIED_CLOSE(Real(1), cond.sum(), 10*cond()*std::numeric_limits<Real>::epsilon());\n            }\n        }\n    };\n\n    boost::hana::for_each(std::make_index_sequence<18>(), f);\n}\n\n\n// Taken from Lin, 2005, doi:10.1016/j.amc.2004.12.038,\n// \"Direct algorithm for computation of derivatives of the Daubechies basis functions\"\nvoid test_first_derivative()\n{\n    auto phi1_3 = boost::math::detail::daubechies_scaling_integer_grid<long double, 3, 1>();\n    std::array<long double, 6> lin_3{0.0L, 1.638452340884085725014976L, -2.232758190463137395017742L,\n                                     0.5501593582740176149905562L, 0.04414649130503405501220997L, 0.0L};\n    for (size_t i = 0; i < lin_3.size(); ++i)\n    {\n        if(!CHECK_ULP_CLOSE(lin_3[i], phi1_3[i], 0))\n        {\n            std::cerr << \"  Index \" << i << \" is incorrect\\n\";\n        }\n    }\n\n    auto phi1_4 = boost::math::detail::daubechies_scaling_integer_grid<long double, 4, 1>();\n    std::array<long double, 8> lin_4 = {0.0L, 1.776072007522184640093776L, -2.785349397229543142492785L, 1.192452536632278174347632L,\n                                       -0.1313745151846729587935189L, -0.05357102822023923595359996L,0.001770396479992522798495351L, 0.0L};\n\n    for (size_t i = 0; i < lin_4.size(); ++i)\n    {\n        if(!CHECK_ULP_CLOSE(lin_4[i], phi1_4[i], 0))\n        {\n            std::cerr << \"  Index \" << i << \" is incorrect\\n\";\n        }\n    }\n\n    std::array<long double, 10> lin_5 = {0.0L, 1.558326313047001366564379L, -2.436012783189551921436896L, 1.235905129801454293947039L, -0.3674377136938866359947561L,\n                                        -0.02178035117564654658884556L,0.03234719350814368885815854L,-0.001335619912770701035229331L,-0.00001216838474354431384970525L,0.0L};\n    auto phi1_5 = boost::math::detail::daubechies_scaling_integer_grid<long double, 5, 1>();\n    for (size_t i = 0; i < lin_5.size(); ++i)\n    {\n        if(!CHECK_ULP_CLOSE(lin_5[i], phi1_5[i], 0))\n        {\n            std::cerr << \"  Index \" << i << \" is incorrect\\n\";\n        }\n    }\n}\n\ntemplate<typename Real, int p>\nvoid test_quadratures()\n{\n    std::cout << \"Testing \" << p << \" vanishing moment scaling function quadratures on type \" << boost::core::demangle(typeid(Real).name()) << \"\\n\";\n    using boost::math::quadrature::trapezoidal;\n    if constexpr (p == 2)\n    {\n        // 2phi is truly bizarre, because two successive trapezoidal estimates are always bitwise equal,\n        // whereas the third is way different. I don' t think that's a reasonable thing to optimize for,\n        // so one-off it is.\n        Real h = Real(1)/Real(256);\n        auto phi = boost::math::daubechies_scaling<Real, p>();\n        std::cout << \"Scaling functor size is \" << phi.bytes() << \" bytes\" << std::endl;\n        Real t = 0;\n        Real Q = 0;\n        while (t < 3) {\n            Q += phi(t);\n            t += h;\n        }\n        Q *= h;\n        CHECK_ULP_CLOSE(Real(1), Q, 32);\n\n        auto [a, b] = phi.support();\n        // Now hit the boundary. Much can go wrong here; this just tests for segfaults:\n        int samples = 500;\n        Real xlo = a;\n        Real xhi = b;\n        for (int i = 0; i < samples; ++i)\n        {\n            CHECK_ULP_CLOSE(Real(0), phi(xlo), 0);\n            CHECK_ULP_CLOSE(Real(0), phi(xhi), 0);\n            xlo = std::nextafter(xlo, std::numeric_limits<Real>::lowest());\n            xhi = std::nextafter(xhi, std::numeric_limits<Real>::max());\n        }\n\n        xlo = a;\n        xhi = b;\n        for (int i = 0; i < samples; ++i) {\n            assert(abs(phi(xlo)) <= 5);\n            assert(abs(phi(xhi)) <= 5);\n            xlo = std::nextafter(xlo, std::numeric_limits<Real>::max());\n            xhi = std::nextafter(xhi, std::numeric_limits<Real>::lowest());\n        }\n\n        return;\n    }\n    else if constexpr (p > 2)\n    {\n        auto phi = boost::math::daubechies_scaling<Real, p>();\n        std::cout << \"Scaling functor size is \" << phi.bytes() << \" bytes\" << std::endl;\n\n        Real tol = std::numeric_limits<Real>::epsilon();\n        Real error_estimate = std::numeric_limits<Real>::quiet_NaN();\n        Real L1 = std::numeric_limits<Real>::quiet_NaN();\n        auto [a, b] = phi.support();\n        Real Q = trapezoidal(phi, a, b, tol, 15, &error_estimate, &L1);\n        if (!CHECK_MOLLIFIED_CLOSE(Real(1), Q, Real(0.0001)))\n        {\n            std::cerr << \"  Quadrature of \" << p << \" vanishing moment scaling function is not equal 1.\\n\";\n            std::cerr << \"  Error estimate is \" << error_estimate << \", L1 norm is \" << L1 << \"\\n\";\n        }\n\n        auto phi_sq = [phi](Real x) { Real t = phi(x); return t*t; };\n        Q = trapezoidal(phi, a, b, tol, 15, &error_estimate, &L1);\n        if (!CHECK_MOLLIFIED_CLOSE(Real(1), Q, 20*std::sqrt(std::numeric_limits<Real>::epsilon())/(p*p)))\n        {\n            std::cerr << \"  L2 norm of \" << p << \" vanishing moment scaling function is not equal 1.\\n\";\n            std::cerr << \"  Error estimate is \" << error_estimate << \", L1 norm is \" << L1 << \"\\n\";\n        }\n\n        std::random_device rd;\n        Real t = static_cast<Real>(rd())/static_cast<Real>(rd.max());\n        Real S = phi(t);\n        Real dS = phi.prime(t);\n        while (t < b)\n        {\n            t += 1;\n            S += phi(t);\n            dS += phi.prime(t);\n        }\n\n        if(!CHECK_ULP_CLOSE(Real(1), S, 64))\n        {\n            std::cerr << \"  Normalizing sum for \" << p << \" vanishing moment scaling function is incorrect.\\n\";\n        }\n\n        // The p = 3, 4 convergence rate is very slow, making this produce false positives:\n        if constexpr(p > 4)\n        {\n            if(!CHECK_MOLLIFIED_CLOSE(Real(0), dS, 100*std::sqrt(std::numeric_limits<Real>::epsilon())))\n            {\n                std::cerr << \"  Derivative of normalizing sum for \" << p << \" vanishing moment scaling function doesn't vanish.\\n\";\n            }\n        }\n\n        // Test boundary for segfaults:\n        int samples = 500;\n        Real xlo = a;\n        Real xhi = b;\n        for (int i = 0; i < samples; ++i)\n        {\n            CHECK_ULP_CLOSE(Real(0), phi(xlo), 0);\n            CHECK_ULP_CLOSE(Real(0), phi(xhi), 0);\n            if constexpr (p > 2) {\n                assert(abs(phi.prime(xlo)) <= 5);\n                assert(abs(phi.prime(xhi)) <= 5);\n                if constexpr (p > 5) {\n                    assert(abs(phi.double_prime(xlo)) <= 5);\n                    assert(abs(phi.double_prime(xhi)) <= 5);\n                }\n            }\n            xlo = std::nextafter(xlo, std::numeric_limits<Real>::lowest());\n            xhi = std::nextafter(xhi, std::numeric_limits<Real>::max());\n        }\n\n        xlo = a;\n        xhi = b;\n        for (int i = 0; i < samples; ++i) {\n            assert(abs(phi(xlo)) <= 5);\n            assert(abs(phi(xhi)) <= 5);\n            xlo = std::nextafter(xlo, std::numeric_limits<Real>::max());\n            xhi = std::nextafter(xhi, std::numeric_limits<Real>::lowest());\n        }\n    }\n}\n\nint main()\n{\n    boost::hana::for_each(std::make_index_sequence<18>(), [&](auto i){\n      test_quadratures<float, i+2>();\n      test_quadratures<double, i+2>();\n    });\n\n    test_agreement_with_ten_lectures();\n\n    boost::hana::for_each(std::make_index_sequence<19>(), [&](auto i){\n      test_daubechies_filters<float, i+1>();\n      test_daubechies_filters<double, i+1>();\n      test_daubechies_filters<long double, i+1>();\n    });\n\n    test_first_derivative();\n\n    // All scaling functions have a first derivative.\n    boost::hana::for_each(std::make_index_sequence<18>(), [&](auto idx){\n        test_integer_grid<float, idx+2, 0>();\n        test_integer_grid<float, idx+2, 1>();\n        test_integer_grid<double, idx+2, 0>();\n        test_integer_grid<double, idx+2, 1>();\n        test_integer_grid<long double, idx+2, 0>();\n        test_integer_grid<long double, idx+2, 1>();\n        #ifdef BOOST_HAS_FLOAT128\n        test_integer_grid<float128, idx+2, 0>();\n        test_integer_grid<float128, idx+2, 1>();\n        #endif\n    });\n\n    // 4-tap (2 vanishing moment) scaling function does not have a second derivative;\n    // all other scaling functions do.\n    boost::hana::for_each(std::make_index_sequence<17>(), [&](auto idx){\n        test_integer_grid<float, idx+3, 2>();\n        test_integer_grid<double, idx+3, 2>();\n        test_integer_grid<long double, idx+3, 2>();\n        #ifdef BOOST_HAS_FLOAT128\n        test_integer_grid<boost::multiprecision::float128, idx+3, 2>();\n        #endif\n    });\n\n    // 8-tap filter (4 vanishing moments) is the first to have a third derivative.\n    boost::hana::for_each(std::make_index_sequence<16>(), [&](auto idx){\n        test_integer_grid<float, idx+4, 3>();\n        test_integer_grid<double, idx+4, 3>();\n        test_integer_grid<long double, idx+4, 3>();\n        #ifdef BOOST_HAS_FLOAT128\n        test_integer_grid<boost::multiprecision::float128, idx+4, 3>();\n        #endif\n    });\n\n    // 10-tap filter (5 vanishing moments) is the first to have a fourth derivative.\n    boost::hana::for_each(std::make_index_sequence<15>(), [&](auto idx){\n        test_integer_grid<float, idx+5, 4>();\n        test_integer_grid<double, idx+5, 4>();\n        test_integer_grid<long double, idx+5, 4>();\n        #ifdef BOOST_HAS_FLOAT128\n        test_integer_grid<boost::multiprecision::float128, idx+5, 4>();\n        #endif\n    });\n\n    test_dyadic_grid<float>();\n    test_dyadic_grid<double>();\n    test_dyadic_grid<long double>();\n    #ifdef BOOST_HAS_FLOAT128\n    test_dyadic_grid<float128>();\n    #endif\n\n\n    #ifdef BOOST_HAS_FLOAT128\n    boost::hana::for_each(std::make_index_sequence<19>(), [&](auto i){\n        test_filter_ulp_distance<float128, long double, i+1>();\n        test_filter_ulp_distance<float128, double, i+1>();\n        test_filter_ulp_distance<float128, float, i+1>();\n    });\n\n    boost::hana::for_each(std::make_index_sequence<19>(), [&](auto i){\n        test_daubechies_filters<float128, i+1>();\n    });\n    #endif\n\n    return boost::math::test::report_errors();\n}\n", "meta": {"hexsha": "febb77d504d37e69c96a6b27f7aa76851e3fb608", "size": 20426, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/math/test/daubechies_scaling_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": "2021-01-12T04:55:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T04:55:21.000Z", "max_issues_repo_path": "3rdparty/boost_1_73_0/libs/math/test/daubechies_scaling_test.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-13T08:54:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-17T17:25:14.000Z", "max_forks_repo_path": "3rdparty/boost_1_73_0/libs/math/test/daubechies_scaling_test.cpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2022-02-27T14:00:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T06:24:22.000Z", "avg_line_length": 37.8961038961, "max_line_length": 195, "alphanum_fraction": 0.5778419661, "num_tokens": 5870, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583695, "lm_q2_score": 0.8633916152464016, "lm_q1q2_score": 0.7338579928263389}}
{"text": "#include <cmath>\n#include <iostream>\n#include <vector>\n#include <catch2/catch.hpp>\n#include <Eigen/Dense>\n#include \"numeric_utils.h\"\n\nTEST_CASE(\"Test correlation to covariance functionality\", \"[Helpers]\") {\n  SECTION(\"Correlation is diagonal matrix with values of 1.0 along diagonal\") {\n    Eigen::MatrixXd test_corr = Eigen::MatrixXd::Zero(3, 3);\n    test_corr(0, 0) = 1.0;\n    test_corr(1, 1) = 1.0;\n    test_corr(2, 2) = 1.0;\n    Eigen::MatrixXd std_dev = Eigen::VectorXd::Ones(3);\n\n    std_dev << 2.0, 3.0, 4.0;\n\n    auto cov = numeric_utils::corr_to_cov(test_corr, std_dev);\n\n    Eigen::MatrixXd expected_matrix = Eigen::MatrixXd::Zero(3, 3);\n    expected_matrix(0, 0) = 4.0;\n    expected_matrix(1, 1) = 9.0;\n    expected_matrix(2, 2) = 16.0;\n\n    REQUIRE(cov(0, 0) == expected_matrix(0, 0));\n    REQUIRE(cov(1, 1) == expected_matrix(1, 1));\n    REQUIRE(cov(2, 2) == expected_matrix(2, 2));\n    REQUIRE(expected_matrix.lpNorm<2>() == Approx(cov.lpNorm<2>()).epsilon(0.01));\n  }\n}\n\nTEST_CASE(\"Test one dimensional convolution\", \"[Helpers][Convolution]\") { \n  SECTION(\"One dimensional convolution of vectors with length 1\") {\n    std::vector<double> input_x{1.0};\n    std::vector<double> input_y{2.0};\n    std::vector<double> response;\n\n    bool status;\n    try {\n      status = numeric_utils::convolve_1d(input_x, input_y, response);\n    } catch (std::exception &exception) {\n      std::cout << \"Convolution error: \" << exception.what() << std::endl;      \n      FAIL(\"One dimensional convolution function throws exception, check where \"\n           \"exception is being generated interally\");\n    }\n\n    REQUIRE(status);\n    REQUIRE(response.size() == 1);\n    REQUIRE(response[0] == Approx(2.0).epsilon(0.01));\n  }\n\n  SECTION(\"One dimensional convolution of vectors with length 2 and 3\") {\n    std::vector<double> input_x{3.0, 4.0, 5.0};\n    std::vector<double> input_y{2.0, 1.0};\n    std::vector<double> response(1);\n\n    bool status;\n    try {\n      status = numeric_utils::convolve_1d(input_x, input_y, response);\n    } catch (std::exception &exception) {\n      std::cout << \"Convolution error: \" << exception.what() << std::endl;      \n      FAIL(\"One dimensional convolution function throws exception, check where \"\n           \"exception is being generated interally\");\n    }\n\n    REQUIRE(status);\n    REQUIRE(response.size() == input_x.size() + input_y.size() - 1);\n    REQUIRE(response[0] == Approx(6.0).epsilon(0.01));\n    REQUIRE(response[1] == Approx(11.0).epsilon(0.01));\n    REQUIRE(response[2] == Approx(14.0).epsilon(0.01));\n    REQUIRE(response[3] == Approx(5.0).epsilon(0.01));\n  }  \n}\n\nTEST_CASE(\"Test trapazoid rule\", \"[Helpers][Trapazoid]\") {\n\n  SECTION(\"STL vector with unit spacing\") {\n    std::vector<double> input_vector{1, 4, 9, 16, 25};\n\n    auto integral = numeric_utils::trapazoid_rule(input_vector, 1.0);\n    REQUIRE(integral == 42);\n  }\n\n  SECTION(\"STL vector with non-unit spacing\") {\n    std::vector<double> input_vector(101, 0.0);\n\n    double accumulator = 0.0;\n    for (unsigned int i = 1; i < input_vector.size(); ++i) {\n      accumulator += M_PI / 100.0;\n      input_vector[i] = std::sin(accumulator);\n    }\n\n    auto integral = numeric_utils::trapazoid_rule(input_vector, M_PI / 100.0);\n    REQUIRE(integral == Approx(1.9998).epsilon(0.01));\n  }\n\n  SECTION(\"Eigen vector with unit spacing\") {\n    Eigen::VectorXd input_vector(5);\n    input_vector << 1, 4, 9, 16, 25;\n\n    auto integral = numeric_utils::trapazoid_rule(input_vector, 1.0);\n    REQUIRE(integral == 42);\n  }\n\n  SECTION(\"Eigen vector with non-unit spacing\") {\n    Eigen::VectorXd input_vector = Eigen::VectorXd::Zero(101);\n\n    double accumulator = 0.0;\n    for (unsigned int i = 1; i < input_vector.size(); ++i) {\n      accumulator += M_PI / 100.0;\n      input_vector[i] = std::sin(accumulator);\n    }\n\n    auto integral = numeric_utils::trapazoid_rule(input_vector, M_PI / 100.0);\n    REQUIRE(integral == Approx(1.9998).epsilon(0.01));\n  }    \n}\n\nTEST_CASE(\"Test 1-D inverse Fast Fourier Transform\", \"[Helpers][FFT]\") {\n  SECTION(\"Calculate real portion of one-dimesional inverse FFT\") {\n    std::vector<std::complex<double>> input_vector = {\n        {15.0, 0.0},\n        {-2.5, 3.440954801177933},\n        {-2.5, 0.812299240582266},\n        {-2.5, -0.812299240582266},\n        {-2.5, -3.440954801177933}};\n\n    std::vector<double> output_vector(4);\n    auto status = numeric_utils::inverse_fft(input_vector, output_vector);\n\n    REQUIRE(status);\n    REQUIRE(output_vector[0] == Approx(1.0).epsilon(0.01));\n    REQUIRE(output_vector[1] == Approx(2.0).epsilon(0.01));\n    REQUIRE(output_vector[2] == Approx(3.0).epsilon(0.01));\n    REQUIRE(output_vector[3] == Approx(4.0).epsilon(0.01));\n    REQUIRE(output_vector[4] == Approx(5.0).epsilon(0.01));\n  }\n\n  SECTION(\"Calculate real portion of one-dimesional inverse FFT\") {\n    Eigen::VectorXcd input_vector(5);\n    input_vector << std::complex<double>(15.0, 0.0),\n      std::complex<double>(-2.5, 3.440954801177933),\n      std::complex<double>(-2.5, 0.812299240582266),\n      std::complex<double>(-2.5, -0.812299240582266),\n      std::complex<double>(-2.5, -3.440954801177933);\n\n    Eigen::VectorXd output_vector;\n    auto status = numeric_utils::inverse_fft(input_vector, output_vector);\n\n    REQUIRE(status);\n    REQUIRE(output_vector[0] == Approx(1.0).epsilon(0.01));\n    REQUIRE(output_vector[1] == Approx(2.0).epsilon(0.01));\n    REQUIRE(output_vector[2] == Approx(3.0).epsilon(0.01));\n    REQUIRE(output_vector[3] == Approx(4.0).epsilon(0.01));\n    REQUIRE(output_vector[4] == Approx(5.0).epsilon(0.01));\n  }\n}\n\nTEST_CASE(\"Test 1-D Fast Fourier Transform\", \"[Helpers][FFT]\") {\n  SECTION(\"Calculate one-dimesional FFT\") {\n    std::vector<double> input_vector = {3.0, 1.0, 0.0, 0.0};\n\n    std::vector<std::complex<double>> output_vector(4);\n    auto status = numeric_utils::fft(input_vector, output_vector);\n\n    REQUIRE(status);\n    REQUIRE(real(output_vector[0]) == Approx(4.0).epsilon(0.01));\n    REQUIRE(imag(output_vector[0]) + 1.0 == Approx(1.0).epsilon(0.01));\n    REQUIRE(real(output_vector[1]) == Approx(3.0).epsilon(0.01));\n    REQUIRE(imag(output_vector[1]) == Approx(-1.0).epsilon(0.01));\n    REQUIRE(real(output_vector[2]) == Approx(2.0).epsilon(0.01));\n    REQUIRE(imag(output_vector[2]) + 1.0 == Approx(1.0).epsilon(0.01));\n    REQUIRE(real(output_vector[3]) == Approx(3.0).epsilon(0.01));\n    REQUIRE(imag(output_vector[3]) == Approx(1.0).epsilon(0.01));\n  }\n\n  SECTION(\"Calculate one-dimesional FFT\") {\n    Eigen::VectorXd input_vector(4);\n    input_vector << 3.0, 1.0, 0.0, 0.0;\n\n    std::vector<std::complex<double>> output_vector(4);\n    auto status = numeric_utils::fft(input_vector, output_vector);\n\n    REQUIRE(status);\n    REQUIRE(real(output_vector[0]) == Approx(4.0).epsilon(0.01));\n    REQUIRE(imag(output_vector[0]) + 1.0 == Approx(1.0).epsilon(0.01));\n    REQUIRE(real(output_vector[1]) == Approx(3.0).epsilon(0.01));\n    REQUIRE(imag(output_vector[1]) == Approx(-1.0).epsilon(0.01));\n    REQUIRE(real(output_vector[2]) == Approx(2.0).epsilon(0.01));\n    REQUIRE(imag(output_vector[2]) + 1.0 == Approx(1.0).epsilon(0.01));\n    REQUIRE(real(output_vector[3]) == Approx(3.0).epsilon(0.01));\n    REQUIRE(imag(output_vector[3]) == Approx(1.0).epsilon(0.01));\n  }\n\n  SECTION(\"Calculate one-dimesional FFT\") {\n    Eigen::VectorXd input_vector(4);\n    input_vector << 3.0, 1.0, 0.0, 0.0;\n\n    Eigen::VectorXcd output_vector(4);\n    auto status = numeric_utils::fft(input_vector, output_vector);\n\n    REQUIRE(status);\n    REQUIRE(real(output_vector(0)) == Approx(4.0).epsilon(0.01));\n    REQUIRE(imag(output_vector(0)) + 1.0 == Approx(1.0).epsilon(0.01));\n    REQUIRE(real(output_vector(1)) == Approx(3.0).epsilon(0.01));\n    REQUIRE(imag(output_vector(1)) == Approx(-1.0).epsilon(0.01));\n    REQUIRE(real(output_vector(2)) == Approx(2.0).epsilon(0.01));\n    REQUIRE(imag(output_vector(2)) + 1.0 == Approx(1.0).epsilon(0.01));\n    REQUIRE(real(output_vector(3)) == Approx(3.0).epsilon(0.01));\n    REQUIRE(imag(output_vector(3)) == Approx(1.0).epsilon(0.01));\n  }\n}\n\nTEST_CASE(\"Test polynomial curve fitting, derivatives, and evaluation\",\n          \"[Helpers][Polynomial]\") {\n  SECTION(\"Fit polynomial with non-zero intercept--should be degree 0\") {\n    Eigen::VectorXd points(4);\n    points << 1.0, 2.0, 3.0, 4.0;\n    Eigen::VectorXd data(4);\n    data << 4.0, 4.0, 4.0, 4.0;\n\n    auto poly_coeffs = numeric_utils::polyfit_intercept(points, data, 4.0, 3);\n\n    REQUIRE(poly_coeffs(0) + 1.0 == Approx(1.0).epsilon(0.01));\n    REQUIRE(poly_coeffs(1) + 1.0 == Approx(1.0).epsilon(0.01));\n    REQUIRE(poly_coeffs(2) + 1.0 == Approx(1.0).epsilon(0.01));\n    REQUIRE(poly_coeffs(3) == Approx(4.0).epsilon(0.01));\n  }\n\n  SECTION(\"Fit polynomial with non-zero intercept--should be degree 0\") {\n    Eigen::VectorXd points(4);\n    points << 1.0, 2.0, 3.0, 4.0;\n    Eigen::VectorXd data(4);\n    data << 4.0, 4.0, 4.0, 4.0;\n\n    auto poly_coeffs = numeric_utils::polyfit_intercept(points, data, 4.0, 2);\n\n    REQUIRE(poly_coeffs(0) + 1.0 == Approx(1.0).epsilon(0.01));\n    REQUIRE(poly_coeffs(1) + 1.0 == Approx(1.0).epsilon(0.01));\n    REQUIRE(poly_coeffs(2) == Approx(4.0).epsilon(0.01));\n  }\n\n  SECTION(\"Fit polynomial with zero intercept--should be degree 3\") {\n    Eigen::VectorXd points(4);\n    points << 1.0, 2.0, 3.0, 4.0;\n    Eigen::VectorXd data(4);\n    data << 1.0, 8.0, 27.0, 64.0;\n\n    auto poly_coeffs = numeric_utils::polyfit_intercept(points, data, 0.0, 3);\n\n    REQUIRE(poly_coeffs(0) == Approx(1.0).epsilon(0.01));\n    REQUIRE(poly_coeffs(1) + 1.0 == Approx(1.0).epsilon(0.01));\n    REQUIRE(poly_coeffs(2) + 1.0 == Approx(1.0).epsilon(0.01));\n    REQUIRE(poly_coeffs(3) + 1.0 == Approx(1.0).epsilon(0.01));\n  }\n\n  SECTION(\"Take derivative of polynomial\") {\n    Eigen::VectorXd coefficients(4);\n    coefficients << 2.0, 2.0, 2.0, 2.0;\n\n    auto derivs = numeric_utils::polynomial_derivative(coefficients);\n\n    REQUIRE(coefficients.size() - 1 == derivs.size());\n    REQUIRE(derivs(0) == Approx(6.0).epsilon(0.01));\n    REQUIRE(derivs(1) == Approx(4.0).epsilon(0.01));\n    REQUIRE(derivs(2) == Approx(2.0).epsilon(0.01));\n  }\n\n  SECTION(\"Evaluate polynomial\") {\n    Eigen::VectorXd coefficients(4);\n    coefficients << 2.0, 2.0, 2.0, 2.0;\n\n    Eigen::VectorXd points(4);\n    points << 1.0, 2.0, 3.0, 4.0;\n\n    auto evaluations = numeric_utils::evaluate_polynomial(coefficients, points);\n\n    REQUIRE(points.size() == evaluations.size());\n    REQUIRE(evaluations(0) == Approx(8.0).epsilon(0.01));\n    REQUIRE(evaluations(1) == Approx(30.0).epsilon(0.01));\n    REQUIRE(evaluations(2) == Approx(80.0).epsilon(0.01));\n    REQUIRE(evaluations(3) == Approx(170.0).epsilon(0.01));\n  }\n\n  SECTION(\"Evaluate polynomial\") {\n    Eigen::VectorXd coefficients(4);\n    coefficients << 2.0, 2.0, 2.0, 2.0;\n\n    std::vector<double> points = {1.0, 2.0, 3.0, 4.0};\n\n    auto evaluations = numeric_utils::evaluate_polynomial(coefficients, points);\n\n    REQUIRE(points.size() == evaluations.size());\n    REQUIRE(evaluations(0) == Approx(8.0).epsilon(0.01));\n    REQUIRE(evaluations(1) == Approx(30.0).epsilon(0.01));\n    REQUIRE(evaluations(2) == Approx(80.0).epsilon(0.01));\n    REQUIRE(evaluations(3) == Approx(170.0).epsilon(0.01));\n  }\n\n  SECTION(\"Evaluate polynomial\") {\n    std::vector<double> coefficients = {2.0, 2.0, 2.0, 2.0};\n\n    std::vector<double> points = {1.0, 2.0, 3.0, 4.0};\n\n    auto evaluations = numeric_utils::evaluate_polynomial(coefficients, points);\n\n    REQUIRE(points.size() == evaluations.size());\n    REQUIRE(evaluations[0] == Approx(8.0).epsilon(0.01));\n    REQUIRE(evaluations[1] == Approx(30.0).epsilon(0.01));\n    REQUIRE(evaluations[2] == Approx(80.0).epsilon(0.01));\n    REQUIRE(evaluations[3] == Approx(170.0).epsilon(0.01));\n  }    \n}\n", "meta": {"hexsha": "38639de3d9b3fa08b111ef3513de5aaf597883e6", "size": 11730, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/numeric_utils_tests.cc", "max_stars_repo_name": "fmckenna/smelt", "max_stars_repo_head_hexsha": "4e8a786fc415fc99bd79ada885e8312ed0eb36e0", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-05-07T03:14:27.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-19T07:10:52.000Z", "max_issues_repo_path": "test/numeric_utils_tests.cc", "max_issues_repo_name": "fmckenna/smelt", "max_issues_repo_head_hexsha": "4e8a786fc415fc99bd79ada885e8312ed0eb36e0", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-04-11T19:29:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-11T19:29:47.000Z", "max_forks_repo_path": "test/numeric_utils_tests.cc", "max_forks_repo_name": "fmckenna/smelt", "max_forks_repo_head_hexsha": "4e8a786fc415fc99bd79ada885e8312ed0eb36e0", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-03-25T20:08:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-04T13:02:31.000Z", "avg_line_length": 37.3566878981, "max_line_length": 82, "alphanum_fraction": 0.6427962489, "num_tokens": 3706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711756575749, "lm_q2_score": 0.8633916205190225, "lm_q1q2_score": 0.7338579907454523}}
{"text": "#include <Eigen/Dense>\n#include <pybind11/eigen.h>\n#include <pybind11/pybind11.h>\n#include <tuple>\n\nnamespace py = pybind11;\n\n// double + Eigen\n\nstd::tuple<Eigen::VectorXd, Eigen::MatrixXd> eigsy(const Eigen::Ref<const Eigen::MatrixXd> & input_sym) {\n    auto solver = Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd>(input_sym, Eigen::ComputeEigenvectors);\n    return {solver.eigenvalues(), solver.eigenvectors()};\n}\n\nPYBIND11_MODULE(eigen_wrapper, m) {\n    m.doc() = \"Wrapper for eigenvalue computation functions\";\n\n    m.def(\n        \"eigsy\",\n        &eigsy,\n        \"Computes eigenvalues using the default eigenvalue solver of Eigen C++ lib\\n\"\n        \"Uses a QR iterative algorithm in O(n^3), according to Eigen's doc\\n\"\n        \"Manipulates double precision only\\n\"\n        \"\\n\"\n        \"input_sym: symmetric matrix of double (numpy.float64)\\n\"\n        \"output = (E,Q):\\n\"\n        \"   E = vector of eigenvalues\\n\"\n        \"   Q = matrix with eigenvectors as columns\",\n        py::arg(\"input_sym\"));\n}", "meta": {"hexsha": "3e1299b5478cf7994d805c2de356a68ebd149195", "size": 1004, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "apt/eigen_wrapper.cpp", "max_stars_repo_name": "lereldarion/anthony_project_tools", "max_stars_repo_head_hexsha": "e1b158dfa799d068857d75a219913f3e11aad30d", "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": "apt/eigen_wrapper.cpp", "max_issues_repo_name": "lereldarion/anthony_project_tools", "max_issues_repo_head_hexsha": "e1b158dfa799d068857d75a219913f3e11aad30d", "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": "apt/eigen_wrapper.cpp", "max_forks_repo_name": "lereldarion/anthony_project_tools", "max_forks_repo_head_hexsha": "e1b158dfa799d068857d75a219913f3e11aad30d", "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.4666666667, "max_line_length": 105, "alphanum_fraction": 0.6573705179, "num_tokens": 263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765281148513, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.7338410435758874}}
{"text": "/*\n * @file sa_test.cpp\n * @auther Zhihao Lou\n *\n * Test file for SA (simulated annealing).\n */\n#include <mlpack/core.hpp>\n#include <mlpack/core/optimizers/sa/sa.hpp>\n#include <mlpack/core/optimizers/sa/exponential_schedule.hpp>\n#include <mlpack/core/optimizers/lbfgs/test_functions.hpp>\n\n#include <mlpack/core/metrics/ip_metric.hpp>\n#include <mlpack/core/metrics/lmetric.hpp>\n#include <mlpack/core/metrics/mahalanobis_distance.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nusing namespace std;\nusing namespace arma;\nusing namespace mlpack;\nusing namespace mlpack::optimization;\nusing namespace mlpack::optimization::test;\nusing namespace mlpack::metric;\n\nBOOST_AUTO_TEST_SUITE(SATest);\n\nBOOST_AUTO_TEST_CASE(GeneralizedRosenbrockTest)\n{\n  size_t dim = 50;\n  GeneralizedRosenbrockFunction f(dim);\n\n  double iteration = 0;\n  double result = DBL_MAX;\n  arma::mat coordinates;\n  while (result > 1e-6)\n  {\n    ExponentialSchedule schedule(1e-5);\n    SA<GeneralizedRosenbrockFunction, ExponentialSchedule>\n        sa(f, schedule, 10000000, 1000., 1000, 100, 1e-10, 3, 20, 0.3, 0.3);\n    coordinates = f.GetInitialPoint();\n    result = sa.Optimize(coordinates);\n    ++iteration;\n\n    BOOST_REQUIRE_LT(iteration, 4); // No more than three tries.\n  }\n\n  // 0.1% tolerance for each coordinate.\n  BOOST_REQUIRE_SMALL(result, 1e-6);\n  for (size_t j = 0; j < dim; ++j)\n      BOOST_REQUIRE_CLOSE(coordinates[j], (double) 1.0, 0.1);\n}\n\n// The Rosenbrock function is a simple function to optimize.\nBOOST_AUTO_TEST_CASE(RosenbrockTest)\n{\n  RosenbrockFunction f;\n  ExponentialSchedule schedule(1e-5);\n  SA<RosenbrockFunction> //sa(f, schedule); // All default parameters.\n      sa(f, schedule, 10000000, 1000., 1000, 100, 1e-11, 3, 20, 0.3, 0.3);\n  arma::mat coordinates = f.GetInitialPoint();\n\n  const double result = sa.Optimize(coordinates);\n\n  BOOST_REQUIRE_SMALL(result, 1e-6);\n  BOOST_REQUIRE_CLOSE(coordinates[0], 1.0, 1e-3);\n  BOOST_REQUIRE_CLOSE(coordinates[1], 1.0, 1e-3);\n}\n\n/**\n * The Rastigrin function, a (not very) simple nonconvex function.  It is\n * defined by\n *\n *   f(x) = 10n + \\sum_{i = 1}^{n} (x_i^2 - 10 cos(2 \\pi x_i)).\n *\n * It has very many local minima, so finding the true global minimum is\n * difficult.  The function is two-dimensional, and has minimum 0 where\n * x = [0 0].  We are only using it for simulated annealing, so there is no need\n * to implement the gradient.\n */\nclass RastrigrinFunction\n{\n public:\n  double Evaluate(const arma::mat& coordinates) const\n  {\n    double objective = 20; // 10 * n, n = 2.\n    objective += std::pow(coordinates[0], 2.0) -\n        10 * std::cos(2 * M_PI * coordinates[0]);\n    objective += std::pow(coordinates[1], 2.0) -\n        10 * std::cos(2 * M_PI * coordinates[1]);\n\n    return objective;\n  }\n\n  arma::mat GetInitialPoint() const\n  {\n    return arma::mat(\"-3 -3\");\n  }\n};\n\nBOOST_AUTO_TEST_CASE(RastrigrinFunctionTest)\n{\n  // Simulated annealing isn't guaranteed to converge (except in very specific\n  // situations).  If this works 1 of 5 times, I'm fine with that.  All I want\n  // to know is that this implementation will escape from local minima.\n  size_t successes = 0;\n\n  for (size_t trial = 0; trial < 5; ++trial)\n  {\n    RastrigrinFunction f;\n    ExponentialSchedule schedule(3e-6);\n    SA<RastrigrinFunction> //sa(f, schedule);\n        sa(f, schedule, 20000000, 100, 50, 1000, 1e-12, 2, 0.2, 0.01, 0.1);\n    arma::mat coordinates = f.GetInitialPoint();\n\n    const double result = sa.Optimize(coordinates);\n\n    if ((std::abs(result) < 1e-3) &&\n        (std::abs(coordinates[0]) < 1e-3) &&\n        (std::abs(coordinates[1]) < 1e-3))\n      ++successes;\n  }\n\n  BOOST_REQUIRE_GE(successes, 1);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "3d87e5d95416ba125f3dd0d8d40379a6eaa47c41", "size": 3714, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/sa_test.cpp", "max_stars_repo_name": "jmlevin7878/mlpack2", "max_stars_repo_head_hexsha": "7fe38005d86b77293f728c34ca176224bdff9ee8", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "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/mlpack/tests/sa_test.cpp", "max_issues_repo_name": "jmlevin7878/mlpack2", "max_issues_repo_head_hexsha": "7fe38005d86b77293f728c34ca176224bdff9ee8", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "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/mlpack/tests/sa_test.cpp", "max_forks_repo_name": "jmlevin7878/mlpack2", "max_forks_repo_head_hexsha": "7fe38005d86b77293f728c34ca176224bdff9ee8", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "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": 29.015625, "max_line_length": 80, "alphanum_fraction": 0.6865912763, "num_tokens": 1140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92522995296862, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.7338053773886208}}
{"text": "#include <iostream>\n#include <string>\n#include <vector>\n#include <sstream>\n#include <iomanip>\n#include <fstream>\n#include <NTL/ZZ.h>\n#include <Windows.h>\n\nusing namespace std;\nusing namespace NTL;\n\nstring toBinary(ZZ n)\n{\n\tstring r;\n\twhile (n != 0) {\n\t\tr += (n % 2 == 0 ? \"0\" : \"1\");\n\t\tn /= 2;\n\t}\n\treturn r;\n}\n\nZZ modulo(ZZ a, ZZ n) {\n    ZZ r = a - (a / n) * n;\n    if (r < 0) {\n        r = r + n;\n    }\n    return r;\n}\n\nclass RSA {\n\nprivate:\n    string msg;\n    string alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ,.-( )abcdefghijklmnopqrstuvwxyz<>*1234567890[]\";\n    ZZ d;\n    ZZ e;\n    ZZ N;\n    ZZ p;\n    ZZ q;\n\npublic:\n    ZZ e_Receiver;\n    ZZ N_Receiver;\n    RSA(string directory);\n    RSA(int bits);\n    RSA(ZZ, ZZ);\n    RSA(ZZ, ZZ, ZZ, ZZ);\n    ZZ chineseRemainder(vector<vector<ZZ>>);\n    string encode_message(string, ZZ, ZZ);\n    string decode_message(string, ZZ, ZZ);\n    string encode(string);\n    string decode(string);\n    long euclidAlgorithm(ZZ a, ZZ b);\n    vector<ZZ> euclidExtendedAlgorithm(ZZ a, ZZ b);\n    ZZ inverse(ZZ a, ZZ b);\n    bool primalityTest(ZZ num);\n    string block(string);\n    ZZ generate_bit();\n    ZZ generate_random(int bits);\n    ZZ prime(int bits);\n    ZZ generateRandom(int bits);\n    ZZ exponenciacion(ZZ b, ZZ e);\n    ZZ binaryExponentiation(ZZ a, ZZ e, ZZ n);\n};\n\nZZ RSA::generate_bit() {\n\n    std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now();\n    // Elapsed time\n    // Elapsed time\n    std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();\n\n    ZZ seed(std::chrono::duration_cast<std::chrono::nanoseconds> (end - begin).count());\n\n    ZZ seed_2 = modulo(seed, ZZ(2));\n\n    return seed_2;\t\n}\n\nZZ RSA::generate_random(int bits)\n{\n\tZZ random(0);\n\tZZ power(2);\n\trandom = random + (generate_bit());\n\tfor (int i = 1;i<bits;i++) {\n\t\trandom = random + (generate_bit()*power);\n\t\tpower = power * 2;\n\t}\n\treturn random;\n}\n\nZZ mod(ZZ a, ZZ n) {\n    ZZ r = a - (a / n) * n;\n    if (r < 0) {\n        r = r + n;\n    }\n    return r;\n}\n\n// Euclid's extended algorithm:\n// Function that returns a vector that stores the values\n// of the gcd between a & b, and also the x and y values\nvector<ZZ> RSA::euclidExtendedAlgorithm(ZZ a, ZZ b) \n{\n    // Initialization\n\tZZ r_1 = a;\n    ZZ r_2 = b;\n    ZZ s_1 = ZZ(1);\n    ZZ s_2 = ZZ(0);\n\tZZ t_1 = ZZ(0);\n\tZZ t_2 = ZZ(1);\n\n\twhile (r_2 != 0) {\n\n        // Quotient\n\t\tZZ quotient = r_1 / r_2;\n\n        // Updating r\n        ZZ temp = r_2;\n\t\tr_2 = r_1 - quotient * r_2;\n\t\tr_1 = temp;\n        \n        // Updating s\n\t\ttemp = s_2;\n\t\ts_2 = s_1 - quotient * s_2;\n\t\ts_1 = temp;\n\n        // Updating t\n\t\ttemp = t_2;\n\t\tt_2 = t_1 - quotient * t_2;\n\t\tt_1 = temp;\n\t}\n\n    // Vector to store values\n\tvector<ZZ> result;\n\n    // Greatest common divisor: result[0]\n\tresult.push_back(r_1);\n    // x: result[1]\n\tresult.push_back(s_1);\n    // y: result[2]\n\tresult.push_back(t_1);\n\n\treturn result;\n}\n\nstring num2String(ZZ number) {\n    ostringstream stringZZ;\n    stringZZ << number;\n    return stringZZ.str();\n}\n\nstring num2String(int number) {\n    ostringstream stringZZ;\n    stringZZ << number;\n    return stringZZ.str();\n}\n\nint string2NumInt(string message){\n    int numberZZ;\n    istringstream num(message);\n    num >> numberZZ;\n    return numberZZ;\n}\n\nZZ string2Num(string message){\n    ZZ numberZZ;\n    istringstream num(message);\n    num >> numberZZ;\n    return numberZZ;\n}\n\nZZ RSA::exponenciacion(ZZ b, ZZ e){\n    \n    ZZ result(1);\n\n    while(e>0){\n        if(e % 2)\n            result = (result*b);\n        b =  (b * b);\n        e /= 2;\n    }\n    return result;\n}\n\nZZ RSA::binaryExponentiation(ZZ a, ZZ e, ZZ n) {\n\tZZ A(1);\n\tstring bin = toBinary(e);\n\tfor (int i = bin.size(); i != -1; i--) {\n\t\tA = modulo(A * A, n);\n\t\tif (bin[i] == '1') {\n\t\t\tA = modulo(A * a, n);\n\t\t}\n\t}\n\treturn A;\n}\n\nbool RSA::primalityTest(ZZ n){\n    \n    if ((n & 1) == 0){\n        return false;\n    }\n    ZZ s(0);\n    ZZ t = n - 1;\n    while ((t & 1) == 0) {\n        s++;\n        t >>= 1;\n    }\n    ZZ a(2);\n    for (int i = 0; i < 10; i++){\n\n        ZZ x = binaryExponentiation(a, t, n);\n        if (x == 1 || x == (n-1))\n            continue;\n        for (ZZ r(0); r < (s-1); r++){\n            x = binaryExponentiation(x, to_ZZ(2), n);\n            if(x == 1){\n                return false;\n            }\n            else if(x == n - 1)\n                break;\n        }\n        if(x != n - 1 )\n            return false;\n        ZZ a = RandomBnd(n-3) + 3;\n    }\n    \n    return true;\n}\n\nZZ RSA::generateRandom(int bits){\n\n    ZZ min(exponenciacion(to_ZZ(2), to_ZZ(bits))>>1), max(exponenciacion(to_ZZ(2), to_ZZ(bits)) - 1);\n\n    ZZ number;\n    do{\n        number = RandomLen_ZZ(bits);\n        // number = generate_random(bits); // No funcional para Linux\n    }while(number < min || number > max);\n\n    return number;\n}\n\nZZ RSA::prime(int bits){\n\n    ZZ prime;\n\n    for (;!primalityTest(prime);prime = generateRandom(bits));\n\n    return prime;\n}\n\nZZ RSA::inverse(ZZ a, ZZ b)\n{\n    ZZ s_1 = euclidExtendedAlgorithm(a, b)[1];\n    if (s_1 < 0) {\n        s_1 = mod(s_1, b);\n    }\n    return s_1;\n}\n\nRSA::RSA(string directory) {\n    this->p = 13;\n\tthis->q = 149;\n    ifstream infile(directory);\n\n    string line;\n    for(int i{0}; getline(infile, line); i++)\n    {\n        if(i == 2) {\n            this->N_Receiver = string2Num(line);\n        }\n        else if(i == 3) {\n            this->e_Receiver = string2Num(line);\n        }\n        else if(i == 7) {\n            this->N = string2Num(line);\n        }\n        else if(i == 8) {\n            this->e = string2Num(line);\n        }\n    }\n\tZZ phiN = (p - 1) * (q - 1);\n\tthis->d = inverse(e, phiN);\n}\n\nRSA::RSA(ZZ e, ZZ N) {\n    this->p = 17;\n\tthis->q = 59;\n\tthis->N = p * q;\n\tZZ phiN = (p - 1) * (q - 1);\n\tthis->d = inverse(e, phiN);\n}\n\n\nRSA::RSA(ZZ p, ZZ q, ZZ e, ZZ d){\n    this->p = p;\n    this->q = q;\n    this->N = p * q;\n    this->e = e;\n    this->d = d;\n}\n\nZZ binaryEuclidAlgorithm(ZZ a, ZZ b) {\n    ZZ g = ZZ(1);\n    while ((mod(a, ZZ(2)) == 0) && (mod(b, ZZ(2)) == 0)) {\n        a = a / 2;\n        b = b / 2;\n        g = 2 * g;\n    }\n    while (a != 0) {\n        if (mod(a, ZZ(2)) == 0) {\n            a = a / 2;\n        }\n        else if (mod(b, ZZ(2)) == 0) {\n            b = b / 2;\n        }\n        else {\n            ZZ t = abs(a - b) / 2;\n            if (a >= b) {\n                a = t;\n            }\n            else {\n                b = t;\n            }\n        }\n    }\n    return g * b;\n}\n\nRSA::RSA(int bits) {\n    this-> p = prime(bits);\n    this-> q = prime(bits);\n    this-> N = p * q;\n    \n    ZZ phiN = (p - 1) * (q - 1);\n    \n    do{\n        this-> e = generateRandom(bits);\n    } while(binaryEuclidAlgorithm(this->e, phiN) != 1);\n    \n    this-> d = inverse(this->e, phiN);\n\n    cout << \"-------------------- Valores generados --------------------\" << endl;\n    cout << \"- Valor p  -\" << endl\n         << p << endl << endl;\n    cout << \"- Valor q -\" << endl\n         << q << endl << endl;;\n    cout << \"- Valor N -\" << endl\n         << N << endl << endl;\n    cout << \"- Valor e -\" << endl\n         << e << endl << endl;\n    cout << \"- Valor d -\" << endl \n         << d << endl << endl;\n}\n\nvoid addZeros(int size, string &block) {\n\tstring zeros(size - block.size(), '0');\n\tzeros += block;\n\tblock = zeros;\n}\n\nZZ phi(ZZ modulus)\n{\n    ZZ result = ZZ(1);\n    for (ZZ i = ZZ(2); i < modulus; i++)\n        if (binaryEuclidAlgorithm(i, ZZ(modulus)) == ZZ(1))\n            result++;\n    return result;\n}\n\nstring convert(string message, string alphabet, int size) {\n    int messageSize = message.length();\n    string decodedMessage;\n    int alphabetIndex = 0;\n    for(int i{0}; i < messageSize; i += size) {\n        alphabetIndex = string2NumInt(message.substr(i, size));\n        char alphabetCharacter = alphabet[alphabetIndex];\n        decodedMessage += alphabetCharacter;\n    }\n    return decodedMessage;\n}\n\nstring RSA::block(string mensaje) {\n    string mensaje_antes;\n    int tamano_mensaje = mensaje.length();\n\n    string tamano_alfabeto = num2String(alphabet.length());\n    int tamano = tamano_alfabeto.length();\n\n    for(int i = 0; i < tamano_mensaje; i++) {\n        int posicion = alphabet.find(mensaje[i]);\n\n        string tamano_posicion = num2String(posicion);\n        int tamano_pos = tamano_posicion.length();\n\n        if( tamano_pos < tamano) {\n            string pos = num2String(posicion);\n            addZeros(tamano, pos);\n            mensaje_antes += pos;\n        }\n        else {\n            string pos = num2String(posicion);\n            mensaje_antes += pos;\n        }\n    }\n    return mensaje_antes;\n}\n\nstring RSA::encode_message(string message, ZZ exponent, ZZ modulus) {\n\n    string codedMessage;\n\n    string blockMessage = block(message);\n    \n    int blockSize = num2String(modulus).length() - 1;\n    int blockMessageLength = blockMessage.length();\n\n    for(int i = 0; i < blockMessageLength; i += blockSize){\n        ZZ base(0);\n        if(i + blockSize > blockMessageLength) {\n            base = string2Num(blockMessage.substr(i, blockMessageLength - i));\n        }\n        else {\n            base = string2Num(blockMessage.substr(i, blockSize));\n        }\n\n        ZZ power = binaryExponentiation(base, exponent, modulus);\n        string powerString = num2String(power);\n        int powerSize = powerString.length();\n        \n        string N_string = num2String(N);\n        int N_size = N_string.length();\n        if( powerSize < N_size) {\n            string pos = num2String(power);\n            addZeros(N_size, pos);\n            codedMessage += pos;\n        }\n        else {\n            string pos = num2String(power);\n            codedMessage += pos;\n        }\n\n    }\n    return codedMessage;\n}\n\nstring RSA::encode(string message) {\n    ifstream infile(\"sign.txt\");\n    string text;\n    string line;\n\n    for(int i{0}; getline(infile, line); i++){\n        text += line;\n    }\n\n    string rubric = encode_message(text, d, N);\n\n    string sign = encode_message(rubric, e_Receiver, N_Receiver);\n\n    ofstream out(\"digital_sign.txt\");\n    out << sign;\n    out.close();\n\n    string code = encode_message(message, e_Receiver, N_Receiver);\n\n    return code;\n}\n\nZZ RSA::chineseRemainder(vector<vector<ZZ>> ecs)\n{\t\t\n\tZZ P(1);\n\tfor (int i = 0; i < ecs.size(); i++) {\n\t\tecs[i][0] = mod(ecs[i][0], ecs[i][1]);\n\t\tP *= ecs[i][1];\n\t}\n\tfor (int i = 0; i < ecs.size(); i++) {\n\t\tecs[i].push_back(P / ecs[i][1]);\n\t}\n\tZZ x0(0);\n\tfor (int i = 0; i < ecs.size(); i++) {\n\t\tx0 += mod(ecs[i][0], P) * mod(ecs[i][2], P) * mod(inverse(ecs[i][2], ecs[i][1]), P);\n\t\tx0 = mod(x0, P);\n\t}\n\tx0 = mod(x0, P);\n\treturn x0;\n}\n\nstring RSA::decode_message(string message, ZZ exponent, ZZ modulus) {\n\n    string decodedCode;\n\n    string N_string = num2String(modulus);\n    int N_size = N_string.length();\n    int codeLength = message.length();\n\n    string alphabetSizeString = num2String(alphabet.length());\n    int alphabetSize = alphabetSizeString.length();\n\n    for(int i = 0; i < codeLength; i += N_size){\n        ZZ base(0);\n        if(i + N_size > codeLength) {\n            base = string2Num(message.substr(i, codeLength - i));\n        }\n        else {\n            base = string2Num(message.substr(i, N_size));\n        }\n\n        ZZ power = binaryExponentiation(base, exponent, modulus);\n\n        string powerString = num2String(power);\n        int powerSize = powerString.length();\n\n        if( powerSize < N_size - 1 && i + N_size < codeLength) {\n            string pos = num2String(power);\n            addZeros(N_size - 1, pos);\n            decodedCode += pos;\n        }\n        else {\n            string pos = num2String(power);\n            decodedCode += pos;\n        }\n\n    }\n    string decodedMessage = convert(decodedCode, alphabet, alphabetSize);\n    return decodedMessage;\n}\n\nstring RSA::decode(string message) {\n    ifstream infile(\"digital_sign.txt\");\n    string line;\n    for(; getline( infile, line ); );\n\n    string decodedSign = decode_message(line, d, N);\n\n    ifstream indirectory(\"directory.txt\");\n\n    string text;\n    ZZ e_Emitter;\n    ZZ N_Emitter;\n\n    for(int i{0}; getline(indirectory, text); i++)\n    {\n        if(i == 7) {\n            N_Emitter = string2Num(text);\n        }     \n        else if(i == 8) {\n            e_Emitter = string2Num(text);\n        }\n    }\n    \n    string sign = decode_message(decodedSign, e_Emitter, N_Emitter);\n\n    ofstream out(\"sign_test.txt\");\n    out << sign;\n    out.close();\n\n    string decodedCode = decode_message(message, d, N);\n    return decodedCode;\n}\n\nint main() {\n\n    int opt;\n\n    cout << \"Choose an option\" << endl;\n    cout << right << setw(12)\n              << \"Encode (1)\" << endl;\n    cout << right << setw(12)\n              << \"Decode (2)\" << endl;\n    cout << right << setw(12)\n              << \"Generate keys (3)\" << endl;\n    cout << \"Option: \";\n    cin >> opt;\n    cin.ignore();\n\n    if ((opt != 1) && (opt != 2) && (opt != 3)) {\n        return 0;\n    }\n\n    // Objeto Receptor:\n    // - Env\u00eda la clave p\u00fablica e\n    // - Env\u00eda el producto N\n    // Directorio p\u00fablico\n    RSA Receiver(ZZ(3), ZZ(1003));\n    // Objeto Emisor:\n    RSA Emitter(\"directory.txt\");\n\n    if (opt == 1) {\n        /*string message;\n        cout << \"Enter message: \";\n        (void) getline(cin, message);*/\n\n        ifstream infile(\"message.txt\");\n        string line;\n        for(; getline( infile, line ); );\n\n        string code = Emitter.encode(line);\n\n        cout << \"\\nEncoded message: \" << code;\n\n        ofstream out(\"encode.txt\");\n        out << code;\n        out.close();\n    }\n    else if (opt == 2) {\n        /*string message;\n        cout << \"Enter message: \";\n        (void) getline(cin, message);*/\n\n        ifstream infile(\"encode.txt\");\n        string line;\n        for(; getline( infile, line ); );\n\n        string code = Receiver.decode(line);\n\n        cout << \"\\nDecoded message: \" << code;\n\n        ofstream out(\"decode.txt\");\n        out << code;\n        out.close();\n    }\n    else if (opt == 3) {\n        RSA Bits(1024);\n    }\n\n}", "meta": {"hexsha": "97886778ca46b75b00a59927e710151b6fe7ce05", "size": 13950, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RSA/RSA.cpp", "max_stars_repo_name": "leonardo-gallegos/Leonardo_Gallegos", "max_stars_repo_head_hexsha": "f5b969a2760462047c5ddd315ca389941cb5a02d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-05T03:25:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-05T03:25:06.000Z", "max_issues_repo_path": "RSA/RSA.cpp", "max_issues_repo_name": "leonardo-gallegos/Renzo_Leonardo_Gallegos_Vilca", "max_issues_repo_head_hexsha": "f5b969a2760462047c5ddd315ca389941cb5a02d", "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": "RSA/RSA.cpp", "max_forks_repo_name": "leonardo-gallegos/Renzo_Leonardo_Gallegos_Vilca", "max_forks_repo_head_hexsha": "f5b969a2760462047c5ddd315ca389941cb5a02d", "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.2133757962, "max_line_length": 101, "alphanum_fraction": 0.5288888889, "num_tokens": 4001, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951607140232, "lm_q2_score": 0.7853085708384735, "lm_q1q2_score": 0.7337885282587153}}
{"text": "#pragma once\n#include \"load_vector.hpp\"\n#include <Eigen/Core>\n\n//----------------AssembleVectorBegin----------------\n//! Assemble the load vector into the full right hand side\n//! for the linear system\n//!\n//! @param[out] F will at the end contain the RHS values for each vertex.\n//! @param[in] vertices a list of triangle vertices\n//! @param[in] triangles a list of triangles\n//! @param[in] f the RHS function f.\nvoid assembleLoadVector(Eigen::VectorXd &      F,\n                        const Eigen::MatrixXd &vertices,\n                        const Eigen::MatrixXi &triangles,\n                        const std::function<double(double, double)> &f) {\n\tconst int numberOfElements = triangles.rows();\n\n\tF.resize(vertices.rows());\n\tF.setZero();\n\t// (write your solution here)\n}\n//----------------AssembleVectorEnd----------------\n", "meta": {"hexsha": "eb8b0086c698c4a88d86c04c7da2f07829c35d70", "size": 829, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "series2_warmup/2d-poissonlFEM/load_vector_assembly.hpp", "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_warmup/2d-poissonlFEM/load_vector_assembly.hpp", "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_warmup/2d-poissonlFEM/load_vector_assembly.hpp", "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": 34.5416666667, "max_line_length": 73, "alphanum_fraction": 0.6043425814, "num_tokens": 170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7335766624007634}}
{"text": "#ifndef RNDCMP_INCLUDE_ESN_HPP_\n#define RNDCMP_INCLUDE_ESN_HPP_\n\n#include <random>\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n#include <Eigen/SVD>\n#include <Eigen/QR>\n\n\nnamespace rndcmp {\n    template<typename DATA_TYPE>\n    class ESN {\n    public:\n        using ESNMatrix = Eigen::Matrix<DATA_TYPE, Eigen::Dynamic, Eigen::Dynamic>;\n\n        ESN(\n            size_t input_size,\n            size_t hidden_size,\n            size_t output_size,\n            double spectral_radius,\n            double sparsity,\n            double regularization,\n            size_t seed\n            ):\n            _input_size(input_size),\n            _hidden_size(hidden_size),\n            _output_size(output_size),\n            _regularization(regularization),\n            _seed(seed) {\n            W_in.resize(_hidden_size, _input_size);\n            W.resize(_hidden_size, _hidden_size);\n            W_out.resize(_output_size, _hidden_size);\n            \n            std::mt19937 rd(_seed);\n            std::uniform_real_distribution<double> generator(-0.5, 0.5);\n\n            initialize_weight_m(W_in, generator, rd, 0.0, hidden_size, input_size);\n            initialize_weight_m(W, generator, rd, sparsity, hidden_size, hidden_size);\n            initialize_weight_m(W_out, generator, rd, 0.0, output_size, hidden_size);\n\n            rescale_weight_m(spectral_radius);\n        }\n\n        double fit(ESNMatrix inputs, ESNMatrix outputs) {\n            ESNMatrix states;\n            states.resize(inputs.rows(), _hidden_size);\n            states.setZero();\n\n            // Calculate hidden states\n            for (size_t i = 0; i < inputs.rows(); i++) {\n                if (i == 0) {\n                    ESNMatrix initial;\n                    initial.resize(1, _hidden_size);\n                    initial.setZero();\n                    states.row(i) = update(initial.transpose(), inputs.row(i).transpose()).transpose();\n                    \n                } else {\n                    states.row(i) = update(states.row(i - 1).transpose(), inputs.row(i).transpose()).transpose();\n                }\n            }\n\n            // Find optimal matrix (we do it in double for numerical stability of fixed and other types)\n            Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> states_d = states.template cast<double>();\n            Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> states_square_d = states_d.transpose() * states_d;\n            \n            for (size_t i = 0; i < states_square_d.rows(); i++) {\n                states_square_d(i, i) += _regularization;\n            }\n            Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> pinv_d = states_square_d.completeOrthogonalDecomposition().pseudoInverse();\n            Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> W_out_d = (pinv_d * states_d.transpose() * outputs.template cast<double>()).transpose();\n            // ESNMatrix pinv = pinv_d.template cast<DATA_TYPE>();\n            // W_out = (pinv * states.transpose() * outputs).transpose();\n            W_out = W_out_d.template cast<DATA_TYPE>();\n\n            // Train prediction\n            double pred = error(states * W_out.transpose(), outputs);\n            return pred;\n        }\n\n        ESNMatrix predict(ESNMatrix inputs, size_t n_future) {\n            size_t n_samples = inputs.rows();\n            ESNMatrix outputs;\n            outputs.resize(n_samples + n_future, _output_size);\n            outputs.setZero();\n\n            ESNMatrix prev;\n            prev.resize(1, _hidden_size);\n            prev.setZero();\n\n            for (size_t i = 0; i < n_samples; i++) {\n                ESNMatrix temp_state =\n                 update(prev.transpose(), inputs.row(i).transpose()).transpose();\n                outputs.row(i) = temp_state * W_out.transpose();\n                prev = temp_state;\n            }\n\n            for (size_t i = 0; i < n_future; i++) {\n                size_t idx = n_samples + i;\n                \n                ESNMatrix input = outputs.row(idx - 1);\n                ESNMatrix temp_state =\n                 update(prev.transpose(), input.transpose()).transpose();\n\n                outputs.row(idx) = temp_state * W_out.transpose();\n                prev = temp_state;\n            }\n            return outputs;\n        }\n\n        ESNMatrix predict(ESNMatrix inputs) {\n            return predict(inputs, 0);\n        }\n\n        double score(ESNMatrix x, ESNMatrix y) {\n            ESNMatrix y_pred = predict(x);\n            return error(y, y_pred);\n        }\n\n        double error(ESNMatrix y, ESNMatrix y_pred) {\n            Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> error_m = (y - y_pred).template cast<double>();\n            return sqrt((error_m.array() * error_m.array()).matrix().rowwise().sum().mean());\n        }\n\n    protected:\n        ESNMatrix update(ESNMatrix state, ESNMatrix input_vector) {\n            ESNMatrix preactivation = W * state.matrix() + W_in * input_vector.matrix();\n            return preactivation.array().tanh();\n        }\n\n        void initialize_weight_m(ESNMatrix& m, \n                                 std::uniform_real_distribution<double> generator, \n                                 std::mt19937 rd, \n                                 double sparsity,\n                                 size_t first_size,\n                                 size_t second_size) {\n            std::mt19937 random_device(_seed);\n            std::uniform_real_distribution<double> probability_gen(0.0, 1.0);\n\n            for (size_t i = 0; i < first_size; i++) {\n                for (size_t j = 0; j < second_size; j++) {\n                    if (probability_gen(random_device) < sparsity) {\n                        m(i, j) = DATA_TYPE(0.0);\n                    } else {\n                        m(i, j) = DATA_TYPE(generator(rd));\n                    }\n                }\n            }\n        }\n\n        void rescale_weight_m(double spectral_radius) {\n            Eigen::EigenSolver<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>> solver(W.template cast<double>());\n            Eigen::VectorXcd eivals = solver.eigenvalues();\n\n            double real_sr = 0.0;\n            for (size_t i = 0; i < eivals.size(); i++) {\n                double temp = sqrt(pow(eivals[i].real(), 2) + pow(eivals[i].imag(), 2));\n                if (temp > real_sr) {\n                    real_sr = temp;\n                }\n            }\n\n            W /= (real_sr / spectral_radius);\n        }\n\n        size_t _seed;\n\n        Eigen::Matrix<DATA_TYPE, Eigen::Dynamic, Eigen::Dynamic> W_in;\n        Eigen::Matrix<DATA_TYPE, Eigen::Dynamic, Eigen::Dynamic> W;\n        Eigen::Matrix<DATA_TYPE, Eigen::Dynamic, Eigen::Dynamic> W_out;\n\n        size_t _input_size;\n        size_t _hidden_size;\n        size_t _output_size;\n        double _regularization;\n    };\n}\n\n#endif  // RNDCMP_INCLUDE_ESN_HPP_\n", "meta": {"hexsha": "7fd1db3787952306715e4faff05e3ef0a9a8b43c", "size": 6850, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/esn.hpp", "max_stars_repo_name": "Xenobyte42/rndcmp_stochastic_emulator", "max_stars_repo_head_hexsha": "9cbf7844a41f100456ef0db603182fd31d99da92", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-05-06T08:33:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-14T21:28:53.000Z", "max_issues_repo_path": "include/esn.hpp", "max_issues_repo_name": "Xenobyte42/rndcmp_stochastic_emulator", "max_issues_repo_head_hexsha": "9cbf7844a41f100456ef0db603182fd31d99da92", "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": "include/esn.hpp", "max_forks_repo_name": "Xenobyte42/rndcmp_stochastic_emulator", "max_forks_repo_head_hexsha": "9cbf7844a41f100456ef0db603182fd31d99da92", "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.0555555556, "max_line_length": 154, "alphanum_fraction": 0.5394160584, "num_tokens": 1486, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109798251323, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.7335685350528924}}
{"text": "/**\n * @file    map_stats.hpp\n * @author  Chirag Jain <cjain7@gatech.edu>\n */\n\n#ifndef MAP_STATS_HPP \n#define MAP_STATS_HPP\n\n#include <vector>\n#include <algorithm>\n#include <deque>\n#include <cmath>\n\n#ifdef USE_BOOST\n    #include <boost/math/distributions/binomial.hpp>\n    using namespace::boost::math;\n#else\n    #include <gsl/gsl_cdf.h>\n#endif\n\n//Own includes\n#include \"map/include/base_types.hpp\"\n#include \"map/include/map_parameters.hpp\"\n\n//External includes\n#include \"common/murmur3.h\"\n#include \"common/kseq.h\"\n#include \"common/prettyprint.hpp\"\n\nnamespace skch\n{\n  /**\n   * @namespace skch::Stat\n   * @brief     Implements utility functions that involve statistical computation\n   */\n  namespace Stat\n  {\n    /**\n     * @brief         jaccard estimate to mash distance\n     * @param[in] j   jaccard estimate\n     * @param[in] k   kmer size \n     * @return        mash distance [0.0 - 1.0]\n     */\n    inline float j2md(float j, int k)\n    {\n      if(j == 0)\n        return 1.0; //jaccard estimate 0 -> 1.0 mash distance\n\n      if(j == 1)\n        return 0.0; //jaccard estimate 1 -> 0.0 mash distance\n\n      float mash_dist = (-1.0 / k) * log(2.0 * j/(1+j) );\n      return mash_dist;\n    }\n\n    /**\n     * @brief         mash distance to jaccard estimate\n     * @param[in] d   mash distance [0.0 - 1.0]\n     * @param[in] k   kmer size \n     * @return        jaccard estimate \n     */\n    inline float md2j(float d, int k)\n    {\n      float jaccard = 1.0 / (2.0 * exp( k*d ) - 1.0);\n      return jaccard;\n    }\n\n    /**\n     * @brief               Given a distance d, compute the lower bound on d within required confidence interval \n     * @details             If a given match has distance d in the L2 stage, we compare its lower distance bound \n     *                      against the assumed cutoff to decide its significance. This makes the mapping algorithm\n     *                      more sensitive to true alignments\n     * @param[in]   d       calculated mash distance\n     * @param[in]   s       sketch size\n     * @param[in]   k       kmer size\n     * @param[in]   ci      confidence interval [0-1], example 0.9 implies 90% confidence interval\n     * @return              computed lower bound on d within 'ci' confidence interval\n     */\n    inline float md_lower_bound(float d, int s, int k, float ci)\n    {\n      //One side interval probability\n      float q2 = (1.0 - ci)/2;\n\n      //Computing count of sketches using confidence interval\n#ifdef USE_BOOST\n      \n      //Inverse binomial \n      int x = quantile(complement(binomial(s, md2j(d,k)), q2));\n\n#else   \n      //GSL \n      int x = std::max( int(ceil(s * md2j(d,k))), 1 );    //Begin search from jaccard * s\n      while(x <= s)\n      {\n        //probability of having x or more shared sketches\n        double cdf_complement = gsl_cdf_binomial_Q(x-1, md2j(d,k), s);\n\n        if (cdf_complement < q2)\n        {\n          x--;  //Last guess was right\n          break;\n        }\n\n        x++;\n      }\n#endif\n\n      float jaccard = float(x) / s;\n      float low_d = j2md(jaccard, k);\n      return low_d; \n    }\n\n    /**\n     * @brief                 Estimate minimum number of shared sketches to achieve the desired identity\n     * @param[in] s           sketch size\n     * @param[in] k           kmer size\n     * @param[in] identity    percentage identity [0-1]\n     * @return                minimum count of hits\n     */\n    inline int estimateMinimumHits(int s, int k, float perc_identity)\n    {\n      //Compute the estimate\n      float mash_dist = 1.0 - perc_identity;\n      float jaccard = md2j(mash_dist, k);\n\n      //function to convert jaccard to min hits\n      //Atleast these many minimizers should match for achieving the required jaccard identity\n      int minimumSharedMinimizers = ceil (1.0 * s * jaccard); \n\n      return minimumSharedMinimizers;\n    }\n\n    /**\n     * @brief                 Estimate minimum number of shared sketches \n     *                        s.t. upper bound identity is >= desired identity\n     *                        Upper bound is computed using the 90% confidence interval\n     * @param[in] s           sketch size\n     * @param[in] k           kmer size\n     * @param[in] identity    percentage identity [0-1]\n     * @return                count of min. shared minimizers\n     */\n    inline int estimateMinimumHitsRelaxed(int s, int k, float perc_identity, float confidence_interval)\n    {\n      // The desired value has be between [0, min  s.t. identity >= perc_identity]\n      auto searchRange = std::pair<int, int>( estimateMinimumHits(s, k, perc_identity) , 0);\n\n      int minimumSharedMinimizers_relaxed = searchRange.first;\n\n      for(int i = searchRange.first ; i >= searchRange.second; i--)\n      {\n        float jaccard = 1.0 * i/s;\n        float d = j2md(jaccard, k);\n\n        float d_lower = md_lower_bound(d, s, k, confidence_interval);\n\n        //Upper bound identity\n        float id_upper = 1.0 - d_lower;\n\n        //Check if it satisfies the criteria\n        if(id_upper >= perc_identity)\n          minimumSharedMinimizers_relaxed = i;\n        else\n          break;    //Stop the search\n      }\n\n      return minimumSharedMinimizers_relaxed;\n    }\n\n    /**\n     * @brief                     calculate p-value for a given alignment identity, sketch size..\n     * @param[in] s               sketch size\n     * @param[in] k               kmer size\n     * @param[in] alphabetSize    alphabet size\n     * @param[in] identity        mapping identity cut-off\n     * @param[in] lengthQuery     query length\n     * @param[in] lengthReference reference length\n     * @return                    p-value\n     */\n    inline double estimate_pvalue (int s, int k, int alphabetSize, \n        float identity,\n        int64_t lengthQuery, uint64_t lengthReference, float confidence_interval)\n    {\n      //total space size of k-mers\n      double kmerSpace = pow(alphabetSize, k);\n\n      //probability of a kmer match by random in |query| sized sequence \n      double pX, pY; \n      pX = pY = 1. / (1. + kmerSpace / lengthQuery);\n\n      //Jaccard similarity of two random given sequences\n      double r = pX * pY / (pX + pY - pX * pY);\n\n      int x = estimateMinimumHitsRelaxed(s, k, identity, confidence_interval);\n\n      //P (x or more minimizers match)\n      double cdf_complement;\n      if(x == 0)\n      {\n        cdf_complement = 1.0;\n      }\n      else\n      {\n#ifdef USE_BOOST\n      cdf_complement = cdf(complement(binomial(s, r), x-1));\n#else\n      cdf_complement =  gsl_cdf_binomial_Q(x-1, r, s);\n#endif\n      }\n\n      double pVal = lengthReference * cdf_complement;\n\n      return pVal;\n    }\n\n    /**\n     * @brief                       calculate minimum window size for sketching that satisfies\n     *                              the given p-value threshold\n     * @param[in] pValue_cutoff     cut off p-value threshold\n     * @param[in] confidence_interval confidence interval to relax jaccard cutoff for mapping\n     * @param[in] k                 kmer size\n     * @param[in] alphabetSize      alphabet size\n     * @param[in] identity          mapping identity cut-off\n     * @param[in] segmentLength     mashmap's internal minimum query sequence length\n     * @param[in] lengthReference   reference length\n     * @return                      optimal window size for sketching\n     */\n    inline int64_t recommendedWindowSize(double pValue_cutoff, float confidence_interval,\n        int k, int alphabetSize,\n        float identity,\n        int64_t segmentLength, uint64_t lengthReference)\n    {\n        int64_t lengthQuery = segmentLength;\n\n      int optimalSketchSize;\n      for (optimalSketchSize = 10; optimalSketchSize < lengthQuery; optimalSketchSize += 50) {\n        //Compute pvalue\n        double pVal = estimate_pvalue(optimalSketchSize, k, alphabetSize, identity, lengthQuery, lengthReference, confidence_interval);\n\n        //Check if pvalue is <= cutoff\n        if(pVal <= pValue_cutoff)\n        {\n          break;\n        }\n      }\n\n      int64_t w =  (2.0 * lengthQuery)/optimalSketchSize;\n\n      // 1 <= w <= lengthQuery\n      return std::min(std::max(w,(int64_t)1), lengthQuery);\n    }\n  }\n}\n\n#endif\n", "meta": {"hexsha": "411f8080c194f28d9cc2a8a1f5614fdc78915dda", "size": 8141, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/map/include/map_stats.hpp", "max_stars_repo_name": "mu94-csl/wfmash", "max_stars_repo_head_hexsha": "98e26fcdfec6a98fe4d0528240a8f5d957604505", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 83.0, "max_stars_repo_stars_event_min_datetime": "2020-09-12T09:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T04:29:46.000Z", "max_issues_repo_path": "src/map/include/map_stats.hpp", "max_issues_repo_name": "mu94-csl/wfmash", "max_issues_repo_head_hexsha": "98e26fcdfec6a98fe4d0528240a8f5d957604505", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 39.0, "max_issues_repo_issues_event_min_datetime": "2020-09-16T18:21:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T17:17:45.000Z", "max_forks_repo_path": "src/map/include/map_stats.hpp", "max_forks_repo_name": "mu94-csl/wfmash", "max_forks_repo_head_hexsha": "98e26fcdfec6a98fe4d0528240a8f5d957604505", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2020-09-25T01:29:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T01:46:58.000Z", "avg_line_length": 31.9254901961, "max_line_length": 135, "alphanum_fraction": 0.5919420219, "num_tokens": 2074, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.921921841290738, "lm_q2_score": 0.7956581049086031, "lm_q1q2_score": 0.7335345851152385}}
{"text": "#include <Eigen/Dense>\n#include <cmath>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <string>\n\n// Print Funktion zur Vereinfachung a l\u00e1 python\ntemplate <typename T>\nvoid print(T x) {\n    std::cout << x << std::endl;\n}\n\n// Bisection Verfahren Analog zu Blatt 5 nur mit Vektoren\nEigen::Vector2d bisection(double function(Eigen::Vector2d), Eigen::Vector2d x0, Eigen::Vector2d gradient) {\n    // print(\"Start bisection method.\");\n    double a, b, c;\n\n    a = 0;\n    b = 10;\n    c = 100;\n    int iterator = 0;\n    while ((function(x0 + a * gradient) < function(x0 + b * gradient)) & (iterator < 100)) {\n        a--;\n        iterator++;\n    }\n    iterator = 0;\n    // print(\"Find a. Iterations:\");\n    // print(iterator);\n    while ((function(x0 + c * gradient) < function(x0 + b * gradient)) & (iterator < 100)) {\n        c++;\n        iterator++;\n    }\n    // print(\"Find c. Iterations:\");\n    // print(iterator);\n\n    if ((a < b) & (b < c) & (function(x0 + b * gradient) < function(x0 + a * gradient)) & (function(x0 + b * gradient) < function(x0 + c * gradient))) {\n        int iteration = 0;\n        do {\n            iteration++;\n            if (abs(b - a) > abs(c - b)) {\n                double a_new = a;\n                double b_new = (a + b) / 2;\n                double c_new = b;\n                if (function(x0 + b_new * gradient) < function(x0 + c_new * gradient)) {\n                    a = a_new;\n                    b = b_new;\n                    c = c_new;\n                } else {\n                    a = b_new;\n                    b = c_new;\n                    c = c;\n                }\n            } else {\n                double a_new = b;\n                double b_new = (b + c) / 2;\n                double c_new = c;\n                if (function(x0 + b_new * gradient) < function(x0 + a_new * gradient)) {\n                    a = a_new;\n                    b = b_new;\n                    c = c_new;\n                } else {\n                    a = a;\n                    b = a_new;\n                    c = b_new;\n                }\n            }\n        } while ((abs(a - c) > 1e-9) & (iteration < 100));\n        // print(\"Iterations: \");\n        // print(iteration);\n        // print(\"a - c = \");\n        // print(abs(a - c));\n    } else {\n        print(\"First requirement of bisection is not fullfiled.\");\n    }\n    Eigen::Vector2d x_min = x0 + a * gradient;\n    // print(\"x_min after Bisection.\");\n    // print(x_min);\n    return x_min;\n}\n\n// BFGS Algorithmus\nEigen::Vector2d calc_BFGS(double function(Eigen::Vector2d), Eigen::Vector2d gradient(Eigen::Vector2d), Eigen::Vector2d x0, Eigen::Matrix2d C0, double epsilon, std::string filename) {\n    // Definiere alle n\u00f6tigen Objekte, x_k = x_k1, x_(k-1)= x_k0, b analog\n    Eigen::Vector2d x_k0, x_k1, b_k0, b_k1, x_min, s, y;\n    // Neue C Matrix, C1\n    Eigen::Matrix2d C1;\n    // Iterator um Schritte zu z\u00e4hlen\n    double rho, iterator;\n    iterator = 0;\n    // Analog zu Skript. Bestimme b_0, mit bisections-Verfahren x1 und damit b1\n    x_k0 = x0;\n    b_k0 = gradient(x_k0);\n    x_k1 = bisection(function, x_k0, b_k0);\n    b_k1 = gradient(x_k1);\n    // Speichere x_k in Datei\n    std::ofstream output;\n    output.open(filename, std::ofstream::trunc);  // std::ofstream::trunc);\n    // Starte Iteration: Bestimmte s, y Vektoren und dann C1, anschlie\u00dfend nach Skript das neue x_k\n    do {\n        s = x_k1 - x_k0;\n        y = b_k1 - b_k0;\n        rho = 1. / (s.transpose() * y);\n        C1 = (Eigen::Matrix2d::Identity() - rho * s * y.transpose()) * C0 * (Eigen::Matrix2d::Identity() - rho * y * s.transpose()) + rho * s * s.transpose();\n        x_k0 = x_k1;\n        C0 = C1;\n        b_k0 = b_k1;\n\n        x_k1 = x_k0 - C0 * b_k0;\n        b_k1 = gradient(x_k1);\n        iterator++;\n        output << std::setprecision(8) << x_k1(0) << \" \" << x_k1(1) << std::endl;\n        // Solange die Norm des Gradienten gr\u00f6\u00dfer als epsilon ist oder bis eine gewisse Anzahl an Iterationen durchgelaufen ist.\n    } while ((b_k1.norm() > epsilon) & (iterator < 1000));\n    output.close();\n    print(\"Iterations of BFGS:\");\n    print(iterator);\n    x_min = x_k1;\n    // Gib Minimum (1,1) zur\u00fcck\n    return x_min;\n}\n\n// 1. C0 Matrix Variante: Inverse Hesse-Matrix\nEigen::Matrix2d inv_HesseC_a(Eigen::Vector2d x) {\n    Eigen::Matrix2d Hesse_C;\n    Hesse_C(0, 0) = 2 - 400 * (x(1) - pow(x(0), 2.)) + 800 * pow(x(0), 2.);  // f_x1_x1\n    Hesse_C(0, 1) = -400 * x(0);                                             // f_x1_x2\n    Hesse_C(1, 0) = -400 * x(0);                                             // f_x2_x1\n    Hesse_C(1, 1) = 200 * x(1);                                              // f_x2_x2\n    return Hesse_C.inverse();\n}\n\n// 2. C0 Matrix Variante: inverse diag. Hesse-Matrix\nEigen::Matrix2d inv_HesseC_b(Eigen::Vector2d x) {\n    Eigen::Matrix2d Hesse_C;\n    Hesse_C(0, 0) = 2 - 400 * (x(1) - pow(x(0), 2.)) + 800 * pow(x(0), 2.);  // f_x1_x1\n    Hesse_C(0, 1) = 0;                                                       // f_x1_x2\n    Hesse_C(1, 0) = 0;                                                       // f_x2_x1\n    Hesse_C(1, 1) = 200 * x(1);                                              //\n    return Hesse_C.inverse();\n}\n\n// 3. C0 Matrix Variante: f(x_0) * identity\nEigen::Matrix2d inv_HesseC_c(Eigen::Vector2d x, double function(Eigen::Vector2d)) {\n    Eigen::Matrix2d identity = Eigen::Matrix2d::Identity(2, 2);\n    return function(x) * identity;\n}\n\n// Rosenbrock Funktion zu Aufgabe 1\ndouble function_1(Eigen::Vector2d x) {\n    return pow(1 - x(0), 2.) + 100 * pow(x(1) - pow(x(0), 2.), 2);\n}\n\n// Gradient zur Aufgabe 1\nEigen::Vector2d gradient_1(Eigen::Vector2d x) {\n    Eigen::Vector2d g(2);\n    g(0) = -2 * (1 - x(0)) - 400 * x(0) * (x(1) - pow(x(0), 2.));\n    g(1) = 200 * (x(1) - pow(x(0), 2.));\n    return g;\n}\n\n// double calc_RungeKutta(double y_prime(double, double), double t, double y_n, double h){\n//     double k_1 = h* y_prime(t, y_n);\n//     double k_2 = h* y_prime(t+ h/2., y_n + 0.5*k_1);\n//     double k_3 = h* y_prime(t+h/2., y_n + 0.5*k_2);\n//     double k_4 = h* y_prime(t+h, y_n + k_3);\n//     double y_n_1 = y_n + 1./6. * (k_1 + 2* k_2 + 2*k_3 + k_4);\n//     return y_n_1;\n// }\n\nint main() {\n    // Nr. 1 Definiere Startvektor, Gradient und die C0 Matrix mit drei verschiedenen Varianten\n    Eigen::Vector2d x(2);\n    x << -1., -1.;\n    Eigen::Vector2d grad = gradient_1(x);\n    Eigen::Matrix2d C0_a = inv_HesseC_a(x);\n    Eigen::Matrix2d C0_b = inv_HesseC_b(x);\n    Eigen::Matrix2d C0_c = inv_HesseC_c(x, function_1);\n\n    // Berechne die Ergebnisse mit dem oben definierten BFGS-Algorithmus f\u00fcr die drei verschiedenen Methoden\n    print(\"1 a)\");\n    Eigen::Vector2d x_min_a = calc_BFGS(function_1, gradient_1, x, C0_a, 1e-5, \"output/output_a.txt\");\n    print(\"Result of BFGS:\");\n    print(x_min_a);\n    print(\"\");\n\n    print(\"1 b)\");\n    Eigen::Vector2d x_min_b = calc_BFGS(function_1, gradient_1, x, C0_b, 1e-5, \"output/output_b.txt\");\n    print(\"Result of BFGS:\");\n    print(x_min_b);\n    print(\"\");\n\n    print(\"1 c)\");\n    Eigen::Vector2d x_min_c = calc_BFGS(function_1, gradient_1, x, C0_c, 1e-5, \"output/output_c.txt\");\n    print(\"Result of BFGS:\");\n    print(x_min_c);\n    print(\"\");\n\n    return 0;\n}", "meta": {"hexsha": "73c5dc42bf9a13baba1158f9ca0f70b41ad36bef", "size": 7217, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Blatt7/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": "Blatt7/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": "Blatt7/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": 36.085, "max_line_length": 182, "alphanum_fraction": 0.5281973119, "num_tokens": 2325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086367, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.7335216347979663}}
{"text": "/**\n * @file test_cylinder.cpp\n * @author Bensuperpc (bensuperpc@gmail.com)\n * @brief \n * @version 1.0.0\n * @date 2021-04-01\n * \n * MIT License\n * \n */\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE cylinder\n\n#include <boost/test/unit_test.hpp>\n//#include <boost/multiprecision/cpp_int.hpp>\n// boost::multiprecision::uint1024_t i = 0;\n\n#include \"math/cylinder_imp.hpp\"\n\n/**\n * @brief Construct a new boost auto test case object\n * \n */\nBOOST_AUTO_TEST_CASE(test_cylinder_volume_1)\n{\n    BOOST_CHECK_MESSAGE(my::math::cylinder::cylinderVolume<uint64_t>(1000, 5) == static_cast<uint64_t>(15707963),\n        my::math::cylinder::cylinderVolume<uint64_t>(1000, 5) << \" instead: \" << static_cast<uint64_t>(15707963));\n\n    BOOST_CHECK_MESSAGE(my::math::cylinder::cylinderVolume<uint64_t>(151, 10) == static_cast<uint64_t>(716314),\n        my::math::cylinder::cylinderVolume<uint64_t>(151, 10) << \" instead: \" << static_cast<uint64_t>(716314));\n    BOOST_CHECK_MESSAGE(my::math::cylinder::cylinderVolume<uint64_t>(0, 0) == static_cast<uint64_t>(0), my::math::cylinder::cylinderVolume<uint64_t>(0, 0)\n                                                                                                            << \" instead: \" << static_cast<uint64_t>(0));\n}\n\n/**\n * @brief Construct a new boost auto test case object\n * \n */\nBOOST_AUTO_TEST_CASE(test_cylinder_volume_2)\n{\n    BOOST_CHECK_MESSAGE(my::math::cylinder::cylinderVolume<int>(32, 3) == static_cast<int>(9650), my::math::cylinder::cylinderVolume<int>(32, 3)\n                                                                                                      << \" instead: \" << static_cast<int>(9650));\n    BOOST_CHECK_MESSAGE(my::math::cylinder::cylinderVolume<int>(151, 2) == static_cast<int>(143262), my::math::cylinder::cylinderVolume<int>(151, 2)\n                                                                                                         << \" instead: \" << static_cast<int>(143262));\n    BOOST_CHECK_MESSAGE(my::math::cylinder::cylinderVolume<int>(0, 0) == static_cast<int>(0), my::math::cylinder::cylinderVolume<int>(0, 0)\n                                                                                                  << \" instead: \" << static_cast<int>(0));\n}\n\nBOOST_AUTO_TEST_CASE(test_cylinder_surface_1)\n{\n    BOOST_CHECK_MESSAGE(my::math::cylinder::cylinderSurface<uint64_t>(10000, 9) == static_cast<uint64_t>(628884017),\n        my::math::cylinder::cylinderSurface<uint64_t>(10000, 9) << \" instead: \" << static_cast<uint64_t>(628884017));\n    BOOST_CHECK_MESSAGE(my::math::cylinder::cylinderSurface<uint64_t>(151, 6) == static_cast<uint64_t>(148955),\n        my::math::cylinder::cylinderSurface<uint64_t>(151, 6) << \" instead: \" << static_cast<uint64_t>(148955));\n    BOOST_CHECK_MESSAGE(my::math::cylinder::cylinderSurface<uint64_t>(0, 0) == static_cast<uint64_t>(0), my::math::cylinder::cylinderSurface<uint64_t>(0, 0)\n                                                                                                             << \" instead: \" << static_cast<uint64_t>(0));\n}\n\nBOOST_AUTO_TEST_CASE(test_cylinder_surface_2)\n{\n    BOOST_CHECK_MESSAGE(my::math::cylinder::cylinderSurface<int>(6598, 4) == static_cast<int>(273695526), my::math::cylinder::cylinderSurface<int>(6598, 4)\n                                                                                                              << \" instead: \" << static_cast<int>(273695526));\n    BOOST_CHECK_MESSAGE(my::math::cylinder::cylinderSurface<int>(151, 6) == static_cast<int>(148955), my::math::cylinder::cylinderSurface<int>(151, 6)\n                                                                                                          << \" instead: \" << static_cast<int>(148955));\n    BOOST_CHECK_MESSAGE(my::math::cylinder::cylinderSurface<int>(0, 0) == static_cast<int>(0), my::math::cylinder::cylinderSurface<int>(0, 0)\n                                                                                                   << \" instead: \" << static_cast<int>(0));\n}\n", "meta": {"hexsha": "92b03b29245e1f5ac2d185d03312108a1638b90a", "size": 4016, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/math/test_cylinder.cpp", "max_stars_repo_name": "Bensuperpc/BenLib", "max_stars_repo_head_hexsha": "1708a27e272a54f437cda50b2ca98ed92f03d721", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-12-02T21:17:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-24T19:57:42.000Z", "max_issues_repo_path": "src/test/math/test_cylinder.cpp", "max_issues_repo_name": "bensuperpc/BenLib", "max_issues_repo_head_hexsha": "1708a27e272a54f437cda50b2ca98ed92f03d721", "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/test/math/test_cylinder.cpp", "max_forks_repo_name": "bensuperpc/BenLib", "max_forks_repo_head_hexsha": "1708a27e272a54f437cda50b2ca98ed92f03d721", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-28T08:43:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-28T08:43:46.000Z", "avg_line_length": 59.0588235294, "max_line_length": 158, "alphanum_fraction": 0.5597609562, "num_tokens": 976, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096067182449, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.7335216307855669}}
{"text": "// Unit test for the isEqualArray1D function in testing_functions.cpp\n// This function determines if each element in two 1D arrays are equal within some tolerance\n// This is important because there is inherent error in double precision numbers\n// COMPLETE. This function works as intended. 2021/11/16\n\n\n// Include headers\n#include <iostream>\n#include <Eigen/Dense>\n#include \"../main/fvm_1D_functions.h\" \n#include \"../main/testing_functions.h\" \n\nusing namespace std;\nusing namespace Eigen;\n\nint main() {\n\n    // Print what we are doing\n    cout << \"------------------------------------- \" << \\\n    \"This is a test of the isEqualArray1D function.\" << \\\n    \" -------------------------------------\" << endl;    \n\n    // Set a tolerance\n    double TOL = 1e-10;\n\n    // Set an array of values\n    ArrayXd vals(4);\n    vals.setConstant(1.1);        \n\n    // We can test 4 different modes of this function to determine how well it works:\n    // Greater and within tolerance\n    // Greater and outside tolerance\n    // Lower and within tolerance\n    // Lower and outside tolerance\n\n    // Build the test array\n    ArrayXd testArray(4);\n    testArray(0) = vals(0) + 0.1*TOL;\n    testArray(1) = vals(1) + 1.1*TOL;\n    testArray(2) = vals(2) - 0.1*TOL;\n    testArray(3) = vals(3) - 1.1*TOL;\n\n    // Use the isEqualArray1D function to see if these are equal.\n    Array<bool,Dynamic,1> boolArray = isEqualArray1D(vals, testArray, TOL);\n\n    // First, we will test to make sure that val+0.1*TOL is considered equal since it will by definition be within the tolerance\n    // This should result in 1\n    if (boolArray(0) == 1) {  // \n        cout << \"Test of higher but within tolerance is a success.\" << endl;\n    } \n    else {\n        cout << \"!!!!!!!!!!!!!!!!!!!!!!!!!!\" << endl \\\n        << \"Test of higher but within tolerance is a failure.\" << endl \\\n        << \"!!!!!!!!!!!!!!!!!!!!!!!!!!\" << endl;\n    }\n\n    // Test to make sure that val+1.1*TOL is not considered equal since it will by definition be outside the tolerance\n    // This should result in 0\n    if (boolArray(1) == 0) {  // \n        cout << \"Test of higher over tolerance is a success.\" << endl;\n    } \n    else {        \n        cout << \"!!!!!!!!!!!!!!!!!!!!!!!!!!\" << endl \\\n        << \"Test of higher over tolerance is a failure.\" << endl \\\n        << \"!!!!!!!!!!!!!!!!!!!!!!!!!!\" << endl;\n    }   \n\n    // Test to make sure that val-0.1*TOL is considered equal since it will by definition be within the tolerance\n    // This should result in 1\n    if (boolArray(2) == 1) {  // \n        cout << \"Test of lower but within tolerance is a success.\" << endl;\n    } \n    else {\n        cout << \"!!!!!!!!!!!!!!!!!!!!!!!!!!\" << endl \\\n        << \"Test of lower but within tolerance is a failure.\" << endl \\\n        << \"!!!!!!!!!!!!!!!!!!!!!!!!!!\" << endl;\n    } \n\n    // Test to make sure that val-1.1*TOL is not considered equal since it will by definition be outside the tolerance\n    // This should result in 0\n    if (boolArray(3) == 0) {  // \n        cout << \"Test of lower but outside tolerance is a success.\" << endl;\n    } \n    else {\n        cout << \"!!!!!!!!!!!!!!!!!!!!!!!!!!\" << endl \\\n        << \"Test of lower but outside tolerance is a failure.\" << endl \\\n        << \"!!!!!!!!!!!!!!!!!!!!!!!!!!\" << endl;\n    } \n\n    cout << endl << endl;\n}", "meta": {"hexsha": "6bf1e1c5a391f2e230eaa9893102292c541e3b3e", "size": 3307, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "FVM_1D/unitTests/test_isEqualArray1D.cpp", "max_stars_repo_name": "Aquadorf/computational-skolar", "max_stars_repo_head_hexsha": "77ebab70fe22a9e48b7d187b965781fe941e3ae1", "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": "FVM_1D/unitTests/test_isEqualArray1D.cpp", "max_issues_repo_name": "Aquadorf/computational-skolar", "max_issues_repo_head_hexsha": "77ebab70fe22a9e48b7d187b965781fe941e3ae1", "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": "FVM_1D/unitTests/test_isEqualArray1D.cpp", "max_forks_repo_name": "Aquadorf/computational-skolar", "max_forks_repo_head_hexsha": "77ebab70fe22a9e48b7d187b965781fe941e3ae1", "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.3406593407, "max_line_length": 128, "alphanum_fraction": 0.5527668582, "num_tokens": 852, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267118111485244, "lm_q2_score": 0.8872046011730965, "lm_q1q2_score": 0.7334625226951149}}
{"text": "/*\n * useG2O.cpp\n * Copyright (C) 2018 exbot <exbot@ubuntu>\n *\n * Distributed under terms of the MIT license.\n */\n\n#include <iostream>\n#include <g2o/core/base_vertex.h>\n#include <g2o/core/base_unary_edge.h>\n#include <g2o/core/block_solver.h>\n#include <g2o/core/optimization_algorithm_levenberg.h>\n#include <g2o/core/optimization_algorithm_gauss_newton.h>\n#include <g2o/core/optimization_algorithm_dogleg.h>\n#include <g2o/solvers/dense/linear_solver_dense.h>\n#include <Eigen/Core>\n#include <opencv2/core/core.hpp>\n#include <cmath>\n#include <chrono>\n\nusing namespace std;\n\nclass CurveFittingVertex: public g2o::BaseVertex<3, Eigen::Vector3d>{\npublic:\n\tEIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\tvirtual void setToOriginImpl()\n\t{\n\t\t_estimate << 0,0,0;\n\t}\n\tvirtual void oplusImpl (const double* update)\n\t{\n\t\t_estimate += Eigen::Vector3d(update);\n\t}\n\tvirtual bool read( istream& in ){}\n\tvirtual bool write( ostream& out ) const {}\n};\n\nclass CurveFittingEdge: public g2o::BaseUnaryEdge<1, double, CurveFittingVertex>\n{\npublic:\n\tEIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\tCurveFittingEdge(double x):BaseUnaryEdge(), _x(x){}\n\tvoid computeError()\n\t{\n\t\tconst CurveFittingVertex* v = static_cast<const CurveFittingVertex*>(_vertices[0]);\n\t\tconst Eigen::Vector3d abc = v->estimate();\n\t\t_error(0,0) = _measurement - std::exp( abc(0,0)*_x*_x+abc(1,0)*_x+abc(2,0) );\n\t}\n\tvirtual bool read( istream& in ){}\n\tvirtual bool write( ostream& out) const {}\n\tdouble _x;\n};\n\nint main(int argc, char **argv){\n\tdouble a = 1.0, b = 2.0, c = 1.0;\n\tint N = 100;\n\tdouble w_sigma = 1.0;\n\tcv::RNG rng;\n\n\tdouble abc[3] = {0, 0, 0};\n\n\tvector<double> x_data, y_data;\n\n\tcout << \"Generating Data: \" << endl;\n\tfor(int i = 0; i < N; i++)\n\t{\n\t\tdouble x = i/100.0;\n\t\tx_data.push_back(x);\n\t\ty_data.push_back(\n\t\t\t\texp(a*x*x + b*x + c) + rng.gaussian(w_sigma));\n\t\tcout << x_data[i] << \" \" << y_data[i] << endl;\n\t}\n\n\ttypedef g2o::BlockSolver< g2o::BlockSolverTraits<3,1> > Block;\n\tBlock::LinearSolverType* linearSolver = new g2o::LinearSolverDense<Block::PoseMatrixType>();\n\tBlock *solver_ptr = new Block(linearSolver);\n\tg2o::OptimizationAlgorithmLevenberg *solver = new g2o::OptimizationAlgorithmLevenberg(solver_ptr);\n\tg2o::SparseOptimizer optimizer;\n\toptimizer.setAlgorithm(solver);\n\toptimizer.setVerbose(true);\n\n\tCurveFittingVertex *v = new CurveFittingVertex();\n\tv->setEstimate(Eigen::Vector3d(0, 0, 0));\n\tv->setId(0);\n\toptimizer.addVertex(v);\n\t\n\tfor(int i = 0; i < N; i++)\n\t{\n\t\tCurveFittingEdge *edge = new CurveFittingEdge(x_data[i]);\n\t\tedge->setId(i);\t\n\t\tedge->setVertex(0, v);\n\t\tedge->setMeasurement( y_data[i]);\n\t\tedge->setInformation( Eigen::Matrix<double, 1, 1>::Identity()*1/(w_sigma*w_sigma) );\n\t\toptimizer.addEdge(edge);\n\t}\n\n\tcout << \"Start\" << endl;\n\tchrono::steady_clock::time_point t1 = chrono::steady_clock::now();\n\toptimizer.initializeOptimization();\n\toptimizer.optimize(100);\n\tchrono::steady_clock::time_point t2 = chrono::steady_clock::now();\n\tchrono::duration<double> time_used = chrono::duration_cast<chrono::duration<double>>(t2 - t1);  \n\tcout << \"time cost:\" << time_used.count() << endl;\n\n\tEigen::Vector3d abc_estimate = v->estimate();\n\tcout << \"estimated model :\" << abc_estimate.transpose() << endl;\n\nreturn 1;\n}\n\n", "meta": {"hexsha": "b8c531cae7437535862bf06714569b5fc868aabe", "size": 3178, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "slam/PA2_code/useG2O.cpp", "max_stars_repo_name": "wallEVA96/algorithm", "max_stars_repo_head_hexsha": "c64e50eff9ad928015ce2780086dd9682c8e2220", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2018-12-27T05:44:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T03:36:15.000Z", "max_issues_repo_path": "slam/PA2_code/useG2O.cpp", "max_issues_repo_name": "wallEVA96/algorithm", "max_issues_repo_head_hexsha": "c64e50eff9ad928015ce2780086dd9682c8e2220", "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": "slam/PA2_code/useG2O.cpp", "max_forks_repo_name": "wallEVA96/algorithm", "max_forks_repo_head_hexsha": "c64e50eff9ad928015ce2780086dd9682c8e2220", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2020-04-23T02:01:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-28T02:55:16.000Z", "avg_line_length": 28.6306306306, "max_line_length": 99, "alphanum_fraction": 0.704845815, "num_tokens": 965, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045817875223, "lm_q2_score": 0.8267117962054048, "lm_q1q2_score": 0.7334624934112275}}
{"text": "#include <iostream>\n#include <memory>\n#include <algorithm>\n#include <iomanip>\n#include <math.h>\n#include <cmath>\n#include <mgl2/mgl.h>\n#include <Eigen/Dense>\n\n#include <data.hpp>\n#include <particle.hpp>\n#include <gravitysolvers.hpp>\n#include <first_task.hpp>\n\nstd::unique_ptr<std::vector<Particle>> p(Data::readFromFile(\"data.ascii\"));\nstd::vector<Particle> particles = *p;\n\nfloat pMass = 0.0;\nfloat totalMass = 0.0;\nfloat radius = 0.0;\nfloat scaleLength = 0.0;\nfloat epsilon = 0.0; // softening\nfloat t_relax = 0.0;\nfloat r0 = std::numeric_limits<float>::max(); // center of system to avoid problems with dividing by 0\nfloat rhm = 0.0; // half mass radius\n\nfloat Mass(float r, bool strictlyLess = false)\n{\n  float M = 0.0;\n\n  for(Particle &p : particles) {\n    float r2 = p.radius2();\n\n    if((!strictlyLess && r2 <= r*r) || (strictlyLess && r2 < r*r)) {\n      M += p.m();\n    }\n  }\n\n  return M;\n}\n\nfloat density_hernquist(float r)\n{\n  return (totalMass / (2 * M_PI)) * (scaleLength / r) * (1 / std::pow(r + scaleLength, 3));\n}\n\n// Computes force F where F = m*a\nfloat force_hernquist(float r)\n{\n  // Assumption: G = 1\n  return -totalMass * pMass / ((r + scaleLength) * (r + scaleLength));\n}\n\nvoid calculate_constants()\n{\n  pMass = particles[0].m(); // all particles have the same mass\n\n  for(Particle &p : particles) {\n    totalMass += p.m();\n    radius = std::max(p.radius2(), radius);\n    r0 = std::min(p.radius2(), r0);\n  }\n\n  r0 = std::sqrt(r0) + std::numeric_limits<float>::epsilon();\n  radius = std::sqrt(radius);\n\n  float dr = radius / 100000;\n  for(float r = r0; r <= radius; r += dr) {\n    if(Mass(r) >= totalMass * 0.5) {\n      rhm = r;\n      break;\n    }\n  }\n\n  scaleLength = rhm / (1 + std::sqrt(2));\n\n  // https://en.wikipedia.org/wiki/Mean_inter-particle_distance\n  // after plugging in n = totalMass / (4/3*PI*r^3) in the formula most terms cancel out\n  epsilon = radius / std::pow(totalMass, 1.0/3.0);\n  t_relax = compute_relaxation();\n\n  // exact mean inter-particle separation\n  /*\n  epsilon = .0;\n\n  for(Particle &p : particles) {\n    for(Particle &q : particles) {\n      epsilon += (p.r() - q.r()).norm();\n    }\n  }\n\n  long n = particles.size();\n  epsilon /= (n*(n-1));\n  */\n\n  std::cout << \"First Task        \" << std::endl;\n  std::cout << \"------------------\" << std::endl;\n  std::cout << \"  pMass:          \" << pMass << std::endl;\n  std::cout << \"  totalMass:      \" << totalMass << std::endl;\n  std::cout << \"  radius:         \" << radius << std::endl;\n  std::cout << \"  r0:             \" << r0 << std::endl;\n  std::cout << \"  rhm:            \" << rhm << std::endl;\n  std::cout << \"  scaleLength:    \" << scaleLength << std::endl;\n  std::cout << \"  softening:      \" << epsilon << std::endl;\n  std::cout << \"  t_relax:        \" << t_relax << std::endl;\n  std::cout << \"------------------\" << std::endl;\n}\n\nfloat compute_relaxation()\n{\n  // Assumption: G = 1\n  float N = particles.size();\n  float vc = std::sqrt(totalMass * 0.5 / rhm);\n  float t_cross = rhm / vc;\n  float t_relax = N / (8 * std::log(N)) * t_cross;\n\n  return t_relax;\n}\n\nvoid step1()\n{\n  r0 = 0.005;\n  int numSteps = 50;\n\n  std::vector<float> hDensity;\n  std::vector<float> nDensity;\n  std::vector<float> rInput;\n  std::vector<float> errors;\n\n  // creates evenly spaced intervals on a log scale on the interval [r0, radius]\n  // drLinToLog(i) gives the start of the ith interval on [r0, radius]\n  auto drLinToLog = [&](int i) {\n    return r0 * std::pow(radius / r0, (float)i / (float)numSteps);\n  };\n\n  // transforms the numerical data into a dimension desirable for plotting\n  // here we want to avoid problems with 0 on log scales since log(0) is undefined\n  auto plotFit = [](float x) {\n    return x + std::numeric_limits<float>::epsilon();\n  };\n\n  for(int i = 0; i <= numSteps; i++) {\n      float r = drLinToLog(i);\n      float r1 = drLinToLog(i + 1);\n      float MShell = Mass(r1, true) - Mass(r, true);\n      float VShell = 4.0/3.0*M_PI*(r1*r1*r1 - r*r*r);\n\n      float nRho = MShell / VShell;\n      float numParticlesInShell = MShell / pMass;\n\n      // p = n*m/v, err = sqrt(n) =>\n      // p_err = sqrt(n)/n*p = sqrt(n)*n*m/(n*v) = sqrt(n)*m/v\n      // p = density, n = #particles, m = pMass\n      float rhoError = std::sqrt(numParticlesInShell) * pMass / VShell;\n\n      hDensity.push_back(plotFit(density_hernquist((r + r1) / 2)));\n      nDensity.push_back(plotFit(nRho));\n      errors.push_back(rhoError);\n      rInput.push_back(r);\n  }\n\n  mglData hData;\n  hData.Set(hDensity.data(), hDensity.size());\n\n  mglData nData;\n  nData.Set(nDensity.data(), nDensity.size());\n\n  mglData rData;\n  rData.Set(rInput.data(), rInput.size());\n\n  mglData eData;\n  eData.Set(errors.data(), errors.size());\n\n  mglGraph gr(0, 1200, 800);\n\n  float outMin = std::min(hData.Minimal(), nData.Minimal());\n  float outMax = std::max(hData.Maximal(), nData.Maximal());\n\n  gr.SetRange('x', rData);\n  gr.SetRange('y', outMin, outMax);\n\n  gr.SetFontSize(2);\n  gr.SetCoor(mglLogLog);\n  gr.Axis();\n\n  gr.Label('x', \"Radius [l]\", 0);\n  gr.Label('y', \"Density [m]/[l]^3\", 0);\n\n  gr.Plot(rData, hData, \"b\");\n  gr.AddLegend(\"Hernquist\", \"b\");\n\n  gr.Plot(rData, nData, \"r .\");\n  gr.AddLegend(\"Numeric\", \"r .\");\n\n  gr.Error(rData, nData, eData, \"qo\");\n  gr.AddLegend(\"Poissonian Error\", \"qo\");\n\n  gr.Legend();\n  gr.WritePNG(\"density_profiles.png\");\n}\n\nvoid step2()\n{\n  r0 = 0.005;\n  int numSteps = 100;\n\n  std::vector<float> softenings;\n  std::vector<float> dAnalytic;\n  std::vector<float> rInput;\n\n  // creates evenly spaced intervals on a log scale on the interval [r0, radius]\n  // drLinToLog(i) gives the start of the ith interval on [r0, radius]\n  auto drLinToLog = [&](int i) {\n    return r0 * std::pow(radius / r0, (float)i / (float)numSteps);\n  };\n\n  // transforms the numerical data into a dimension desirable for plotting\n  // here we want to plot the magnitude of the force and add a small nonzero\n  // number to the force to avoid problems with 0 on log scales since log(0) is undefined\n  auto plotFit = [](float x) {\n    return std::abs(x) + std::numeric_limits<float>::epsilon();\n  };\n\n  // calculate the analytical force in the hernquist model\n  for(int i = 0; i <= numSteps; i++) {\n    float r = drLinToLog(i);\n    dAnalytic.push_back(plotFit(force_hernquist(r)));\n    rInput.push_back(r);\n  }\n\n  std::unique_ptr<Gravitysolver::Direct> solver(new Gravitysolver::Direct());\n  std::vector<mglData> plotData;\n\n  for(int i = 1; i <= 7; i++) {\n    solver->readData(\"data/direct-nbody-\" + std::to_string(i) + \".txt\");\n    softenings.push_back(solver->softening());\n\n    std::vector<float> dNumeric;\n\n    // project the force vector of each particle towards the center of the system\n    const MatrixData &solverData = solver->data();\n    Eigen::VectorXf f_center(solverData.cols());\n\n    float fx, fy, fz, x, y, z, norm;\n\n    for(int i = 0; i < solverData.cols(); i++) {\n      x = solverData(1, i);\n      y = solverData(2, i);\n      z = solverData(3, i);\n      fx = solverData(7, i);\n      fy = solverData(8, i);\n      fz = solverData(9, i);\n\n      norm = std::sqrt(x*x + y*y + z*z);\n\n      // project the force vector onto the normalized sphere normal\n      f_center(i) = (x*fx + y*fy + z*fz) / norm;\n    }\n\n    for(int i = 0; i <= numSteps; i++) {\n      float r = drLinToLog(i);\n      float r1 = drLinToLog(i + 1);\n      float dr = r1 - r;\n\n      float f = 0.0;\n      int numParticles = 0;\n\n      // calculate the average gravitational force in a shell\n      for(int i = 0; i < particles.size(); i++) {\n        Particle p = particles[i];\n\n        if(r <= p.radius() && p.radius() < r1) {\n          f += f_center(i);\n          numParticles++;\n        }\n      }\n\n      f = (numParticles == 0 ? .0 : f / numParticles);\n      dNumeric.push_back(plotFit(f));\n    }\n\n    mglData cData;\n    cData.Set(dNumeric.data(), dNumeric.size());\n    plotData.push_back(cData);\n  }\n\n  mglData aData;\n  aData.Set(dAnalytic.data(), dAnalytic.size());\n\n  mglData rData;\n  rData.Set(rInput.data(), rInput.size());\n\n  mglGraph gr(0, 1200, 800);\n\n  float outMin;\n  float outMax;\n\n  for(int i = 0; i < plotData.size(); i++) {\n    outMin = std::max(std::min(plotData[i].Minimal(), aData.Minimal()), 50.0);\n    outMax = std::max(plotData[i].Maximal(), aData.Maximal());\n  }\n\n  gr.SetRange('x', rData);\n  gr.SetRange('y', outMin, outMax);\n\n  gr.SetFontSize(2);\n  gr.SetCoor(mglLogLog);\n  gr.Axis();\n\n  gr.Label('x', \"Radius [l]\", 0);\n  gr.Label('y', \"Force [m]^2[l]^{-2}\", 0);\n\n  gr.Plot(rData, aData, \"b\");\n  gr.AddLegend(\"Analytic\", \"b\");\n\n  // colors for plotting\n  const char *opt[7] = {\"r +\", \"c +\", \"m +\", \"h +\", \"l +\", \"n +\", \"q +\"};\n\n  for(int i = 0; i < plotData.size(); i++) {\n    std::stringstream ss;\n    ss << \"\\\\epsilon = \" << std::setprecision(4) << softenings[i] << \" [l]\";\n\n    gr.Plot(rData, plotData[i], opt[i]);\n    gr.AddLegend(ss.str().c_str(), opt[i]);\n  }\n\n  gr.Legend();\n  gr.WritePNG(\"forces.png\");\n}\n\nvoid first_task()\n{\n  calculate_constants();\n  step1();\n  step2();\n}\n", "meta": {"hexsha": "95f140b8535828e931c7bd2944b73516533b56d2", "size": 8943, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/first_task.cpp", "max_stars_repo_name": "azurite/AST-245-N-Body", "max_stars_repo_head_hexsha": "cc3e3acd61f62415c1e5f40c8aba5b93703837fa", "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/first_task.cpp", "max_issues_repo_name": "azurite/AST-245-N-Body", "max_issues_repo_head_hexsha": "cc3e3acd61f62415c1e5f40c8aba5b93703837fa", "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/first_task.cpp", "max_forks_repo_name": "azurite/AST-245-N-Body", "max_forks_repo_head_hexsha": "cc3e3acd61f62415c1e5f40c8aba5b93703837fa", "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.5370919881, "max_line_length": 102, "alphanum_fraction": 0.5921950129, "num_tokens": 2807, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7334237952706478}}
{"text": "/***************************************************************************\n/* Javier Juan Albarracin - jajuaal1@ibime.upv.es                         */\n/* Universidad Politecnica de Valencia, Spain                             */\n/*                                                                        */\n/* Copyright (C) 2020 Javier Juan Albarracin                              */\n/*                                                                        */\n/***************************************************************************\n* Global Principal Compoment Analysis filtering                            *\n***************************************************************************/\n\n#include <itkImage.h>\n#include <Eigen/Dense>\n#include <EigenITK.hpp>\n#include <ITKUtils.hpp>\n#include <PrincipalComponentAnalysis.hpp>\n#include <cstdlib>\n#include <cmath>\n\nusing namespace Eigen;\n\nint main(int argc, char *argv [])\n{\n    if (argc < 5)\n    {\n        std::cerr << \"Error! Invalid number of arguments!\" << std::endl << \"Usage: GlobalPCADenoising inputImage maskImage variance outputImage [minComponents=5% of number of components] [maxComponents=25% of number of components] [verbose=0]\" << std::endl;\n        return EXIT_FAILURE;\n    }\n\n    // Typedefs\n    typedef itk::Image<float, 4> ComponentsImageType;\n    typedef itk::Image<unsigned char, 3> MaskType;\n    try\n    {\n        // Get PWI\n        typename ComponentsImageType::Pointer PWI = ITKUtils::ReadNIfTIImage<ComponentsImageType>(std::string(argv[1]));\n        // Get mask\n        typename MaskType::Pointer mask = ITKUtils::ReadNIfTIImage<MaskType>(std::string(argv[2]));\n        // Get variance\n        const double variance = std::strtod(argv[3], NULL);\n        // Default min and max number of components\n        typename ComponentsImageType::SizeType imageSize = PWI->GetLargestPossibleRegion().GetSize();\n        unsigned int minComponents = std::ceil(imageSize[3] * 0.0500);\n        unsigned int maxComponents = std::ceil(imageSize[3] * 0.3333);\n        // Get user min number of components\n        if (argc > 5)\n            minComponents = std::atoi(argv[5]);\n        // Get user max number of components\n        if (argc > 6)\n            maxComponents = std::atoi(argv[6]);\n        // Get user max number of components\n        bool verbose = false;\n        if (argc > 7)\n            verbose = (bool) std::atoi(argv[7]);\n        // Print configuration\n        if (verbose)\n        {\n            std::cout << \"CONFIGURATION\" << std::endl;\n            std::cout << \"-------------\" << std::endl;\n            std::cout << \"Variance explained\" << std::endl;\n            std::cout << \"\\tValue: \" << variance << std::endl;\n            std::cout << \"Number of components\" << std::endl;\n            std::cout << \"\\tMinium: \" << minComponents << std::endl;\n            std::cout << \"\\tMaximum: \" << maxComponents << std::endl;    \n        }\n        // Compute Non-Zeros mask\n        typename MaskType::Pointer nonZerosMask = ITKUtils::ZerosMaskIntersect<ComponentsImageType, MaskType>(PWI, mask, true, false, 0.05);\n        // Convert to Eigen Matrix\n        MatrixXf dataset(EigenITK::toEigen<ComponentsImageType, MaskType>(PWI, nonZerosMask));\n        // Compute PCA filtering\n        PrincipalComponentAnalysis pca;\n        MatrixXf PWIPCARawdata = pca.filteringVarianceExplained(dataset, variance, minComponents, maxComponents);\n        if (verbose)\n        {\n            std::cout << \"PCA\" << std::endl;\n            std::cout << \"---\" << std::endl;\n            std::cout << \"Reconstruction with \" << pca.components() << \" components out of \" << imageSize[3] << std::endl;\n        }\n        // Correct curves with negative values\n        #pragma omp parallel for\n        for (int i = 0; i < PWIPCARawdata.rows(); i++)\n        {\n            ArrayXf row = PWIPCARawdata.row(i);\n            if ((row <= 0).any())\n                PWIPCARawdata.row(i) = (row - row.minCoeff() + 1);\n        }\n        // Convert to ITK image\n        EigenITK::toITK<ComponentsImageType, MaskType>(PWIPCARawdata, nonZerosMask, PWI);\n        // Save new filtered image\n        ITKUtils::WriteNIfTIImage<ComponentsImageType>(PWI, std::string(argv[4]));\n    }\n    catch (itk::ExceptionObject & err)\n    {\n        std::cerr << \"ExceptionObject caught !\" << std::endl;\n        std::cerr << err << std::endl;\n        return EXIT_FAILURE;\n    }\n    \n    return EXIT_SUCCESS;\n}", "meta": {"hexsha": "4b5df7aed459aa739ab45e0afc28c933e24e563c", "size": 4413, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "GlobalPCADenoising.cpp", "max_stars_repo_name": "javierjuan/ONTs", "max_stars_repo_head_hexsha": "d27168ceafac70f729df7a9138285e2352a49e99", "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": "GlobalPCADenoising.cpp", "max_issues_repo_name": "javierjuan/ONTs", "max_issues_repo_head_hexsha": "d27168ceafac70f729df7a9138285e2352a49e99", "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": "GlobalPCADenoising.cpp", "max_forks_repo_name": "javierjuan/ONTs", "max_forks_repo_head_hexsha": "d27168ceafac70f729df7a9138285e2352a49e99", "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": 44.5757575758, "max_line_length": 257, "alphanum_fraction": 0.5354634036, "num_tokens": 1021, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008906, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.7332001742753547}}
{"text": "//\n//  myMath.cpp\n//  pbeam\n//\n//  Created by Andrew Ning on 2/4/12.\n//  Copyright (c) 2012 NREL. All rights reserved.\n//\n\n//#include <Accelerate/Accelerate.h>\n#include <cstdlib> // for malloc\n#include <algorithm> // for max/min\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n\n#include \"myMath.h\"\n\nusing namespace std;\n\nnamespace myMath {\n\n  // MARK: ------------- EIGENVALUES --------------\n\n        \n  // solves generalized eigenvalue problem Ax = lambda * Bx\n  int generalizedEigenvalues(bool cmpVec, const Matrix &A, const Matrix &B, Vector &eig, Matrix &eig_vec){\n\n    int flag = cmpVec ? Eigen::ComputeEigenvectors : Eigen::EigenvaluesOnly;\n\n    Eigen::GeneralizedSelfAdjointEigenSolver<Matrix> es(A, B, flag);\n\n    eig = es.eigenvalues().real();\n    if (cmpVec) eig_vec = es.eigenvectors().real();\n    return es.info(); // != Eigen::Success) abort();\n   }\n\n  int generalizedEigenvalues(const Matrix &A, const Matrix &B, Vector &eig){\n    Matrix empty(0, 0);\n    return generalizedEigenvalues(false, A, B, eig, empty);\n  }\n    \n  int generalizedEigenvalues(const Matrix &A, const Matrix &B, Vector &eig, Matrix &eig_vec){\n    return generalizedEigenvalues(true, A, B, eig, eig_vec);\n  }\n\n\n  // -------------------------------------\n\n\n\n  // MARK: -------------- LINEAR SYSTEM SOLVER -----------------\n\n\n  int solveSPDBLinearSystem(const Matrix &A, const Vector &b, Vector &x){\n    //x = A.llt().solve(b);\n    x = A.ldlt().solve(b);\n    return 0;\n  }\n\n  //TODO: add unit test for this\n  int solveLinearSystem(const Matrix &A, const Vector &b, Vector &x){\n    x = A.householderQr().solve(b);\n    return 0;\n  }\n\n\n  // -------------------------------------\n\n\n  // MARK: ------------ INTEGRATION -----------------\n  // TODO: add unit tests\n    \n  void cumtrapz(const Vector &f, const Vector &x, Vector &y){\n        \n    y(0) = 0.0;\n        \n    for (int i = 1; i < x.size(); i++) {\n      y(i) = y(i-1) + 0.5*(f(i)+f(i-1)) * (x(i)-x(i-1));\n    }\n  }\n    \n  double trapz(const Vector &f, const Vector &x){\n        \n    int n = (int) x.size();\n    Vector y(n);\n    cumtrapz(f, x, y);\n        \n    return y(n-1);\n  }\n    \n\n  void vectorFromArray(double x[], Vector &v){\n\n    for (int i = 0; i < v.size(); i++) {\n      v(i) = x[i];\n    }\n        \n  }\n\n}\n", "meta": {"hexsha": "a33025026190142c49e24af15d4a75e41729631e", "size": 2254, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "wisdem/pBeam/src/myMath.cpp", "max_stars_repo_name": "ptrbortolotti/WISDEM", "max_stars_repo_head_hexsha": "2b7e44716d022e2f62140073dd078c5deeb8bf0a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2015-07-09T15:21:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-19T07:32:28.000Z", "max_issues_repo_path": "wisdem/pBeam/src/myMath.cpp", "max_issues_repo_name": "ptrbortolotti/WISDEM", "max_issues_repo_head_hexsha": "2b7e44716d022e2f62140073dd078c5deeb8bf0a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 17.0, "max_issues_repo_issues_event_min_datetime": "2019-09-13T22:21:15.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-25T20:04:26.000Z", "max_forks_repo_path": "wisdem/pBeam/src/myMath.cpp", "max_forks_repo_name": "ptrbortolotti/WISDEM", "max_forks_repo_head_hexsha": "2b7e44716d022e2f62140073dd078c5deeb8bf0a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-01-02T16:02:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T19:27:05.000Z", "avg_line_length": 22.54, "max_line_length": 106, "alphanum_fraction": 0.5505767524, "num_tokens": 649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582554941718, "lm_q2_score": 0.7879311906630568, "lm_q1q2_score": 0.7331370811137935}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n//\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.\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// Point Example - showing geographic (latitude longitude) points\n\n#include <iostream>\n#include <iomanip>\n\n#include <boost/geometry/geometry.hpp>\n#include <boost/geometry/extensions/algorithms/parse.hpp>\n#include <boost/geometry/extensions/gis/latlong/latlong.hpp>\n\n// Formula to get the course (direction) between two points.\n// This might be a GGL-function in the future.\ntemplate <typename P1, typename P2>\ninline double get_course(P1 const& p1, P2 const& p2)\n{\n    double const& lat1 = boost::geometry::get_as_radian<1>(p1);\n    double const& lon1 = boost::geometry::get_as_radian<0>(p1);\n    double const& lat2 = boost::geometry::get_as_radian<1>(p2);\n    double const& lon2 = boost::geometry::get_as_radian<0>(p2);\n    // http://williams.best.vwh.net/avform.htm#Crs\n    return atan2(sin(lon1-lon2)*cos(lat2),\n       cos(lat1)*sin(lat2)-sin(lat1)*cos(lat2)*cos(lon1-lon2));\n}\n\n\n// Formula to calculate the point at a distance/angle from another point\n// This might be a GGL-function in the future.\ntemplate <typename P1, typename P2>\ninline void point_at_distance(P1 const& p1,\n        double distance, double tc, double radius,\n        P2& p2)\n{\n    double const two_pi = 2.0 * boost::geometry::math::pi<double>();\n    double earth_perimeter = radius * two_pi;\n;\n    double d = (distance / earth_perimeter) * two_pi;\n    double const& lat1 = boost::geometry::get_as_radian<1>(p1);\n    double const& lon1 = boost::geometry::get_as_radian<0>(p1);\n\n    // http://williams.best.vwh.net/avform.htm#LL\n    double lat = asin(sin(lat1)*cos(d)+cos(lat1)*sin(d)*cos(tc));\n    double dlon = atan2(sin(tc)*sin(d)*cos(lat1),cos(d)-sin(lat1)*sin(lat));\n    double lon = lon1 - dlon;\n\n    boost::geometry::set_from_radian<1>(p2, lat);\n    boost::geometry::set_from_radian<0>(p2, lon);\n}\n\n\n\nint main()\n{\n    using namespace boost::geometry;\n\n    typedef model::ll::point<degree> latlon_point;\n    \n    latlon_point paris;\n\n    // Assign coordinates to the latlong point, using the methods lat and lon\n    // Paris 48 52' 0\" N, 2 19' 59\" E\n    paris.lat(dms<north>(48, 52, 0));\n    paris.lon(dms<east>(2, 19, 59));\n\n    std::cout << \"Paris: \" << boost::geometry::dsv(paris) << std::endl;\n\n    // Constructor using explicit latitude/longitude\n    // Lima 12 2' 36\" S, 77 1' 42\" W\n    latlon_point lima(\n            latitude<>(dms<south>(12, 2, 36)),\n            longitude<>(dms<west>(77, 1, 42)));\n\n    std::cout << \"Lima: \" << boost::geometry::dsv(lima) << std::endl;\n\n    // Construction with parse utiity\n    latlon_point amsterdam = parse<latlon_point>(\"52 22'23\\\"N\", \"4 53'32\\\"E\");\n    std::cout << \"Amsterdam: \" << boost::geometry::dsv(amsterdam) << std::endl;\n\n    // Calculate the distance using the default strategy (Andoyer), and Vincenty\n    std::cout << std::setprecision(9);\n    std::cout << \"Distance Paris-Lima, Andoyer (default) \"\n        << 0.001 * distance(paris, lima)\n        << \" km\" << std::endl;\n\n    std::cout << \"Distance Paris-Lima, Vincenty \"\n        << 0.001 * distance(paris, lima, strategy::distance::vincenty<double>())\n        << \" km\" << std::endl;\n\n    // Using great circle (=haversine), this is less precise because earth is not a sphere\n    double const average_earth_radius = 6372795.0;\n    std::cout << \"Distance Paris-Lima, great circle \"\n        << 0.001 * distance(paris, lima, strategy::distance::haversine<double>(average_earth_radius))\n        << \" km\" << std::endl;\n\n    // Convert a latlong point to radians. This might be convenient, although algorithms\n    // are transparent on degree/radians\n    model::ll::point<radian> paris_rad;\n    transform(paris, paris_rad);\n    std::cout << \"Paris in radians: \" << boost::geometry::dsv(paris_rad) << std::endl;\n\n    model::ll::point<radian> amsterdam_rad;\n    transform(amsterdam, amsterdam_rad);\n    std::cout << \"Amsterdam in radians: \" << boost::geometry::dsv(amsterdam_rad) << std::endl;\n\n    std::cout << \"Distance Paris-Amsterdam, (degree) \" << 0.001 * distance(paris, amsterdam) << \" km\" << std::endl;\n    std::cout << \"Distance Paris-Amsterdam, (radian) \" << 0.001 * distance(paris_rad, amsterdam_rad) << \" km\" << std::endl;\n\n    std::cout << \"Distance Paris-Amsterdam, (mixed) \" << 0.001 * distance(paris, amsterdam_rad) << \" km\" << std::endl;\n\n    // Other way round: have Amsterdam and go 430 km to the south (i.e. first calculate direction)\n    double tc = get_course(amsterdam, paris);\n    std::cout << \"Course: \" << (tc * boost::geometry::math::r2d) << std::endl;\n\n    latlon_point paris_calculated;\n    point_at_distance(amsterdam, 430 * 1000.0, tc, average_earth_radius, paris_calculated);\n    std::cout << \"Paris calculated (degree): \" << boost::geometry::dsv(paris_calculated) << std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "dca4637b270fda15e181f196b671517c52cf57f1", "size": 5081, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "extensions/example/gis/latlong/point_ll_example.cpp", "max_stars_repo_name": "jonasdmentia/geometry", "max_stars_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "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": "extensions/example/gis/latlong/point_ll_example.cpp", "max_issues_repo_name": "jonasdmentia/geometry", "max_issues_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "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": "extensions/example/gis/latlong/point_ll_example.cpp", "max_forks_repo_name": "jonasdmentia/geometry", "max_forks_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "max_forks_repo_licenses": ["BSL-1.0"], "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": 40.3253968254, "max_line_length": 123, "alphanum_fraction": 0.6626648298, "num_tokens": 1481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133498259924, "lm_q2_score": 0.7799929104825006, "lm_q1q2_score": 0.7331257493321326}}
{"text": "#ifndef MLT_UTILS_OPTIMIZERS_GRADIENT_DESCENT_UPDATES_HPP\n#define MLT_UTILS_OPTIMIZERS_GRADIENT_DESCENT_UPDATES_HPP\n\n#include <Eigen/Core>\n\n#include \"../../defs.hpp\"\n\nnamespace mlt {\nnamespace utils {\nnamespace optimizers {\n\t// Implementation of the Vanilla Gradient Descent update rule\n\tclass VanillaGradientDescentUpdate {\n\tpublic:\n\t\tvoid restart() {}\n\n\t\tauto step(double learning_rate, MatrixXdRef gradient) {\n\t\t\treturn (-learning_rate * gradient).eval();\n\t\t}\n\t};\n\n\t// Implementation of the Momentum Gradient Descent update rule\n\t// Parameters:\n\t// - double mu: amount of momentum applied on each descent\n\tclass MomentumGradientDescentUpdate {\n\tpublic:\n\t\tMomentumGradientDescentUpdate(double mu = 0.9) : _mu(mu), _init(false) {}\n\n\t\tvoid restart() { _init = false; }\n\n\t\tauto step(double learning_rate, MatrixXdRef gradient) {\n\t\t\tif (!_init || _cache.rows() != gradient.rows() || _cache.cols() != gradient.cols()) {\n\t\t\t\t_cache = MatrixXd::Zero(gradient.rows(), gradient.cols());\n\t\t\t}\n\n\t\t\t_cache = _mu * _cache - learning_rate * gradient;\n\t\t\t_init = true;\n\t\t\treturn _cache;\n\t\t}\n\n\tprotected:\n\t\tbool _init;\n\t\tdouble _mu;\n\t\tMatrixXd _cache;\n\t};\n\n\t// Implementation of the Nesterov's Accelerated Momentum Gradient Descent update rule\n\t// Parameters:\n\t// - double mu: amount of momentum applied on each descent\n\tclass NesterovMomentumGradientDescentUpdate {\n\tpublic:\n\t\tNesterovMomentumGradientDescentUpdate(double mu = 0.9) : _mu(mu), _init(false) {}\n\n\t\tvoid restart() { _init = false; }\n\n\t\tauto step(double learning_rate, MatrixXdRef gradient) {\n\t\t\tif (!_init || _cache.rows() != gradient.rows() || _cache.cols() != gradient.cols()) {\n\t\t\t\t_cache = MatrixXd::Zero(gradient.rows(), gradient.cols());\n\t\t\t}\n\n\t\t\tVectorXd velocity_prev = _cache;\n\t\t\t_cache = _mu * _cache - learning_rate * gradient;\n\t\t\t_init = true;\n\t\t\treturn (-_mu * velocity_prev + (1 + _mu) * _cache).eval();\n\t\t}\n\n\tprotected:\n\t\tbool _init;\n\t\tdouble _mu;\n\t\tMatrixXd _cache;\n\t};\n\n\t// Implementation of the Adagrad Gradient Descent update rule\n\tclass AdagradGradientDescentUpdate {\n\tpublic:\n\t\tAdagradGradientDescentUpdate() : _init(false) {}\n\n\t\tvoid restart() { _init = false; }\n\n\t\tauto step(double learning_rate, MatrixXdRef gradient) {\n\t\t\tif (!_init || _cache.rows() != gradient.rows() || _cache.cols() != gradient.cols()) {\n\t\t\t\t_cache = MatrixXd::Zero(gradient.rows(), gradient.cols());\n\t\t\t}\n\n\t\t\t_cache += gradient.array().pow(2).matrix();\n\t\t\t_init = true;\n\t\t\treturn (-learning_rate * (gradient.array() / (_cache.array() + 1e-8).sqrt()).matrix()).eval();\n\t\t}\n\n\tprotected:\n\t\tbool _init;\n\t\tMatrixXd _cache;\n\t};\n\n\t// Implementation of the RMSProp Gradient Descent update rule\n\t// Parameters:\n\t// - double decay_rate: the decay rate of the moving average of squared gradients at each step\n\tclass RMSPropGradientDescentUpdate {\n\tpublic:\n\t\tRMSPropGradientDescentUpdate(double decay_rate = 0.9) : _decay_rate(decay_rate), _init(false) {}\n\n\t\tvoid restart() { _init = false; }\n\n\t\tMatrixXd step(double learning_rate, MatrixXdRef gradient) {\n\t\t\tif (!_init || _cache.rows() != gradient.rows() || _cache.cols() != gradient.cols()) {\n\t\t\t\t_cache = MatrixXd::Zero(gradient.rows(), gradient.cols());\n\t\t\t}\n\n\t\t\t_cache = _decay_rate * _cache + (1 - _decay_rate) * gradient.array().pow(2).matrix();\n\t\t\t_init = true;\n\t\t\treturn (-learning_rate * (gradient.array() / (_cache.array() + 1e-8).sqrt()).matrix()).eval();\n\t\t}\n\t\t\n\tprotected:\n\t\tbool _init;\n\t\tdouble _decay_rate;\n\t\tMatrixXd _cache;\n\t};\n}\n}\n}\n#endif", "meta": {"hexsha": "46da4dc5b08411b8f3447b671667c2f250965c06", "size": 3442, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/mlt/utils/optimizers/gradient_descent_updates.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/optimizers/gradient_descent_updates.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/optimizers/gradient_descent_updates.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": 28.4462809917, "max_line_length": 98, "alphanum_fraction": 0.6914584544, "num_tokens": 909, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802350995702, "lm_q2_score": 0.7981867777396212, "lm_q1q2_score": 0.7331187792716557}}
{"text": "//  Copyright Madhur Chauhan 2020.\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#include <boost/math/policies/error_handling.hpp>\n#include <boost/math/special_functions/fibonacci.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/test/tools/old/interface.hpp>\n#include <cstdint>\n#include <exception>\n#define BOOST_TEST_MODULE Fibonacci_Test_Module\n#include <boost/test/included/unit_test.hpp>\n\nusing boost::math::fibonacci;\nusing boost::math::unchecked_fibonacci;\nusing namespace boost::multiprecision;\ntypedef cpp_int BST;\ntypedef number<backends::cpp_int_backend<2048, 2048, unsigned_magnitude, unchecked>> BST_2048;\n\n// Some sanity checks using OEIS A000045\nBOOST_AUTO_TEST_CASE(sanity_checks) {\n    BOOST_TEST(fibonacci<char>(0) == 0);    // Base case\n    BOOST_TEST(fibonacci<int>(1) == 1);     // Base case\n    BOOST_TEST(fibonacci<int16_t>(2) == 1); // Base Case\n    BOOST_TEST(fibonacci<int16_t>(3) == 2); // First computation\n    BOOST_TEST(fibonacci<int16_t>(10) == 55);\n    BOOST_TEST(fibonacci<int16_t>(15) == 610);\n    BOOST_TEST(fibonacci<int16_t>(18) == 2584);\n    BOOST_TEST(fibonacci<int32_t>(40) == 102334155);\n}\n\n// Tests unchecked_fibonacci by computing naively\nBOOST_AUTO_TEST_CASE(big_integer_check) {\n    // GMP is used as type for fibonacci and cpp_int is for naive computation\n    BST val = 0, a = 0, b = 1;\n    for (int i = 0; i <= 1e4; ++i) {\n        BOOST_TEST(fibonacci<BST>(i) == a);\n        val = b, b += a, a = val;\n    }\n}\n\n// Check for overflow throw using magic constants\nBOOST_AUTO_TEST_CASE(overflow_check) {\n\n    // 1. check for unsigned integer overflow\n    BOOST_CHECK_NO_THROW(fibonacci<uint64_t>(93));\n    BOOST_CHECK_THROW(fibonacci<uint64_t>(94), std::exception);\n    BOOST_CHECK_NO_THROW(unchecked_fibonacci<uint64_t>(94));\n\n    // 2. check for signed integer overflow\n    BOOST_CHECK_NO_THROW(fibonacci<int64_t>(91));\n    // BOOST_CHECK_THROW(fibonacci<int64_t>(92), std::exception); // this should be the correct value but imprecisions\n    BOOST_CHECK_THROW(fibonacci<int64_t>(93), std::exception);\n    // In UBSAN this will error out, but it is expected\n    BOOST_CHECK_NO_THROW(unchecked_fibonacci<int64_t>(93));\n\n    // 3. check for floating point (double)\n    BOOST_CHECK_NO_THROW(fibonacci<double>(78));\n    BOOST_CHECK_THROW(fibonacci<double>(79), std::exception);\n    BOOST_CHECK_NO_THROW(unchecked_fibonacci<double>(79));\n\n    // 4. check using boost's multiprecision unchecked integer\n    BOOST_CHECK_NO_THROW(fibonacci<BST_2048>(2950));\n    // BOOST_CHECK_THROW(fibonacci<T>(2951), std::exception); // this should be the correct value but imprecisions\n    BOOST_CHECK_THROW(fibonacci<BST_2048>(2952), std::exception);\n    BOOST_CHECK_NO_THROW(unchecked_fibonacci<BST_2048>(2952));\n}\n\nBOOST_AUTO_TEST_CASE(generator_check) {\n    // first 5 values\n    boost::math::fibonacci_generator<BST_2048> gen;\n    for (int i : {0, 1, 1, 2, 3, 5, 8, 13, 21}) {\n        BOOST_TEST(gen() == i);\n    }\n\n    // test whether the generator is set correctly to the given index --- next\n    const int next = 1000; // next <=2950 (checked from test above)\n    gen.set(next);\n    BST_2048 a = fibonacci<BST_2048>(next), b = fibonacci<BST_2048>(next + 1);\n    for (int i = next; i < next + 50; ++i) {\n        BOOST_TEST(gen() == a);\n        swap(a, b);\n        b += a;\n    }\n\n    // shift the generator back to next and check again\n    a = fibonacci<BST_2048>(next), b = fibonacci<BST_2048>(next + 1);\n    gen.set(next);\n    for (int i = next; i < next + 50; ++i) {\n        BOOST_TEST(gen() == a);\n        swap(a, b);\n        b += a;\n    }\n}\n\nBOOST_AUTO_TEST_CASE(constexpr_check) {\n    constexpr int x = boost::math::unchecked_fibonacci<int>(32);\n    BOOST_TEST(x == 2178309);\n\n    constexpr double y = boost::math::unchecked_fibonacci<double>(40);\n    BOOST_TEST(y == 102334155.0);\n\n    // checked fibonacci can't be constexpr because of non-constexpr\n    // dependency in detail::log_2, detail::fib_bits_phi, detail::fib_bits_deno\n}\n", "meta": {"hexsha": "429819a7312c4523640cc6e80906e8f49bc846f8", "size": 4130, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_fibonacci.cpp", "max_stars_repo_name": "jblumsch/boost.math", "max_stars_repo_head_hexsha": "8682f48e439ba9fef34f381581756ba40c7d514b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-05-10T12:37:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-10T13:59:44.000Z", "max_issues_repo_path": "test/test_fibonacci.cpp", "max_issues_repo_name": "jblumsch/boost.math", "max_issues_repo_head_hexsha": "8682f48e439ba9fef34f381581756ba40c7d514b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 30.0, "max_issues_repo_issues_event_min_datetime": "2021-06-22T12:59:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-02T09:27:49.000Z", "max_forks_repo_path": "test/test_fibonacci.cpp", "max_forks_repo_name": "jblumsch/boost.math", "max_forks_repo_head_hexsha": "8682f48e439ba9fef34f381581756ba40c7d514b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-07T21:15:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-07T21:15:02.000Z", "avg_line_length": 38.5981308411, "max_line_length": 118, "alphanum_fraction": 0.6934624697, "num_tokens": 1168, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774768002981829, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.7331174172448772}}
{"text": "//\n// Created by peri on 11/17/17.\n//\n\n#ifndef VANILLA_ACTIVATION_FUNCTIONS_HPP\n#define VANILLA_ACTIVATION_FUNCTIONS_HPP\n\n#include <cmath>\n#include <iostream>\n#include <boost/multi_array.hpp>\n#include \"boost/array.hpp\"\n#include <boost/next_prior.hpp>\n#include \"boost/cstdlib.hpp\"\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\nclass activation_functions{\n\npublic:\n    template <typename Array>\n    void ReLu(Array& A)\n    {\n        const auto n = A.data() + A.num_elements();\n        for (auto i = A.data(); i != n; ++i){\n            if(*i < 0){\n                *i = 0.0;\n            }\n        }\n    }\n\npublic:\n    template <typename Array>\n    void sigmoid(Array& A)\n    {\n        const auto n = A.data() + A.num_elements();\n        for (auto i = A.data(); i != n; ++i){\n            auto x = *i;\n            if(x < 0){\n                *i = expl(x) / (1.0 + expl(x));\n            }\n            else{\n                *i = 1.0 / (1.0 + expl(-1.0*x));\n            }\n\n        }\n    }\n\npublic:\n    template <typename Array>\n    void tanh(Array& A)\n    {\n        const auto n = A.data() + A.num_elements();\n        for (auto i = A.data(); i != n; ++i){\n            *i = (2*expl(-1 *i) - 1)/(2*expl(-1 *i) + 1);\n        }\n    }\n\n\npublic:\n    template <typename T>\n    void ReLu(boost::numeric::ublas::matrix<T>& M)\n    {\n        for(unsigned i = 0; i < M.size1(); ++ i){\n            for(unsigned j = 0; j < M.size2(); ++ j){\n                if(M(i, j) < 0){\n                    M(i, j) = 0;\n                }\n            }\n        }\n    }\n\npublic:\n    template <typename T>\n    void sigmoid(boost::numeric::ublas::matrix<T>& M)\n    {\n        for(unsigned i = 0; i < M.size1(); ++ i){\n            for (unsigned j = 0; j < M.size2(); ++j) {\n                auto x = M(i, j);\n                if(x < 0){\n                    M(i, j) = expl(x) / (1.0 + expl(x));\n                }\n                else {\n                    M(i, j) = 1.0 / (1.0 + expl(-1.0*x));\n                }\n            }\n        }\n\n    }\n\npublic:\n    template <typename T>\n    void tanh(boost::numeric::ublas::matrix<T>& M)\n    {\n        for(unsigned i = 0; i < M.size1(); ++ i){\n            for(unsigned j = 0; j < M.size2(); ++ j) {\n                M(i, j) = (2 * expl(-1 * M(i, j)) - 1) / (2 * expl(-1 * M(i, j)) + 1);\n            }\n        }\n    }\n\n\n};\n#endif //ACTIVATION_FUNCTIONS_HPP\n", "meta": {"hexsha": "bdf3e864c25139d4116e68ec3cf38bdb941b484b", "size": 2385, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "header/activation_functions.hpp", "max_stars_repo_name": "pjavia/Vanilla", "max_stars_repo_head_hexsha": "5b6160aec297ad79593bd0d60a25950f21f8a63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-25T16:02:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-25T16:02:10.000Z", "max_issues_repo_path": "header/activation_functions.hpp", "max_issues_repo_name": "pjavia/Vanilla", "max_issues_repo_head_hexsha": "5b6160aec297ad79593bd0d60a25950f21f8a63a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-02-25T18:46:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-25T18:46:38.000Z", "max_forks_repo_path": "header/activation_functions.hpp", "max_forks_repo_name": "pjavia/Vanilla", "max_forks_repo_head_hexsha": "5b6160aec297ad79593bd0d60a25950f21f8a63a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-25T16:02:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-25T16:02:17.000Z", "avg_line_length": 22.9326923077, "max_line_length": 86, "alphanum_fraction": 0.4314465409, "num_tokens": 690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.8354835289107307, "lm_q1q2_score": 0.733117397588658}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n\n#include <cmath>\n#include <iostream>\n#include <type_traits>\n\nnamespace pcv\n{\n\ntemplate<class NumericType0, class NumericType1>\ndouble getEuclideanDistance(\n    const Eigen::Matrix<NumericType0, 2, 1> &point0,\n    const Eigen::Matrix<NumericType1, 2, 1> &point1)\n{\n    return std::sqrt(\n            std::pow(point0.x()-point1.x(), 2)\n          + std::pow(point0.y()-point1.y(), 2));\n}\n\ntemplate<class NumericType>\nstd::optional<Eigen::Vector2d> getSegmentIntersectionPoint2(\n    const Eigen::Matrix<NumericType, 2, 1> &segmentOnePoint0,\n    const Eigen::Matrix<NumericType, 2, 1> &segmentOnePoint1,\n    const Eigen::Matrix<NumericType, 2, 1> &segmentTwoPoint0,\n    const Eigen::Matrix<NumericType, 2, 1> &segmentTwoPoint1,\n    double error = 1e-10)\n{\n    static_assert(std::is_arithmetic<NumericType>::value,\n                  \"Must have a numerical point type.\");\n\n    Eigen::Matrix<double, 2, 2> linearEquationsLhs;\n    linearEquationsLhs <<\n        segmentOnePoint0.y() - segmentOnePoint1.y(),\n        segmentOnePoint1.x() - segmentOnePoint0.x(),\n        segmentTwoPoint0.y() - segmentTwoPoint1.y(),\n        segmentTwoPoint1.x() - segmentTwoPoint0.x();\n\n    Eigen::Vector2d linearEquationsRhs;\n    linearEquationsRhs <<\n          segmentOnePoint0.y() * (segmentOnePoint1.x() - segmentOnePoint0.x())\n        - segmentOnePoint0.x() * (segmentOnePoint1.y() - segmentOnePoint0.y()),\n          segmentTwoPoint0.y() * (segmentTwoPoint1.x() - segmentTwoPoint0.x())\n        - segmentTwoPoint0.x() * (segmentTwoPoint1.y() - segmentTwoPoint0.y());\n\n    Eigen::Vector2d intersection =\n        linearEquationsLhs.colPivHouseholderQr().solve(linearEquationsRhs);\n\n    if (intersection.x() >= std::min(segmentOnePoint0.x(), segmentOnePoint1.x())-error\n        && intersection.x() <= std::max(segmentOnePoint0.x(), segmentOnePoint1.x())+error\n        && intersection.y() >= std::min(segmentOnePoint0.y(), segmentOnePoint1.y())-error\n        && intersection.y() <= std::max(segmentOnePoint0.y(), segmentOnePoint1.y())+error\n        && intersection.x() >= std::min(segmentTwoPoint0.x(), segmentTwoPoint1.x())-error\n        && intersection.x() <= std::max(segmentTwoPoint0.x(), segmentTwoPoint1.x())+error\n        && intersection.y() >= std::min(segmentTwoPoint0.y(), segmentTwoPoint1.y())-error\n        && intersection.y() <= std::max(segmentTwoPoint0.y(), segmentTwoPoint1.y())+error)\n    {\n        return intersection;\n    }\n\n    return {};\n}\n\n}\n", "meta": {"hexsha": "192f252d01a83ca5f74a83d63ebbe329ebb8a015", "size": 2471, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cpp/Geometry/include/Geometry/LineSegment.hpp", "max_stars_repo_name": "Pratool/homography", "max_stars_repo_head_hexsha": "c9daeaa3364b7c658b39c225952288dd828c332e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-08-12T17:38:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-12T17:38:22.000Z", "max_issues_repo_path": "cpp/Geometry/include/Geometry/LineSegment.hpp", "max_issues_repo_name": "Pratool/homography", "max_issues_repo_head_hexsha": "c9daeaa3364b7c658b39c225952288dd828c332e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-03-03T15:43:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-04T03:22:47.000Z", "max_forks_repo_path": "cpp/Geometry/include/Geometry/LineSegment.hpp", "max_forks_repo_name": "Pratool/homography", "max_forks_repo_head_hexsha": "c9daeaa3364b7c658b39c225952288dd828c332e", "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.4393939394, "max_line_length": 90, "alphanum_fraction": 0.6641036018, "num_tokens": 688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070011518829, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.7330503733536375}}
{"text": "#include <cmath>\n#include <catch2/catch.hpp>\n#include <Eigen/Dense>\n#include \"configure.h\"\n#include \"factory.h\"\n#include \"normal_multivar.h\"\n#include \"numeric_utils.h\"\n\nTEST_CASE(\"Test generation of random numbers\", \"[RandomNumbers]\") {\n  // Initialize the factories\n  config::initialize();\n  // Seed value for repeatability\n  int seed = 100;\n  auto random_generator = Factory<numeric_utils::RandomGenerator, int>::instance()\n    ->create(\"MultivariateNormal\", std::move(seed));\n  Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> random_numbers;  \n  \n  SECTION(\"Generate normally distributed random numbers for single random \"\n          \"variable\") {\n    Eigen::VectorXd means(1);\n    Eigen::MatrixXd cov(1,1);    \n    means(0) = 1.789;\n    cov(0, 0) = 0.0123;\n    \n    // Single random variable\n    random_generator->generate(random_numbers, means, cov, 100);\n    \n    double average = 0.0;    \n    for (unsigned int i = 0; i < random_numbers.size(); ++i) {\n      average = average + random_numbers(i);\n    }\n    average = average / random_numbers.size();\n    REQUIRE(average == Approx(means(0)).epsilon(0.01));\n  }\n\n  SECTION(\"Generate normally distributed random numbers for multiple \"\n          \"uncorrelated random variables\", \"[RandomNumbers]\") {\n    Eigen::VectorXd means(4);\n    Eigen::MatrixXd cov = Eigen::MatrixXd::Zero(4,4);\n    means << 1.789, 0.01, -10012.7, 702;\n    cov(0, 0) = 0.0123 * 0.0123;\n    cov(1, 1) = 0.00005;\n    cov(2, 2) = 50.0;\n    cov(3, 3) = 25;\n\n    // Random variable vector\n    random_generator->generate(random_numbers, means, cov, 1000);\n\n    std::vector<double> averages(means.size());\n    for (unsigned int i = 0; i < random_numbers.cols(); ++i) {\n      for (unsigned int j = 0; j < means.size(); ++j) {\n\taverages[j] = averages[j] + random_numbers(j, i);\n      }\n    }\n\n    REQUIRE(averages[0] / random_numbers.cols() == Approx(means(0)).epsilon(0.01));\n    REQUIRE(averages[1] / random_numbers.cols() == Approx(means(1)).epsilon(0.02));\n    REQUIRE(averages[2] / random_numbers.cols() == Approx(means(2)).epsilon(0.01));\n    REQUIRE(averages[3] / random_numbers.cols() == Approx(means(3)).epsilon(0.01));\n  }\n\n  SECTION(\"Generate normally distributed random numbers for correlated random \"\n          \"variable\", \"[RandomNumbers]\") {\n    Eigen::VectorXd means(3);\n    Eigen::MatrixXd cov = Eigen::MatrixXd::Zero(3, 3);\n    means << 64.0, 300.0, 60.0;\n\n    // Try bad COV matrix\n    // clang-format off\n    cov << 1.0, 1.0, 0.0, \n           1.0, 1.0, 1.0,\n           0.0, 1.0, 1.0;    \n    // clang-format on\n\n    bool success = random_generator->generate(random_numbers, means, cov, 250000);\n    REQUIRE(success == false);\n\n    // Try good COV matrix\n    // clang-format off   \n    cov << 504.0, 360.0, 180.0, \n           360.0, 360.0, 0.0,\n           180.0, 0.0, 720.0;\n    // clang-format on\n    success = random_generator->generate(random_numbers, means, cov, 250000);\n    REQUIRE(success == true);    \n    \n    Eigen::VectorXd averages = Eigen::VectorXd::Zero(means.size());\n    for (unsigned int i = 0; i < means.size(); ++i) {\n      for (unsigned int j = 0; j < random_numbers.cols(); ++j) {\n\taverages(i) = averages(i) + random_numbers(i, j);\n      }\n    }\n\n    averages = averages / random_numbers.cols();\n\n    REQUIRE(averages(0) == Approx(means(0)).epsilon(0.01));\n    REQUIRE(averages(1) == Approx(means(1)).epsilon(0.01));\n    REQUIRE(averages(2) == Approx(means(2)).epsilon(0.01));\n\n    // Compute covariance matrix from random values\n    Eigen::MatrixXd deviation_scores =\n        Eigen::MatrixXd::Zero(random_numbers.rows(), random_numbers.cols());\n\n    for (unsigned int i = 0; i < random_numbers.cols(); ++i) {\n      deviation_scores.col(i) = random_numbers.col(i) - averages;\n    }\n\n    Eigen::MatrixXd calculated_cov =\n        (deviation_scores * deviation_scores.transpose()) / random_numbers.cols();\n\n    REQUIRE(cov.lpNorm<2>() == Approx(calculated_cov.lpNorm<2>()).epsilon(0.01));\n  }\n\n  SECTION(\"Check that number generated using the same seed match\", \"[RandomNumbers]\") {\n    int seed = 500;\n    auto random_generator1 =\n        Factory<numeric_utils::RandomGenerator, int>::instance()->create(\n            \"MultivariateNormal\", std::move(seed));\n    auto random_generator2 =\n        Factory<numeric_utils::RandomGenerator, int>::instance()->create(\n            \"MultivariateNormal\", std::move(seed));    \n   \n    Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> random_numbers1;\n    Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> random_numbers2;\n    Eigen::VectorXd means(1);\n    Eigen::MatrixXd cov(1,1);    \n    means(0) = 1.789;\n    cov(0, 0) = 0.0123;\n\n    random_generator1->generate(random_numbers1, means, cov, 100);\n    random_generator2->generate(random_numbers2, means, cov, 100);    \n    REQUIRE(random_numbers1 == random_numbers2);\n  }\n}\n", "meta": {"hexsha": "6b4bbe90b7aa599aa5017c9646fe0e79d9e08ce0", "size": 4832, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/multi_var_tests.cc", "max_stars_repo_name": "fmckenna/smelt", "max_stars_repo_head_hexsha": "4e8a786fc415fc99bd79ada885e8312ed0eb36e0", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-05-07T03:14:27.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-19T07:10:52.000Z", "max_issues_repo_path": "test/multi_var_tests.cc", "max_issues_repo_name": "fmckenna/smelt", "max_issues_repo_head_hexsha": "4e8a786fc415fc99bd79ada885e8312ed0eb36e0", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-04-11T19:29:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-11T19:29:47.000Z", "max_forks_repo_path": "test/multi_var_tests.cc", "max_forks_repo_name": "fmckenna/smelt", "max_forks_repo_head_hexsha": "4e8a786fc415fc99bd79ada885e8312ed0eb36e0", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-03-25T20:08:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-04T13:02:31.000Z", "avg_line_length": 35.7925925926, "max_line_length": 87, "alphanum_fraction": 0.6343129139, "num_tokens": 1354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308147331957, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.7330312331651855}}
{"text": "#include <Eigen/Core>\n#include <iostream>\n\nusing namespace Eigen;\n\nint main()\n{\n  for (int size=1; size<=4; ++size)\n  {\n    MatrixXi m(size,size+1);         // a (size)x(size+1)-matrix of int's\n    for (int j=0; j<m.cols(); ++j)   // loop over columns\n      for (int i=0; i<m.rows(); ++i) // loop over rows\n        m(i,j) = i+j*m.rows();       // to access matrix coefficients,\n                                     // use operator()(int,int)\n    std::cout << m << \"\\n\\n\";\n  }\n\n  VectorXf v(4); // a vector of 4 float's\n  // to access vector coefficients, use either operator () or operator []\n  v[0] = 1; v[1] = 2; v(2) = 3; v(3) = 4;\n  std::cout << \"\\nv:\\n\" << v << std::endl;\n}\n", "meta": {"hexsha": "0f0280e0e95d2e8fc7f43669af040e6f18ac6ce9", "size": 680, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Eigen-3.3/doc/examples/Tutorial_simple_example_dynamic_size.cpp", "max_stars_repo_name": "shareq2005/CarND-MPC-Project", "max_stars_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2392.0, "max_stars_repo_stars_event_min_datetime": "2016-12-17T14:14:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T19:40:40.000Z", "max_issues_repo_path": "src/Eigen-3.3/doc/examples/Tutorial_simple_example_dynamic_size.cpp", "max_issues_repo_name": "shareq2005/CarND-MPC-Project", "max_issues_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 119.0, "max_issues_repo_issues_event_min_datetime": "2019-05-14T10:50:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-01T22:01:09.000Z", "max_forks_repo_path": "src/Eigen-3.3/doc/examples/Tutorial_simple_example_dynamic_size.cpp", "max_forks_repo_name": "shareq2005/CarND-MPC-Project", "max_forks_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1380.0, "max_forks_repo_forks_event_min_datetime": "2017-06-12T23:58:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:52:48.000Z", "avg_line_length": 29.5652173913, "max_line_length": 73, "alphanum_fraction": 0.5102941176, "num_tokens": 220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391386, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.732844816619063}}
{"text": "#include <armadillo>\n#include <cassert>\n\nnamespace mona\n{\n    auto meshgrid(const arma::fvec& x, const arma::fvec& y) -> std::tuple<arma::fmat, arma::fmat>\n    {\n        arma::fmat x_mat(y.size(), x.size());\n        arma::fmat y_mat(y.size(), x.size());\n\n        x_mat.each_row() = x.t();\n        y_mat.each_col() = y;\n\n        return {x_mat, y_mat};\n    }\n\n    template <typename Callable>\n    auto apply(Callable f, const arma::fmat& x, const arma::fmat& y) -> arma::fmat\n    {\n        assert(x.n_rows == y.n_rows);\n        assert(x.n_cols == y.n_cols);\n\n        arma::fmat z(x.n_rows, x.n_cols);\n\n        for(auto j = 0ul; j < x.n_cols; j++)\n        {\n            for(auto i = 0ul; i < x.n_rows; i++)\n            {\n                z(i , j) = f(x(i, j), y(i, j));\n            }\n        }\n        return z;\n    }\n\n\n    auto linspace(float a, float b, size_t n)\n    {\n        assert(b > a);\n        assert(n > 1);\n\n        arma::fvec res(n);\n        const auto step = (b - a) / (n - 1);\n        auto val = a;\n        for(auto& e: res)\n        {\n            e = val;\n            val += step;\n        }\n        // make the last value match b exactly\n        res[n - 1] = b;\n        return res;\n    }\n}", "meta": {"hexsha": "1f9af3593bf95a8e4963faafea7af5ba44bba17e", "size": 1199, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mona/utility.hpp", "max_stars_repo_name": "Eleobert/mona", "max_stars_repo_head_hexsha": "079e70b190b0850cf2579c1b0872da87f2706d80", "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/mona/utility.hpp", "max_issues_repo_name": "Eleobert/mona", "max_issues_repo_head_hexsha": "079e70b190b0850cf2579c1b0872da87f2706d80", "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": "include/mona/utility.hpp", "max_forks_repo_name": "Eleobert/mona", "max_forks_repo_head_hexsha": "079e70b190b0850cf2579c1b0872da87f2706d80", "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.6226415094, "max_line_length": 97, "alphanum_fraction": 0.4553794829, "num_tokens": 353, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.888758793492457, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.7327477927168994}}
{"text": "#include <ros/ros.h>\r\n#include \"std_msgs/String.h\"\r\n#include <geometry_msgs/Twist.h>\r\n#include <stdlib.h>\r\n#include <iostream>\r\n#include <Eigen/Dense>\r\n#include <Eigen/QR>\r\n#include <Eigen/LU>\r\n#include <math.h>\r\n#include <stdio.h>\r\n//#include <turtlesim/Pose.h>\r\n#include <Eigen/Geometry>\r\n#include \"gazebo_msgs/ApplyJointEffort.h\"\r\n#include <math.h>\r\n\r\nusing namespace Eigen;\r\n\r\n//For geometry_msgs::Twist using:\r\n// \t\tdummy.linear.x\r\n// \t\tdummy.linear.y\r\n// \t\tdummy.angular.z\r\ngeometry_msgs::Twist robot_position;\r\ngeometry_msgs::Twist velocity_msg;\r\n\r\n//rate_hz assignment\r\ndouble rate_hz = 1;\r\n\r\n// Transform robot velocities (x,y,w) to motor velocities (m1,m2,m3,m4)\r\ndouble* getMotorValue(int x_velocity, int y_velocity, int w_velocity){\r\n\tdouble deg1 = 3 * M_PI / 10;\r\n\tdouble deg2 = 3 * M_PI / 10;\r\n\tdouble deg3 = 7 * M_PI / 30;\r\n\tdouble deg4 = 7 * M_PI / 30;\r\n\tdouble s1 = sin(deg1), c1 = cos(deg1);\r\n\tdouble s2 = sin(deg2), c2 = cos(deg2);\r\n\tdouble s3 = sin(deg3), c3 = cos(deg3);\r\n\tdouble s4 = sin(deg4), c4 = cos(deg4);\r\n\tdouble R = 8.5;\r\n\tdouble r = 3.4;\r\n\r\n\tdouble velXMod = x_velocity * 3.5 / ( 2 * M_PI * r );\r\n    double velYMod = y_velocity * 3.5 / ( 2 * M_PI * r );\r\n    double velWMod = w_velocity * 3.5 / ( 2 * M_PI * r );\r\n\r\n    velWMod = R * velWMod;\r\n    double velMots[4];\r\n\r\n    velMots[0] = (double)( s1 * velXMod + c1 * velYMod + velWMod);\r\n    velMots[1] = (double)(-s2 * velXMod + c2 * velYMod + velWMod);\r\n    velMots[2] = (double)(-s3 * velXMod - c3 * velYMod + velWMod);\r\n    velMots[3] = (double)( s4 * velXMod - c4 * velYMod + velWMod);\r\n\r\n    return velMots;\r\n}\r\n\r\nvoid get_vel_vec(const geometry_msgs::Twist& msg) {\r\n\tvelocity_msg.linear.x = msg.linear.x;\r\n\tvelocity_msg.linear.y = msg.linear.y;\r\n    velocity_msg.angular.z = msg.linear.z; \r\n}\r\n\r\n\r\nint main(int argc, char **argv){\r\n\tros::init(argc,argv,\"robot_velocity_node\");\r\n\tros::NodeHandle nh;\r\n\tROS_INFO_STREAM(\"robot_velocity_node initialized\");\r\n\tROS_INFO_STREAM(ros::this_node::getName());\r\n\t\r\n\t// Suscribe to Gazebo service ApplyJointEffor\r\n\tros::ServiceClient client = nh.serviceClient<gazebo_msgs::ApplyJointEffort>(\"/gazebo/apply_joint_effort\");\r\n\tgazebo_msgs::ApplyJointEffort eff_msg[4];\r\n\t\r\n\r\n\tros::Subscriber sub_vel = nh.subscribe(\"/target_vel_topic\", 1000, &get_vel_vec);\r\n\r\n\tdouble tiempo = 0;\r\n\r\n    //define the max speed\r\n\tdouble cruise_speed = 50;\r\n\r\n    //define the rate\r\n\tros::Rate rate(rate_hz);\r\n\tros::Time start_time ;\r\n\tros::Duration duration ;\r\n\r\n\tdouble effort[4];\r\n\t\r\n\twhile (ros::ok())\r\n\t{\r\n\tdouble* velMots = getMotorValue(velocity_msg.linear.x,velocity_msg.linear.y,velocity_msg.angular.z);\r\n\t\r\n\teffort [0] = velMots[0];\r\n\teffort [1] = velMots[1];\r\n\teffort [2] = velMots[2];\r\n\teffort [3] = velMots[3];\r\n  \r\n\t\tif(client.exists()){\r\n\t\t\t\r\n\t\t\tstart_time.sec = 0;\r\n\t\t\tstart_time.nsec = 0;\r\n\t\t\tduration.sec = 1/rate_hz;\r\n\t\t\tduration.nsec = 0;\r\n\r\n\t\t\t// Wheel-Joint 1\r\n\t\t\teff_msg[0].request.joint_name = \"chassis_JOINT_1\";\r\n\t\t\teff_msg[0].request.duration = duration;\r\n\t\t\teff_msg[0].request.effort = effort[0];\r\n\t\t\teff_msg[0].request.start_time = start_time;\r\n\r\n\t\t\t// Wheel-Joint 2\r\n\t\t\teff_msg[1].request.joint_name = \"chassis_JOINT_2\";\r\n\t\t\teff_msg[1].request.duration = duration;\r\n\t\t\teff_msg[1].request.effort = effort[1];\r\n\t\t\teff_msg[1].request.start_time = start_time;\r\n\r\n\t\t\t// Wheel-Joint 3\r\n\t\t\teff_msg[2].request.joint_name = \"chassis_JOINT_3\";\r\n\t\t\teff_msg[2].request.duration = duration;\r\n\t\t\teff_msg[2].request.effort = effort[2];\r\n\t\t\teff_msg[2].request.start_time = start_time;\r\n\r\n\t\t\t// Wheel-Joint 4\r\n\t\t\teff_msg[3].request.joint_name = \"chassis_JOINT_4\";\r\n\t\t\teff_msg[3].request.duration = duration;\r\n\t\t\teff_msg[3].request.effort = effort[03];\r\n\t\t\teff_msg[3].request.start_time = start_time;\r\n\r\n\t\t\tclient.call(eff_msg[0]);\r\n\t\t\tclient.call(eff_msg[1]);\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\tclient.call(eff_msg[2]);\r\n\t\t\tclient.call(eff_msg[3]);\r\n\t\t\tROS_INFO_STREAM(\"Joints ==> 1: \" << ((eff_msg[0].response.success == 1) ? \"TRUE\" : \"FALSE\") <<\r\n\t\t\t\" 2: \" << ((eff_msg[1].response.success == 1) ? \"TRUE\" : \"FALSE\") <<\r\n\t\t\t\" 3: \" << ((eff_msg[2].response.success == 1) ? \"TRUE\" : \"FALSE\") <<\r\n\t\t\t\" 4: \" << ((eff_msg[3].response.success == 1) ? \"TRUE\" : \"FALSE\"));\r\n\t\t}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\r\n\t\tros::spinOnce();\r\n\t\trate.sleep();\r\n    }\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "4359b6724c8c0b5a3cbeee21f1b5eb5179c22d35", "size": 4391, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "data/SDI-11911/Proyecto2/src/ekbot_ctrl/robot_velocity_node.cpp", "max_stars_repo_name": "khairulislam/phys", "max_stars_repo_head_hexsha": "fc702520fcd3b23022b9253e7d94f878978b4500", "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": "data/SDI-11911/Proyecto2/src/ekbot_ctrl/robot_velocity_node.cpp", "max_issues_repo_name": "khairulislam/phys", "max_issues_repo_head_hexsha": "fc702520fcd3b23022b9253e7d94f878978b4500", "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": "data/SDI-11911/Proyecto2/src/ekbot_ctrl/robot_velocity_node.cpp", "max_forks_repo_name": "khairulislam/phys", "max_forks_repo_head_hexsha": "fc702520fcd3b23022b9253e7d94f878978b4500", "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.7062937063, "max_line_length": 108, "alphanum_fraction": 0.6160327944, "num_tokens": 1373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896758909756, "lm_q2_score": 0.795658104908603, "lm_q1q2_score": 0.7326337685388205}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n\nusing namespace std;\nusing namespace Eigen;\n\nint main() {\n  Matrix3f A;\n  Vector3f b;\n  A << 1, 2, 3, 4, 5, 6, 7, 8, 10;\n  b << 3, 3, 4;\n  cout << \"Here is the matrix A:\\n\" << A << endl;\n  cout << \"Here is the vector b:\\n\" << b << endl;\n  Vector3f x = A.colPivHouseholderQr().solve(b);\n  cout << \"The solution is:\\n\" << x << endl;\n}\n", "meta": {"hexsha": "f9c1166faccfd567daae69b5fd2d735a8d539969", "size": 377, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/Eigen-3.3/doc/examples/TutorialLinAlgExSolveColPivHouseholderQR.cpp", "max_stars_repo_name": "chen0510566/CarND-Path-Planning-Project", "max_stars_repo_head_hexsha": "4652e5c459980252e4ab72a0fd687341f3245466", "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/Eigen-3.3/doc/examples/TutorialLinAlgExSolveColPivHouseholderQR.cpp", "max_issues_repo_name": "chen0510566/CarND-Path-Planning-Project", "max_issues_repo_head_hexsha": "4652e5c459980252e4ab72a0fd687341f3245466", "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": "include/Eigen-3.3/doc/examples/TutorialLinAlgExSolveColPivHouseholderQR.cpp", "max_forks_repo_name": "chen0510566/CarND-Path-Planning-Project", "max_forks_repo_head_hexsha": "4652e5c459980252e4ab72a0fd687341f3245466", "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.1764705882, "max_line_length": 49, "alphanum_fraction": 0.5782493369, "num_tokens": 144, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9207896715436482, "lm_q2_score": 0.7956580976404297, "lm_q1q2_score": 0.7326337583873752}}
{"text": "\n#include \"stdafx.h\"\n#include \"CppUnitTest.h\"\n#include \"splines.h\"\n#include <iostream>\n#include <iomanip>\n#include <limits>\n#include <vector>\n #include <fstream>\n#include <array>\n#include <Eigen/Dense>\n#include <Eigen/StdVector>\n\n\nusing namespace Microsoft::VisualStudio::CppUnitTestFramework;\n\nnamespace UnitTest1\n{\t\t\n\tTEST_CLASS(UnitTest1)\n\n\t{\n\tpublic:\n\t\tdouble max_double = std::numeric_limits<double>::max();\n\n\t\tTEST_METHOD(Cubic2dCoefficient)\n\t\t{\n\t\t\tstd::ifstream in_file(\"cubic2d.dat\");\n\t\t\tAssert::IsTrue(in_file.is_open());\n\t\t\tstd::ofstream out_file(\"cubic2dcoeff.points\");\n\t\t\tEigen::Vector2d control_point;\n\t\t\tstd::vector<Eigen::Vector2d> control_points;\n\t\t\twhile (in_file >> control_point.x() >> control_point.y()) {\n\t\t\t\tcontrol_points.push_back(control_point);\n\t\t\t}\n\t\t\tstd::vector<double> coefficients;\n\t\t\tfor (size_t i = 0; i < control_points.size() / 4; ++i) {\n\t\t\t\tcoefficients = bezier::GetCoefficients<double>(control_points, i, 3, bezier::k2d);\n\t\t\t\tAssert::IsTrue(coefficients.size() == 8);\n\t\t\t\tout_file << std::fixed << std::setprecision(14);\n\t\t\t\tfor (auto j : coefficients) {\n\t\t\t\t\tout_file << j << '\\n';\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tTEST_METHOD(Cubic3dCoefficient)\n\t\t{\n\t\t\tstd::ifstream in_file(\"cubic3d.dat\");\n\t\t\tAssert::IsTrue(in_file.is_open());\n\t\t\tstd::ofstream out_file(\"cubic3dcoeff.points\");\n\t\t\tEigen::Vector3d control_point;\n\t\t\tstd::vector<Eigen::Vector3d> control_points;\n\t\t\twhile (in_file >> control_point.x() >> control_point.y() >> control_point.z()) {\n\t\t\t\tcontrol_points.push_back(control_point);\n\t\t\t}\n\t\t\tstd::vector<double> coefficients;\n\t\t\tfor (size_t i = 0; i < control_points.size() / 4; ++i) {\n\t\t\t\tcoefficients = bezier::GetCoefficients<double>(control_points, i);\n\t\t\t\tAssert::IsTrue(coefficients.size() == 12);\n\t\t\t\tout_file << std::fixed << std::setprecision(14);\n\t\t\t\tfor (auto j : coefficients) {\n\t\t\t\t\tout_file << j << '\\n';\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tTEST_METHOD(Quad2dCoefficient)\n\t\t{\n\t\t\tstd::ifstream in_file(\"quad2d.dat\");\n\t\t\tAssert::IsTrue(in_file.is_open());\n\t\t\tstd::ofstream out_file(\"quad2dcoeff.points\");\n\t\t\tEigen::Vector2d control_point;\n\t\t\tstd::vector<Eigen::Vector2d> control_points;\n\t\t\twhile (in_file >> control_point.x() >> control_point.y()) {\n\t\t\t\tcontrol_points.push_back(control_point);\n\t\t\t}\n\t\t\tstd::vector<double> coefficients;\n\t\t\tfor (size_t i = 0; i < control_points.size() / 3; ++i) {\n\t\t\t\tcoefficients = bezier::GetCoefficients<double>(control_points, i, 2, bezier::k2d);\n\t\t\t\tAssert::IsTrue(coefficients.size() == 6);\n\t\t\t\tout_file << std::fixed << std::setprecision(14);\n\t\t\t\tfor (auto j : coefficients) {\n\t\t\t\t\tout_file << j << '\\n';\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tTEST_METHOD(Quad3dCoefficient)\n\t\t{\n\t\t\tstd::ifstream in_file(\"quad3d.dat\");\n\t\t\tAssert::IsTrue(in_file.is_open());\n\t\t\tstd::ofstream out_file(\"quad3dcoeff.points\");\n\t\t\tEigen::Vector3d control_point;\n\t\t\tstd::vector<Eigen::Vector3d> control_points;\n\t\t\twhile (in_file >> control_point.x() >> control_point.y() >> control_point.z()) {\n\t\t\t\tcontrol_points.push_back(control_point);\n\t\t\t}\n\t\t\tstd::vector<double> coefficients;\n\t\t\tfor (size_t i = 0; i < control_points.size() / 3; ++i) {\n\t\t\t\tcoefficients = bezier::GetCoefficients<double>(control_points, i, 2, bezier::k3d);\n\t\t\t\tAssert::IsTrue(coefficients.size() == 9);\n\t\t\t\tout_file << std::fixed << std::setprecision(14);\n\t\t\t\tfor (auto j : coefficients) {\n\t\t\t\t\tout_file << j << '\\n';\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tTEST_METHOD(Cubic2dCoordinate)\n\t\t{\n\t\t\tstd::ifstream in_file(\"cubic2d.dat\");\n\t\t\tAssert::IsTrue(in_file.is_open());\n\t\t\tstd::ofstream out_file(\"cubic2dcoord.points\");\n\t\t\tEigen::Vector2d control_point;\n\t\t\tstd::vector<Eigen::Vector2d> control_points;\n\t\t\twhile (in_file >> control_point.x() >> control_point.y()) {\n\t\t\t\tcontrol_points.push_back(control_point);\n\t\t\t}\n\n\t\t\tEigen::Vector2d coordinate;\n\t\t\tEigen::Vector2d empty;\n\t\t\tempty << max_double, max_double;\n\t\t\tcoordinate = empty;\n\t\t\tout_file << std::fixed << std::setprecision(14);\n\t\t\tfor (size_t i = 0; i < control_points.size() / 4; ++i) {\n\t\t\t\tcoordinate = bezier::GetPosition<double>(control_points, .25, i, 3, bezier::k2d);\n\t\t\t\tAssert::IsFalse(coordinate == empty);\n\t\t\t\tout_file << coordinate.transpose() << '\\n';\n\t\t\t\tcoordinate = empty;\n\t\t\t\tcoordinate = bezier::GetPosition<double>(control_points, .5, i, 3, bezier::k2d);\n\t\t\t\tAssert::IsFalse(coordinate == empty);\n\t\t\t\tout_file << coordinate.transpose() << '\\n';\n\t\t\t\tcoordinate = empty;\n\t\t\t\tcoordinate = bezier::GetPosition<double>(control_points, .75, i, 3, bezier::k2d);\n\t\t\t\tAssert::IsFalse(coordinate == empty);\n\t\t\t\tout_file << coordinate.transpose() << '\\n';\n\t\t\t\tcoordinate = empty;\n\t\t\t}\n\n\t\t}\n\n\t\tTEST_METHOD(Cubic3dCoordinate)\n\t\t{\n\t\t\tstd::ifstream in_file(\"cubic3d.dat\");\n\t\t\tAssert::IsTrue(in_file.is_open());\n\t\t\tstd::ofstream out_file(\"cubic3dcoord.points\");\n\t\t\tEigen::Vector3d control_point;\n\t\t\tstd::vector<Eigen::Vector3d> control_points;\n\t\t\twhile (in_file >> control_point.x() >> control_point.y() >> control_point.z()) {\n\t\t\t\tcontrol_points.push_back(control_point);\n\t\t\t}\n\n\t\t\tEigen::Vector3d coordinate;\n\t\t\tEigen::Vector3d empty;\n\t\t\tempty << max_double, max_double, max_double;\n\t\t\tcoordinate = empty;\n\t\t\tout_file << std::fixed << std::setprecision(14);\n\t\t\tfor (size_t i = 0; i < control_points.size() / 4; ++i) {\n\t\t\t\tcoordinate = bezier::GetPosition<double>(control_points, .25, i);\n\t\t\t\tAssert::IsFalse(coordinate == empty);\n\t\t\t\tout_file << coordinate.transpose() << '\\n';\n\t\t\t\tcoordinate = empty;\n\t\t\t\tcoordinate = bezier::GetPosition<double>(control_points, .5, i);\n\t\t\t\tAssert::IsFalse(coordinate == empty);\n\t\t\t\tout_file << coordinate.transpose() << '\\n';\n\t\t\t\tcoordinate = empty;\n\t\t\t\tcoordinate = bezier::GetPosition<double>(control_points, .75, i);\n\t\t\t\tAssert::IsFalse(coordinate == empty);\n\t\t\t\tout_file << coordinate.transpose() << '\\n';\n\t\t\t\tcoordinate = empty;\n\t\t\t}\n\n\t\t}\n\n\t\tTEST_METHOD(Quad2dCoordinate)\n\t\t{\n\t\t\tstd::ifstream in_file(\"quad2d.dat\");\n\t\t\tAssert::IsTrue(in_file.is_open());\n\t\t\tstd::ofstream out_file(\"quad2dcoord.points\");\n\t\t\tEigen::Vector2d control_point;\n\t\t\tstd::vector<Eigen::Vector2d> control_points;\n\t\t\twhile (in_file >> control_point.x() >> control_point.y()) {\n\t\t\t\tcontrol_points.push_back(control_point);\n\t\t\t}\n\t\t\tEigen::Vector2d coordinate;\n\t\t\tEigen::Vector2d empty;\n\t\t\tempty << max_double, max_double;\n\t\t\tcoordinate = empty;\n\t\t\tout_file << std::fixed << std::setprecision(14);\n\t\t\tfor (size_t i = 0; i < control_points.size() / 3; ++i) {\n\t\t\t\tcoordinate = bezier::GetPosition<double>(control_points, .25, i, 2, bezier::k2d);\n\t\t\t\tAssert::IsFalse(coordinate == empty);\n\t\t\t\tout_file << coordinate.transpose() << '\\n';\n\t\t\t\tcoordinate = empty;\n\t\t\t\tcoordinate = bezier::GetPosition<double>(control_points, .5, i, 2, bezier::k2d);\n\t\t\t\tAssert::IsFalse(coordinate == empty);\n\t\t\t\tout_file << coordinate.transpose() << '\\n';\n\t\t\t\tcoordinate = empty;\n\t\t\t\tcoordinate = bezier::GetPosition<double>(control_points, .75, i, 2, bezier::k2d);\n\t\t\t\tAssert::IsFalse(coordinate == empty);\n\t\t\t\tout_file << coordinate.transpose() << '\\n';\n\t\t\t\tcoordinate = empty;\n\t\t\t}\n\n\t\t}\n\n\t\tTEST_METHOD(Quad3dCoordinate)\n\t\t{\n\t\t\tstd::ifstream in_file(\"quad3d.dat\");\n\t\t\tAssert::IsTrue(in_file.is_open());\n\t\t\tstd::ofstream out_file(\"quad3dcoord.points\");\n\t\t\tEigen::Vector3d control_point;\n\t\t\tstd::vector<Eigen::Vector3d> control_points;\n\t\t\twhile (in_file >> control_point.x() >> control_point.y() >> control_point.z()) {\n\t\t\t\tcontrol_points.push_back(control_point);\n\t\t\t}\n\t\t\tEigen::Vector3d coordinate;\n\t\t\tEigen::Vector3d empty;\n\t\t\tempty << max_double, max_double, max_double;\n\t\t\tcoordinate = empty;\n\t\t\tout_file << std::fixed << std::setprecision(14);\n\t\t\tfor (size_t i = 0; i < control_points.size() / 3; ++i) {\n\t\t\t\tcoordinate = bezier::GetPosition<double>(control_points, .25, i, 2);\n\t\t\t\tAssert::IsFalse(coordinate == empty);\n\t\t\t\tout_file << coordinate.transpose() << '\\n';\n\t\t\t\tcoordinate = empty;\n\t\t\t\tcoordinate = bezier::GetPosition<double>(control_points, .5, i, 2);\n\t\t\t\tAssert::IsFalse(coordinate == empty);\n\t\t\t\tout_file << coordinate.transpose() << '\\n';\n\t\t\t\tcoordinate = empty;\n\t\t\t\tcoordinate = bezier::GetPosition<double>(control_points, .75, i, 2);\n\t\t\t\tAssert::IsFalse(coordinate == empty);\n\t\t\t\tout_file << coordinate.transpose() << '\\n';\n\t\t\t\tcoordinate = empty;\n\t\t\t}\n\n\t\t}\n\n\t\tTEST_METHOD(Cubic2dTangent)\n\t\t{\n\t\t\tstd::ifstream in_file(\"cubic2d.dat\");\n\t\t\tAssert::IsTrue(in_file.is_open());\n\t\t\tstd::ofstream out_file(\"cubic2dtan.points\");\n\t\t\tEigen::Vector2d control_point;\n\t\t\tstd::vector<Eigen::Vector2d> control_points;\n\t\t\twhile (in_file >> control_point.x() >> control_point.y()) {\n\t\t\t\tcontrol_points.push_back(control_point);\n\t\t\t}\n\n\t\t\tEigen::Vector2d coordinate;\n\t\t\tEigen::Vector2d tangent;\n\t\t\tEigen::Vector2d empty;\n\t\t\tempty << max_double, max_double;\n\t\t\tcoordinate = empty;\n\t\t\ttangent = empty;\n\t\t\tout_file << std::fixed << std::setprecision(14);\n\t\t\tfor (size_t i = 0; i < control_points.size() / 4; ++i) {\n\t\t\t\tcoordinate = bezier::GetPosition<double>(control_points, .5, i, 3, bezier::k2d);\n\t\t\t\tAssert::IsFalse(coordinate == empty);\n\t\t\t\tout_file << coordinate.transpose() << '\\n';\n\t\t\t\ttangent = bezier::GetFirstDerivative<double>(control_points, .5, i, 3, bezier::k2d);\n\t\t\t\tAssert::IsFalse(tangent == empty);\n\t\t\t\ttangent.normalize();\n\t\t\t\ttangent += coordinate;\n\t\t\t\tout_file << tangent.transpose() << '\\n';\n\t\t\t\tcoordinate = empty;\n\t\t\t\ttangent = empty;\n\t\t\t}\n\t\t}\n\n\t\tTEST_METHOD(Cubic3dTangent)\n\t\t{\n\t\t\t//using Point = Eigen::Vector3d;\n\t\t\tusing Point = std::array<double, 3>;\n\t\t\tstd::ifstream in_file(\"cubic.dat\");\n\t\t\tAssert::IsTrue(in_file.is_open());\n\t\t\tstd::ofstream out_file(\"cubic.points\");\n\t\t\tPoint control_point;\n\t\t\tstd::vector<Point> control_points;\n\t\t\t//while (in_file >> control_point.x() >> control_point.y() >> control_point.z()) {\n\t\t\t//\tcontrol_points.push_back(control_point);\n\t\t\t//}\n\t\t\twhile (in_file >> control_point[0] >> control_point[1] >> control_point[2]) {\n\t\t\t\tcontrol_points.push_back(control_point);\n\t\t\t}\n\n\t\t\tPoint coordinate;\n\t\t\tPoint tangent;\n\t\t\tPoint normal;\n\t\t\tPoint empty;\n\t\t\t//empty << max_double, max_double, max_double;\n\t\t\tfor (size_t i = 0; i < 3; ++i) {\n\t\t\t\tempty[i] = max_double;\n\t\t\t}\n\t\t\tcoordinate = empty;\n\t\t\tnormal = empty;\n\t\t\ttangent = empty;\n\t\t\tout_file << std::fixed << std::setprecision(14);\n\t\t\tfor (size_t i = 0; i < control_points.size() / 4; ++i) {\n\t\t\t\tcoordinate = bezier::GetPosition<double>(control_points, .25, i);\n\t\t\t\tAssert::IsFalse(coordinate == empty);\n\t\t\t\tEigen::Vector3d eigen_coordinate;\n\t\t\t\teigen_coordinate << coordinate[0], coordinate[1], coordinate[2];\n\t\t\t\tout_file << eigen_coordinate.transpose() << '\\n';\n\t\t\t\t//out_file << coordinate[0] << ' ' << coordinate[1] << ' ' << coordinate[2] << '\\n';\n\t\t\t\ttangent = bezier::GetFirstDerivative<double>(control_points, .25, i);\n\t\t\t\tAssert::IsFalse(tangent == empty);\n\t\t\t\tEigen::Vector3d normal_tangent;\n\t\t\t\tnormal_tangent << tangent[0], tangent[1], tangent[2];\n\t\t\t\tnormal_tangent.normalize();\n\t\t\t\tnormal_tangent += eigen_coordinate;\n\t\t\t\tout_file << normal_tangent.transpose() << '\\n';\n\t\t\t\t//out_file << tangent.transpose() << '\\n';\n\t\t\t\tnormal = bezier::GetNormal<double>(control_points, .25, i);\n\t\t\t\tAssert::IsFalse(normal == empty);\n\t\t\t\tEigen::Vector3d eigen_normal;\n\t\t\t\teigen_normal << normal[0], normal[1], normal[2];\n\t\t\t\teigen_normal.normalize();\n\t\t\t\teigen_normal += eigen_coordinate;\n\t\t\t\tout_file << eigen_normal.transpose() << '\\n';\n\t\t\t\tcoordinate = empty;\n\t\t\t\ttangent = empty;\n\n\t\t\t\tcoordinate = bezier::GetPosition<double>(control_points, .5, i);\n\t\t\t\tAssert::IsFalse(coordinate == empty);\n\t\t\t\teigen_coordinate << coordinate[0], coordinate[1], coordinate[2];\n\t\t\t\tout_file << eigen_coordinate.transpose() << '\\n';\n\t\t\t\t//out_file << coordinate[0] << ' ' << coordinate[1] << ' ' << coordinate[2] << '\\n';\n\t\t\t\ttangent = bezier::GetFirstDerivative<double>(control_points, .5, i);\n\t\t\t\tAssert::IsFalse(tangent == empty);\n\t\t\t\tnormal_tangent << tangent[0], tangent[1], tangent[2];\n\t\t\t\tnormal_tangent.normalize();\n\t\t\t\tnormal_tangent += eigen_coordinate;\n\t\t\t\tout_file << normal_tangent.transpose() << '\\n';\n\t\t\t\t//out_file << tangent.transpose() << '\\n';\n\t\t\t\tnormal = bezier::GetNormal<double>(control_points, .5, i);\n\t\t\t\tAssert::IsFalse(normal == empty);\n\t\t\t\teigen_normal << normal[0], normal[1], normal[2];\n\t\t\t\teigen_normal.normalize();\n\t\t\t\teigen_normal += eigen_coordinate;\n\t\t\t\tout_file << eigen_normal.transpose() << '\\n';\n\t\t\t\tcoordinate = empty;\n\t\t\t\ttangent = empty;\n\n\t\t\t\tcoordinate = bezier::GetPosition<double>(control_points, .75, i);\n\t\t\t\tAssert::IsFalse(coordinate == empty);\n\t\t\t\teigen_coordinate << coordinate[0], coordinate[1], coordinate[2];\n\t\t\t\tout_file << eigen_coordinate.transpose() << '\\n';\n\t\t\t\t//out_file << coordinate[0] << ' ' << coordinate[1] << ' ' << coordinate[2] << '\\n';\n\t\t\t\ttangent = bezier::GetFirstDerivative<double>(control_points, .75, i);\n\t\t\t\tAssert::IsFalse(tangent == empty);\n\t\t\t\tnormal_tangent << tangent[0], tangent[1], tangent[2];\n\t\t\t\tnormal_tangent.normalize();\n\t\t\t\tnormal_tangent += eigen_coordinate;\n\t\t\t\tout_file << normal_tangent.transpose() << '\\n';\n\t\t\t\t//out_file << tangent.transpose() << '\\n';\n\t\t\t\tnormal = bezier::GetNormal<double>(control_points, .75, i);\n\t\t\t\tAssert::IsFalse(normal == empty);\n\t\t\t\teigen_normal << normal[0], normal[1], normal[2];\n\t\t\t\teigen_normal.normalize();\n\t\t\t\teigen_normal += eigen_coordinate;\n\t\t\t\tout_file << eigen_normal.transpose() << '\\n';\n\t\t\t\tcoordinate = empty;\n\t\t\t\ttangent = empty;\n\t\t\t}\n\t\t}\n\n\t\tTEST_METHOD(Quad2dTangent)\n\t\t{\n\t\t\tstd::ifstream in_file(\"quad2d.dat\");\n\t\t\tAssert::IsTrue(in_file.is_open());\n\t\t\tstd::ofstream out_file(\"quad2dtan.points\");\n\t\t\tEigen::Vector2d control_point;\n\t\t\tstd::vector<Eigen::Vector2d> control_points;\n\t\t\twhile (in_file >> control_point.x() >> control_point.y()) {\n\t\t\t\tcontrol_points.push_back(control_point);\n\t\t\t}\n\n\t\t\tEigen::Vector2d coordinate;\n\t\t\tEigen::Vector2d tangent;\n\t\t\tEigen::Vector2d normal;\n\t\t\tEigen::Vector2d empty;\n\t\t\tempty << max_double, max_double;\n\t\t\tcoordinate = empty;\n\t\t\ttangent = empty;\n\t\t\tnormal = empty;\n\t\t\tout_file << std::fixed << std::setprecision(14);\n\t\t\tfor (size_t i = 0; i < control_points.size() / 3; ++i) {\n\t\t\t\tcoordinate = bezier::GetPosition<double>(control_points, .5, i, 2, bezier::k2d);\n\t\t\t\tAssert::IsFalse(coordinate == empty);\n\t\t\t\tout_file << coordinate.transpose() << '\\n';\n\t\t\t\ttangent = bezier::GetFirstDerivative<double>(control_points, .5, i, 2, bezier::k2d);\n\t\t\t\tAssert::IsFalse(tangent == empty);\n\t\t\t\ttangent.normalize();\n\t\t\t\ttangent += coordinate;\n\t\t\t\tout_file << tangent.transpose() << '\\n';\n\t\t\t\t//normal = bezier::GetNormal<double, bezier::k2d, 2>(control_points, i, .5);\n\t\t\t\t//Assert::IsFalse(normal == empty);\n\t\t\t\t//normal.normalize();\n\t\t\t\t//normal += coordinate;\n\t\t\t\t//out_file << normal.transpose() << '\\n';\n\t\t\t\tcoordinate = empty;\n\t\t\t\ttangent = empty;\n\t\t\t}\n\t\t}\n\n\t\tTEST_METHOD(Quad3dTangent)\n\t\t{\n\t\t\tusing Point = Eigen::Vector3d;\n\t\t\tstd::ifstream in_file(\"quad3d.dat\");\n\t\t\tAssert::IsTrue(in_file.is_open());\n\t\t\tstd::ofstream out_file(\"quad3dtan.points\");\n\t\t\tPoint control_point;\n\t\t\tstd::vector<Point> control_points;\n\t\t\twhile (in_file >> control_point.x() >> control_point.y() >> control_point.z()) {\n\t\t\t\tcontrol_points.push_back(control_point);\n\t\t\t}\n\n\t\t\tPoint coordinate;\n\t\t\tPoint tangent;\n\t\t\tPoint normal;\n\t\t\tPoint empty;\n\t\t\tempty << max_double, max_double, max_double;\n\t\t\tcoordinate = empty;\n\t\t\ttangent = empty;\n\t\t\tnormal = empty;\n\t\t\tout_file << std::fixed << std::setprecision(14);\n\t\t\tfor (size_t i = 0; i < control_points.size() / 3; ++i) {\n\t\t\t\tcoordinate = bezier::GetPosition<double>(control_points, .75, i, 2);\n\t\t\t\tAssert::IsFalse(coordinate == empty);\n\t\t\t\tout_file << coordinate.transpose() << '\\n';\n\t\t\t\ttangent = bezier::GetFirstDerivative<double>(control_points, .75, i, 2);\n\t\t\t\tAssert::IsFalse(tangent == empty);\n\t\t\t\ttangent.normalize();\n\t\t\t\ttangent += coordinate;\n\t\t\t\tout_file << tangent.transpose() << '\\n';\n\t\t\t\tnormal = bezier::GetNormal<double>(control_points, .75, i, 2);\n\t\t\t\tAssert::IsFalse(normal == empty);\n\t\t\t\tnormal.normalize();\n\t\t\t\tnormal += coordinate;\n\t\t\t\tout_file << normal.transpose() << '\\n';\n\t\t\t\tcoordinate = empty;\n\t\t\t\ttangent = empty;\n\t\t\t}\n\t\t}\n\n\t\tTEST_METHOD(Quartic3dTangent)\n\t\t{\n\t\t\tusing Point = Eigen::Vector3d;\n\t\t\t//using Point = std::array<double, 3>;\n\t\t\tstd::ifstream in_file(\"quartic3d.dat\");\n\t\t\tAssert::IsTrue(in_file.is_open());\n\t\t\tstd::ofstream out_file(\"quartic3dtan.points\");\n\t\t\tPoint control_point;\n\t\t\tstd::vector<Point> control_points;\n\t\t\t//while (in_file >> control_point.x() >> control_point.y() >> control_point.z()) {\n\t\t\t//\tcontrol_points.push_back(control_point);\n\t\t\t//}\n\t\t\twhile (in_file >> control_point[0] >> control_point[1] >> control_point[2]) {\n\t\t\t\tcontrol_points.push_back(control_point);\n\t\t\t}\n\n\t\t\tPoint coordinate;\n\t\t\tPoint tangent;\n\t\t\tPoint normal;\n\t\t\tPoint empty;\n\t\t\t//empty << max_double, max_double, max_double;\n\t\t\tfor (size_t i = 0; i < 3; ++i) {\n\t\t\t\tempty[i] = max_double;\n\t\t\t}\n\t\t\tcoordinate = empty;\n\t\t\tnormal = empty;\n\t\t\ttangent = empty;\n\t\t\tout_file << std::fixed << std::setprecision(14);\n\t\t\tfor (size_t i = 0; i < control_points.size() / 5; ++i) {\n\t\t\t\tcoordinate = bezier::GetPosition<double>(control_points, .5, i, 4);\n\t\t\t\tAssert::IsFalse(coordinate == empty);\n\t\t\t\tEigen::Vector3d eigen_coordinate;\n\t\t\t\teigen_coordinate << coordinate[0], coordinate[1], coordinate[2];\n\t\t\t\tout_file << eigen_coordinate.transpose() << '\\n';\n\t\t\t\t//out_file << coordinate[0] << ' ' << coordinate[1] << ' ' << coordinate[2] << '\\n';\n\t\t\t\ttangent = bezier::GetFirstDerivative<double>(control_points, .5, i, 4, bezier::k3d);\n\t\t\t\tAssert::IsFalse(tangent == empty);\n\t\t\t\tEigen::Vector3d normal_tangent;\n\t\t\t\tnormal_tangent << tangent[0], tangent[1], tangent[2];\n\t\t\t\tnormal_tangent.normalize();\n\t\t\t\tnormal_tangent += eigen_coordinate;\n\t\t\t\tout_file << normal_tangent.transpose() << '\\n';\n\t\t\t\tnormal = bezier::GetNormal<double>(control_points, .5, i, 4);\n\t\t\t\tAssert::IsFalse(normal == empty);\n\t\t\t\tEigen::Vector3d eigen_normal;\n\t\t\t\teigen_normal << normal[0], normal[1], normal[2];\n\t\t\t\teigen_normal.normalize();\n\t\t\t\teigen_normal += eigen_coordinate;\n\t\t\t\tout_file << eigen_normal.transpose() << '\\n';\n\t\t\t\tcoordinate = empty;\n\t\t\t\ttangent = empty;\n\t\t\t}\n\t\t}\n\n\t\tTEST_METHOD(PascalRow) {\n\t\t\tstd::ofstream out_file(\"pascalRow.dat\");\n\t\t\tout_file << std::fixed << std::setprecision(0);\n\t\t\tEigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> pascal_row = bezier::GetBinomialCoefficients<double>(10);\n\t\t\t//out_file << pascal_row.transpose() << '\\n';\n\t\t}\n\n\t};\n}", "meta": {"hexsha": "d9a7e684aeb4d79ff69bff787124da847abf54d2", "size": 18159, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "UnitTest1/unittest1.cpp", "max_stars_repo_name": "hpmachining/splines", "max_stars_repo_head_hexsha": "9df0e51eac3169f0f518159752719f3b0fbfdb9c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-07-22T15:29:18.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-04T21:31:33.000Z", "max_issues_repo_path": "UnitTest1/unittest1.cpp", "max_issues_repo_name": "hpmachining/splines", "max_issues_repo_head_hexsha": "9df0e51eac3169f0f518159752719f3b0fbfdb9c", "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": "UnitTest1/unittest1.cpp", "max_forks_repo_name": "hpmachining/splines", "max_forks_repo_head_hexsha": "9df0e51eac3169f0f518159752719f3b0fbfdb9c", "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.6758349705, "max_line_length": 114, "alphanum_fraction": 0.656478881, "num_tokens": 5068, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896671963207, "lm_q2_score": 0.7956581000631541, "lm_q1q2_score": 0.7326337571592085}}
{"text": "#include <vector>\n#include <chrono>\n#include <iostream>\n#include <Eigen/Dense>\n\ntemplate<typename vectype>\ndouble Clenshaw1D(const vectype &c, double ind){\n    int N = static_cast<int>(c.size()) - 1;\n    double u_k = 0, u_kp1 = 0, u_kp2 = 0;\n    for (int k = N; k >= 0; --k){\n        // Do the recurrent calculation\n        u_k = 2.0*ind*u_kp1 - u_kp2 + c[k];\n        if (k > 0){\n            // Update the values\n            u_kp2 = u_kp1; u_kp1 = u_k;\n        }\n    }\n    return (u_k - u_kp2)/2;\n}\n\n/// With STL datatypes\ntemplate<typename Mat, typename vectype>\ndouble Clenshaw2D(const Mat& a, double x, double y, vectype& b) {\n    std::size_t m = a.size() - 1;\n    std::size_t n = a[0].size() - 1;\n    for (auto i = 0; i < b.size(); ++i) {\n        b[i] = Clenshaw1D(a[i], y);\n    }\n    return Clenshaw1D(b, x);\n}\n\ntemplate<typename MatType, int Cols = MatType::ColsAtCompileTime>\nauto Clenshaw1DByRow(const MatType& c, double ind) {\n    int N = static_cast<int>(c.rows()) - 1;\n    static Eigen::Array<double, 1, Cols> u_k, u_kp1, u_kp2;\n    // Not statically sized    \n    if constexpr (Cols < 0) {\n        int M = c.rows();\n        u_k.resize(M); \n        u_kp1.resize(M);\n        u_kp2.resize(M);\n    }\n    u_k.setZero(); u_kp1.setZero(); u_kp2.setZero();\n    \n    for (int k = N; k >= 0; --k) {\n        // Do the recurrent calculation\n        u_k = 2.0 * ind * u_kp1 - u_kp2 + c.row(k);\n        if (k > 0) {\n            // Update the values\n            u_kp2 = u_kp1; u_kp1 = u_k;\n        }\n    }\n    return (u_k - u_kp2) / 2;\n}\n\n/// With Eigen datatypes\ntemplate<typename MatType>\ndouble Clenshaw2DEigen(const MatType& a, double x, double y) {\n    auto b = Clenshaw1DByRow(a, y);\n    return Clenshaw1D(b.matrix(), x);\n}\n\ntemplate<int Rows, int Cols>\nvoid test_Eigen(int M){\n    using MatType = Eigen::Array<double, Rows, Cols>;\n    MatType aa; \n    if constexpr ((Rows < 0) || (Cols < 0)) {\n        aa.resize(M + 1, M + 1);\n    }\n    else{\n        aa.resize(M + 1, M + 1);\n    }\n    aa.fill(0.0);\n    for (auto i = 0; i < M + 1; ++i) {\n        for (auto j = 0; j < M + 1; ++j) {\n            aa(i, j) = i + j;\n        }\n    }\n    int N = 1000 * 1000;\n    volatile auto r = 0.0, x = 0.1, y = 0.7;\n    auto startTime = std::chrono::system_clock::now();\n    for (int i = 0; i < N; ++i) {\n        auto v = Clenshaw2DEigen(aa, x, y);\n        r += v;\n    }\n    auto endTime = std::chrono::system_clock::now();\n    auto elap_us = std::chrono::duration<double>(endTime - startTime).count() / N * 1e6;\n    std::cout << elap_us << \" us/call. (Eigen-powered) value:\" << (r / N) << std::endl;\n}\n\nint main(){\n    std::vector<std::vector<double>> a;\n    const int M = 8;\n    for (auto i = 0; i <= M; ++i){\n        a.push_back(std::vector<double>(M+1, 0.0)); // One would normally use Eigen here, but the challenge is to use only standard library elements...\n    }\n    {\n        for (auto i = 0; i < M + 1; ++i) {\n            for (auto j = 0; j < M + 1; ++j) {\n                a[i][j] = i + j;\n            }\n        }\n        std::vector<double> b(M+1, 0.0);\n        int N = 1000 * 1000;\n        volatile auto r = 0.0, x = 0.1, y = 0.7;\n        auto startTime = std::chrono::system_clock::now();\n        for (int i = 0; i < N; ++i) {\n            auto v = Clenshaw2D(a, x, y, b);\n            r += v;\n        }\n        auto endTime = std::chrono::system_clock::now();\n        auto elap_us = std::chrono::duration<double>(endTime - startTime).count() / N * 1e6;\n        std::cout << elap_us << \" us/call. value:\" << (r / N) << std::endl;\n    }\n    std::cout  << \"Dynamic:\" << std::endl;\n    test_Eigen<Eigen::Dynamic, Eigen::Dynamic>(M);\n\n    std::cout  << \"Static:\" << std::endl;\n    test_Eigen<M+1, M+1>(M);\n}", "meta": {"hexsha": "eddbcfa37b75ef42136b229f08a94ced86bd39b5", "size": 3699, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scripts/Basu/BasuEigen.cpp", "max_stars_repo_name": "usnistgov/chebby", "max_stars_repo_head_hexsha": "75dbccfd9a029e91cbfdfd263befc51b893822ea", "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/Basu/BasuEigen.cpp", "max_issues_repo_name": "usnistgov/chebby", "max_issues_repo_head_hexsha": "75dbccfd9a029e91cbfdfd263befc51b893822ea", "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": "scripts/Basu/BasuEigen.cpp", "max_forks_repo_name": "usnistgov/chebby", "max_forks_repo_head_hexsha": "75dbccfd9a029e91cbfdfd263befc51b893822ea", "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.825, "max_line_length": 151, "alphanum_fraction": 0.5193295485, "num_tokens": 1283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146761176671, "lm_q2_score": 0.8333246015211008, "lm_q1q2_score": 0.7326146244361157}}
{"text": "/*************************************************\n * @Description: file content\n * @Author: yuanquan\n * @Email: yuanquan2011@qq.com\n * @Date: 2021-05-17 21:20:13\n * @LastEditors: yuanquan\n * @LastEditTime: 2021-07-24 12:20:47\n * @copyright: Copyright (c) yuanquan\n *************************************************/\n#include <iostream>\n#include <vector>\n#include <set>\n#include <string>\n#include <gtest/gtest.h>\n#include <boost/array.hpp>\n#include <tuple>\n\nusing namespace std;\nusing namespace boost;\nusing namespace testing;\n\n// 10: b1010, 3: b0011\nint divide(int dividend, int divisor) {\n\tif(dividend == 0) return 0;\n\tif(divisor == INT32_MIN) \n\t{\n\t\tif(dividend == INT32_MIN)return 1;\n\t\telse return 0;\n\t}\n\tif(dividend == INT32_MIN && divisor == -1) return INT32_MAX;\n\tif(dividend == INT32_MIN && divisor == 1) return INT32_MIN;\n\n\tbool isPositive = (dividend > 0 && divisor > 0) || (dividend < 0 && divisor < 0);\n\t\n\tint result = 0;\n\tif(divisor < 0) divisor = -divisor;\n\tif(dividend == INT32_MIN)\n\t{\n\t\t++result;\n\t\tdividend += divisor;\n\t}\n\tif(dividend < 0) dividend = -dividend;\n\tfor(int i=31; i >= 0; --i)\n\t{\n\t\tif((dividend >> i) >= divisor)\n\t\t{\n\t\t\tdividend -= (divisor << i);\n\t\t\tresult += (1 << i);\n\t\t}\n\t}\n\tif(isPositive) return result;\n\telse return -result;\n}\n\nTEST(divideTest, all)\n{\n\tusing TestData = tuple<int, int, int>;\n\tvector<TestData> datas{\n\t\tmake_tuple(10, 3, 3),\n\t\tmake_tuple(7, -3, -2),\n\t\tmake_tuple(0, 1, 0),\n\t\tmake_tuple(1, 1, 1),\n\t\tmake_tuple(INT32_MIN, -1, INT32_MAX),\n\t\tmake_tuple(INT32_MIN, INT32_MIN, 1),\n\t};\n\n\tfor(auto& dat : datas)\n\t{\n\t\tauto [dividend, divisor, result] = dat;\n\t\tEXPECT_EQ(result, divide(dividend, divisor)) << dividend << \"/\" << divisor;\n\t}\n}\n", "meta": {"hexsha": "1837f1f2ef6033d58b5940991f662eec084f849c", "size": 1683, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "solved/29_divide.cpp", "max_stars_repo_name": "ysdg/Leetcode", "max_stars_repo_head_hexsha": "772245ba8f6aff92d3ce13a3d27c0a4f62162354", "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": "solved/29_divide.cpp", "max_issues_repo_name": "ysdg/Leetcode", "max_issues_repo_head_hexsha": "772245ba8f6aff92d3ce13a3d27c0a4f62162354", "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": "solved/29_divide.cpp", "max_forks_repo_name": "ysdg/Leetcode", "max_forks_repo_head_hexsha": "772245ba8f6aff92d3ce13a3d27c0a4f62162354", "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.0547945205, "max_line_length": 82, "alphanum_fraction": 0.6042780749, "num_tokens": 528, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.8539127492339909, "lm_q1q2_score": 0.73245912073733}}
{"text": "// https://projecteuler.net/problem=57\n/*\nSquare root convergents\n\nIt is possible to show that the square root of two can be expressed as\nan infinite continued fraction.\n\n2^1/2 = 1 + 1/(2 + 1/(2 + 1/(2 + ... ))) = 1.414213...\n\nBy expanding this for the first four iterations, we get:\n\n1 + 1/2 = 3/2 = 1.5\n1 + 1/(2 + 1/2) = 7/5 = 1.4\n1 + 1/(2 + 1/(2 + 1/2)) = 17/12 = 1.41666...\n1 + 1/(2 + 1/(2 + 1/(2 + 1/2))) = 41/29 = 1.41379...\n\nThe next three expansions are 99/70, 239/169, and 577/408, but the eighth expansion,\n1393/985, is the first example where the number of digits in the numerator exceeds\nthe number of digits in the denominator.\n\nIn the first one-thousand expansions, how many fractions contain a numerator\nwith more digits than denominator?\n\nSolution:\n*/\n\n#include <iostream>\n#include <cstdint>\n#include <string>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <chrono>\n\nauto compute() {\n\tusing namespace boost::multiprecision;\n\tconstexpr uint32_t limit = 1000;\n\n\tcpp_int natural = 3, den = 2;\n\tuint32_t count = 0;\n\tfor (uint32_t t = 2; t <= limit; ++t) {\n\t\tnatural += den << 1;\n\t\tden = natural - den;\n\t\tif (natural.str().length() > den.str().length()) {\n\t\t\t++count;\n\t\t\t//std::cout << t << ',';\n\t\t}\n\t}\n\n\treturn count;\n}\n\n#ifdef _MSC_VER\n\ttemplate <class T>\n\tinline void DoNotOptimize(const T &value) {\n\t\t__asm { lea ebx, value }\n\t}\n#else\n\ttemplate <class T>\n\t__attribute__((always_inline)) inline void DoNotOptimize(const T &value) {\n\t\tasm volatile(\"\" : \"+m\"(const_cast<T &>(value)));\n\t}\n#endif\n\nint main() {\n\tusing namespace std;\n\tusing namespace chrono;\n\tauto start = high_resolution_clock::now();\n\tauto result = compute();\n\tDoNotOptimize(result);\n\tcout << \"Done in \"\n\t\t<< duration_cast<nanoseconds>(high_resolution_clock::now() - start).count() / 1e6\n\t\t<< \" miliseconds.\" << endl;\n\tcout << result << endl;\n}", "meta": {"hexsha": "7d6d9cee44ae464658efe0f7f3d3502b8b6c3bfe", "size": 1828, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ProjectEuler/Problems/problem051_075/Solution057.cpp", "max_stars_repo_name": "ankitdixit/code-gems", "max_stars_repo_head_hexsha": "bdb30ba5c714f416dbf54d479d055458bde36085", "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": "ProjectEuler/Problems/problem051_075/Solution057.cpp", "max_issues_repo_name": "ankitdixit/code-gems", "max_issues_repo_head_hexsha": "bdb30ba5c714f416dbf54d479d055458bde36085", "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": "ProjectEuler/Problems/problem051_075/Solution057.cpp", "max_forks_repo_name": "ankitdixit/code-gems", "max_forks_repo_head_hexsha": "bdb30ba5c714f416dbf54d479d055458bde36085", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-09-30T06:26:02.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-20T14:41:55.000Z", "avg_line_length": 25.0410958904, "max_line_length": 84, "alphanum_fraction": 0.6597374179, "num_tokens": 570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.859663743319094, "lm_q2_score": 0.8519527963298947, "lm_q1q2_score": 0.732392930024127}}
{"text": "// Ax=b\n#include <iostream>\n#include <Eigen/Dense>\nusing namespace std;\nusing namespace Eigen;\nint main()\n{\n   Matrix3f A;\n   Vector3f b;\n   A << 1,2,3,  4,5,6,  7,8,10;\n   b << 3, 3, 4;\n   cout << \"Here is the matrix A:\\n\" << A << endl;\n   cout << \"Here is the vector b:\\n\" << b << endl;\n   Vector3f x = A.colPivHouseholderQr().solve(b); // QR decompsition\n   // ColPivHouseholderQR<Matrix3f> dec(A);\n   // Vector3f x = dec.solve(b);\n   cout << \"The solution is:\\n\" << x << endl;\n}\n\nPartialPivLU            partialPivLu()          Invertible              ++      ++      +\nFullPivLU               fullPivLu()             None                    -       - -     +++\nHouseholderQR           householderQr()         None                    ++      ++      +\nColPivHouseholderQR     colPivHouseholderQr()   None                    ++      -       +++\nFullPivHouseholderQR    fullPivHouseholderQr()  None                    -       - -     +++\nLLT                     llt()                   Positive definite       +++     +++     +\nLDLT                    ldlt()                  Positive or\n                                                negative semidefinite   +++     +       ++\nJacobiSVD               jacobiSvd()             None                    - -     - - -   +++\n", "meta": {"hexsha": "1c1dc1fe45db10c6606911391c1e96607ddf4f2d", "size": 1273, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "snippets/eigen-colPivHouseholderQr.cpp", "max_stars_repo_name": "district10/snippet-manager", "max_stars_repo_head_hexsha": "bebe45a601368947168e3ee6e6ab8c1fc2ee2055", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2018-08-04T09:28:19.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-19T17:46:34.000Z", "max_issues_repo_path": "snippets/eigen-colPivHouseholderQr.cpp", "max_issues_repo_name": "district10/snippet-manager", "max_issues_repo_head_hexsha": "bebe45a601368947168e3ee6e6ab8c1fc2ee2055", "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": "snippets/eigen-colPivHouseholderQr.cpp", "max_forks_repo_name": "district10/snippet-manager", "max_forks_repo_head_hexsha": "bebe45a601368947168e3ee6e6ab8c1fc2ee2055", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-07-31T04:14:55.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-02T01:22:39.000Z", "avg_line_length": 43.8965517241, "max_line_length": 91, "alphanum_fraction": 0.4226237235, "num_tokens": 341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.926303724190573, "lm_q2_score": 0.7905303211371898, "lm_q1q2_score": 0.7322711805549486}}
{"text": "/**\n\t@file rotation.cpp\n\tUtilities for expressing and converting rotations of reference frames\n\n\t@brief All of the rotation parameterizations here represent rotations\n\tof an initial fixed frame to a new frame. Therefore using these\n\tparameterizations to operate on a vector is the same as transforming\n\tthe new frame coordinates into the original fixed frame.\n\n\tExamples if rotation describes relation of body w.r.t. inertial\n\t(how to rotate inertial to body):\n\tR: coverts body frame coordinates into inertial frame coordinates\n\teuler: usual roll-pitch-yaw of body frame w.r.t inertial frame\n\n*/\n\n#include <utils/rotation.hpp>\n\n#include <Eigen/Dense>\n#include <cmath>\n\n/** \n    @brief Converts the rotation matrix R to the Euler angles (ZYX)\n    (Yaw-Pitch-Roll) (psi, theta, phi) used for aircraft conventions.\n    Note to compute the Euler angles for the aircraft this should be\n    the R matrix that converts a vector from body frame coordinates\n    to a vector in inertial frame coordinates.\n\n    @param[in] R  rotation matrix\n    @param[in] e  euler angles e = (phi, theta, psi) = (roll, pitch, yaw)\n*/\nvoid Rot::R_to_euler(const Eigen::Matrix3d& R, Eigen::Vector3d& e) {\n    // Check for singularity that occurs when pitch = 90 deg\n    if (sqrt(R(0,0)*R(0,0) + R(1,0)*R(1,0)) >= 1e-6) {\n    \te(0) = atan2(R(2,1), R(2,2));\n        e(1) = asin(-R(2,0));\n        e(2) = atan2(R(1,0), R(0,0));\n    }\n    else {\n    \te(0) = atan2(-R(1,2), R(1,1));\n        e(1) = asin(-R(2,0));\n        e(2) = 0.0;\n    }\t\n}\n\n/**\n    @brief Converts Euler angles (ZYX) (Yaw-Pitch-Roll) (psi, theta, phi) \n    into the inertial to body rotation matrix\n\t\n    @param[in] e  euler angles e = (phi, theta, psi) = (roll, pitch, yaw)\n    @param[in] R  rotation matrix\n*/\nvoid Rot::euler_to_R(const Eigen::Vector3d& e, Eigen::Matrix3d& R) {\n    R(0,0) = cos(e(1))*cos(e(2));\n    R(0,1) = sin(e(0))*sin(e(1))*cos(e(2)) - cos(e(0))*sin(e(2));\n    R(0,2) = sin(e(0))*sin(e(2)) + cos(e(0))*sin(e(1))*cos(e(2));\n    R(1,0) = cos(e(1))*sin(e(2));\n    R(1,1) = cos(e(0))*cos(e(2)) + sin(e(0))*sin(e(1))*sin(e(2));\n    R(1,2) = cos(e(0))*sin(e(1))*sin(e(2)) - sin(e(0))*cos(e(2));\n    R(2,0) = -sin(e(1));\n    R(2,1) = sin(e(0))*cos(e(1));\n    R(2,2) = cos(e(0))*cos(e(1));\n}\n\n/**\n    @brief Converts a unit quaternion into a rotation matrix\n\n    @param[in] q  unit quaternion q = (w, x, y, z) = w + (x i, y j, z k) \n    @param[in] R  rotation matrix\n*/\nvoid Rot::quat_to_R(const Eigen::Vector4d& q, Eigen::Matrix3d& R) {\n    R(0,0) = 1.0 - 2.0*q(2)*q(2) - 2.0*q(3)*q(3);\n    R(0,1) = 2.0*q(1)*q(2) - 2.0*q(3)*q(0);\n    R(0,2) = 2.0*q(1)*q(3) + 2.0*q(2)*q(0);\n    R(1,0) = 2.0*q(1)*q(2) + 2.0*q(3)*q(0);\n    R(1,1) = 1.0 - 2.0*q(1)*q(1) - 2.0*q(3)*q(3);\n    R(1,2) = 2.0*q(2)*q(3) - 2.0*q(1)*q(0);\n    R(2,0) = 2.0*q(1)*q(3) - 2.0*q(2)*q(0);\n    R(2,1) = 2.0*q(2)*q(3) + 2.0*q(1)*q(0);\n    R(2,2) = 1.0 - 2.0*q(1)*q(1) - 2.0*q(2)*q(2);\n}\n\n/**\n    @brief Converts a unit quaternion into the aircraft Euler angles\n    (ZYX) (Yaw-Pitch-Roll) (psi, theta, phi)\n\n    @param[in] q  unit quaternion q = (w, x, y, z) = w + (x i, y j, z k) \n    @param[in] e  euler angles e = (phi, theta, psi) = (roll, pitch, yaw)\n*/\nvoid Rot::quat_to_euler(const Eigen::Vector4d& q, Eigen::Vector3d& e) {\n    double R00 = 1.0 - 2.0*q(2)*q(2) - 2.0*q(3)*q(3);\n    double R10 = 2.0*q(1)*q(2) + 2*q(3)*q(0);\n    if (sqrt(R00*R00 + R10*R10 >= 1e-6)) {\n        e(0) = atan2(2.0*q(2)*q(3) + 2.0*q(1)*q(0), 1.0 - 2.0*q(1)*q(1) - 2.0*q(2)*q(2));\n        e(1) = asin(-2.0*q(1)*q(3) + 2.0*q(2)*q(0));\n        e(2) = atan2(R10, R00);\n    }\n    else {\n        e(0) = atan2(-2.0*q(2)*q(3) - 2.0*q(1)*q(0), 1.0 - 2.0*q(1)*q(1) - 2.0*q(3)*q(3));\n        e(1) = asin(-2.0*q(1)*q(3) + 2.0*q(2)*q(0));\n        e(2) = 0.0;\n    }\n}\n\n/**\n    @brief Converts aircraft Euler angles (ZYX) (Yaw-Pitch-Roll) (psi, theta, phi)\n    into unit quaternion\n\n    @param[in] e  euler angles e = (phi, theta, psi) = (roll, pitch, yaw)\n    @param[in] q  unit quaternion q = (w, x, y, z) = w + (x i, y j, z k)\n*/\nvoid Rot::euler_to_quat(const Eigen::Vector3d& e, Eigen::Vector4d& q) {\n    double phi = 0.5 * e(0);\n    double th = 0.5 * e(1);\n    double psi = 0.5 * e(2);\n    q(0) = cos(phi) * cos(th) * cos(psi) + sin(phi) * sin(th) * sin(psi);\n    q(1) = sin(phi) * cos(th) * cos(psi) - cos(phi) * sin(th) * sin(psi);\n    q(2) = cos(phi) * sin(th) * cos(psi) + sin(phi) * cos(th) * sin(psi);\n    q(3) = cos(phi) * cos(th) * sin(psi) - sin(phi) * sin(th) * cos(psi);\n}\n\n/**\n    @brief Converts an axis and angle into a unit quaternion\n\n    @param[in] aa  axis/angle aa = (x, y, z), th = ||aa||, e = aa/th \n    @param[in] q   unit quaternion q = (w, x, y, z) = w + (x i, y j, z k) \n*/\nvoid Rot::axis_to_quat(const Eigen::Vector3d& aa, Eigen::Vector4d& q) {\n    double th = aa.norm();\n    if (th < 0.0000001) {\n        q(0) = 1.0;\n        q(1) = 0.0;\n        q(2) = 0.0;\n        q(3) = 0.0;\n    }\n    else {\n        Eigen::Vector3d e = aa.normalized();\n        q(0) = cos(th/2.0);\n        q(1) = e(0)*sin(th/2.0);\n        q(2) = e(1)*sin(th/2.0);\n        q(3) = e(2)*sin(th/2.0);\n    }\n}    \n\n/**\n    @brief Converts a unit quaternion into a normalized axis and angle.\n\n    @param[in] q   unit quaternion q = (w, x, y, z) = w + (x i, y j, z k) \n    @param[in] aa  axis/angle aa = (x, y, z), th = ||aa||, e = aa/th \n*/\nvoid Rot::quat_to_axis(const Eigen::Vector4d& q, Eigen::Vector3d& aa) {\n    if (q(0) > 0.9999999) { // no rotation\n        aa(0) = 0.0;\n        aa(1) = 0.0;\n        aa(2) = 0.0;\n\t}\n    else {\n        double m = 2.0*acos(q(0))/sqrt(1.0 - q(0)*q(0));\n        aa(0) = m*q(1);\n        aa(1) = m*q(2);\n        aa(2) = m*q(3);\n\n        // Scale to keep magnitude less than pi\n        double th = aa.norm();\n        if (th > M_PI) {\n            double th_new = 2 * M_PI - th;\n            aa = -(th_new/th)*aa;\n        }\n    }\n}\n\n/**\n    @brief Composes two rotations parameterized by unit quaternions\n    and outputs a single quaternion representing the composed rotation.\n    This performs rotation p first and then rotation q after.\n\n    @param[in] p   unit quaternion p = (pw, px, py, pz) = pw + (px i, py j, pz k) \n    @param[in] q   unit quaternion q = (qw, qx, qy, qz) = qw + (qx i, qy j, qz k) \n    @param[in] o   composed unit quaternion o = (ow, ox, oy, oz) = ow + (ox i, oy j, oz k) \n*/\nvoid Rot::compose_quats(const Eigen::Vector4d& p, const Eigen::Vector4d q, Eigen::Vector4d& o) {\n    o(0) = p(0)*q(0) - (p(1)*q(1) + p(2)*q(2) + p(3)*q(3));\n    o(1) = p(0)*q(1) + p(1)*q(0) + p(2)*q(3) - p(3)*q(2);\n    o(2) = p(0)*q(2) - p(1)*q(3) + p(2)*q(0) + p(3)*q(1);\n    o(3) = p(0)*q(3) + p(1)*q(2) - p(2)*q(1) + p(3)*q(0);\n}\n\n/**\n    @brief Inverts a unit quaternion, gives the opposite rotation\n\n    @param[in] q   unit quaternion q = (qw, qx, qy, qz) = qw + (qx i, qy j, qz k) \n*/\nvoid Rot::invert_quat(Eigen::Vector4d& q) {\n    q(1) *= -1.0;\n    q(2) *= -1.0;\n    q(3) *= -1.0;\n}\n\ndouble Rot::rad_to_deg(double th) {\n    return th*(180.0/M_PI);\n}\n\ndouble Rot::deg_to_rad(double th) {\n    return th*(M_PI/180.0);\n}\n\n/**\n    @brief Wraps angle th [rad] to range [0, 2pi]\n*/\ndouble Rot::wrap_to_2pi(double th) {\n    th = fmod(th, 2.0*M_PI);\n    if (th < 0) return th + 2.0 * M_PI;\n    else return th;\n}\n\n/**\n    @brief Wraps angle th [rad] to range [-pi, pi]\n*/\ndouble Rot::wrap_to_pi(double th) {\n    return Rot::wrap_to_2pi(th + M_PI) - M_PI;\n}\n\n", "meta": {"hexsha": "7b246c33c88ad61d72bafc6255c5d984c6c8f602", "size": 7368, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/utils/rotation.cpp", "max_stars_repo_name": "jlorenze/asl_fixedwing", "max_stars_repo_head_hexsha": "9cac7c8d31f5d1c9f7d059d4614d6b60f1a3fbef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-06-28T17:30:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T09:04:35.000Z", "max_issues_repo_path": "src/utils/rotation.cpp", "max_issues_repo_name": "jlorenze/asl_fixedwing", "max_issues_repo_head_hexsha": "9cac7c8d31f5d1c9f7d059d4614d6b60f1a3fbef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-08-31T16:22:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-31T16:36:15.000Z", "max_forks_repo_path": "src/utils/rotation.cpp", "max_forks_repo_name": "jlorenze/asl_fixedwing", "max_forks_repo_head_hexsha": "9cac7c8d31f5d1c9f7d059d4614d6b60f1a3fbef", "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.0403587444, "max_line_length": 96, "alphanum_fraction": 0.5337947883, "num_tokens": 3009, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105696, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.7321009008749532}}
{"text": "// Computer the winding number of a polygon at a point\n// Author: Shayan Hoshyari\n\n#ifndef polyvec_winding_number_\n#define polyvec_winding_number_\n\n#include <Eigen/Core>\n\nnamespace polyvec {\n    namespace WindingNumber {\n        // Input:\n        // polygon: polygon 2 x numpoints matrix\n        // point: the point to compute the winding number at\n        // Returns:\n        // winding_number: value of winding number\n        // is_trustable: is the number trustable, or are we too close to the boundary?\n        // NOTE: assumes that the polygon points are sorted in CCW order.\n        // multiply the answer by -1 if the order is CW.\n        void compute_winding ( const Eigen::Matrix2Xd& polygon, const Eigen::Vector2d& point,  double& winding_number, bool& is_trustable );\n\n        // Input:\n        // polygon: polygon 2 x numpoints matrix\n        // Returns:\n        // winding_number: is ccw\n       void compute_orientation ( const Eigen::Matrix2Xd& polygon,  bool &is_ccw, double &area );\n       void compute_orientation ( const Eigen::Matrix2Xd& polygon,  bool &is_ccw );\n\n    }\n} // end of polyvec\n\n\n#endif", "meta": {"hexsha": "88a34298d09e8156af9585c2c85cca4e436adf52", "size": 1118, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/polyvec/geometry/winding_number.hpp", "max_stars_repo_name": "ShnitzelKiller/polyfit", "max_stars_repo_head_hexsha": "51ddc6365a794db1678459140658211cb78f65b1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2020-08-17T17:25:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T05:49:12.000Z", "max_issues_repo_path": "include/polyvec/geometry/winding_number.hpp", "max_issues_repo_name": "ShnitzelKiller/polyfit", "max_issues_repo_head_hexsha": "51ddc6365a794db1678459140658211cb78f65b1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-08-26T13:54:59.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-21T07:19:22.000Z", "max_forks_repo_path": "include/polyvec/geometry/winding_number.hpp", "max_forks_repo_name": "ShnitzelKiller/polyfit", "max_forks_repo_head_hexsha": "51ddc6365a794db1678459140658211cb78f65b1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-08-26T23:26:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-04T09:06:07.000Z", "avg_line_length": 34.9375, "max_line_length": 140, "alphanum_fraction": 0.6672629696, "num_tokens": 269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971872, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.7321008945026413}}
{"text": "#include \"SGFitLeastSquares.h\"\n#include <Eigen/Eigen>\n#include <Eigen/nnls.h>\n\nnamespace Probulator\n{\n\tSgBasis sgFitLeastSquares(const SgBasis& basis, const std::vector<RadianceSample>& samples)\n\t{\n\t\tusing namespace Eigen;\n\t\tSgBasis result = basis;\n\n\t\tMatrixXf A;\n\t\tA.resize(samples.size(), basis.size());\n\t\tfor (u64 sampleIt = 0; sampleIt < samples.size(); ++sampleIt)\n\t\t{\n\t\t\tfor (u64 lobeIt = 0; lobeIt < basis.size(); ++lobeIt)\n\t\t\t{\n\t\t\t\tA(sampleIt, lobeIt) = sgEvaluate(basis[lobeIt].p, basis[lobeIt].lambda, samples[sampleIt].direction);\n\t\t\t}\n\t\t}\n\n\t\tfor (u32 channelIt = 0; channelIt < 3; ++channelIt)\n\t\t{\n\t\t\tVectorXf b;\n\t\t\tb.resize(samples.size());\n\t\t\tfor (u64 sampleIt = 0; sampleIt < samples.size(); ++sampleIt)\n\t\t\t{\n\t\t\t\tb[sampleIt] = samples[sampleIt].value[channelIt];\n\t\t\t}\n\n\t\t\tVectorXf x = A.jacobiSvd(ComputeThinU | ComputeThinV).solve(b);\n\t\t\tfor (u64 lobeIt = 0; lobeIt < basis.size(); ++lobeIt)\n\t\t\t{\n\t\t\t\tresult[lobeIt].mu[channelIt] = x[lobeIt];\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t}\n\n\t// Non-negative version of least squares\n\tSgBasis sgFitNNLeastSquares(const SgBasis& basis, const std::vector<RadianceSample>& samples)\n\t{\n\t\tusing namespace Eigen;\n\t\tSgBasis result = basis;\n\n\t\tMatrixXf A;\n\t\tA.resize(samples.size(), basis.size());\n\t\tfor (u64 sampleIt = 0; sampleIt < samples.size(); ++sampleIt)\n\t\t{\n\t\t\tfor (u64 lobeIt = 0; lobeIt < basis.size(); ++lobeIt)\n\t\t\t{\n\t\t\t\tA(sampleIt, lobeIt) = sgEvaluate(basis[lobeIt].p, basis[lobeIt].lambda, samples[sampleIt].direction);\n\t\t\t}\n\t\t}\n\n\t\tNNLS<MatrixXf> nnlssolver(A);\n\t\tfor (u32 channelIt = 0; channelIt < 3; ++channelIt)\n\t\t{\n\t\t\tVectorXf b;\n\t\t\tb.resize(samples.size());\n\t\t\tfor (u64 sampleIt = 0; sampleIt < samples.size(); ++sampleIt)\n\t\t\t{\n\t\t\t\tb[sampleIt] = samples[sampleIt].value[channelIt];\n\t\t\t}\n\n\t\t\t// -- run the solver\n\t\t\tnnlssolver.solve(b);\n\t\t\tVectorXf x = nnlssolver.x();\n\n\t\t\tfor (u64 lobeIt = 0; lobeIt < basis.size(); ++lobeIt)\n\t\t\t{\n\t\t\t\tresult[lobeIt].mu[channelIt] = x[lobeIt];\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t}\n}\n", "meta": {"hexsha": "4b57eb163952861c26ce47acf3ea8e990e6929ac", "size": 1969, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Source/Probulator/SGFitLeastSquares.cpp", "max_stars_repo_name": "kayru/Probulator", "max_stars_repo_head_hexsha": "b8adb56850fdeac62061d1d733718ee0763f29b6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 362.0, "max_stars_repo_stars_event_min_datetime": "2016-03-30T20:03:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T02:15:37.000Z", "max_issues_repo_path": "Source/Probulator/SGFitLeastSquares.cpp", "max_issues_repo_name": "kayru/Probulator", "max_issues_repo_head_hexsha": "b8adb56850fdeac62061d1d733718ee0763f29b6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2016-03-31T14:55:35.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-07T07:04:46.000Z", "max_forks_repo_path": "Source/Probulator/SGFitLeastSquares.cpp", "max_forks_repo_name": "kayru/Probulator", "max_forks_repo_head_hexsha": "b8adb56850fdeac62061d1d733718ee0763f29b6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 32.0, "max_forks_repo_forks_event_min_datetime": "2016-03-31T01:12:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T02:55:30.000Z", "avg_line_length": 24.6125, "max_line_length": 105, "alphanum_fraction": 0.6470289487, "num_tokens": 671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465098415278, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.7320606133308725}}
{"text": "/**\n * Copyright 2014-2017 Steven T Sell (ssell@vertexfragment.com)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#include \"Math/MathCommon.hpp\"\n\n#ifdef _DEBUG\n\n#include \"gtest/gtest.h\"\n\n#include <boost/utility/binary.hpp>\n\n//------------------------------------------------------------------------------------------\n\nTEST(MathCommon, Normalise)\n{\n    double dValue = 240.0f;\n    dValue = Ocular::Math::Normalize<double>(dValue, 0.0, 180.0);\n\n    EXPECT_NEAR(dValue, 60.0, Ocular::Math::EPSILON_DOUBLE);\n\n    int iValue = -20;\n    iValue = Ocular::Math::Normalize<int>(iValue, -18, 18);\n\n    EXPECT_EQ(iValue, 16);\n}\n\nTEST(MathCommon, DegreesToRadians)\n{\n    double degrees = 180.0;\n    double result  = Ocular::Math::DegreesToRadians<double>(degrees);\n\n    EXPECT_NEAR(result, Ocular::Math::PI, Ocular::Math::EPSILON_DOUBLE);\n\n    degrees = -90.0;\n    result  = Ocular::Math::DegreesToRadians<double>(degrees);\n\n    EXPECT_NEAR(result, -Ocular::Math::PI_OVER_TWO, Ocular::Math::EPSILON_DOUBLE);\n\n    degrees = 0.0;\n    result  = Ocular::Math::DegreesToRadians<double>(degrees);\n\n    EXPECT_NEAR(result, 0.0, Ocular::Math::EPSILON_DOUBLE);\n}\n\nTEST(MathCommon, RadiansToDegrees)\n{\n    double radians = Ocular::Math::PI;\n    double result  = Ocular::Math::RadiansToDegrees<double>(radians);\n\n    EXPECT_NEAR(result, 180.0, Ocular::Math::EPSILON_DOUBLE);\n\n    radians = -Ocular::Math::PI_OVER_TWO;\n    result  = Ocular::Math::RadiansToDegrees<double>(radians);\n\n    EXPECT_NEAR(result, -90.0, Ocular::Math::EPSILON_DOUBLE);\n\n    radians = 0.0;\n    result  = Ocular::Math::RadiansToDegrees<double>(radians);\n\n    EXPECT_NEAR(result, 0.0, Ocular::Math::EPSILON_DOUBLE);\n}\n\nTEST(MathCommon, Clamp)\n{\n    double valA = 35.0;\n\n    double expectA = 20.0;\n    double expectB = 50.0;\n    double expectC = 35.0;\n\n    double resultA = Ocular::Math::Clamp<double>(valA, 0.0, 20.0);\n    double resultB = Ocular::Math::Clamp<double>(valA, 50.0, 100.0);\n    double resultC = Ocular::Math::Clamp<double>(valA, 0.0, 100.0);\n\n    EXPECT_NEAR(expectA, resultA, Ocular::Math::EPSILON_DOUBLE);\n    EXPECT_NEAR(expectB, resultB, Ocular::Math::EPSILON_DOUBLE);\n    EXPECT_NEAR(expectC, resultC, Ocular::Math::EPSILON_DOUBLE);\n}\n\nTEST(MathCommon, RoundUpDecimal)\n{\n    double valA = 0.2749999;\n    double valB = 0.975;\n    double valC = 0.86736;\n\n    double expectA = 0.275;\n    double expectB = 0.98;\n    double expectC = 0.868;\n\n    double resultA = Ocular::Math::RoundUpDecimal<double>(valA, 3);\n    double resultB = Ocular::Math::RoundUpDecimal<double>(valB, 2);\n    double resultC = Ocular::Math::RoundUpDecimal<double>(valC, 3);\n\n    EXPECT_NEAR(expectA, resultA, Ocular::Math::EPSILON_DOUBLE);\n    EXPECT_NEAR(expectB, resultB, Ocular::Math::EPSILON_DOUBLE);\n    EXPECT_NEAR(expectC, resultC, Ocular::Math::EPSILON_DOUBLE);\n}\n\nTEST(MathCommon, RoundUpPowTen)\n{\n    double valA = 1250.0;\n    double valB = 18.0;\n\n    double expectA = 1300.0;\n    double expectB = 100.0;\n\n    double resultA = Ocular::Math::RoundUpPowTen<double>(valA, 2);\n    double resultB = Ocular::Math::RoundUpPowTen<double>(valB, 2);\n\n    EXPECT_NEAR(expectA, resultA, Ocular::Math::EPSILON_DOUBLE);\n    EXPECT_NEAR(expectB, resultB, Ocular::Math::EPSILON_DOUBLE);\n}\n\nTEST(MathCommon, RoundDownDecimal)\n{\n    double valA = 0.2749999;\n    double valB = 0.975;\n    double valC = 0.86736;\n\n    double expectA = 0.274;\n    double expectB = 0.97;\n    double expectC = 0.867;\n\n    double resultA = Ocular::Math::RoundDownDecimal<double>(valA, 3);\n    double resultB = Ocular::Math::RoundDownDecimal<double>(valB, 2);\n    double resultC = Ocular::Math::RoundDownDecimal<double>(valC, 3);\n\n    EXPECT_NEAR(expectA, resultA, Ocular::Math::EPSILON_DOUBLE);\n    EXPECT_NEAR(expectB, resultB, Ocular::Math::EPSILON_DOUBLE);\n    EXPECT_NEAR(expectC, resultC, Ocular::Math::EPSILON_DOUBLE);\n}\n\nTEST(MathCommon, RoundDownPowTen)\n{\n    double valA = 1250.0;\n    double valB = 18.0;\n\n    double expectA = 1200.0;\n    double expectB = 0.0;\n\n    double resultA = Ocular::Math::RoundDownPowTen<double>(valA, 2);\n    double resultB = Ocular::Math::RoundDownPowTen<double>(valB, 2);\n\n    EXPECT_NEAR(expectA, resultA, Ocular::Math::EPSILON_DOUBLE);\n    EXPECT_NEAR(expectB, resultB, Ocular::Math::EPSILON_DOUBLE);\n}\n\nTEST(MathCommon, RoundDecimal)\n{\n    double valA = 0.127;\n    double valB = 0.123;\n\n    double expectA = 0.13;\n    double expectB = 0.12;\n\n    double resultA = Ocular::Math::RoundDecimal(valA, 2);\n    double resultB = Ocular::Math::RoundDecimal(valB, 2);\n\n    EXPECT_NEAR(expectA, resultA, Ocular::Math::EPSILON_DOUBLE);\n    EXPECT_NEAR(expectB, resultB, Ocular::Math::EPSILON_DOUBLE);\n}\n\nTEST(MathCommon, RoundPowTen)\n{\n    double valA = 1270.0;\n    double valB = 1230.0;\n\n    double expectA = 1300.0;\n    double expectB = 1200.0;\n\n    double resultA = Ocular::Math::RoundPowTen<double>(valA, 2);\n    double resultB = Ocular::Math::RoundPowTen<double>(valB, 2);\n\n    EXPECT_NEAR(expectA, resultA, Ocular::Math::EPSILON_DOUBLE);\n    EXPECT_NEAR(expectB, resultB, Ocular::Math::EPSILON_DOUBLE);\n}\n\nTEST(MathCommon, Clz32)\n{\n\tconst uint32_t valueA    = 100;\n\tconst uint32_t expectedA = 25;\n\tconst uint32_t resultA   = Ocular::Math::Clz(valueA);\n\n\tEXPECT_EQ(expectedA, resultA);\n\n\tconst uint32_t valueB    = 4294967295;\n\tconst uint32_t expectedB = 0;\n\tconst uint32_t resultB   = Ocular::Math::Clz(valueB);\n\n\tEXPECT_EQ(expectedB, resultB);\n\n\tconst uint32_t valueC    = 1;\n\tconst uint32_t expectedC = 31;\n\tconst uint32_t resultC   = Ocular::Math::Clz(valueC);\n\n\tEXPECT_EQ(expectedC, resultC);\n}\n\nTEST(MathCommon, Clz64)\n{\n\tconst uint64_t valueA    = 100;\n\tconst uint64_t expectedA = 57;\n\tconst uint64_t resultA   = Ocular::Math::Clz(valueA);\n\n\tEXPECT_EQ(expectedA, resultA);\n\n\tconst uint64_t valueB    = 4294967295;\n\tconst uint64_t expectedB = 32;\n\tconst uint64_t resultB   = Ocular::Math::Clz(valueB);\n\n\tEXPECT_EQ(expectedB, resultB);\n\n\tconst uint64_t valueC    = 1;\n\tconst uint64_t expectedC = 63;\n\tconst uint64_t resultC   = Ocular::Math::Clz(valueC);\n\n\tEXPECT_EQ(expectedC, resultC);\n}\n\n#endif", "meta": {"hexsha": "e5bda682ae273d4567a80306a98200946a2652fe", "size": 6554, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "OcularTest/src/Tests/Core/Math/TestMathCommon.cpp", "max_stars_repo_name": "ssell/OcularEngine", "max_stars_repo_head_hexsha": "c80cc4fcdb7dd7ce48d3af330bd33d05312076b1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-01-27T01:06:06.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-05T20:23:19.000Z", "max_issues_repo_path": "OcularTest/src/Tests/Core/Math/TestMathCommon.cpp", "max_issues_repo_name": "ssell/OcularEngine", "max_issues_repo_head_hexsha": "c80cc4fcdb7dd7ce48d3af330bd33d05312076b1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 39.0, "max_issues_repo_issues_event_min_datetime": "2016-06-03T02:00:36.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-19T17:47:39.000Z", "max_forks_repo_path": "OcularTest/src/Tests/Core/Math/TestMathCommon.cpp", "max_forks_repo_name": "ssell/OcularEngine", "max_forks_repo_head_hexsha": "c80cc4fcdb7dd7ce48d3af330bd33d05312076b1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-22T09:13:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-01T03:17:45.000Z", "avg_line_length": 28.1287553648, "max_line_length": 92, "alphanum_fraction": 0.6856881294, "num_tokens": 1962, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.8128673246376008, "lm_q1q2_score": 0.7320112379981225}}
{"text": "// STL includes\n#include <iostream>\n#include <vector>\n\n// BGL includes\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n\ntypedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS,\n  boost::no_property, boost::property<boost::edge_weight_t, int> >      weighted_graph;\ntypedef boost::property_map<weighted_graph, boost::edge_weight_t>::type weight_map;\ntypedef boost::graph_traits<weighted_graph>::edge_descriptor            edge_desc;\ntypedef boost::graph_traits<weighted_graph>::vertex_descriptor          vertex_desc;\n\nusing namespace std;\n\nint furthest_dist(const weighted_graph &G, int s) {\n  int n = boost::num_vertices(G);\n  std::vector<int> dist_map(n);\n\n  boost::dijkstra_shortest_paths(G, s,\n    boost::distance_map(boost::make_iterator_property_map(\n      dist_map.begin(), boost::get(boost::vertex_index, G))));\n  \n  int max_dist = 0;\n  for(int i = 1; i < n; i++) {\n    if(dist_map[i] > max_dist) \n      max_dist = dist_map[i];\n  }\n  return max_dist;\n}\n\nint span_tree_weight(const weighted_graph &G, const weight_map &weights) {\n  std::vector<edge_desc> mst;    // vector to store MST edges (not a property map!)\n\n  boost::kruskal_minimum_spanning_tree(G, std::back_inserter(mst));\n  int total_weight = 0;\n  for (std::vector<edge_desc>::iterator it = mst.begin(); it != mst.end(); ++it) {\n    total_weight += weights[*it];\n  }\n  return total_weight;\n}\n\n\nvoid testcase() {\n  int n; cin >> n;\n  int m; cin >> m;\n  weighted_graph G(n);\n  weight_map weights = boost::get(boost::edge_weight, G);\n  edge_desc e;\n  for(int i = 0; i < m; i++) {\n    int u,v; cin >> u; cin >> v;\n    int w; cin >> w;\n    e = boost::add_edge(u, v, G).first; weights[e] = w;\n  }\n  \n  cout << span_tree_weight(G, weights) << \" \";\n  cout << furthest_dist(G, 0) << endl;\n  \n}\nint main()\n{\n  std::ios_base::sync_with_stdio(false); // Always!\n  int t; cin >> t;\n  for(int i = 0; i < t; i++)\n    testcase();\n  return 0;\n}\n", "meta": {"hexsha": "61ffaa179e41e27e056b958c94e37604544a1af9", "size": 2013, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problems/week04-first_steps_bgl/src/algorithm.cpp", "max_stars_repo_name": "haeggee/algolab", "max_stars_repo_head_hexsha": "176a7d4efbbfb2842f46e93250be00d3b59e0ec3", "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": "problems/week04-first_steps_bgl/src/algorithm.cpp", "max_issues_repo_name": "haeggee/algolab", "max_issues_repo_head_hexsha": "176a7d4efbbfb2842f46e93250be00d3b59e0ec3", "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": "problems/week04-first_steps_bgl/src/algorithm.cpp", "max_forks_repo_name": "haeggee/algolab", "max_forks_repo_head_hexsha": "176a7d4efbbfb2842f46e93250be00d3b59e0ec3", "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.7571428571, "max_line_length": 87, "alphanum_fraction": 0.6696472926, "num_tokens": 569, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297941266013, "lm_q2_score": 0.8128673087708699, "lm_q1q2_score": 0.7320112302196758}}
{"text": "#include <cmath>\n#include <boost/test/unit_test.hpp>\n\n#include \"../test_utils.hh\"\n#include \"../fixture.hh\"\n#include \"../vector_utils.hh\"\n\nBOOST_FIXTURE_TEST_CASE(vector_dot_float, vector_fixture)\n{\n    // Given two vector of five values.\n    std::vector<float> values1 = {4.234f, 3214.4243f, 290342.0f, 0.0f, -1.0f};\n    std::vector<float> values2 = {3.0f, 392.9001f, 0.005f, 5.0f, 29844.05325811f};\n    auto vector1 = getScyllaVectorOf(test_const::float_vector_1_id, values1);\n    auto vector2 = getScyllaVectorOf(test_const::float_vector_2_id, values2);\n\n    // When performing dot product of these two vectors.\n    float res = scheduler->sdot(*vector1, *vector2);\n\n    float sum = 0;\n    for (int i = 0; i < values1.size(); i++) {\n        sum += values1[i] * values2[i];\n    }\n\n    print_vector(*vector1);\n    print_vector(*vector2);\n    std::cout << std::setprecision(20) << sum << \"=sum\\n\";\n    std::cout << std::setprecision(20) << res << \"=res\\n\";\n\n    // Then the dot product is correctly calculated and equal to sum.\n    BOOST_CHECK(std::abs(sum - res) < scylla_blas::epsilon);\n}\n\nBOOST_FIXTURE_TEST_CASE(vector_dot_float_same_obj, vector_fixture)\n{\n    // Given one vector of five values.\n    std::vector<float> values1 = {4.234f, 214.4243f, 342.0f, 0.0f, -1.0f};\n    auto vector1 = getScyllaVectorOf(test_const::float_vector_1_id, values1);\n\n    // When performing dot product of this vector x this vector.\n    float res = scheduler->sdot(*vector1, *vector1);\n\n    float sum = 0;\n    for (float v : values1) {\n        sum += v * v;\n    }\n    std::cout << std::setprecision(20) << sum << \"=sum\\n\";\n    std::cout << std::setprecision(20) << res << \"=res\\n\";\n\n    // Then the dot product is correctly calculated and equal to sum.\n    BOOST_CHECK(std::abs(sum - res) < scylla_blas::epsilon);\n}\n\nBOOST_FIXTURE_TEST_CASE(vector_sdsdot_float, vector_fixture)\n{\n    // Given two vector of five values.\n    std::vector<float> values1 = {4.234f, 3214.4243f, 290342.0f, 0.0f, -1.0f};\n    std::vector<float> values2 = {3.0f, 392.9001f, 0.005f, 5.0f, 29844.05325811f};\n    auto vector1 = getScyllaVectorOf(test_const::float_vector_1_id, values1);\n    auto vector2 = getScyllaVectorOf(test_const::float_vector_2_id, values2);\n\n    // When performing dot product of double precision plus value\n    // of these two vectors.\n    float res = scheduler->sdsdot(0.5f, *vector1, *vector2);\n\n    double sum = 0.5f;\n    for (int i = 0; i < values1.size(); i++) {\n        sum += (double)values1[i] * (double)values2[i];\n    }\n    std::cout << std::setprecision(20) << sum << \"=sum\\n\";\n    std::cout << std::setprecision(20) << res << \"=res\\n\";\n\n    // Then the dot product is correctly calculated and equal to sum + value.\n    BOOST_CHECK(std::abs((float)sum - res) < scylla_blas::epsilon);\n}\n\nBOOST_FIXTURE_TEST_CASE(vector_dsdot_float, vector_fixture)\n{\n    // Given two vector of five values.\n    std::vector<float> values1 = {4.234f, 3214.4243f, 290342.0f, 0.0f, -1.0f};\n    std::vector<float> values2 = {3.0f, 392.9001f, 0.005f, 5.0f, 29844.05325811f};\n    auto vector1 = getScyllaVectorOf(test_const::float_vector_1_id, values1);\n    auto vector2 = getScyllaVectorOf(test_const::float_vector_2_id, values2);\n\n    // When performing dot product with double precision of these two vectors.\n    double res = scheduler->dsdot(*vector1, *vector2);\n\n    double sum = 0.0f;\n    for (int i = 0; i < values1.size(); i++) {\n        sum += (double)values1[i] * (double)values2[i];\n    }\n    std::cout << std::setprecision(20) << sum << \"=sum\\n\";\n    std::cout << std::setprecision(20) << res << \"=res\\n\";\n\n    // Then the dot product is correctly calculated and equal to sum.\n    BOOST_CHECK(std::abs(sum - res) < scylla_blas::epsilon);\n}\n\nBOOST_FIXTURE_TEST_CASE(vector_dot_double, vector_fixture)\n{\n    // Given two vector of five values.\n    std::vector<double> values1 = {4.234, 3214.4243, 290342.0, 0.0, -1.0};\n    std::vector<double> values2 = {3.0, 392.9001, 0.005, 5.0, 29844.05325811};\n    auto vector1 = getScyllaVectorOf(test_const::double_vector_1_id, values1);\n    auto vector2 = getScyllaVectorOf(test_const::double_vector_2_id, values2);\n\n    // When performing dot product of these two vectors.\n    double res = scheduler->ddot(*vector1, *vector2);\n\n    double sum = 0;\n    for (int i = 0; i < values1.size(); i++) {\n        sum += values1[i] * values2[i];\n    }\n    std::cout << std::setprecision(20) << sum << \"=sum\\n\";\n    std::cout << std::setprecision(20) << res << \"=res\\n\";\n\n    // Then the dot product is correctly calculated and equal to sum.\n    BOOST_CHECK(std::abs(sum - res) < scylla_blas::epsilon);\n}\n\n\nBOOST_FIXTURE_TEST_CASE(vector_norm_float, vector_fixture)\n{\n    // Given vector of some values.\n    std::vector<float> values1 = {0.00494931f, 0.119193f, 0.927604f, 0.354004f};\n    auto vector1 = getScyllaVectorOf(test_const::float_vector_1_id, values1);\n\n    // When performing vector euclidean norm.\n    float res = scheduler->snrm2(*vector1);\n\n    float nrm = 0;\n    for (float v : values1) {\n        nrm += v * v;\n    }\n    nrm = std::sqrt(nrm);\n    std::cout << std::setprecision(20) << nrm << \"=sum\\n\";\n    std::cout << std::setprecision(20) << res << \"=res\\n\";\n\n    // Then the norm is correctly calculated and equal to nrm.\n    BOOST_CHECK(std::abs(nrm - res) < scylla_blas::epsilon);\n}\n\nBOOST_FIXTURE_TEST_CASE(vector_sasum_float, vector_fixture)\n{\n    // Given vector of some values.\n    std::vector<float> values1 = {0.00494931f, 0.119193f, -0.927604f, 0.354004f};\n    auto vector1 = getScyllaVectorOf(test_const::float_vector_1_id, values1);\n\n    // When performing sum of absolute values in this vector.\n    float res = scheduler->sasum(*vector1);\n\n    float abs_sum = 0;\n    for (float v : values1) {\n        abs_sum += std::abs(v);\n    }\n    std::cout << std::setprecision(20) << abs_sum << \"=sum\\n\";\n    std::cout << std::setprecision(20) << res << \"=res\\n\";\n\n    // Then it is correctly calculated and equal to sum.\n    BOOST_CHECK(std::abs(abs_sum - res) < scylla_blas::epsilon);\n}\n\nBOOST_FIXTURE_TEST_CASE(vector_isamax_float, vector_fixture)\n{\n    // Given vector of some values.\n    std::vector<float> values1 = {0.00494931f, 0.119193f, -0.927604f, 0.354004f};\n    auto vector1 = getScyllaVectorOf(test_const::float_vector_1_id, values1);\n\n    // When performing max fetch on the abs values in this vector.\n    scylla_blas::index_t res = scheduler->isamax(*vector1);\n\n    scylla_blas::index_t max_index = 0;\n    for (scylla_blas::index_t i = 1; i < values1.size(); i++) {\n        if (std::abs(values1[i]) > std::abs(values1[max_index])) {\n            max_index = i;\n        }\n    }\n    std::cout << std::setprecision(20) << values1[max_index] << \"=sum\\n\";\n    std::cout << res << \"=res index\\n\";\n\n    // Then the found index corresponds to the index of largest absolute value's index.\n    BOOST_CHECK(max_index + 1 == res);\n}\n\nBOOST_FIXTURE_TEST_CASE(vector_norm_double, vector_fixture)\n{\n    // Given vector of some values.\n    std::vector<double> values1 = {0.00494931, 0.119193, 0.927604, 0.354004};\n    auto vector1 = getScyllaVectorOf(test_const::double_vector_1_id, values1);\n\n    // When performing vector euclidean norm.\n    double res = scheduler->dnrm2(*vector1);\n\n    double nrm = 0;\n    for (double i : values1) {\n        nrm += i * i;\n    }\n    nrm = sqrt(nrm);\n    std::cout << std::setprecision(20) << nrm << \"=sum\\n\";\n    std::cout << std::setprecision(20) << res << \"=res\\n\";\n\n    // Then the norm is correctly calculated and equal to nrm.\n    BOOST_CHECK(std::abs(nrm - res) < scylla_blas::epsilon);\n}\n\nBOOST_FIXTURE_TEST_CASE(vector_dasum_double, vector_fixture)\n{\n    // Given vector of some values.\n    std::vector<double> values1 = {0.00494931, 0.119193, -0.927604, 0.354004};\n    auto vector1 = getScyllaVectorOf(test_const::double_vector_1_id, values1);\n\n    // When performing sum of absolute values in this vector.\n    double res = scheduler->dasum(*vector1);\n\n    double abs_sum = 0;\n    for (double v : values1) {\n        abs_sum += std::abs(v);\n    }\n    std::cout << std::setprecision(20) << abs_sum << \"=sum\\n\";\n    std::cout << std::setprecision(20) << res << \"=res\\n\";\n\n    // Then it is correctly calculated and equal to sum.\n    BOOST_CHECK(std::abs(abs_sum - res) < scylla_blas::epsilon);\n}\n\nBOOST_FIXTURE_TEST_CASE(vector_idamax_double, vector_fixture)\n{\n    // Given vector of some values.\n    std::vector<double> values1 = {0.00494931, 0.119193, -0.927604, 0.354004};\n    auto vector1 = getScyllaVectorOf(test_const::double_vector_1_id, values1);\n\n    // When performing max fetch on the abs values in this vector.\n    scylla_blas::index_t res = scheduler->idamax(*vector1);\n\n    scylla_blas::index_t max_index = 0;\n    for (scylla_blas::index_t i = 1; i < values1.size(); i++) {\n        if (std::abs(values1[i]) > std::abs(values1[max_index])) {\n            max_index = i;\n        }\n    }\n    std::cout << std::setprecision(20) << values1[max_index] << \"=sum\\n\";\n    std::cout << max_index << \"=max_index\\n\";\n    std::cout << res << \"=res index\\n\";\n\n    // Then the found index corresponds to the index of largest absolute value's index.\n    BOOST_CHECK(max_index + 1 == res);\n}\n", "meta": {"hexsha": "22f5d670904d350a6faf4a6cbd402726cab0a875", "size": 9156, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tests/blas_level_1/vector_const_op.cc", "max_stars_repo_name": "scylla-zpp-blas/linear-algebra", "max_stars_repo_head_hexsha": "823fe4085fdac992ed9695416d9a38d2cf6908d8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-09-07T18:36:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-01T19:23:30.000Z", "max_issues_repo_path": "tests/blas_level_1/vector_const_op.cc", "max_issues_repo_name": "scylla-zpp-blas/linear-algebra", "max_issues_repo_head_hexsha": "823fe4085fdac992ed9695416d9a38d2cf6908d8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2020-12-19T18:10:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-14T18:06:17.000Z", "max_forks_repo_path": "tests/blas_level_1/vector_const_op.cc", "max_forks_repo_name": "scylla-zpp-blas/linear-algebra", "max_forks_repo_head_hexsha": "823fe4085fdac992ed9695416d9a38d2cf6908d8", "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": 37.0688259109, "max_line_length": 87, "alphanum_fraction": 0.6530144168, "num_tokens": 2806, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942173896132, "lm_q2_score": 0.8221891283434877, "lm_q1q2_score": 0.7319902265648136}}
{"text": "/**\t\\file \ttest_main.cpp\n*\t\\brief\tTesting Kernels in MLearnKernels.h\n*/\n// Test framework\n#define CATCH_CONFIG_MAIN\n#include <catch.hpp>\n#include <test_common.h>\n\n// MLearn\n#include <MLearn/Core>\n#include <MLearn/Sampling/GaussianSampling.h>\n\n// Eigen \n#include <Eigen/Core>\n#include <Eigen/Cholesky>\n#include <Eigen/Eigenvalues>\n#include <Eigen/LU>\n\n// Boost includes\n#include <boost/random/taus88.hpp>\n\nTEST_CASE(\"Test utility functions for multivariate gaussian sampling.\"){\t\n\ttypedef double FT;\n\tusing namespace MLearn;\n\tusing namespace Eigen;\n\tusing namespace Sampling::Gaussian;\n\tusing namespace SamplingImpl; \n\tuint dim = 3;\n\tuint N_samples = 10;\n\tMLMatrix<FT> A(dim, dim);\t\n\n\tA << 4, 1 ,-1,\n\t     1, 2 , 1,\n\t    -1, 1 , 2;\n\n\tSECTION(\"Test transformation extraction\"){\n\t\t// Preallocation\n\t\tMLMatrix<FT> transform(dim, dim);\n\n\t\tSECTION(\"Test using pure cholesky!\"){\n\t\t\tLLT<MLMatrix<FT>> cholesky(A);\n\t\t\ttransform = MLMatrix<FT>::Random(dim, dim);\n\n\t\t\tREQUIRE_FALSE( \n\t\t\t\tTestUtils::diff_norm(transform*transform.transpose(), A) ==\n\t\t\t\tApprox(0).margin(TEST_FLOAT_TOLERANCE));\n\n\t\t\ttransform_from_decomposition(transform, cholesky);\n\t\t\t\n\t\t\tREQUIRE( \n\t\t\t\tTestUtils::diff_norm(transform*transform.transpose(), A) ==\n\t\t\t\tApprox(0).margin(TEST_FLOAT_TOLERANCE));\n\t\t}\n\n\t\tSECTION(\"Test using eigensolver!\"){\n\t\t\tSelfAdjointEigenSolver<MLMatrix<FT>> eigensolver(A);\n\t\t\ttransform = MLMatrix<FT>::Random(dim, dim);\n\t\t\t\n\t\t\tREQUIRE_FALSE( \n\t\t\t\tTestUtils::diff_norm(transform*transform.transpose(), A) ==\n\t\t\t\tApprox(0).margin(TEST_FLOAT_TOLERANCE));\n\n\t\t\ttransform_from_decomposition(transform, eigensolver);\n\t\t\t\n\t\t\tREQUIRE( \n\t\t\t\tTestUtils::diff_norm(transform*transform.transpose(), A) ==\n\t\t\t\tApprox(0).margin(TEST_FLOAT_TOLERANCE));\n\n\t\t}\n\n\t}\n\n\tSECTION(\"Test samples transformation\"){\n\t\tMLMatrix<FT> orig_samples = MLMatrix<FT>::Random(dim, N_samples);\n\t\tMLMatrix<FT> samples = orig_samples;\n\t\tMLVector<FT> mean = MLVector<FT>::Random(dim);\n\n\t\tMLMatrix<FT> transform(dim, dim);\n\t\ttransform_from_covariance<TransformMethod::CHOL>(transform, A);\n\n\t\tSECTION(\"Test transformation using transform\"){\n\t\t\ttransform_gaussian_samples_with_transform(mean, transform, samples);\n\n\t\t\tMLMatrix<FT> reverted_samples = samples;\n\t\t\treverted_samples.colwise() -= mean;\n\t\t\treverted_samples = transform.inverse()*reverted_samples;\n\n\t\t\tREQUIRE(\n\t\t\t\tTestUtils::diff_norm(orig_samples, reverted_samples) ==\n\t\t\t\tApprox(0).margin(TEST_FLOAT_TOLERANCE));\n\t\t}\n\n\t\tSECTION(\"Test transformation using covariance\"){\n\t\t\ttransform_gaussian_samples_with_covariance<TransformMethod::CHOL>\n\t\t\t\t(mean, A, samples);\n\n\t\t\tMLMatrix<FT> reverted_samples = samples;\n\t\t\treverted_samples.colwise() -= mean;\n\t\t\treverted_samples = transform.inverse()*reverted_samples;\n\n\t\t\tREQUIRE(\n\t\t\t\tTestUtils::diff_norm(orig_samples, reverted_samples) ==\n\t\t\t\tApprox(0).margin(TEST_FLOAT_TOLERANCE));\n\t\t}\n\t}\n\n\tSECTION(\"Test samples generation ...\"){\n\t\tuint N_samples = 34;\n\t\tuint dim = 5;\n\t\tSECTION(\"... with custom random number generator.\"){\n\t\t\tboost::random::taus88 rng(seed_from_time());\n\t\n\t\t\tMLMatrix<FT> samples = \n\t\t\t\tsample_standard_gaussian<FT>(dim, N_samples, rng);\n\t\n\t\t\tREQUIRE(samples.rows() == dim);\n\t\t\tREQUIRE(samples.cols() == N_samples);\n\t\t\tREQUIRE(samples.norm() > 0.0);\n\t\t}\n\t\n\t\tSECTION(\"... without random number generator.\"){\n\t\t\tMLMatrix<FT> samples = \n\t\t\t\tsample_standard_gaussian<FT>(dim, N_samples);\n\t\n\t\t\tREQUIRE(samples.rows() == dim);\n\t\t\tREQUIRE(samples.cols() == N_samples);\n\t\t\tREQUIRE(samples.norm() > 0.0);\n\t\t}\n\t}\n\n}\n\nTEST_CASE(\"Multivariate gaussian class test\"){\t\n\ttypedef double FT;\n\tusing namespace MLearn;\n\tusing namespace Eigen;\n\tusing namespace Sampling::Gaussian;\n\n\tuint N_samples = 17;\n\tuint dim = 3;\n\n\tMLVector<FT> mean = MLVector<FT>::Random(dim);\n\tMLMatrix<FT> covariance(dim, dim);\n\n\tcovariance << 4, 1 ,-1,\n\t              1, 2 , 1,\n\t             -1, 1 , 2;\n\n\tSECTION(\"Test static sampling function\"){\n\t\tMLMatrix<FT> samples = MultivariateGaussian<FT>::sample(\n\t\t\tmean, covariance, N_samples);\n\n\t\tREQUIRE(samples.cols() == N_samples);\n\t\tREQUIRE(samples.rows() == dim);\n\t\tREQUIRE(samples.norm() > 0.0);\n\t}\n\n\tSECTION(\"Test sampling using instantiated class\"){\n\t\tMultivariateGaussian<FT> mg(mean, covariance);\n\t\tMLMatrix<FT> samples = mg.sample(N_samples);\n\n\t\tREQUIRE(samples.cols() == N_samples);\n\t\tREQUIRE(samples.rows() == dim);\n\t\tREQUIRE(samples.norm() > 0.0);\n\t}\n\n\tSECTION(\"Test class\"){\n\t\tMultivariateGaussian<FT> ref_mg(mean, covariance);\n\n\t\tREQUIRE(TestUtils::diff_norm(mean, ref_mg.mean()) == \n\t\t\tApprox(0).margin(TEST_FLOAT_TOLERANCE));\n\t\tREQUIRE(TestUtils::diff_norm(covariance, ref_mg.covariance()) == \n\t\t\tApprox(0).margin(TEST_FLOAT_TOLERANCE));\n\n\t\tMultivariateGaussian<FT> copy_mg(ref_mg);\n\n\t\tREQUIRE(TestUtils::diff_norm(mean, copy_mg.mean()) == \n\t\t\tApprox(0).margin(TEST_FLOAT_TOLERANCE));\n\t\tREQUIRE(TestUtils::diff_norm(covariance, copy_mg.covariance()) == \n\t\t\tApprox(0).margin(TEST_FLOAT_TOLERANCE));\n\n\n\t\tMultivariateGaussian<FT> \n\t\t\tmove_mg(std::move(MultivariateGaussian<FT>(ref_mg)));\n\n\t\tREQUIRE(TestUtils::diff_norm(mean, move_mg.mean()) == \n\t\t\tApprox(0).margin(TEST_FLOAT_TOLERANCE));\n\t\tREQUIRE(TestUtils::diff_norm(covariance, move_mg.covariance()) == \n\t\t\tApprox(0).margin(TEST_FLOAT_TOLERANCE));\n\n\t\tMultivariateGaussian<FT> copy_assign_mg;\n\t\tcopy_assign_mg = ref_mg;\n\t\tREQUIRE(TestUtils::diff_norm(mean, copy_assign_mg.mean()) == \n\t\t\tApprox(0).margin(TEST_FLOAT_TOLERANCE));\n\t\tREQUIRE(TestUtils::diff_norm(covariance, copy_assign_mg.covariance()) == \n\t\t\tApprox(0).margin(TEST_FLOAT_TOLERANCE));\n\n\n\t\tMultivariateGaussian<FT> move_assign_mg;\n\t\tmove_assign_mg = std::move(MultivariateGaussian<FT>(ref_mg));\n\t\tREQUIRE(TestUtils::diff_norm(mean, move_assign_mg.mean()) == \n\t\t\tApprox(0).margin(TEST_FLOAT_TOLERANCE));\n\t\tREQUIRE(TestUtils::diff_norm(covariance, move_assign_mg.covariance()) == \n\t\t\tApprox(0).margin(TEST_FLOAT_TOLERANCE));\n\n\t\tMLVector<FT> new_mean = MLVector<FT>::Random(dim);\n\t\tMLMatrix<FT> new_covariance = 5.0*covariance;\n\n\t\tref_mg.set_mean(new_mean);\n\t\tREQUIRE(TestUtils::diff_norm(new_mean, ref_mg.mean()) == \n\t\t\tApprox(0).margin(TEST_FLOAT_TOLERANCE));\n\t\tref_mg.set_covariance(new_covariance);\n\t\tREQUIRE(TestUtils::diff_norm(new_covariance, ref_mg.covariance()) == \n\t\t\tApprox(0).margin(TEST_FLOAT_TOLERANCE));\n\t\tREQUIRE(TestUtils::diff_norm(new_covariance, \n\t\t\t\t\t\tref_mg.transform()*ref_mg.transform().transpose()) == \n\t\t\tApprox(0).margin(TEST_FLOAT_TOLERANCE));\n\t}\n\n}", "meta": {"hexsha": "40be379b0173050ad25dcb50b78e5157e057b98d", "size": 6375, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_sampling/test_gaussian/test_main.cpp", "max_stars_repo_name": "phineasng/MLearn", "max_stars_repo_head_hexsha": "20ac852179029dac2e9e363acc6b21ad9ddfc8d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-11-14T19:37:33.000Z", "max_stars_repo_stars_event_max_datetime": "2017-02-05T02:29:35.000Z", "max_issues_repo_path": "test/test_sampling/test_gaussian/test_main.cpp", "max_issues_repo_name": "phineasng/MLearn", "max_issues_repo_head_hexsha": "20ac852179029dac2e9e363acc6b21ad9ddfc8d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2016-01-23T17:49:50.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-25T22:43:30.000Z", "max_forks_repo_path": "test/test_sampling/test_gaussian/test_main.cpp", "max_forks_repo_name": "phineasng/MLearn", "max_forks_repo_head_hexsha": "20ac852179029dac2e9e363acc6b21ad9ddfc8d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-05-23T18:17:14.000Z", "max_forks_repo_forks_event_max_datetime": "2017-05-23T18:17:14.000Z", "avg_line_length": 28.9772727273, "max_line_length": 75, "alphanum_fraction": 0.713254902, "num_tokens": 1755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.8031738034238807, "lm_q1q2_score": 0.731835671355657}}
{"text": "#include <boost/random/uniform_int.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <map>\n#include <vector>\n#include <iostream>\n#include <iomanip>\n\nstatic void boost_uniform( const int trials , unsigned seed )\n{\n  // Generate numbers from a uniforma distribution using boost\n  // Roll dice and keep track of the some of the dice\n  // Print the resulting distribuiton for the trial\n\n  boost::mt19937 random_num_gen( seed );\n  boost::uniform_int<> urange(1,6);\n  boost::variate_generator< boost::mt19937 , boost::uniform_int<> > dice( random_num_gen , urange );\n\n  // create a map to store the count of the number of occurrences of the sum on the dist\n  // first is the dice sum the second is the count;\n  std::map<int,int> throw_cnt;\n  for( int i = 2 ; i <=12 ; i++ ) throw_cnt[i]=0;\n\n  for( int i = 0; i < trials ; i++ )\n    {\n      int d1 = dice() , d2 = dice() , s = d1 + d2;\n      std::map<int,int>::iterator itr = throw_cnt.find(s);\n      (*itr).second++;\n    }\n\n  double n = static_cast<double>(trials);\n  std::cout << \"Dice Throw : Trials = \" << std::setprecision(1) << std::scientific << n << std::endl;\n  for( std::map<int,int>::iterator itr = throw_cnt.begin() ; itr != throw_cnt.end() ; ++itr )\n    {\n      double p = static_cast<double>((*itr).second) / n;\n      std::cout << std::setw(3) << (*itr).first << \",\" << std::setw(10) << std::setprecision(8) << std::fixed << p << std::endl;\n    }\n  std::cout << std::endl;\n}\n\nstatic void boost_normal( const int trials , unsigned seed , double mean , double variance )\n{\n  // Generate Normal Random Variables using boost libraties\n  // Then assess the density at +/- 2 sigma and +/- 1 sigma \n\n  boost::mt19937 random_num_gen( seed );\n  boost::normal_distribution<double> n_dist(mean,variance);\n  boost::variate_generator< boost::mt19937 , boost::normal_distribution<double> > normal_rv( random_num_gen , n_dist );\n\n  std::vector<double> dist;\n  dist.reserve(trials);\n  for( int i = 0 ; i < trials ; i++ )\n    {\n      dist.push_back( normal_rv() );\n    }\n\n  std::sort( dist.begin(), dist.end() );\n\n  double s = sqrt(variance);\n\n  if( dist.empty() ) return;\n  std::vector<double>::iterator itr_2slb = std::lower_bound( dist.begin() , dist.end() , -2.0*s );\n  std::vector<double>::iterator itr_2sub = std::lower_bound( dist.begin() , dist.end() , 2.0*s );\n\n  std::vector<double>::iterator itr_1slb = std::lower_bound( dist.begin() , dist.end() , -1.0*s );\n  std::vector<double>::iterator itr_1sub = std::lower_bound( dist.begin() , dist.end() , 1.0*s );\n\n  double nobs_2sd = itr_2sub - itr_2slb;\n  double nobs_1sd = itr_1sub - itr_1slb;\n  double n = static_cast<double>( trials );\n  std::cout << \"Normal RV : \";\n  std::cout << std::setw(8) << std::setprecision(1) << std::scientific << static_cast<double>(trials);\n  std::cout << \" : mean +/- 2sigma % = \" << std::setw(10) << std::setprecision(6) << std::fixed << nobs_2sd/n;\n  std::cout << \" : mean +/- 1sigma % = \" << std::setw(10) << std::setprecision(6) << std::fixed << nobs_1sd/n;\n  std::cout << std::endl;\n}\n\nstatic void boost_number_gen()\n{\n  const unsigned  seed = 5489u;;\n  boost_uniform(1e3,seed);\n  boost_uniform(1e6,seed);\n  boost_uniform(1e7,seed);\n\n  const double mean= 0.0 , variance = 1.0 ;\n  boost_normal( 1e2 , seed , mean , variance );\n  boost_normal( 1e3 , seed , mean , variance );\n  boost_normal( 1e6 , seed , mean , variance );\n  boost_normal( 1e7 , seed , mean , variance );\n}\n", "meta": {"hexsha": "ab4590b0ff3fca9cabbad536d8a52bcadc7a9d71", "size": 3509, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++/random_var.cpp", "max_stars_repo_name": "jrrpanix/reference", "max_stars_repo_head_hexsha": "2d6774ca5aefee8d215279ee552a684a1d6a3906", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-27T16:21:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T16:21:49.000Z", "max_issues_repo_path": "c++/random_var.cpp", "max_issues_repo_name": "jrrpanix/reference", "max_issues_repo_head_hexsha": "2d6774ca5aefee8d215279ee552a684a1d6a3906", "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": "c++/random_var.cpp", "max_forks_repo_name": "jrrpanix/reference", "max_forks_repo_head_hexsha": "2d6774ca5aefee8d215279ee552a684a1d6a3906", "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.1413043478, "max_line_length": 128, "alphanum_fraction": 0.6471929325, "num_tokens": 1042, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760038, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.7318356567490975}}
{"text": "// Copyright (c) 2017 Evan S Weinberg\n// A reference piece of code which computes matrix elements\n// of a reference sparse Laplace operator to fill a dense\n// Eigen matrix, then computes the spectrum and prints\n// the Eigenvalues.\n\n// This code is for real, symmetric matrices.\n// This code lives on github at github.com/weinbe2/eigens-with-eigen/\n\n#include <iostream>\n#include <iomanip>\n#include <cmath>\n#include <string>\n\n// Borrow dense matrix eigenvalue routines.\n#include <Eigen/Dense>\n\nusing namespace std; \nusing namespace Eigen;\n\n\n// This is just for convenience. By default, all matrices\n// in Eigen are column major. You can replace \"Dynamic\"\n// with a specific number to template just one size.\n// You can also ust use \"MatrixXd\".\ntypedef Matrix<double, Dynamic, Dynamic, ColMajor> dMatrix;\n\n// Reference 1-D Laplace function.\nvoid laplace_1d(double* out, double* in, const int L, const double m2);\n\nint main(int argc, char** argv)\n{  \n  double *in_real;\n  double *out_real;\n\n  // Set output precision to be long.\n  cout << setprecision(10);\n\n  // Basic information about the lattice.\n  const int length = 8;\n  const double m_sq = 0.001;\n\n  // Print the basic info.\n  std::cout << \"1D Laplace operator, length \" << length << \", mass squared \" << m_sq << \", zero boundary conditions.\\n\";\n  std::cout << \"Change the length and mass by modifying the source.\\n\";\n  \n  // Allocate.\n  in_real = new double[length];\n  out_real = new double[length];\n\n  // Zero out.\n  for (int i = 0; i < length; i++)\n  {\n    in_real[i] = out_real[i] = 0.0;\n  }\n\n  //////////////////////////\n  // REAL, SYMMETRIC CASE //\n  //////////////////////////\n\n  std::cout << \"Real, Symmetric case.\\n\\n\";\n\n  // Allocate a sufficiently gigantic matrix.\n  dMatrix mat_real = dMatrix::Zero(length, length);\n\n  // Form matrix elements. This is where it's important that\n  // dMatrix is column major.\n  for (int i = 0; i < length; i++)\n  {\n    // Set a point on the rhs for a matrix element.\n    // If appropriate, zero out the previous point.\n    if (i > 0)\n    {\n      in_real[i-1] = 0.0;\n    }\n    in_real[i] = 1.0;\n\n    // Zero out the \"out\" vector. I defined \"laplace_1d\" to\n    // not require this, but I put this here for generality.\n    for (int j = 0; j < length; j++)\n      out_real[j] = 0.0;\n\n    // PUT YOUR MAT-VEC HERE.\n    laplace_1d(out_real, in_real, length, m_sq);\n\n    // Copy your output into the right memory location.\n    // If your data layout supports it, you can also pass\n    // \"mptr\" directly as your \"output vector\" when you call\n    // your mat-vec.\n    double* mptr = &(mat_real(i*length));\n    \n    for (int j = 0; j < length; j++)\n    {\n      mptr[j] = out_real[j];\n    }\n  }\n\n  // We've now formed the dense matrix. We print it here\n  // as a sanity check if it's small enough.\n  if (length <= 16)\n  {\n    std::cout << mat_real << \"\\n\";\n  }\n\n  // Get the eigenvalues and eigenvectors.\n  SelfAdjointEigenSolver< dMatrix > eigsolve_real(length);\n  eigsolve_real.compute(mat_real);\n\n  // Remark: if you only want the eigenvalues, you can call\n  // eigsolve_real.compute(mat_real, EigenvaluesOnly);\n\n  // Print the eigenvalues.\n  dMatrix evals = eigsolve_real.eigenvalues();\n  std::cout << \"The eigenvalues are:\\n\" << evals << \"\\n\\n\";\n  // You can also index individual eigenvalues as \"evals(i)\", where\n  // \"i\" zero-indexes the eigenvalues.\n\n  // Print the eigenvectors if the matrix is small enough.\n  // As a remark, this also shows you how to access the eigenvectors. \n  if (length <= 16)\n  {\n    for (int i = 0; i < length; i++)\n    {\n      // You can use \"VectorXd\" as the type instead.\n      dMatrix evec = eigsolve_real.eigenvectors().col(i);\n      \n      // Print the eigenvector.\n      std::cout << \"Eigenvector \" << i << \" equals:\\n\" << evec << \"\\n\\n\";\n\n      // You can also copy the eigenvector into another array as such:\n      for (int j = 0; j < length; j++)\n      {\n        out_real[j] = evec(j);\n      }\n    }\n  }\n\n  // Clean up.\n  delete[] in_real;\n  delete[] out_real;\n\n  return 0;\n}\n\n\n\n// Reference 1-D Laplace function.\nvoid laplace_1d(double* out, double* in, const int L, const double m2)\n{\n  // Zero boundary conditions. Set first and last element explicitly.\n  out[0] = (2+m2)*in[0] - in[1];\n  out[L-1] = (2+m2)*in[L-1] - in[L-2];\n\n  // The rest.\n  for (int i = 1; i < L-1; i++)\n  {\n    out[i] = (2+m2)*in[i] - in[i-1] - in[i+1];\n  }\n\n  // Done.\n  return;\n}\n\n", "meta": {"hexsha": "d0ef1718bbe9c905f8a8dab85416b6240080d6ac", "size": 4386, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "eigens-with-eigen/real_symmetric/example_real_symmetric.cpp", "max_stars_repo_name": "weinbe2/utilities-esw", "max_stars_repo_head_hexsha": "b4d36b214316147c3ce850d9fa1fe80ac42dcc6c", "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": "eigens-with-eigen/real_symmetric/example_real_symmetric.cpp", "max_issues_repo_name": "weinbe2/utilities-esw", "max_issues_repo_head_hexsha": "b4d36b214316147c3ce850d9fa1fe80ac42dcc6c", "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": "eigens-with-eigen/real_symmetric/example_real_symmetric.cpp", "max_forks_repo_name": "weinbe2/utilities-esw", "max_forks_repo_head_hexsha": "b4d36b214316147c3ce850d9fa1fe80ac42dcc6c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-01-22T21:51:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-22T21:51:46.000Z", "avg_line_length": 26.743902439, "max_line_length": 120, "alphanum_fraction": 0.6251709986, "num_tokens": 1269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813454, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.731830368097}}
{"text": "#include <iostream>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\nusing namespace std;\n\nint main(int argc, char** argv)\n{\n    // \u673a\u5668\u4ebaB\u5728\u5750\u6807\u7cfbO\u4e2d\u7684\u5750\u6807\uff1a\n    Eigen::Vector3d B(3, 4, M_PI);\n\n    // \u5750\u6807\u7cfbB\u5230\u5750\u6807O\u7684\u8f6c\u6362\u77e9\u9635\uff1a\n    Eigen::Matrix3d TOB;\n    TOB << cos(B(2)), -sin(B(2)), B(0),\n           sin(B(2)),  cos(B(2)), B(1),\n              0,          0,        1;\n\n    // \u5750\u6807\u7cfbO\u5230\u5750\u6807B\u7684\u8f6c\u6362\u77e9\u9635:\n    Eigen::Matrix3d TBO = TOB.inverse();\n\n    // \u673a\u5668\u4ebaA\u5728\u5750\u6807\u7cfbO\u4e2d\u7684\u5750\u6807\uff1a\n    Eigen::Vector3d A(1, 3, -M_PI / 2);\n\n    // \u6c42\u673a\u5668\u4ebaA\u5728\u673a\u5668\u4ebaB\u4e2d\u7684\u5750\u6807\uff1a\n    Eigen::Vector3d BA;\n    // TODO \u53c2\u7167\u7b2c\u4e00\u8bfePPT\n    // start your code here (5~10 lines)\n    Eigen::Matrix3d TOA;\n    \n    // end your code here\n\n    cout << \"The right answer is BA: 2 1 1.5708\" << endl;\n    cout << \"Your answer is BA: \" << BA.transpose() << endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "1d68409b7763d3ea658fb07e9796db5f36d0dab1", "size": 779, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "shenlan/lidar slam/basicTransformStudy/basic_transform_study.cpp", "max_stars_repo_name": "linksdl/futuretec-project-coursera_cerficates", "max_stars_repo_head_hexsha": "278a533501b702abd90ac3124739d3d85935e1f8", "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": "shenlan/lidar slam/basicTransformStudy/basic_transform_study.cpp", "max_issues_repo_name": "linksdl/futuretec-project-coursera_cerficates", "max_issues_repo_head_hexsha": "278a533501b702abd90ac3124739d3d85935e1f8", "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": "shenlan/lidar slam/basicTransformStudy/basic_transform_study.cpp", "max_forks_repo_name": "linksdl/futuretec-project-coursera_cerficates", "max_forks_repo_head_hexsha": "278a533501b702abd90ac3124739d3d85935e1f8", "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": 21.0540540541, "max_line_length": 60, "alphanum_fraction": 0.5455712452, "num_tokens": 333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952893703477, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7318303634180402}}
{"text": "// A majority of this code is from Rosetta Code: https://rosettacode.org/wiki/Ackermann_function#Efficient_version\n// This adaptation allows for user input\n#include <iostream>\n#include <sstream>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/lexical_cast.hpp>\n\nusing big_int = boost::multiprecision::cpp_int;\n\nbig_int ipow(big_int base, big_int exp);\nbig_int ackermann(unsigned m, unsigned n);\n\nint main(){\n\tstd::string mStr, nStr;\n\t\n\tstd::cout << \"Ack(m,n)\\nm = \";\n\tstd::getline(std::cin, mStr);\n\n\tstd::cout << \"n = \";\n\tstd::getline(std::cin, nStr);\n\n\tstd::cout << \"Ack(\" + mStr + ',' + nStr + \") = \" \n\t\t<< ackermann(boost::lexical_cast<unsigned>(mStr),boost::lexical_cast<unsigned>(nStr)) << '\\n';\n\n\treturn 0;\n}\n\nbig_int ipow(big_int base, big_int exp){\n\tbig_int result(1);\n\twhile(exp){\n\t\tif(exp & 1){\n\t\t\tresult *= base;\n\t\t}\n\t\texp >>= 1;\n\t\tbase *= base;\n\t}\n\treturn result;\n}\n\nbig_int ackermann(unsigned m, unsigned n){\n\tstatic big_int (*ack)(unsigned, big_int) =\n\t\t[](unsigned m, big_int n)->big_int {\n\t\t\tswitch(m){\n\t\t\t\tcase 0:\n\t\t\t\t\treturn n+1;\n\t\t\t\tcase 1:\n\t\t\t\t\treturn n+2;\n\t\t\t\tcase 2:\n\t\t\t\t\treturn 3+2*n;\n\t\t\t\tcase 3:\n\t\t\t\t\treturn 5 + 8 * (ipow(big_int(2), n) - 1);\n\t\t\t\tdefault:\n\t\t\t\t\treturn n == 0 ? ack(m - 1, big_int(1)) : ack(m - 1, ack(m, n - 1));\n\t\t\t}\n\t\t};\n\treturn ack(m, big_int(n));\n}\n", "meta": {"hexsha": "d6adf84718811338acd92eef3613fc250dd71a51", "size": 1305, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Ackermann-function/Ackermann-function-optimal.cpp", "max_stars_repo_name": "esote/mathematical-functions", "max_stars_repo_head_hexsha": "0bdf761583a49b6479a82d7e0668744d9bb75dad", "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": "Ackermann-function/Ackermann-function-optimal.cpp", "max_issues_repo_name": "esote/mathematical-functions", "max_issues_repo_head_hexsha": "0bdf761583a49b6479a82d7e0668744d9bb75dad", "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": "Ackermann-function/Ackermann-function-optimal.cpp", "max_forks_repo_name": "esote/mathematical-functions", "max_forks_repo_head_hexsha": "0bdf761583a49b6479a82d7e0668744d9bb75dad", "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.5, "max_line_length": 114, "alphanum_fraction": 0.6245210728, "num_tokens": 408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377237352756, "lm_q2_score": 0.7634837635542925, "lm_q1q2_score": 0.7318279888261728}}
{"text": "/* EuropeanOption.cpp\r\n-Description:\r\n\t*Derived option class that uses Black-Scholes formula to give exact price.\r\n-Variable/Object Catalogue:\r\n\t*normal_distribution<> normDist: Normal Distribution RNG object.\r\n-Member Functions:\r\n\t// Constructors/Destructor:\r\n\t*EuropeanOption(double, double, double, double, double, bool): Set parameters to corresponding passed values.\r\n\t*EuropeanOption(const EuropeanOption&): Copy constructor.\r\n\t*~EuropeanOption(): Destructor.\r\n\t// Misc. Methods:\r\n\t*double AltPrice() const: Return price of alternate form of option using Put-Call Parity.\r\n\t*double D1() const: Return \"d1\", Z-score used in Black-Scholes model.\r\n\t*double D2() const: Return \"d2\", Z-score used in Black-Scholes model.\r\n\t*double Price() const: Return price using Black-Scholes formula.\r\n\t*double Delta() const: Return change in Price given change in s.\r\n\t*double Gamma() const: Return 2nd order change in Price given change in s.\r\n*/\r\n\r\n#include <boost\\math\\distributions.hpp>\r\n#include <string>\r\n#include <iostream>\r\n#include <strstream>\r\n#include \"EuropeanOption.hpp\"\r\n#include \"OptionExcept.hpp\"\r\n\r\nnamespace Options\r\n{\r\n\t////////////////////////////\r\n\t// Constructors/Destructor:\r\n\t////////////////////////////\r\n\tEuropeanOption::EuropeanOption(double t, double s, double k, double b, double r, double sigma, bool isCall) :\t/* Overloaded Constructor. Set all values of */\r\n\tOption(t, s, k, b, r, sigma, isCall) \r\n\t{\r\n\r\n\t}\r\n\tEuropeanOption::EuropeanOption(const EuropeanOption &in) : Option(in)\t/* Copy Constructor. */\r\n\t{\r\n\r\n\t}\r\n\tEuropeanOption::~EuropeanOption()\t\t\t\t\t/* Destructor. */\r\n\t{\r\n\r\n\t}\r\n\t//////////////////////////\r\n\t// Misc. Methods:\r\n\t//////////////////////////\r\n\tdouble EuropeanOption::AltPrice() const\t\t\t    /* Return price of alternative type using Put-Call Parity. */\r\n\t{\r\n\t\tif (Type()) // Return corresponding price of Put option if option is Call using Put-Call Parity.\r\n\t\t{\r\n\t\t\treturn Price() + Param(\"k\") * exp(-Param(\"r\") * Param(\"t\")) - Param(\"s\");\r\n\t\t}\r\n\t\telse\t\t// Return corresponding price of corresponding Call option if option is Put.\r\n\t\t{\r\n\t\t\treturn Price() - Param(\"k\") * exp(-Param(\"r\") * Param(\"t\")) + Param(\"s\");\r\n\t\t}\r\n\t}\r\n\tdouble EuropeanOption::D1()\tconst\t\t\t\t\t/* Calculate Z-Score used in Black-Scholes formula. */\r\n\t{\r\n\t\t// d1 = (ln(s/k) + (b + sigma^2/2) * t) / (sigma * sqrt(t))\r\n\t\treturn (log(Param(\"s\") / Param(\"k\")) + (Param(\"b\") + .5 * pow(Param(\"sigma\"), 2)) * Param(\"t\")) / (Param(\"sigma\") * sqrt(Param(\"t\")));\r\n\t}\r\n\tdouble EuropeanOption::D2() const\t\t\t\t\t/* Calculate Z-Score used in Black-Scholes formula. */\r\n\t{\r\n\t\t// d2 = d1 - sigma * sqrt(t)\r\n\t\treturn  D1() - Param(\"sigma\") * sqrt(Param(\"t\"));\r\n\t}\r\n\tdouble EuropeanOption::Price() const\t\t\t\t/* Return price of option. */\r\n\t{\r\n\t\ttry\r\n\t\t{\r\n\t\t\tif (Type())\r\n\t\t\t{\r\n\t\t\t\treturn boost::math::cdf(normDist, D1()) * Param(\"s\") * std::exp((Param(\"b\") - Param(\"r\")) * Param(\"t\")) - boost::math::cdf(normDist, D2()) * Param(\"k\") * std::exp(-Param(\"r\") * Param(\"t\"));\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\treturn boost::math::cdf(normDist, -D2()) * Param(\"k\") * std::exp(-Param(\"r\") * Param(\"t\")) - boost::math::cdf(normDist, -D1()) * Param(\"s\") * std::exp((Param(\"b\") - Param(\"r\")) * Param(\"t\"));\r\n\t\t\t}\r\n\t\t}\r\n\t\tcatch (...)\r\n\t\t{\r\n\t\t\tthrow Exceptions::OptionExcept(\"EuropeanOption::Price() Error: Unhandled exception. \");\r\n\t\t}\r\n\t}\r\n\t// Greeks:\r\n\tdouble EuropeanOption::Delta() const\t\t\t\t/* Change in price with respect to s (1st order). */\r\n\t{\r\n\t\tif (Type())\r\n\t\t{\r\n\t\t\treturn boost::math::cdf(normDist, D1()) * std::exp((Param(\"b\") - Param(\"r\")) * Param(\"t\"));  // dC/dS = N(d1) * e^((b - r)t).\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\t// Using Put-Call Parity, can see that dP/dS = dC/dS - e^((b - r))t = (N(d1) - 1) * e^((b - r)t):\r\n\t\t\treturn (boost::math::cdf(normDist, D1()) - 1) * std::exp((Param(\"b\") - Param(\"r\")) * Param(\"t\"));\r\n\t\t}\r\n\t}\r\n\tdouble EuropeanOption::Gamma() const\t\t\t\t/* Change in price with respect to s (2nd order). */\r\n\t{\r\n\t\t// Following Put-Call Parity, we see that Gamma is the same for both Puts and Calls ((d/dS)^2P = (d/dS)^2C):\r\n\t\treturn boost::math::cdf(normDist, D1()) / (Param(\"s\") * Param(\"sigma\") * sqrt(Param(\"t\"))) * exp((Param(\"b\") - Param(\"r\")) * Param(\"t\"));\r\n\t}\r\n\t//////////////////////////\r\n\t// Overloaded Operators: \r\n\t//////////////////////////\r\n\tEuropeanOption& EuropeanOption::operator=(const EuropeanOption &in) /* Assignment Operator. */\r\n\t{\r\n\t\tif (this != &in)\r\n\t\t{\r\n\t\t\tOption::operator=(in);\r\n\t\t}\r\n\t\treturn *this;\r\n\t}\r\n}", "meta": {"hexsha": "1f252339baa57d2dcc11564efdc1429b430933a8", "size": 4423, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Options/Files/EuropeanOption.cpp", "max_stars_repo_name": "BRutan/Cpp", "max_stars_repo_head_hexsha": "8acbc6c341f49d6d83168ccd5ba49bd6824214f9", "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": "Options/Files/EuropeanOption.cpp", "max_issues_repo_name": "BRutan/Cpp", "max_issues_repo_head_hexsha": "8acbc6c341f49d6d83168ccd5ba49bd6824214f9", "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": "Options/Files/EuropeanOption.cpp", "max_forks_repo_name": "BRutan/Cpp", "max_forks_repo_head_hexsha": "8acbc6c341f49d6d83168ccd5ba49bd6824214f9", "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.1293103448, "max_line_length": 196, "alphanum_fraction": 0.5919059462, "num_tokens": 1283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.948154531885212, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.7318269103822526}}
{"text": "//          Copyright Rein Halbersma 2010-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#include <dctl/egdb/binomial.hpp>       // choose\n#include <boost/test/unit_test.hpp>     // BOOST_AUTO_TEST_SUITE, BOOST_AUTO_TEST_CASE, BOOST_CHECK_EQUAL, BOOST_AUTO_TEST_SUITE_END\n\nBOOST_AUTO_TEST_SUITE(Binomial)\n\nusing dctl::egdb::choose;\nconstexpr auto N = 64;\n\nBOOST_AUTO_TEST_CASE(CoefficientsAreSymmetric)\n{\n        for (auto n = 0; n < N + 1; ++n) {\n                for (auto k = 0; k < n + 1; ++k) {\n                        BOOST_CHECK_EQUAL(choose(n, k), choose(n, n - k));\n                }\n        }\n}\n\nBOOST_AUTO_TEST_CASE(CoefficientsSatisfyPascalTriangle)\n{\n        for (auto n = 0; n < N + 1; ++n) {\n                BOOST_CHECK_EQUAL(choose(n, 0), 1);\n                for (auto k = 1; k < n; ++k) {\n                        BOOST_CHECK_EQUAL(choose(n, k), choose(n - 1, k - 1) + choose(n - 1, k));\n                }\n                BOOST_CHECK_EQUAL(choose(n, n), 1);\n        }\n}\n\nBOOST_AUTO_TEST_CASE(CoefficientsSatisfyNewtonTheorem)\n{\n        // Type int64_t values lie within the half-open interval [-2^63, 2^63).\n        // Hence, we can test Newton's Theorem for at most n = 62.\n        for (auto n = 0; n < N - 1; ++n) {\n                auto sum = 0LL;\n                for (auto k = 0; k < n + 1; ++k) {\n                        sum += choose(n, k);\n                }\n                BOOST_CHECK_EQUAL(sum, 1LL << n);\n        }\n}\n\nBOOST_AUTO_TEST_CASE(SmallCoefficientsAreTrivial)\n{\n        for (auto n = 0; n <= N; ++n) {\n                BOOST_CHECK_EQUAL(choose(n, -1    ), 0);\n                BOOST_CHECK_EQUAL(choose(n,  0    ), 1);\n                BOOST_CHECK_EQUAL(choose(n,  1    ), n);\n                BOOST_CHECK_EQUAL(choose(n,  n - 1), n);\n                BOOST_CHECK_EQUAL(choose(n,  n    ), 1);\n                BOOST_CHECK_EQUAL(choose(n,  n + 1), 0);\n        }\n}\n\nBOOST_AUTO_TEST_CASE(LargeCoefficientsMatchWolframAlpha)\n{\n        // https://www.wolframalpha.com/input/?i=binomial%5B64,+32%5D\n        BOOST_CHECK_EQUAL(choose(64, 32), 1'832'624'140'942'590'534LL);\n\n        // https://www.wolframalpha.com/input/?i=binomial%5B90,+18%5D\n        BOOST_CHECK_EQUAL((choose<90, 18>)(90, 18), 3'789'648'142'708'598'775LL);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "44cf33887d605d5a5e507fd8a1b5a08fbd8f4698", "size": 2402, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/src/egdb/binomial.cpp", "max_stars_repo_name": "sagarpant1/dctl", "max_stars_repo_head_hexsha": "b858fa139159eff73e8f3eec32da93ba077e0bd3", "max_stars_repo_licenses": ["BSL-1.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": "test/src/egdb/binomial.cpp", "max_issues_repo_name": "sagarpant1/dctl", "max_issues_repo_head_hexsha": "b858fa139159eff73e8f3eec32da93ba077e0bd3", "max_issues_repo_licenses": ["BSL-1.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": "test/src/egdb/binomial.cpp", "max_forks_repo_name": "sagarpant1/dctl", "max_forks_repo_head_hexsha": "b858fa139159eff73e8f3eec32da93ba077e0bd3", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-27T14:19:28.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-27T14:19:28.000Z", "avg_line_length": 34.8115942029, "max_line_length": 132, "alphanum_fraction": 0.5549542048, "num_tokens": 708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777929, "lm_q2_score": 0.7956580976404297, "lm_q1q2_score": 0.7317210268661523}}
{"text": "#pragma once\n#include \"coordinate_transform.hpp\"\n#include \"integrate.hpp\"\n#include \"shape.hpp\"\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <functional>\n\n//----------------L2Begin----------------\n//! Computes the L^2 differences between\n//! u1 (considered as coefficients for Quadratic FEM) and u2.\ndouble computeL2Difference(const Eigen::MatrixXd &vertices,\n                           const Eigen::MatrixXi &dofs,\n                           const Eigen::VectorXd &u1,\n                           const std::function<double(double, double)> &u2) {\n\tconst int numberOfElements = dofs.rows();\n\n\tdouble error = 0;\n\tfor (int i = 0; i < numberOfElements; ++i) {\n\t\tauto &idSet = dofs.row(i);\n\n\t\tconst auto &a = vertices.row(idSet(0));\n\t\tconst auto &b = vertices.row(idSet(1));\n\t\tconst auto &c = vertices.row(idSet(2));\n\n\t\tauto coordinateTransform = makeCoordinateTransform(b - a, c - a);\n\t\tauto volumeFactor        = std::abs(coordinateTransform.determinant());\n\n\t\t// (write your solution here)\n\t\tauto f = [&](double x, double y) -> double {\n\t\t\tEigen::Vector2d transformedPoint = coordinateTransform * Eigen::Vector2d(x, y) + a.transpose();\n\n\t\t\tdouble approximateValue = 0;\n\t\t\tfor (int j = 0; j < 6; ++j) {\n\t\t\t\tapproximateValue += u1(idSet(j)) * shapefun(j, x, y);\n\t\t\t}\n\n\t\t\tdouble diff = u2(transformedPoint.x(), transformedPoint.y()) - approximateValue;\n\n\t\t\treturn diff * diff * volumeFactor;\n\t\t};\n\n\t\terror += integrate(f);\n\t}\n\n\treturn std::sqrt(error);\n}\n//----------------L2End----------------\n", "meta": {"hexsha": "fae9d8e8163915095388e690afd7720c9fe9a7c5", "size": 1499, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "series3/2d-poissonqFEM/L2_norm.hpp", "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": "series3/2d-poissonqFEM/L2_norm.hpp", "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": "series3/2d-poissonqFEM/L2_norm.hpp", "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": 30.5918367347, "max_line_length": 98, "alphanum_fraction": 0.6144096064, "num_tokens": 379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554475, "lm_q2_score": 0.7879311881731379, "lm_q1q2_score": 0.7315222493320516}}
{"text": "#include<iostream>\n\n#include <Eigen/Dense>\n#include \"Classes.h\"\nusing namespace Eigen;\n\nvoid Point::setCoordinates(double t1, double t2, double t3){\n\t///\n\t/// Setter Function for Point Class, to set coordinates\n\t///\n\tx=t1;\n\ty=t2;\n\tz=t3;\n}\n\nvoid Point::setCoordinatesAndLabel(double t1,double t2,double t3,string s){\n\t///\n\t/// Setter Function for Point Class, to set coordinates and label\n\t///\n\tx=t1;\n\ty=t2;\n\tz=t3;\n\tlabel = s;\n\t//cout<< \"label is this \"\t<< label <<endl;\n} \n\nPoint Point::projectPoint(double projectionPlane[]) {\n    ///\n    /// Function to give the projection of the current calling object on the projection plane passed in parameters as \"projectionPlane\"\n    ///\n    double a = projectionPlane[0];\n\tdouble b = projectionPlane[1];\n\tdouble c = projectionPlane[2];\n\tdouble d = projectionPlane[3];\n\tdouble t =((d-(a*x+b*y+c*z))/(a*a+b*b+c*c));\n\tPoint projectedpoint;\n\tprojectedpoint.x = (x+a*t);\n\tprojectedpoint.y = (y+b*t);\n\tprojectedpoint.z = (z+c*t);\n\treturn projectedpoint;\n}\n\ndouble Point::relativePosition(double plane[]) {\n    ///\n    /// Function to calculate the relative position of the current calling object w.r.t the passed parameter \"plane\"\n    ///\n    double a = plane[0];\n\tdouble b = plane[1];\n\tdouble c = plane[2];\n\tdouble d = plane[3];\n\tdouble t = ((a*x+b*y+c*z-d)/(a*a+b*b+c*c));\n\treturn t;\n}\n\nbool Point::checkcollinear(Point * a, Point * b){\n\t///\n\t/// Function to check if the current Pint object is collinear with the points passed as parameters\n\t///\n\tVector3d v1(x, y, z);\n\tVector3d v2(a->x, a->y, a->z);\n\tVector3d v3(b->x, b->y, b->z);\n\tVector3d v4 = (v2-v1).cross(v3-v1);\n\tdouble k = v4.dot(v4);\n\treturn (k<0.00001);\n}\n", "meta": {"hexsha": "cbd8c3eab4279df505c6f085ece3eb1bc790e7f1", "size": 1657, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Point.cpp", "max_stars_repo_name": "DivyanshuSaxena/COP290-Assignment", "max_stars_repo_head_hexsha": "dbf06f0aa29de9c3d4250c232fb2dd14eabe1b52", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2018-03-04T18:44:22.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-04T23:07:12.000Z", "max_issues_repo_path": "src/Point.cpp", "max_issues_repo_name": "DivyanshuSaxena/COP290-Assignment", "max_issues_repo_head_hexsha": "dbf06f0aa29de9c3d4250c232fb2dd14eabe1b52", "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/Point.cpp", "max_forks_repo_name": "DivyanshuSaxena/COP290-Assignment", "max_forks_repo_head_hexsha": "dbf06f0aa29de9c3d4250c232fb2dd14eabe1b52", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-02-09T10:55:18.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-28T08:53:33.000Z", "avg_line_length": 25.1060606061, "max_line_length": 135, "alphanum_fraction": 0.656004828, "num_tokens": 472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.8244619285331332, "lm_q1q2_score": 0.7314664103394608}}
{"text": "#ifndef MATHTOOLBOX_RBF_INTERPOLATION_HPP\n#define MATHTOOLBOX_RBF_INTERPOLATION_HPP\n\n#include <Eigen/Core>\n#include <cmath>\n#include <functional>\n#include <memory>\n#include <vector>\n\nnamespace mathtoolbox\n{\n    class AbstractRbfKernel\n    {\n    public:\n        AbstractRbfKernel() {}\n        virtual ~AbstractRbfKernel(){};\n\n        virtual double operator()(const double r) const = 0;\n    };\n\n    class GaussianRbfKernel final : public AbstractRbfKernel\n    {\n    public:\n        GaussianRbfKernel(const double theta = 1.0) : m_theta(theta) {}\n\n        double operator()(const double r) const override\n        {\n            assert(r >= 0.0);\n            return std::exp(-m_theta * r * r);\n        }\n\n    private:\n        const double m_theta;\n    };\n\n    class ThinPlateSplineRbfKernel final : public AbstractRbfKernel\n    {\n    public:\n        ThinPlateSplineRbfKernel() {}\n\n        double operator()(const double r) const override\n        {\n            assert(r >= 0.0);\n            const double value = r * r * std::log(r);\n            return std::isnan(value) ? 0.0 : value;\n        }\n    };\n\n    class LinearRbfKernel final : AbstractRbfKernel\n    {\n    public:\n        LinearRbfKernel() {}\n\n        double operator()(const double r) const override { return std::abs(r); }\n    };\n\n    class InverseQuadraticRbfKernel final : public AbstractRbfKernel\n    {\n    public:\n        InverseQuadraticRbfKernel(const double theta = 1.0) : m_theta(theta) {}\n\n        double operator()(const double r) const override { return 1.0 / std::sqrt(r * r + m_theta * m_theta); }\n\n    private:\n        const double m_theta;\n    };\n\n    class RbfInterpolator\n    {\n    public:\n        RbfInterpolator(const std::function<double(const double)>& rbf_kernel = ThinPlateSplineRbfKernel());\n\n        /// \\brief Set data points and their values\n        void SetData(const Eigen::MatrixXd& X, const Eigen::VectorXd& y);\n\n        /// \\brief Calculate the interpolation weights\n        ///\n        /// \\details This method should be called after setting the data\n        void CalcWeights(const bool use_regularization = false, const double lambda = 0.001);\n\n        /// \\brief Calculate the interpolatetd value at the specified data point\n        ///\n        /// \\details This method should be called after calculating the weights\n        double CalcValue(const Eigen::VectorXd& x) const;\n\n    private:\n        // RBF kernel\n        const std::function<double(double)> m_rbf_kernel;\n\n        // Data points\n        Eigen::MatrixXd m_X;\n        Eigen::VectorXd m_y;\n\n        // Weights\n        Eigen::VectorXd m_w;\n\n        // Returns f(||xj - xi||)\n        double CalcRbfValue(const Eigen::VectorXd& xi, const Eigen::VectorXd& xj) const;\n    };\n} // namespace mathtoolbox\n\n#endif // MATHTOOLBOX_RBF_INTERPOLATION_HPP\n", "meta": {"hexsha": "914c46c1e4d5b12104ca6f472939dadff8c93ab6", "size": 2794, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mathtoolbox/rbf-interpolation.hpp", "max_stars_repo_name": "amazing89/mathtoolbox", "max_stars_repo_head_hexsha": "8904bb06ced2ac501594f9574ef1ba3454b8e38e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-02-01T03:39:24.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-01T03:39:24.000Z", "max_issues_repo_path": "include/mathtoolbox/rbf-interpolation.hpp", "max_issues_repo_name": "amazing89/mathtoolbox", "max_issues_repo_head_hexsha": "8904bb06ced2ac501594f9574ef1ba3454b8e38e", "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": "include/mathtoolbox/rbf-interpolation.hpp", "max_forks_repo_name": "amazing89/mathtoolbox", "max_forks_repo_head_hexsha": "8904bb06ced2ac501594f9574ef1ba3454b8e38e", "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.1262135922, "max_line_length": 111, "alphanum_fraction": 0.6231209735, "num_tokens": 672, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476800298183, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7312230031363868}}
{"text": "/*\n * A very basic demo of libeigen3.\n *\n * USAGE:\n *    g++ -o predefined_matrices -I /PATH/TO/EIGEN/ predefined_matrices.cc\n * or\n *    g++ -o predefined_matrices $(pkg-config --cflags eigen3) predefined_matrices.cc\n */\n\n#include <iostream>\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\nint size = 3;\nint low = 1;\nint high = 3;\n\nint main()\n{\n    /*\n     * Using matrix template\n     */\n    {\n        Matrix<double, 2, 3> m1 = Matrix<double, 2, 3>::Zero();\n        Matrix<double, 2, 3> m2 = Matrix<double, 2, 3>::Ones();\n        Matrix<double, 2, 3> m3 = Matrix<double, 2, 3>::Constant(3);\n        Matrix<double, 2, 3> m4 = Matrix<double, 2, 3>::Random();\n        Matrix<double, 1, 3> m5 = Matrix<double, 1, 3>::LinSpaced(size, low, high);\n        Matrix<double, 3, 3> m6 = Matrix<double, 3, 3>::Identity();\n\n        std::cout << std::endl << \"Matrix<double, 2, 3>::Zero()\" << std::endl << m1 << std::endl;\n        std::cout << std::endl << \"Matrix<double, 2, 3>::Ones();\" << std::endl << m2 << std::endl;\n        std::cout << std::endl << \"Matrix<double, 2, 3>::Constant(3)\" << std::endl << m3 << std::endl;\n        std::cout << std::endl << \"Matrix<double, 2, 3>::Random()\" << std::endl << m4 << std::endl;\n        std::cout << std::endl << \"Matrix<double, 2, 3>::LinSpaced(size, low, high)\" << std::endl << m5 << std::endl;\n        std::cout << std::endl << \"Matrix<double, 3, 3>::Identity()\" << std::endl << m6 << std::endl;\n    }\n\n    /*\n     * Using typedef matrices\n     */\n    {\n        Matrix3d m1 = Matrix3d::Zero();\n        Matrix3d m2 = Matrix3d::Ones();\n        Matrix3d m3 = Matrix3d::Constant(3);\n        Matrix3d m4 = Matrix3d::Random();\n        Matrix3d m6 = Matrix3d::Identity();\n\n        std::cout << std::endl << \"Matrix3d::Zero()\" << std::endl << m1 << std::endl;\n        std::cout << std::endl << \"Matrix3d::Ones();\" << std::endl << m2 << std::endl;\n        std::cout << std::endl << \"Matrix3d::Constant(3)\" << std::endl << m3 << std::endl;\n        std::cout << std::endl << \"Matrix3d::Random()\" << std::endl << m4 << std::endl;\n        std::cout << std::endl << \"Matrix3d::Identity()\" << std::endl << m6 << std::endl;\n    }\n\n    /*\n     * Using dynamic matrices\n     */\n    {\n        MatrixXd m1 = MatrixXd::Zero(2, 3);\n        MatrixXd m2 = MatrixXd::Ones(2, 3);\n        MatrixXd m3 = MatrixXd::Constant(2, 3, 9);\n        MatrixXd m4 = MatrixXd::Random(2, 3);\n        MatrixXd m6 = MatrixXd::Identity(3, 3);\n\n        std::cout << std::endl << \"MatrixXd::Zero(2, 3)\" << std::endl << m1 << std::endl;\n        std::cout << std::endl << \"MatrixXd::Ones(2, 3);\" << std::endl << m2 << std::endl;\n        std::cout << std::endl << \"MatrixXd::Constant(2, 3, 9)\" << std::endl << m3 << std::endl;\n        std::cout << std::endl << \"MatrixXd::Random(2, 3)\" << std::endl << m4 << std::endl;\n        std::cout << std::endl << \"MatrixXd::Identity(3, 3)\" << std::endl << m6 << std::endl;\n    }\n\n    /*\n     * Using dynamic vectors\n     */\n    {\n        VectorXd m1 = VectorXd::Zero(3);\n        VectorXd m2 = VectorXd::Ones(3);\n        VectorXd m3 = VectorXd::Constant(3, 9);\n        VectorXd m4 = VectorXd::Random(3);\n        VectorXd m5 = VectorXd::LinSpaced(size, low, high);\n\n        std::cout << std::endl << \"VectorXd::Zero(3)\" << std::endl << m1 << std::endl;\n        std::cout << std::endl << \"VectorXd::Ones(3);\" << std::endl << m2 << std::endl;\n        std::cout << std::endl << \"VectorXd::Constant(3, 9)\" << std::endl << m3 << std::endl;\n        std::cout << std::endl << \"VectorXd::Random(3)\" << std::endl << m4 << std::endl;\n        std::cout << std::endl << \"VectorXd::LinSpaced(size, low, high)\" << std::endl << m5 << std::endl;\n    }\n}\n", "meta": {"hexsha": "38a395f748c829aa676af98a624932c8fc90ae0f", "size": 3663, "ext": "cc", "lang": "C++", "max_stars_repo_path": "cpp/eigen/eigen3/predefined_matrices/predefined_matrices.cc", "max_stars_repo_name": "jeremiedecock/snippets", "max_stars_repo_head_hexsha": "4bd4e7f459eee610d5cf19f845299ca942ff4b64", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2015-06-08T13:01:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-30T08:20:04.000Z", "max_issues_repo_path": "cpp/eigen/eigen3/predefined_matrices/predefined_matrices.cc", "max_issues_repo_name": "jeremiedecock/snippets", "max_issues_repo_head_hexsha": "4bd4e7f459eee610d5cf19f845299ca942ff4b64", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-10-22T02:36:10.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-22T02:36:10.000Z", "max_forks_repo_path": "cpp/eigen/eigen3/predefined_matrices/predefined_matrices.cc", "max_forks_repo_name": "jeremiedecock/snippets", "max_forks_repo_head_hexsha": "4bd4e7f459eee610d5cf19f845299ca942ff4b64", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-10-31T09:48:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T15:59:45.000Z", "avg_line_length": 40.2527472527, "max_line_length": 117, "alphanum_fraction": 0.5274365274, "num_tokens": 1195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767938900121, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7312229977963003}}
{"text": "/**\n * @file finitevolumerobin_test.cc\n * @brief NPDE homework FiniteVolumeRobin code\n * @author Philippe Peter\n * @date February 2020\n * @copyright Developed at ETH Zurich\n */\n\n#include \"../finitevolumerobin.h\"\n\n#include <gtest/gtest.h>\n#include <lf/assemble/assemble.h>\n#include <lf/fe/fe.h>\n#include <lf/mesh/test_utils/test_meshes.h>\n#include <lf/mesh/utils/utils.h>\n#include <lf/uscalfe/uscalfe.h>\n\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n#include <memory>\n\nnamespace FiniteVolumeRobin::test {\n\nTEST(FiniteVolumeRobin, EdgeMatrixProvider) {\n  // Build triangular test mesh\n  auto mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh(3);\n\n  // initialize functors gamma and v\n  auto gamma = [](Eigen::Vector2d x) { return 2.0; };\n  auto v = [](Eigen::Vector2d x) { return 2 * x(0) + x(1); };\n  auto v_mf = lf::mesh::utils::MeshFunctionGlobal(v);\n\n  // set up finite element space and dofhandler\n  auto fe_space =\n      std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n  auto &dofh = fe_space->LocGlobMap();\n\n  // mark boudnary edges\n  auto bd_flags{lf::mesh::utils::flagEntitiesOnBoundary(mesh_p, 1)};\n\n  // assemble galerkin matrix corresponding to correction term.\n  lf::assemble::COOMatrix<double> A(dofh.NumDofs(), dofh.NumDofs());\n  EdgeMatrixProvider edmat_provider(gamma, bd_flags);\n  lf::assemble::AssembleMatrixLocally(1, dofh, dofh, edmat_provider, A);\n  Eigen::SparseMatrix<double> A_crs = A.makeSparse();\n\n  // project v into the FEspace\n  auto v_vec = lf::fe::NodalProjection<double>(*fe_space, v_mf);\n\n  // create a ones vector\n  Eigen::VectorXd ones = Eigen::VectorXd::Ones(dofh.NumDofs());\n\n  // evaluated product should corresponds to the integral of v*gamma over the\n  // boundary of the mesh. Explanation: \\union_i(\\partial C_i \\cap \\partial\n  // \\Omega) = \\partial \\Omega, and the union is disjoint.\n  auto product = (ones.transpose() * A_crs * v_vec).eval();\n  EXPECT_NEAR(product(0, 0), 108, 1E-6);\n}\n\nTEST(FiniteVolumeRobin, EdgeVectorProvider) {\n  // Build triangular test mesh\n  auto mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh(3);\n\n  // initialize functor g\n  auto g = [](Eigen::Vector2d x) { return 2 * x(0) + x(1); };\n\n  // set up finite element space and dofhandler\n  auto fe_space =\n      std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n  auto &dofh = fe_space->LocGlobMap();\n\n  // mark boudnary edges\n  auto bd_flags{lf::mesh::utils::flagEntitiesOnBoundary(mesh_p, 1)};\n\n  // assemble rhs vector\n  Eigen::VectorXd phi(dofh.NumDofs());\n  phi.setZero();\n  EdgeVectorProvider edvec_provider(g, bd_flags);\n  lf::assemble::AssembleVectorLocally(1, dofh, edvec_provider, phi);\n\n  // create a ones vector\n  Eigen::VectorXd ones = Eigen::VectorXd::Ones(dofh.NumDofs());\n\n  // evaluated product should corresponds to the integral of g over the boundary\n  // of the mesh. Explanation: \\union_i(\\partial C_i \\cap \\partial \\Omega) =\n  // \\partial \\Omega, and the union is disjoint\n  auto product = (ones.transpose() * phi).eval();\n  EXPECT_NEAR(product(0, 0), 54.0, 1E-6);\n}\n\n}  // namespace FiniteVolumeRobin::test\n", "meta": {"hexsha": "2bd8c101cbe2ca0522d5b5eab174e95953de9ebe", "size": 3099, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/FiniteVolumeRobin/templates/test/finitevolumerobin_test.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": "homeworks/FiniteVolumeRobin/templates/test/finitevolumerobin_test.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": "homeworks/FiniteVolumeRobin/templates/test/finitevolumerobin_test.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": 33.6847826087, "max_line_length": 80, "alphanum_fraction": 0.7095837367, "num_tokens": 909, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7312229870078921}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main()\n{\n  ArrayXf a = ArrayXf::Random(5);\n  a *= 2;\n  cout << \"a =\" << endl\n       << a << endl;\n  cout << \"a.abs() =\" << endl\n       << a.abs() << endl;\n  cout << \"a.abs().sqrt() =\" << endl\n       << a.abs().sqrt() << endl;\n  cout << \"a.min(a.abs().sqrt()) =\" << endl\n       << a.min(a.abs().sqrt()) << endl;\n}\n", "meta": {"hexsha": "8d3eba729c0abf3e738f27272727f908c773c389", "size": 406, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "simulator/external/habitat-sim-geodesic/habitat_sim_geodesic/csrc/eigen/doc/examples/Tutorial_ArrayClass_cwise_other.cpp", "max_stars_repo_name": "eundersander/bps-nav", "max_stars_repo_head_hexsha": "a33bac7d10dc077baa596a76790b4fc829d332f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2021-03-15T01:49:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-11T23:17:14.000Z", "max_issues_repo_path": "simulator/external/habitat-sim-geodesic/habitat_sim_geodesic/csrc/eigen/doc/examples/Tutorial_ArrayClass_cwise_other.cpp", "max_issues_repo_name": "eundersander/bps-nav", "max_issues_repo_head_hexsha": "a33bac7d10dc077baa596a76790b4fc829d332f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-06-27T21:41:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-18T21:46:40.000Z", "max_forks_repo_path": "simulator/external/habitat-sim-geodesic/habitat_sim_geodesic/csrc/eigen/doc/examples/Tutorial_ArrayClass_cwise_other.cpp", "max_forks_repo_name": "eundersander/bps-nav", "max_forks_repo_head_hexsha": "a33bac7d10dc077baa596a76790b4fc829d332f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-03-27T17:17:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-19T12:00:06.000Z", "avg_line_length": 20.3, "max_line_length": 43, "alphanum_fraction": 0.4852216749, "num_tokens": 127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9219218327098193, "lm_q2_score": 0.7931059536292271, "lm_q1q2_score": 0.731181694302926}}
{"text": "//\n// Created by GXSN-Pro on 2018/10/17.\n//\n\n#include \"sphere_util.hpp\"\n#include \"math_util.hpp\"\n#include <cmath>\n#include <boost/range/size_type.hpp>\n\n#define earth_radius  6371008.8\n\n#define MAX_COORDINATE_VALUE 1000000\n#define MIN_COORDINATE_VALUE -1000000\n\nusing namespace OpenEarth::Geometry;\n\ndouble SphereUtil::degreesToRadians(double degree) {\n    return degree * M_PI / 180.0;\n}\n\ndouble SphereUtil::radiansToDegrees(double rad) {\n    return rad * 180.0 / M_PI;\n}\n\n/**\n * \u8ba1\u7b97\u4e24\u70b9\u95f4\u7684\u7403\u9762\u8ddd\u79bb(\u5355\u4f4d m)\n * @param from\n * @param to\n * */\ndouble SphereUtil::distance(const LatLng &from,const LatLng &to) {\n    //\u5148\u8ba1\u7b97\u4e24\u70b9\u4e4b\u95f4\u7684\u5927\u5706\u5939\u89d2\n    double rad = computeAngleBetween(from,to);\n    return rad * earth_radius;\n}\n\n/**\n * \u8ba1\u7b97\u533a\u57df\u9762\u79ef\n * google maps\n * */\ndouble SphereUtil::area(std::vector<LatLng *> *points) {\n    uint size = points->size();\n    if (size < 3) { return 0; }\n    double total = 0;\n    LatLng *prePoint = points->at(size - 1);\n    double prevTanLat = tan((M_PI / 2 - degreesToRadians(prePoint->lat)) / 2);\n    double prevLng = degreesToRadians(prePoint->lon);\n    for (uint i = 0; i < size; i++) {\n        LatLng *point = points->at(i);\n        double tanLat = tan((M_PI / 2 - degreesToRadians(point->lat)) / 2);\n        double lng = degreesToRadians(point->lon);\n        total += polarTriangleArea(tanLat, lng, prevTanLat, prevLng);\n        prevTanLat = tanLat;\n        prevLng = lng;\n    }\n    return fabs(total * (earth_radius * earth_radius));\n}\n\ndouble SphereUtil::polarTriangleArea(double tan1, double lng1, double tan2, double lng2) {\n    double deltaLng = lng1 - lng2;\n    double t = tan1 * tan2;\n    return 2 * atan2(t * sin(deltaLng), 1 + t * cos(deltaLng));\n}\n\ndouble SphereUtil::bearing(const LatLng &start,const  LatLng &end) {\n    double lon1 = degreesToRadians(start.lon);\n    double lon2 = degreesToRadians(end.lon);\n    double lat1 = degreesToRadians(start.lat);\n    double lat2 = degreesToRadians(end.lat);\n    double a = sin(lon2 - lon1) * cos(lat2);\n    double b = cos(lat1) * sin(lat2) -\n               sin(lat1) * cos(lat2) * cos(lon2 - lon1);\n    return radiansToDegrees(atan2(a, b));\n}\n\nEnvelope  SphereUtil::envelope(std::vector<LatLng *> *points) {\n    if (points == nullptr) {\n        return  Envelope(0, 0, 0, 0);\n    }\n    double minLon = MAX_COORDINATE_VALUE;\n    double minLat = MAX_COORDINATE_VALUE;\n    double maxLon = MIN_COORDINATE_VALUE;\n    double maxLat = MIN_COORDINATE_VALUE;\n    u_long length = points->size();\n    for (u_long i = 0; i < length; i++) {\n        LatLng *point = points->at(i);\n        minLon = fmin(minLon, point->lon);\n        minLat = fmin(minLat, point->lat);\n        maxLon = fmax(maxLon, point->lon);\n        maxLat = fmax(maxLat, point->lat);\n    }\n    return  Envelope(minLon, minLat, maxLon, maxLat);\n}\n\nLatLng SphereUtil::interpolate(const LatLng &from, const LatLng &to, double fraction) {\n    double fromLat = degreesToRadians(from.lat);\n    double fromLng = degreesToRadians(from.lon);\n    double toLat = degreesToRadians(to.lat);\n    double toLng = degreesToRadians(to.lon);\n    double cosFromLat = cos(fromLat);\n    double cosToLat = cos(toLat);\n\n    // Computes Spherical interpolation coefficients.\n    double angle = computeAngleBetween(from, to);\n    double sinAngle = sin(angle);\n    if (sinAngle < 1E-6) {\n         LatLng latlng =  LatLng(\n                from.lat + fraction * (to.lat - from.lat),\n                from.lon + fraction * (to.lon - from.lon));;\n        return latlng;\n    }\n    double a = sin((1 - fraction) * angle) / sinAngle;\n    double b = sin(fraction * angle) / sinAngle;\n\n    // Converts from polar to vector and interpolate.\n    double x = a * cosFromLat * cos(fromLng) + b * cosToLat * cos(toLng);\n    double y = a * cosFromLat * sin(fromLng) + b * cosToLat * sin(toLng);\n    double z = a * sin(fromLat) + b * sin(toLat);\n\n    // Converts interpolated vector back to polar.\n    double lat = atan2(z, sqrt(x * x + y * y));\n    double lng = atan2(y, x);\n    return  LatLng(radiansToDegrees(lat), radiansToDegrees(lng));\n}\n\ndouble SphereUtil::computeAngleBetween(const LatLng &from, const LatLng &to) {\n    return distanceRadians(degreesToRadians(from.lat), degreesToRadians(from.lon),\n                           degreesToRadians(to.lat), degreesToRadians(to.lon));\n}\n\ndouble SphereUtil::distanceRadians(double lat1, double lng1, double lat2, double lng2) {\n    return MathUtil::arcHav(MathUtil::havDistance(lat1, lat2, lng1 - lng2));\n}", "meta": {"hexsha": "4679949e74d1504c6004a7496790d76ed6d380e2", "size": 4427, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "openearthsdk/src/main/cpp/earth/geometry/util/sphere_util.cpp", "max_stars_repo_name": "Darlun1024/OpenEarth", "max_stars_repo_head_hexsha": "f30f5fd2d4bb91e00d323f8c8a1d17169a3e8fbb", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-12-05T01:32:19.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-15T17:42:47.000Z", "max_issues_repo_path": "openearthsdk/src/main/cpp/earth/geometry/util/sphere_util.cpp", "max_issues_repo_name": "Darlun1024/OpenEarth", "max_issues_repo_head_hexsha": "f30f5fd2d4bb91e00d323f8c8a1d17169a3e8fbb", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-12-08T06:48:41.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-08T06:48:41.000Z", "max_forks_repo_path": "openearthsdk/src/main/cpp/earth/geometry/util/sphere_util.cpp", "max_forks_repo_name": "Darlun1024/OpenEarth", "max_forks_repo_head_hexsha": "f30f5fd2d4bb91e00d323f8c8a1d17169a3e8fbb", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2017-12-05T01:34:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-15T17:42:53.000Z", "avg_line_length": 33.5378787879, "max_line_length": 90, "alphanum_fraction": 0.6491981026, "num_tokens": 1249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.953966096291997, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.7310181603996215}}
{"text": "\n#include \"projection.hpp\"\n\n#include <Eigen/Geometry>\n\nnamespace neon::geometry\n{\nmatrix2x project_to_plane(matrix3x const& nodal_coordinates)\n{\n    auto const lnodes = nodal_coordinates.cols();\n\n    matrix2x plane_coordinates = matrix::Zero(2, lnodes);\n\n    auto const normal = unit_outward_normal(nodal_coordinates);\n\n    // Orthogonal basis vectors\n    vector3 e1, e2;\n\n    // Algorithm implemented from Jeppe Revall Frisvad titled\n    // Building an Orthonormal Basis from a 3D Unit Vector Without Normalization\n    if (normal(2) <= -0.9999999)\n    {\n        // Handle the singularity\n        e1 = -vector3::UnitY();\n        e2 = -vector3::UnitX();\n    }\n    else\n    {\n        auto const a = 1.0 / (1.0 + normal(2));\n        auto const b = -normal(0) * normal(1) * a;\n        e1 << 1.0 - normal(0) * normal(0) * a, b, -normal(0);\n        e2 << b, 1.0 - normal(1) * normal(1) * a, -normal(1);\n    }\n    // Project the points onto the plane using e1 and e2\n    for (int lnode = 0; lnode < lnodes; ++lnode)\n    {\n        plane_coordinates(0, lnode) = e1.dot(nodal_coordinates.col(lnode));\n        plane_coordinates(1, lnode) = e2.dot(nodal_coordinates.col(lnode));\n    }\n    return plane_coordinates;\n}\n\nvector3 unit_outward_normal(matrix3x const& nodal_coordinates)\n{\n    using namespace Eigen;\n    Hyperplane<double, 3> hp = Hyperplane<double, 3>::Through(nodal_coordinates.col(0),\n                                                              nodal_coordinates.col(1),\n                                                              nodal_coordinates.col(2));\n    return -hp.normal();\n}\n}\n", "meta": {"hexsha": "e14540dec0f044fafecefb6096abd8259c6d48f2", "size": 1592, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/geometry/projection.cpp", "max_stars_repo_name": "annierhea/neon", "max_stars_repo_head_hexsha": "4eb51a06bda6bbf32c54fff8f39c9e02d429cfd1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2018-07-12T17:06:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-20T23:13:26.000Z", "max_issues_repo_path": "src/geometry/projection.cpp", "max_issues_repo_name": "annierhea/neon", "max_issues_repo_head_hexsha": "4eb51a06bda6bbf32c54fff8f39c9e02d429cfd1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 119.0, "max_issues_repo_issues_event_min_datetime": "2016-06-22T07:36:04.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-10T19:38:12.000Z", "max_forks_repo_path": "src/geometry/projection.cpp", "max_forks_repo_name": "annierhea/neon", "max_forks_repo_head_hexsha": "4eb51a06bda6bbf32c54fff8f39c9e02d429cfd1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2017-10-08T16:51:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-15T08:08:04.000Z", "avg_line_length": 30.6153846154, "max_line_length": 88, "alphanum_fraction": 0.5961055276, "num_tokens": 428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107931567176, "lm_q2_score": 0.7799929053683039, "lm_q1q2_score": 0.7310177694968407}}
{"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 <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/signal_statistics.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#include <boost/multiprecision/cpp_complex.hpp>\n\nusing std::abs;\nusing boost::multiprecision::cpp_bin_float_50;\nusing boost::multiprecision::cpp_complex_50;\nusing boost::math::constants::two_pi;\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 * 6) Does it work with integer data if sensible?\n */\n\ntemplate<class Real>\nvoid test_hoyer_sparsity()\n{\n    using std::sqrt;\n    Real tol = 5*std::numeric_limits<Real>::epsilon();\n    std::vector<Real> v{1,0,0};\n    Real hs = boost::math::statistics::hoyer_sparsity(v.begin(), v.end());\n    BOOST_TEST(abs(hs - 1) < tol);\n\n    hs = boost::math::statistics::hoyer_sparsity(v);\n    BOOST_TEST(abs(hs - 1) < tol);\n\n    // Does it work with constant iterators?\n    hs = boost::math::statistics::hoyer_sparsity(v.cbegin(), v.cend());\n    BOOST_TEST(abs(hs - 1) < tol);\n\n    v[0] = 1;\n    v[1] = 1;\n    v[2] = 1;\n    hs = boost::math::statistics::hoyer_sparsity(v.cbegin(), v.cend());\n    BOOST_TEST(abs(hs) < tol);\n\n    std::array<Real, 3> w{1,1,1};\n    hs = boost::math::statistics::hoyer_sparsity(w);\n    BOOST_TEST(abs(hs) < tol);\n\n    // Now some statistics:\n    // If x_i ~ Unif(0,1), E[x_i] = 1/2, E[x_i^2] = 1/3.\n    // Therefore, E[||x||_1] = N/2, E[||x||_2] = sqrt(N/3),\n    // and hoyer_sparsity(x) is close to (1-sqrt(3)/2)/(1-1/sqrt(N))\n    std::mt19937 gen(82);\n    std::uniform_real_distribution<long double> dis(0, 1);\n    v.resize(5000);\n    for (size_t i = 0; i < v.size(); ++i) {\n        v[i] = dis(gen);\n    }\n    hs = boost::math::statistics::hoyer_sparsity(v);\n    Real expected = (1.0 - boost::math::constants::root_three<Real>()/2)/(1.0 - 1.0/sqrt(v.size()));\n    BOOST_TEST(abs(expected - hs) < 0.01);\n\n    // Does it work with a forward list?\n    std::forward_list<Real> u1{1, 1, 1};\n    hs = boost::math::statistics::hoyer_sparsity(u1);\n    BOOST_TEST(abs(hs) < tol);\n\n    // Does it work with a boost ublas vector?\n    boost::numeric::ublas::vector<Real> u2(3);\n    u2[0] = 1;\n    u2[1] = 1;\n    u2[2] = 1;\n    hs = boost::math::statistics::hoyer_sparsity(u2);\n    BOOST_TEST(abs(hs) < tol);\n\n}\n\ntemplate<class Z>\nvoid test_integer_hoyer_sparsity()\n{\n    using std::sqrt;\n    double tol = 5*std::numeric_limits<double>::epsilon();\n    std::vector<Z> v{1,0,0};\n    double hs = boost::math::statistics::hoyer_sparsity(v);\n    BOOST_TEST(abs(hs - 1) < tol);\n\n    v[0] = 1;\n    v[1] = 1;\n    v[2] = 1;\n    hs = boost::math::statistics::hoyer_sparsity(v);\n    BOOST_TEST(abs(hs) < tol);\n}\n\n\ntemplate<class Complex>\nvoid test_complex_hoyer_sparsity()\n{\n    typedef typename Complex::value_type Real;\n    using std::sqrt;\n    Real tol = 5*std::numeric_limits<Real>::epsilon();\n    std::vector<Complex> v{{0,1}, {0, 0}, {0,0}};\n    Real hs = boost::math::statistics::hoyer_sparsity(v.begin(), v.end());\n    BOOST_TEST(abs(hs - 1) < tol);\n\n    hs = boost::math::statistics::hoyer_sparsity(v);\n    BOOST_TEST(abs(hs - 1) < tol);\n\n    // Does it work with constant iterators?\n    hs = boost::math::statistics::hoyer_sparsity(v.cbegin(), v.cend());\n    BOOST_TEST(abs(hs - 1) < tol);\n\n    // All are the same magnitude:\n    v[0] = {0, 1};\n    v[1] = {1, 0};\n    v[2] = {0,-1};\n    hs = boost::math::statistics::hoyer_sparsity(v.cbegin(), v.cend());\n    BOOST_TEST(abs(hs) < tol);\n}\n\n\ntemplate<class Real>\nvoid test_absolute_gini_coefficient()\n{\n    using boost::math::statistics::absolute_gini_coefficient;\n    using boost::math::statistics::sample_absolute_gini_coefficient;\n    Real tol = std::numeric_limits<Real>::epsilon();\n    std::vector<Real> v{-1,0,0};\n    Real gini = sample_absolute_gini_coefficient(v.begin(), v.end());\n    BOOST_TEST(abs(gini - 1) < tol);\n\n    gini = absolute_gini_coefficient(v);\n    BOOST_TEST(abs(gini - Real(2)/Real(3)) < tol);\n\n    v[0] = 1;\n    v[1] = -1;\n    v[2] = 1;\n    gini = absolute_gini_coefficient(v.begin(), v.end());\n    BOOST_TEST(abs(gini) < tol);\n    gini = sample_absolute_gini_coefficient(v.begin(), v.end());\n    BOOST_TEST(abs(gini) < tol);\n\n    std::vector<std::complex<Real>> w(128);\n    std::complex<Real> i{0,1};\n    for(size_t k = 0; k < w.size(); ++k)\n    {\n        w[k] = exp(i*static_cast<Real>(k)/static_cast<Real>(w.size()));\n    }\n    gini = absolute_gini_coefficient(w.begin(), w.end());\n    BOOST_TEST(abs(gini) < tol);\n    gini = sample_absolute_gini_coefficient(w.begin(), w.end());\n    BOOST_TEST(abs(gini) < tol);\n\n    // The population Gini index is invariant under \"cloning\": If w = v \\oplus v, then G(w) = G(v).\n    // We use the sample Gini index, so we need to rescale\n    std::vector<Real> u(1000);\n    std::mt19937 gen(35);\n    std::uniform_real_distribution<long double> dis(0, 50);\n    for (size_t i = 0; i < u.size()/2; ++i)\n    {\n        u[i] = dis(gen);\n    }\n    for (size_t i = 0; i < u.size()/2; ++i)\n    {\n        u[i + u.size()/2] = u[i];\n    }\n    Real population_gini1 = absolute_gini_coefficient(u.begin(), u.begin() + u.size()/2);\n    Real population_gini2 = absolute_gini_coefficient(u.begin(), u.end());\n\n    BOOST_TEST(abs(population_gini1 - population_gini2) < 10*tol);\n\n    // The Gini coefficient of a uniform distribution is (b-a)/(3*(b+a)), see https://en.wikipedia.org/wiki/Gini_coefficient\n    Real expected = (dis.b() - dis.a() )/(3*(dis.a() + dis.b()));\n\n    BOOST_TEST(abs(expected - population_gini1) < 0.01);\n\n    std::exponential_distribution<long double> exp_dis(1);\n    for (size_t i = 0; i < u.size(); ++i)\n    {\n        u[i] = exp_dis(gen);\n    }\n    population_gini2 = absolute_gini_coefficient(u);\n\n    BOOST_TEST(abs(population_gini2 - 0.5) < 0.01);\n}\n\n\ntemplate<class Real>\nvoid test_oracle_snr()\n{\n    using std::abs;\n    Real tol = 100*std::numeric_limits<Real>::epsilon();\n    size_t length = 100;\n    std::vector<Real> signal(length, 1);\n    std::vector<Real> noisy_signal = signal;\n\n    noisy_signal[0] += 1;\n    Real snr = boost::math::statistics::oracle_snr(signal, noisy_signal);\n    Real snr_db = boost::math::statistics::oracle_snr_db(signal, noisy_signal);\n    BOOST_TEST(abs(snr - length) < tol);\n    BOOST_TEST(abs(snr_db - 10*log10(length)) < tol);\n}\n\ntemplate<class Z>\nvoid test_integer_oracle_snr()\n{\n    double tol = std::numeric_limits<double>::epsilon();\n    size_t length = 100;\n    std::vector<Z> signal(length, 1);\n    std::vector<Z> noisy_signal = signal;\n\n    noisy_signal[0] += 1;\n    double snr = boost::math::statistics::oracle_snr(signal, noisy_signal);\n    double snr_db = boost::math::statistics::oracle_snr_db(signal, noisy_signal);\n    BOOST_TEST(abs(snr - length) < tol);\n    BOOST_TEST(abs(snr_db - 10*log10(length)) < tol);\n}\n\ntemplate<class Complex>\nvoid test_complex_oracle_snr()\n{\n    using Real = typename Complex::value_type;\n    using std::abs;\n    using std::log10;\n    Real tol = 100*std::numeric_limits<Real>::epsilon();\n    size_t length = 100;\n    std::vector<Complex> signal(length, {1,0});\n    std::vector<Complex> noisy_signal = signal;\n\n    noisy_signal[0] += Complex(1,0);\n    Real snr = boost::math::statistics::oracle_snr(signal, noisy_signal);\n    Real snr_db = boost::math::statistics::oracle_snr_db(signal, noisy_signal);\n    BOOST_TEST(abs(snr - length) < tol);\n    BOOST_TEST(abs(snr_db - 10*log10(length)) < tol);\n}\n\ntemplate<class Real>\nvoid test_m2m4_snr_estimator()\n{\n    Real tol = std::numeric_limits<Real>::epsilon();\n    std::vector<Real> signal(5000, 1);\n    std::vector<Real> x(signal.size());\n    std::mt19937 gen(18);\n    std::normal_distribution<Real> dis{0, 1.0};\n\n    for (size_t i = 0; i < x.size(); ++i)\n    {\n        signal[i] = 5*sin(100*6.28*i/x.size());\n        x[i] = signal[i] + dis(gen);\n    }\n\n    // Kurtosis of a sine wave is 1.5:\n    auto m2m4_db = boost::math::statistics::m2m4_snr_estimator_db(x, 1.5);\n    auto oracle_snr_db = boost::math::statistics::mean_invariant_oracle_snr_db(signal, x);\n    BOOST_TEST(abs(m2m4_db - oracle_snr_db) < 0.2);\n\n    std::uniform_real_distribution<Real> uni_dis{-1,1};\n    for (size_t i = 0; i < x.size(); ++i)\n    {\n        x[i] = signal[i] + uni_dis(gen);\n    }\n\n    // Kurtosis of continuous uniform distribution over [-1,1] is 1.8:\n    m2m4_db = boost::math::statistics::m2m4_snr_estimator_db(x, 1.5, 1.8);\n    oracle_snr_db = boost::math::statistics::mean_invariant_oracle_snr_db(signal, x);\n    // The performance depends on the exact numbers generated by the distribution, but this isn't bad:\n    BOOST_TEST(abs(m2m4_db - oracle_snr_db) < 0.2);\n\n    // The SNR estimator should be scale invariant.\n    // If x has snr y, then kx should have snr y.\n    Real ka = 1.5;\n    Real kw = 1.8;\n    auto m2m4 = boost::math::statistics::m2m4_snr_estimator(x.begin(), x.end(), ka, kw);\n    for(size_t i = 0; i < x.size(); ++i)\n    {\n        x[i] *= 4096;\n    }\n    auto m2m4_2 = boost::math::statistics::m2m4_snr_estimator(x.begin(), x.end(), ka, kw);\n    BOOST_TEST(abs(m2m4 - m2m4_2) < tol);\n}\n\nint main()\n{\n    test_absolute_gini_coefficient<float>();\n    test_absolute_gini_coefficient<double>();\n    test_absolute_gini_coefficient<long double>();\n\n    test_hoyer_sparsity<float>();\n    test_hoyer_sparsity<double>();\n    test_hoyer_sparsity<long double>();\n    test_hoyer_sparsity<cpp_bin_float_50>();\n\n    test_integer_hoyer_sparsity<int>();\n    test_integer_hoyer_sparsity<unsigned>();\n\n    test_complex_hoyer_sparsity<std::complex<float>>();\n    test_complex_hoyer_sparsity<std::complex<double>>();\n    test_complex_hoyer_sparsity<std::complex<long double>>();\n    test_complex_hoyer_sparsity<cpp_complex_50>();\n\n    test_oracle_snr<float>();\n    test_oracle_snr<double>();\n    test_oracle_snr<long double>();\n    test_oracle_snr<cpp_bin_float_50>();\n\n    test_integer_oracle_snr<int>();\n    test_integer_oracle_snr<unsigned>();\n\n    test_complex_oracle_snr<std::complex<float>>();\n    test_complex_oracle_snr<std::complex<double>>();\n    test_complex_oracle_snr<std::complex<long double>>();\n    test_complex_oracle_snr<cpp_complex_50>();\n\n    test_m2m4_snr_estimator<float>();\n    test_m2m4_snr_estimator<double>();\n    test_m2m4_snr_estimator<long double>();\n\n    return boost::report_errors();\n}\n", "meta": {"hexsha": "79f7b1a1c6fd1116b36a3b40f518142a173f5d0a", "size": 10983, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/signal_statistics_test.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": "3rdparty/boost_1_73_0/libs/math/test/signal_statistics_test.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "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": "3rdparty/boost_1_73_0/libs/math/test/signal_statistics_test.cpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_forks_repo_licenses": ["MIT"], "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": 33.0813253012, "max_line_length": 124, "alphanum_fraction": 0.6506419011, "num_tokens": 3284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.7309876772187768}}
{"text": "/*\r\nimgalt - Image Alignment Tool\r\nAuthor: GreatAttractor\r\n\r\nversion 0.5\r\n2014/05/22\r\n\r\nThis code can be freely distributed and used for any purpose.\r\n\r\nFile description:\r\n    Fast Fourier Transform functions implementation.\r\n\r\n*/\r\n#include \"fft.h\"\r\n#include <cmath>\r\n#include <stdlib.h>\r\n#include <boost/cstdint.hpp>\r\nusing namespace std;\r\nusing namespace boost;\r\n\r\nconst float PI = 3.1415926536f;\r\nconst complex<float> I = complex<float>(0, 1);\r\n\r\n/// Returns floor(log2(N))\r\ninline int quickLog2(unsigned N)\r\n{\r\n    int result = 0;\r\n    while (N > 0)\r\n    {\r\n        N >>= 1;\r\n        result++;\r\n    }\r\n    return result - 1;\r\n}\r\n\r\n/*\r\n/// Quick raising to integer power\r\ntemplate<typename T>\r\ninline T binpow(T x, int n)\r\n{\r\n    T pow = 1;\r\n    while (n != 0)\r\n    {\r\n        if (n & 1)\r\n            pow *= x;\r\n        n /= 2;\r\n        x *= x;\r\n    }\r\n    return pow;\r\n}\r\n\r\nuint32_t ReverseBits(uint32_t n, int width)\r\n{\r\n    uint32_t result = 0;\r\n    result |= (n & 1);\r\n    for (int i = 1; i <= width-1; i++)\r\n    {\r\n        result <<= 1;\r\n        n >>= 1;\r\n        result |= (n & 1);\r\n    }\r\n\r\n    return result;\r\n}*/\r\n\r\n// Not using fft1d_Pease at the moment, because even with precalculated twiddle factors\r\n// and without bit reversal it's not faster than the recursive approach.\r\n\r\n/// Calculates 1-dimensional discrete Fourier transform\r\n/** Uses in-place Pease algorithm (iterative). */\r\n/*template<typename InputT>\r\nvoid fft1d_Pease(\r\n    InputT input[],  ///< Input vector of length 'N'\r\n    unsigned N,      ///< Number of elements in 'input', has to be a power of two\r\n    std::complex<float> output[] ///< Output vector of length 'N'\r\n)\r\n{\r\n    int t = quickLog2(N);\r\n\r\n    for (unsigned i = 0; i < N; i++)\r\n        output[ReverseBits(i, t)] = input[i];\r\n\r\n    complex<float> w = exp(-2.0f * PI * I * (1.0f/N));\r\n\r\n    for (int c = t-1; c >= 0; c--)\r\n        for (int r = 0; r < 1<<(t-1); r++)\r\n        {\r\n            unsigned r0 = r & ((1<<c) - 1);\r\n            unsigned r1 = r >> c;\r\n            unsigned a0 = (r0 << (t-c)) + r1;\r\n            unsigned a1 = a0 + (1 << (t-c-1));\r\n            complex<float> y0 = output[a0 + 1];\r\n            complex<float> y1 = binpow<complex<float> >(w, r1 << c) * output[a1 + 1];\r\n            output[a0 + 1] = y0 + y1;\r\n            output[a1 + 1] = y0 - y1;\r\n        }\r\n}*/\r\n\r\n\r\n/// Calculates 1-dimensional discrete Fourier transform or its inverse (not normalized by N, caller must do this)\r\ntemplate<typename InputT>\r\nvoid fft1d(\r\n    InputT input[],  ///< Input vector of length 'N'\r\n    unsigned N,      ///< Number of elements in 'input', has to be a power of two\r\n    std::complex<float> output[], ///< Output vector of length 'N'\r\n    int stride,       ///< Stride of the input vector\r\n    int outputStride, ///< Stride of the output vector\r\n\r\n    /// Pointer to the initial twiddle factor for N, i.e. exp(-2*pi*i/N) (or exp(2*pi*i/N) for inverse transform).\r\n    /// NOTE: (twiddlePtr-1) has to point to the lower twiddle factor, i.e. exp(+-2*pi*i/(N/2))\r\n    complex<float> *twiddlePtr\r\n)\r\n{\r\n    if (N == 1)\r\n        output[0] = input[0];\r\n    else\r\n    {\r\n        fft1d(input, N/2, output, 2*stride, outputStride, twiddlePtr - 1);\r\n        fft1d(input + stride, N/2, output + N/2*outputStride, 2*stride, outputStride, twiddlePtr - 1);\r\n\r\n        // Initial twiddle factor\r\n        complex<float> tfactor0 = *twiddlePtr;\r\n\r\n        complex<float> tfactor = 1.0f;\r\n        for (unsigned k = 0; k <= N/2 - 1; k++)\r\n        {\r\n            complex<float> t = output[k*outputStride];\r\n            complex<float> h = tfactor * output[(k + (N>>1))*outputStride];\r\n            output[k*outputStride] = t + h;\r\n            output[(k + (N>>1))*outputStride] = t - h;\r\n            tfactor *= tfactor0; // in effect, tfactor = exp(-2*PI*I * k/N)\r\n        }\r\n    }\r\n}\r\n\r\nvoid CalcTwiddleFactors(unsigned N, complex<float> table[], bool inverse)\r\n{\r\n    for (int n = quickLog2(N); n >= 0; n--)\r\n    {\r\n        table[n] = (inverse ?\r\n            exp(2.0f * PI * I * (1.0f/N)) :\r\n            exp(-2.0f * PI * I * (1.0f/N)));\r\n\r\n        N >>= 1;\r\n    }\r\n}\r\n\r\n/// Calculates 1-dimensional discrete Fourier transform\r\nvoid CalcFFT1D(\r\n    uint8_t input[],\r\n    unsigned N,\r\n    std::complex<float> output[])\r\n{\r\n    complex<float> *twiddleFactors = new complex<float>[(quickLog2(N) + 1)];\r\n    CalcTwiddleFactors(N, twiddleFactors, false);\r\n\r\n    fft1d<uint8_t>(input, N, output, 1, 1, twiddleFactors + quickLog2(N));\r\n\r\n    free(twiddleFactors);\r\n}\r\n\r\n/// Calculates 1-dimensional inverse discrete Fourier transform\r\nvoid CalcFFTinv1D(\r\n    complex<float> input[],\r\n    unsigned N,\r\n    std::complex<float> output[])\r\n{\r\n    complex<float> *twiddleFactors = new complex<float>[(quickLog2(N) + 1)];\r\n    CalcTwiddleFactors(N, twiddleFactors, true);\r\n    \r\n    fft1d(input, N, output, 1, 1, twiddleFactors + quickLog2(N));\r\n    \r\n    // Normalize to obtain the inverse transform\r\n    float Ninv = 1.0f/N;\r\n    for (unsigned k = 0; k < N; k++)\r\n        output[k] *= Ninv;\r\n\r\n    free(twiddleFactors);\r\n}\r\n\r\n\r\n/// Calculates 2-dimensional discrete Fourier transform using row-column algorithm\r\nvoid CalcFFT2D(\r\n    float input[], ///< Input array containing N*N elements\r\n    unsigned N, ///< Number of rows and columns; has to be a power of two\r\n    std::complex<float> output[] ///< Output array containing N*N elements\r\n        )\r\n{\r\n    int k;\r\n\r\n    complex<float> *twiddleFactors = new complex<float>[(quickLog2(N) + 1)];\r\n    CalcTwiddleFactors(N, twiddleFactors, false);\r\n\r\n    // Calculate 1-dimensional transforms of all the rows\r\n    std::complex<float> *fftrows = new std::complex<float>[N*N*sizeof(std::complex<float>)];\r\n    #pragma omp parallel for\r\n    for (k = 0; k < N; k++)\r\n        fft1d<float>(input + k*N, N, fftrows + k*N, 1, 1, twiddleFactors + quickLog2(N));\r\n\r\n    // Calculate 1-dimensional transforms of all columns in 'fftrows' to get the final result\r\n    #pragma omp parallel for\r\n    for (k = 0; k < N; k++)\r\n        fft1d<std::complex<float> >(fftrows + k, N, output + k, N, N, twiddleFactors + quickLog2(N));\r\n\r\n    free(twiddleFactors);\r\n    free(fftrows);\r\n}\r\n\r\n/// Calculates 2-dimensional inverse discrete Fourier transform using row-column algorithm\r\nvoid CalcFFTinv2D(\r\n    std::complex<float> input[], ///< Input array containing N*N elements\r\n    unsigned N, ///< Number of rows and columns; has to be a power of two\r\n    std::complex<float> output[] ///< Output array containing N*N elements\r\n        )\r\n{\r\n    int k;\r\n    float Ninv = 1.0f/N;\r\n\r\n    complex<float> *twiddleFactors = new complex<float>[(quickLog2(N) + 1)];\r\n    CalcTwiddleFactors(N, twiddleFactors, true);\r\n\r\n    // Calculate 1-dimensional inverse transforms of all the rows\r\n    std::complex<float> *fftrows = new std::complex<float>[N*N];\r\n    #pragma omp parallel for\r\n    for (k = 0; k < N; k++)\r\n        fft1d<std::complex<float> >(input + k*N, N, fftrows + k*N, 1, 1, twiddleFactors + quickLog2(N));\r\n\r\n    for (k = 0; k < N*N; k++)\r\n        fftrows[k] *= Ninv;\r\n\r\n    // Calculate 1-dimensional inverse transforms of all columns in 'fftrows' to get the final result\r\n    #pragma omp parallel for\r\n    for (k = 0; k < N; k++)\r\n        fft1d<std::complex<float> >(fftrows + k, N, output + k, N, N, twiddleFactors + quickLog2(N));\r\n\r\n    free(twiddleFactors);\r\n    free(fftrows);\r\n\r\n    for (k = 0; k < N*N; k++)\r\n        output[k] *= Ninv;\r\n}\r\n\r\n/// Calculates cross-power spectrum of two 2D discrete Fourier transforms\r\nvoid CalcCrossPowerSpectrum2D(\r\n    std::complex<float> F1[], ///< First discrete Fourier transform (N*N elements)\r\n    std::complex<float> F2[], ///< Second discrete Fourier transform (N*N elements)\r\n    std::complex<float> output[], ///< Cross-correlation of F1 and F2 (N*N elements)\r\n    unsigned N ///< Number of rows and columns, has to be a power of 2\r\n    )\r\n{\r\n    #pragma omp parallel for\r\n    for (int i = 0; i < N*N; i++)\r\n    {\r\n        output[i] = std::conj(F1[i]) * F2[i];\r\n        float magn = std::abs(output[i]);\r\n        if (magn > 1.0e-8f)\r\n            output[i] /= magn;\r\n    }\r\n}\r\n", "meta": {"hexsha": "f1084b5ceab9c996b6b645760680bdf5c0500cba", "size": 8082, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "fft.cpp", "max_stars_repo_name": "johnnybeckett/imgalt", "max_stars_repo_head_hexsha": "8eac799d624013cdf9900f875ed690b3e27c352e", "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": "fft.cpp", "max_issues_repo_name": "johnnybeckett/imgalt", "max_issues_repo_head_hexsha": "8eac799d624013cdf9900f875ed690b3e27c352e", "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": "fft.cpp", "max_forks_repo_name": "johnnybeckett/imgalt", "max_forks_repo_head_hexsha": "8eac799d624013cdf9900f875ed690b3e27c352e", "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": 31.0846153846, "max_line_length": 115, "alphanum_fraction": 0.5772086117, "num_tokens": 2278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122188543453, "lm_q2_score": 0.8056321796478255, "lm_q1q2_score": 0.7309599204967311}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n\r\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\r\n// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.\r\n// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n//\r\n// Custom triangle template Example\r\n\r\n#include <iostream>\r\n\r\n#include <boost/array.hpp>\r\n#include <boost/tuple/tuple.hpp>\r\n\r\n#include <boost/geometry/algorithms/area.hpp>\r\n#include <boost/geometry/algorithms/centroid.hpp>\r\n#include <boost/geometry/geometries/adapted/boost_tuple.hpp>\r\n#include <boost/geometry/geometries/register/ring.hpp>\r\n#include <boost/geometry/strategies/strategies.hpp>\r\n#include <boost/geometry/io/dsv/write.hpp>\r\n\r\nBOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS(cs::cartesian)\r\n\r\n\r\ntemplate <typename P>\r\nstruct triangle : public boost::array<P, 3>\r\n{\r\n};\r\n\r\n\r\n// Register triangle<P> as a ring\r\nBOOST_GEOMETRY_REGISTER_RING_TEMPLATED(triangle)\r\n\r\n\r\nnamespace boost { namespace geometry { namespace dispatch {\r\n\r\n// Specializations of area dispatch structure, implement algorithm\r\ntemplate<typename Point>\r\nstruct area<triangle<Point>, ring_tag>\r\n{\r\n    template <typename Strategy>\r\n    static inline double apply(triangle<Point> const& t, Strategy const&)\r\n    {\r\n        return 0.5  * ((get<0>(t[1]) - get<0>(t[0])) * (get<1>(t[2]) - get<1>(t[0]))\r\n                     - (get<0>(t[2]) - get<0>(t[0])) * (get<1>(t[1]) - get<1>(t[0])));\r\n    }\r\n};\r\n\r\n}}} // namespace boost::geometry::dispatch\r\n\r\n\r\nint main()\r\n{\r\n    //triangle<boost::geometry::point_xy<double> > t;\r\n    triangle<boost::tuple<double, double> > t;\r\n    t[0] = boost::make_tuple(0, 0);\r\n    t[1] = boost::make_tuple(5, 0);\r\n    t[2] = boost::make_tuple(2.5, 2.5);\r\n\r\n    std::cout << \"Triangle: \" << boost::geometry::dsv(t) << std::endl;\r\n    std::cout << \"Area: \" << boost::geometry::area(t) << std::endl;\r\n\r\n    //boost::geometry::point_xy<double> c;\r\n    boost::tuple<double, double> c;\r\n    boost::geometry::centroid(t, c);\r\n    std::cout << \"Centroid: \" << boost::geometry::dsv(c) << std::endl;\r\n\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "284dbe7a355c02ba1b144e3ab78e16143e3a8cc4", "size": 2247, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/geometry/example/c04_b_custom_triangle_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": 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/geometry/example/c04_b_custom_triangle_example.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/geometry/example/c04_b_custom_triangle_example.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": 30.7808219178, "max_line_length": 87, "alphanum_fraction": 0.6559857588, "num_tokens": 621, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636754, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.7308663840713153}}
{"text": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union\u2019s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n\n#include \"../../data/FluidIndex.hpp\"\n#include <Eigen/Core>\n#include <cmath>\n\nnamespace fluid {\nnamespace algorithm {\n\nclass Stats\n{\npublic:\n  using ArrayXd = Eigen::ArrayXd;\n  ArrayXd process(Eigen::Ref<ArrayXd> input, double low, double mid,\n                  double high)\n  {\n    using namespace std;\n    index   length = input.size();\n    ArrayXd out = ArrayXd::Zero(7);\n    double  mean = input.mean();\n    double  stdev = sqrt((input - mean).square().mean());\n    double skewness = ((input - mean) / (stdev == 0 ? 1 : stdev)).cube().mean();\n    double kurtosis = ((input - mean) / (stdev == 0 ? 1 : stdev)).pow(4).mean();\n    ArrayXd sorted = input;\n    sort(sorted.data(), sorted.data() + length);\n    double lowVal = sorted(lrint(low * (length - 1)));\n    double midVal = sorted(lrint(mid * (length - 1)));\n    double highVal = sorted(lrint(high * (length - 1)));\n    out << mean, stdev, skewness, kurtosis, lowVal, midVal, highVal;\n    return out;\n  }\n};\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "619385adac00f52a2305460ed500e42967106175", "size": 1432, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/util/Stats.hpp", "max_stars_repo_name": "chriskiefer/flucoma-core", "max_stars_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2020-05-11T15:42:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T01:51:36.000Z", "max_issues_repo_path": "include/algorithms/util/Stats.hpp", "max_issues_repo_name": "chriskiefer/flucoma-core", "max_issues_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 90.0, "max_issues_repo_issues_event_min_datetime": "2020-05-13T20:25:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T18:05:35.000Z", "max_forks_repo_path": "include/algorithms/util/Stats.hpp", "max_forks_repo_name": "chriskiefer/flucoma-core", "max_forks_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2020-05-11T15:15:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-15T12:15:36.000Z", "avg_line_length": 31.8222222222, "max_line_length": 80, "alphanum_fraction": 0.6696927374, "num_tokens": 371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.7956580927949806, "lm_q1q2_score": 0.7307962392310234}}
{"text": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union\u2019s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n\n#include \"FluidEigenMappings.hpp\"\n#include \"../../data/FluidIndex.hpp\"\n#include \"../../data/FluidTensor.hpp\"\n#include <Eigen/Core>\n#include <limits>\n\nnamespace fluid {\nnamespace algorithm {\n\nclass PeakDetection\n{\n\n  using ArrayXd = Eigen::ArrayXd;\n  using pairs_vector = std::vector<std::pair<double, double>>;\n\npublic:\n  pairs_vector process(const Eigen::Ref<ArrayXd>& input, index numPeaks = 0,\n                       double minHeight = 0, bool interpolate = true,\n                       bool sort = true)\n  {\n    using std::make_pair;\n    pairs_vector peaks;\n\n    for (index i = 1; i < input.size() - 1; i++)\n    {\n      double current = input(i);\n      double prev = input(i - 1);\n      double next = input(i + 1);\n\n      if (current > prev && current > next && current > minHeight)\n      {\n        if (interpolate)\n        {\n          double p = 0.5 * (prev - next) / (prev - 2 * current + next);\n          double newIndex = i + p;\n          double newVal = current - 0.25 * (prev - next) * p;\n          peaks.push_back(make_pair(newIndex, newVal));\n        }\n        else\n        {\n          peaks.push_back(make_pair(static_cast<double>(i), input(i)));\n        }\n      }\n    }\n    if (sort)\n    {\n      std::sort(peaks.begin(), peaks.end(), [](auto& left, auto& right) {\n        return left.second > right.second;\n      });\n    }\n    if (numPeaks > 0 && peaks.size() > 0)\n    { return pairs_vector(peaks.begin(), peaks.begin() + numPeaks); }\n    else\n      return peaks;\n  }\n};\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "d27fee01ef6ccd9ac00158d2dd103442518249b2", "size": 1954, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/util/PeakDetection.hpp", "max_stars_repo_name": "chriskiefer/flucoma-core", "max_stars_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2020-05-11T15:42:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T01:51:36.000Z", "max_issues_repo_path": "include/algorithms/util/PeakDetection.hpp", "max_issues_repo_name": "chriskiefer/flucoma-core", "max_issues_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 90.0, "max_issues_repo_issues_event_min_datetime": "2020-05-13T20:25:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T18:05:35.000Z", "max_forks_repo_path": "include/algorithms/util/PeakDetection.hpp", "max_forks_repo_name": "chriskiefer/flucoma-core", "max_forks_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2020-05-11T15:15:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-15T12:15:36.000Z", "avg_line_length": 27.5211267606, "max_line_length": 76, "alphanum_fraction": 0.610542477, "num_tokens": 476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.888758793492457, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7307278254736848}}
{"text": "#include <iostream>\n#include <Eigen/Geometry>\n#include <Eigen/Dense>\nusing namespace std;\nusing namespace Eigen;\n\n/**\nEuler angle defination: zyx\nRotation matrix: C_body2ned\n**/\nQuaterniond euler2quaternion(Vector3d euler)\n{\n  double cr = cos(euler(0)/2);\n  double sr = sin(euler(0)/2);\n  double cp = cos(euler(1)/2);\n  double sp = sin(euler(1)/2);\n  double cy = cos(euler(2)/2);\n  double sy = sin(euler(2)/2);\n  Quaterniond q;\n  q.w() = cr*cp*cy + sr*sp*sy;\n  q.x() = sr*cp*cy - cr*sp*sy;\n  q.y() = cr*sp*cy + sr*cp*sy;\n  q.z() = cr*cp*sy - sr*sp*cy;\n  return q; \n}\n\n\nMatrix3d quaternion2mat(Quaterniond q)\n{\n  Matrix3d m;\n  double a = q.w(), b = q.x(), c = q.y(), d = q.z();\n  m << a*a + b*b - c*c - d*d, 2*(b*c - a*d), 2*(b*d+a*c),\n       2*(b*c+a*d), a*a - b*b + c*c - d*d, 2*(c*d - a*b),\n       2*(b*d - a*c), 2*(c*d+a*b), a*a-b*b - c*c + d*d;\n  return m;\n}\n\nVector3d mat2euler(Matrix3d m)\n{ \n  double r = atan2(m(2, 1), m(2, 2));\n  double p = asin(-m(2, 0));\n  double y = atan2(m(1, 0), m(0, 0));\n  Vector3d rpy(r, p, y);\n  return rpy;\n}\n\nQuaterniond mat2quaternion(Matrix3d m)\n{\n  //return euler2quaternion(mat2euler(m));\n  Quaterniond q;\n  double a, b, c, d;\n  a = sqrt(1 + m(0, 0) + m(1, 1) + m(2, 2))/2;\n  b = (m(2, 1) - m(1, 2))/(4*a);\n  c = (m(0, 2) - m(2, 0))/(4*a);\n  d = (m(1, 0) - m(0, 1))/(4*a);\n  q.w() = a; q.x() = b; q.y() = c; q.z() = d;\n  return q;\n}\n\n//ZYX\nMatrix3d euler2mat(Vector3d euler)\n{\n  double cr = cos(euler(0));\n  double sr = sin(euler(0));\n  double cp = cos(euler(1));\n  double sp = sin(euler(1));\n  double cy = cos(euler(2));\n  double sy = sin(euler(2));\n  Matrix3d m;\n  m << cp*cy,  -cr*sy + sr*sp*cy, sr*sy + cr*sp*cy, \n       cp*sy,  cr*cy + sr*sp*sy,  -sr*cy + cr*sp*sy, \n       -sp,    sr*cp,             cr*cp;\n  return m;\n}\n\nVector3d quaternion2euler(Quaterniond q)\n{\n  return mat2euler(quaternion2mat(q));\n}\n\ndouble quaternion2yaw(Quaterniond q)\n{\n  double a = q.w(), b = q.x(), c = q.y(), d = q.z();\n  double y = atan2(2*(b*c+a*d), (a*a + b*b - c*c - d*d));\n  return y;\n}\n\n//Euler motion equation\n//ZYX Euler angles velocity to body frame wx wy wz  w_phi,  w_theta,  w_psi     q: roll pitch yaw  (phi theta psi)\nMatrix3d w_Euler2Body(Vector3d q)\n{\n    double cr = cos( q(0));\n    double sr = sin( q(0));\n    double cp = cos( q(1));\n    double sp = sin( q(1));\n    double cy = cos( q(2));\n    double sy = sin( q(2));\n\n    Matrix3d G;\n    G << 1.,    0.,       -sp,\n         0.,    cr,   cp * sr,\n         0.,   -sr,   cp * cr;\n    \n    // Vector3d w(0,0,0);\n    // w = G * qdot;\n    return G;\n} \nMatrix3d w_Body2Euler(Vector3d q)\n{\n    double cr = cos( q(0));\n    double sr = sin( q(0));\n    double cp = cos( q(1)) + 0.00000001;\n    double sp = sin( q(1));\n    double cy = cos( q(2));\n    double sy = sin( q(2));\n\n    Matrix3d G_inv;\n    G_inv << 1., sp*sr/cp, cr*sp/cp,\n             0.,       cr,      -sr,\n             0.,    sr/cp,    cr/cp;\n\n    // Vector3d qdot(0,0,0);\n    // qdot = G_inv * w;\n    return G_inv;\n}\n//ZXY Euler angles velocity to body frame wx wy wz  w_phi,  w_theta,  w_psi\n// Vector3d Euler2Body(Vector3d q, Vector3d qdot)\n// {\n//     Vector3d w(0,0,0);\n//     Matrix3d G;\n//     G << cos(q.y),   0.,  -cos(q.x)*sin(q.y),\n//          0.,         1.,   sin(q.x),\n//          sin(q.y),   0.,   cos(q.x)*cos(q.y);\n//     w = G * qdot;\n//     return w;\n// } \n// Vector3d Body2Euler(Vector3d q, Vector3d w)\n// {\n//     Vector3d qdot(0,0,0);\n//     Matrix3d G_inv;\n//     G_inv << cos(q.y),   0.,    sin(q.y),\n//              (sin(q.x)*sin(q.y))/(cos(q.x)+0.00000001), 1., -(cos(q.y)*sin(q.x))/(cos(q.x)+0.00000001),\n//              -sin(q.y)/(cos(q.x)+0.00000001), 0., cos(q.y)/(cos(q.x)+0.00000001);\n//     qdot = G_inv * w;\n//     return qdot;\n// }\n", "meta": {"hexsha": "1f86f4bf16f3c6eb3f6a62c2a56de0352bf5a45d", "size": 3713, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Modules/mocap_ekf/src/conversion.cpp", "max_stars_repo_name": "473867143/Prometheus", "max_stars_repo_head_hexsha": "df1e1b0d861490223ac8b94d8cc4796537172292", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1217.0, "max_stars_repo_stars_event_min_datetime": "2020-07-02T13:15:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T06:17:44.000Z", "max_issues_repo_path": "Modules/mocap_ekf/src/conversion.cpp", "max_issues_repo_name": "473867143/Prometheus", "max_issues_repo_head_hexsha": "df1e1b0d861490223ac8b94d8cc4796537172292", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 167.0, "max_issues_repo_issues_event_min_datetime": "2020-07-12T15:35:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T11:57:40.000Z", "max_forks_repo_path": "Modules/mocap_ekf/src/conversion.cpp", "max_forks_repo_name": "473867143/Prometheus", "max_forks_repo_head_hexsha": "df1e1b0d861490223ac8b94d8cc4796537172292", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 270.0, "max_forks_repo_forks_event_min_datetime": "2020-07-02T13:28:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T05:43:08.000Z", "avg_line_length": 25.2585034014, "max_line_length": 114, "alphanum_fraction": 0.5119849179, "num_tokens": 1483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542185, "lm_q2_score": 0.7879311956428946, "lm_q1q2_score": 0.730698471916026}}
{"text": "#include <iostream>\n#include <fstream>\n#include <cstring>\n\n#include \"Common.hpp\"\n#include \"BUSData.h\"\n\n#include \"bustools_predict.h\"\n#include <iostream>\n#include <fstream>\n#include <cmath>\n\n#include <Eigen/Core>\n#include <unsupported/Eigen/SpecialFunctions>\n#include <LBFGSB.h>\n#include <cppoptlib/meta.h>\n#include <cppoptlib/boundedproblem.h>\n#include <cppoptlib/solver/lbfgsbsolver.h>\n#include <thread>\n#include <memory>\n#include <mutex>\n\n//based on the boost implementation\n//r is the size parameter\ninline double DensityNegBin(double k, double r, double mu) {\n\t//so, the standard parameterization is r and p, but we use mean (mu) and size\n\t//mean = mu = r(1-p)/p <=> p = r/(mu+r), size (i.e. r) in this parameterization and r in the standard one is the same.\n\tdouble p = r / (mu + r);\n\treturn exp(lgamma(r + k) - lgamma(r) - lgamma(k + 1)) * pow(p, r) * pow((1 - p), k);\n}\n\n\n//So, this one is different from the negative binomial below in that the zero is not included.\n//We here want to look at the log likelihood for observed molecules (i.e. not including the zeros) and how they would fit the negative\n//binomial, which means that the density function needs to be modified. The probability for zero needs to be set to zero, and the other\n//values scaled up to get to a sum of 1.\ninline double ZTNBLogLikelihood(const double* hist, size_t histLen, double size, double mu) {\n\t//first, get the probability of zero, probZero - all other values should be divided by 1-probZero to normalize the sum of non-zeros to 1\n\tdouble probZero = DensityNegBin(0, size, mu);\n\tdouble scale = 1 - probZero;\n\n\t//now calculate the log likelihood\n\tdouble ll = 0;\n\tfor (size_t i = 0; i < histLen; ++i) {\n\t\tll += log(DensityNegBin(double(i + 1), size, mu) / scale) * (*(hist + i));\n\t}\n\n\treturn ll;\n}\n\ninline double NegBinLogLikelihood(const double* hist, size_t histLen, double size, double mu, double zeroCount) {\n\t//loglikelihood for nonzero counts\n\tdouble ll = 0;\n\tfor (size_t i = 0; i < histLen; ++i) {\n\t\tll += log(DensityNegBin(double(i + 1), size, mu)) * (*(hist + i));\n\t}\n\t//...and for the zero counts\n\tll += log(DensityNegBin(0, size, mu)) * zeroCount;\n\t\n\treturn ll;\n}\n\n//using LBFGSpp\nclass Optimizer\n{\npublic:\n\t//make the variables public to be able to update them without a lot of extra code\n\tdouble mean = 0;\n\tdouble zeroCounts = 0;\n\tdouble totMol = 0;\n\tconst double* hist = nullptr;\n\tsize_t histLen = 0;\n\tOptimizer() {}\n\n\t//returns objective function value. The grad vector should be modified (i.e. set gradients)\n\t//the vector x is the in parameters, in this case the size (i.e. r) parameter in the distribution\n\t//The math here is the same as in preseqR\n\tdouble operator()(const Eigen::VectorXd& x, Eigen::VectorXd& grad) {\n\t\tdouble firstTerm = Eigen::numext::digamma(x[0]) * zeroCounts;\n\t\tfor (size_t i = 0; i < histLen; ++i) {\n\t\t\tfirstTerm += *(hist+i) * Eigen::numext::digamma(double(i + 1 + x[0]));\n\t\t}\n\t\tfirstTerm /= totMol;\n\t\t\n\t\tdouble secondTerm = Eigen::numext::digamma(x[0]);\n\n\t\tdouble thirdTerm = log(x[0]) - log(x[0] + mean);\n\n\t\tgrad[0] = -firstTerm + secondTerm - thirdTerm;\n\n\t\treturn -NegBinLogLikelihood(hist, histLen, x[0], mean, zeroCounts) / totMol;\n\t}\n};\n\n//using CppOptimizationLibrary\nclass Optimizer2 : public cppoptlib::BoundedProblem<double, 1> {\npublic:\n\t//make the variables public to be able to update them without a lot of extra code\n\tdouble mean = 0;\n\tdouble zeroCounts = 0;\n\tdouble totMol = 0;\n\tconst double* hist = nullptr;\n\tsize_t histLen = 0;\n\n\t//The math here is the same as in preseqR\n\n\tdouble value(const TVector& x) {\n\t\treturn -NegBinLogLikelihood(hist, histLen, x[0], mean, zeroCounts) / totMol;\n\t}\n\n\tvoid gradient(const TVector& x, TVector& grad)\n\t{\n\t\tdouble firstTerm = Eigen::numext::digamma(x[0]) * zeroCounts;\n\t\tfor (size_t i = 0; i < histLen; ++i) {\n\t\t\tfirstTerm += *(hist + i) * Eigen::numext::digamma(double(i + 1 + x[0]));\n\t\t}\n\t\tfirstTerm /= totMol;\n\n\t\tdouble secondTerm = Eigen::numext::digamma(x[0]);\n\n\t\tdouble thirdTerm = log(x[0]) - log(x[0] + mean);\n\n\t\tgrad[0] = -firstTerm + secondTerm - thirdTerm;\n\t}\n};\n\n//size and mu are both in and out parameters - the in parameters are the inital values in the expectation maximization algorithm\n//the hist is just a pointer into the large hist vector to avoid unnecessary copying\n//returns the log likelihood\n//This function uses LBFGSpp\ndouble PredictZTNBEmAlg1(const double* hist, size_t histLen, double& size, double& mu) {\n\t//estimate start values\n\tdouble histSum = 0; //S in the R code\n\tdouble histWeights = 0;\n\tfor (size_t i = 0; i < histLen; ++i) {\n\t\thistSum += *(hist + i);\n\t\thistWeights += (*(hist + i)) * (i+1);\n\t}\n\tmu = (histWeights - histSum)/histSum;\n\tsize = 1;\n\n\tdouble zeroProbability = DensityNegBin(0, size, mu);\n\t\n\t//estimate the total number of molecules\n\tdouble totMol = histSum / (1 - zeroProbability); //L in the R code\n\n\t//the estimated number of zero counts\n\tdouble zeroCounts = totMol * zeroProbability;\n\n\t//estimate the mean and variance\n\tdouble mean = 0, variance = 0;\n\tdouble precalcMeanSum = 0; //reuse this sum in the EM loop below since it is constant throughout the algorithm\n\tfor (size_t i = 0; i < histLen; ++i) {\n\t\tprecalcMeanSum += *(hist + i) * double(i + 1);//remember that the hist index is off by one, i.e. that the hist[0] corresponds to molecules with 1 copy and so forth\n\t}\n\tmean = precalcMeanSum / totMol;\n\t//..and the variance\n\tfor (size_t i = 0; i < histLen; ++i) {\n\t\tvariance += *(hist + i) * pow(double(i + 1) - mean, 2);\n\t}\n\tvariance = (variance + mean * mean * zeroCounts) / (totMol - 1);\n\n\tOptimizer op;\n\n\t// set all params\n\top.mean = mean;\n\top.zeroCounts = zeroCounts;\n\top.totMol = totMol;\n\top.hist = hist;\n\top.histLen = histLen;\n\n\n\t//using LBFGSpp\n\tLBFGSpp::LBFGSBParam<double> param;\n\t//So, the epsilon and max iterations here are for the LBFGS algorithm, not the EM, that comes later!\n\tparam.epsilon = 1e-8; //It seems that the optim function in R uses about 1e-8\n\tparam.max_iterations = 100; //defaults to 100 in the optim function in R\n\tparam.max_linesearch = 500; //don't want it to fail...\n\n\t// Create solver and function object\n\tLBFGSpp::LBFGSBSolver<double> solver(param);\n\n\t// Initial guess\n\tEigen::VectorXd x = Eigen::VectorXd::Zero(1);\n\n\tif (variance > mean) {\n\t\tx[0] = mean * mean / (variance - mean);\n\t}\n\telse {\n\t\tx[0] = size;\n\t}\n\n\t// Bounds\n\tEigen::VectorXd lb = Eigen::VectorXd::Constant(1, 0.0001);\n\tEigen::VectorXd ub = Eigen::VectorXd::Constant(1, 10000);\n\n\t// x will be overwritten to be the best point found\n\tdouble fx = 0;\n\tint numIter = solver.minimize(op, x, fx, lb, ub);\n\n\n\tsize_t iter = 0;\n\tdouble lastNegLL = 10000000000000;\n\tdouble currNegLL = -ZTNBLogLikelihood(hist, histLen, x[0], mean);\n\n\n\t//termination criteria for the EM algorithm\n\tconst double MAX_ERROR = 1e-8;\n\tconst double MAX_ERROR_FAST = 1e-5;\n\tconst size_t MAX_ITER = 100000;\n\tconst size_t ITER_FAST_LIMIT = 200; //if the number of iterations goes over this number, start using the lower error threshold, MAX_ERROR_FAST, to quicken things up\n\n\n\t//The EM algorithm starts here\n\twhile (fabs(lastNegLL - currNegLL) / histSum > MAX_ERROR&&\n\t\titer < MAX_ITER &&\n\t\t!(iter >= ITER_FAST_LIMIT && fabs(lastNegLL - currNegLL) / histSum <= MAX_ERROR_FAST))\n\t{\n\t\tlastNegLL = currNegLL;\n\n\t\t//update distribution params\n\t\tsize = x[0];\n\t\tmu = mean;\n\n\t\t// E step: estimate the number of unobserved species\n\n\t\tzeroProbability = DensityNegBin(0, size, mu);\n\t\ttotMol = histSum / (1 - zeroProbability);\n\t\tzeroCounts = totMol * zeroProbability;\n\n\t\t//mean and variance\n\t\tmean = precalcMeanSum / totMol;\n\t\t//...and variance\n\t\tfor (size_t i = 0; i < histLen; ++i) {\n\t\t\tvariance += *(hist + i) * pow(double(i + 1) - mean, 2);\n\t\t}\n\t\tvariance = (variance + mean * mean * zeroCounts) / (totMol - 1);\n\n\n\n\t\t// M step: estimate the parameters size and mu\n\t\t//rerun the LBFGSB\n\n\t\t// set params\n\t\top.mean = mean;\n\t\top.zeroCounts = zeroCounts;\n\t\top.totMol = totMol;\n\n\t\tif (variance > mean) {\n\t\t\tx[0] = mean * mean / (variance - mean);\n\t\t}\n\t\telse {\n\t\t\tx[0] = size;\n\t\t}\n\n\t\t//avoid printing of warning text in console\n\t\tif (x[0] > 10000.0) {\n\t\t\tx[0] = 10000.0;\n\t\t}\n\t\tif (x[0] < 0.0001) {\n\t\t\tx[0] = 0.0001;\n\t\t}\n\n\n\t\tint numIter = solver.minimize(op, x, fx, lb, ub);\n\n\t\tcurrNegLL = -ZTNBLogLikelihood(hist, histLen, x[0], mean);\n\n\t\t//std::cout << \"error: \" << (lastNegLL - currNegLL) / histSum << \"\\n\";\n\n\t\t++iter;\n\n\t\t//if (iter > 300) break;//tmp\n\t}\n\n\t//std::cout << \"iterations: \" << iter << \" error: \" << (lastNegLL - currNegLL) / histSum << \"\\n\";\n\n\treturn -currNegLL;\n}\n\n//Similar to above, but uses CppOptimizationLibrary\ndouble PredictZTNBEmAlg2(const double* hist, size_t histLen, double& size, double& mu) {\n\n\t//estimate start values\n\tdouble histSum = 0; //S in the R code\n\tdouble histWeights = 0;\n\tfor (size_t i = 0; i < histLen; ++i) {\n\t\thistSum += *(hist + i);\n\t\thistWeights += (*(hist + i)) * (i+1);\n\t}\n\tmu = (histWeights - histSum)/histSum;\n\tsize = 1;\n\n\tdouble zeroProbability = DensityNegBin(0, size, mu);\n\t\n\t//estimate the total number of molecules\n\tdouble totMol = histSum / (1 - zeroProbability); //L in the R code\n\n\t//the estimated number of zero counts\n\tdouble zeroCounts = totMol * zeroProbability;\n\n\t//estimate the mean and variance\n\tdouble mean = 0, variance = 0;\n\tdouble precalcMeanSum = 0; //reuse this sum in the EM loop below since it is constant throughout the algorithm\n\tfor (size_t i = 0; i < histLen; ++i) {\n\t\tprecalcMeanSum += *(hist + i) * double(i + 1);//remember that the hist index is off by one, i.e. that the hist[0] corresponds to molecules with 1 copy and so forth\n\t}\n\tmean = precalcMeanSum / totMol;\n\t//..and the variance\n\tfor (size_t i = 0; i < histLen; ++i) {\n\t\tvariance += *(hist + i) * pow(double(i + 1) - mean, 2);\n\t}\n\tvariance = (variance + mean * mean * zeroCounts) / (totMol - 1);\n\n\tOptimizer2 op;\n\t// set all params\n\top.mean = mean;\n\top.zeroCounts = zeroCounts;\n\top.totMol = totMol;\n\top.hist = hist;\n\top.histLen = histLen;\n\n\n\t//using CppOptimizationLibrary\n\top.setLowerBound(Optimizer2::TVector::Ones(1) * 0.0001);\n\top.setUpperBound(Optimizer2::TVector::Ones(1) * 10000);\n\tcppoptlib::LbfgsbSolver<Optimizer2> solver;\n\t//change the stop criteria to speed things up\n\tcppoptlib::LbfgsbSolver<Optimizer2>::TCriteria crit = cppoptlib::LbfgsbSolver<Optimizer2>::TCriteria::defaults(); \n\tcrit.iterations = 1000; //default is 10000\n\tsolver.setStopCriteria(crit);\n\tOptimizer2::TVector x = Optimizer2::TVector::Zero(1);\n\n\tif (variance > mean) {\n\t\tx[0] = mean * mean / (variance - mean);\n\t}\n\telse {\n\t\tx[0] = size;\n\t}\n\n//\tsolver.setDebug(cppoptlib::DebugLevel::Low);\n\t// x will be overwritten to be the best point found\n\tsolver.minimize(op, x);\n\n\n\t// Bounds\n\tEigen::VectorXd lb = Eigen::VectorXd::Constant(1, 0.0001);\n\tEigen::VectorXd ub = Eigen::VectorXd::Constant(1, 10000);\n\n\n\n\tsize_t iter = 0;\n\tdouble lastNegLL = 10000000000000;\n\tdouble currNegLL = -ZTNBLogLikelihood(hist, histLen, x[0], mean);\n\n\n\t//termination criteria for the EM algorithm\n\tconst double MAX_ERROR = 1e-8;\n\tconst double MAX_ERROR_FAST = 1e-5;\n\tconst size_t MAX_ITER = 400; //Since this algorithm is pretty slow, don't iterate too many times. The algorithm may get stuck here, on a few values only, don't let them dictate the total execution time too much.\n\tconst size_t ITER_FAST_LIMIT = 200; //if the number of iterations goes over this number, start using the lower error threshold, MAX_ERROR_FAST, to quicken things up\n\tconst double LARGE_NEG_LL = 100000000000000000.0;\n\t\n\tdouble bestNegLL = LARGE_NEG_LL;\n\tdouble bestMu = -1;\n\tdouble bestSize = -1;\n\t\n\t//The EM algorithm starts here\n\twhile (fabs(lastNegLL - currNegLL) / histSum > MAX_ERROR&&\n\t\titer < MAX_ITER &&\n\t\t!(iter >= ITER_FAST_LIMIT && fabs(lastNegLL - currNegLL) / histSum <= MAX_ERROR_FAST))\n\t{\n\t\t//temp, remove\n\t\t//double err = fabs(lastNegLL - currNegLL);\n\t\t\n\t\t\n\t\tlastNegLL = currNegLL;\n\n\t\t//update distribution params\n\t\tsize = x[0];\n\t\tmu = mean;\n\n\t\t// E step: estimate the number of unobserved species\n\n\t\tzeroProbability = DensityNegBin(0, size, mu);\n\t\ttotMol = histSum / (1 - zeroProbability);\n\t\tzeroCounts = totMol * zeroProbability;\n\n\t\t//mean and variance\n\t\tmean = precalcMeanSum / totMol;\n\t\t//...and variance\n\t\tfor (size_t i = 0; i < histLen; ++i) {\n\t\t\tvariance += *(hist + i) * pow(double(i + 1) - mean, 2);\n\t\t}\n\t\tvariance = (variance + mean * mean * zeroCounts) / (totMol - 1);\n\n\n\n\t\t// M step: estimate the parameters size and mu\n\t\t//rerun the LBFGSB\n\n\t\t// set params\n\t\top.mean = mean;\n\t\top.zeroCounts = zeroCounts;\n\t\top.totMol = totMol;\n\n\t\tif (variance > mean) {\n\t\t\tx[0] = mean * mean / (variance - mean);\n\t\t}\n\t\telse {\n\t\t\tx[0] = size;\n\t\t}\n\t\t\n\t\t//avoid printing of warning text in console\n\t\tif (x[0] > 10000.0) {\n\t\t\tx[0] = 10000.0;\n\t\t}\n\t\tif (x[0] < 0.0001) {\n\t\t\tx[0] = 0.0001;\n\t\t}\n\n\t\tsolver.minimize(op, x);\n\t\t//std::cout << \"val: \" << x[0] << \"\\n\";\n\n\t\tcurrNegLL = -ZTNBLogLikelihood(hist, histLen, x[0], mean);\n\t\t\n\t\t//std::cout << \"Iteration: \" << iter << \" x val: \" << x[0] << \" ll \" << currNegLL << \" lldiff: \" << err << \"\\n\";\n\t\t\n\t\t//keep track of the best values we had in case it doesn't converge - better to return those\n\t\tif (currNegLL < bestNegLL) {\n\t\t\tbestNegLL = currNegLL;\n\t\t\tbestMu = mu;\n\t\t\tbestSize = size;\n\t\t}\n\n\t\t//std::cout << \"error: \" << (lastNegLL - currNegLL) / histSum << \"\\n\";\n\n\t\t++iter;\n\n\t\t//if (iter > 300) break;//tmp\n\t}\n\n\t//std::cout << \"iterations: \" << iter << \" error: \" << (lastNegLL - currNegLL) / histSum << \"\\n\";\n\t\n\tif (bestNegLL < LARGE_NEG_LL) {\n\t\tcurrNegLL = bestNegLL;\n\t\tmu = bestMu;\n\t\tsize = bestSize;\n\t}\n\n\t//std::cout << \"Iteration: \" << iter << \" mu: \" << mu << \" size: \" << size << \" ll: \" << currNegLL << \"\\n\";\n\n\treturn -currNegLL;\n}\n\n//size and mu are out parameters describing the negative binomial\ndouble PredictZTNBForGene(const double* hist, size_t histLen, double t, double& size, double& mu, int index) {\n\tdouble histSum = 0; //S in the R code\n\tfor (size_t i = 0; i < histLen; ++i) {\n\t\thistSum += *(hist + i);\n\t}\n\tif (histSum == 0.0) {\n\t\treturn 0.0;//nothing to do...\n\t}\n\t//initial values of negative binomial, taken from R code\n\tsize = 1.0;\n\tmu = 0.5;\n\t//fit the ZTNB (will update size and mu)\n\t//So, the trick here is to first use Alg1 - it is faster, but fails sometimes. If it fails,\n\t//use Alg2\n\ttry {\n\t\t//std::cout << \"Alg1: \" << index << \"\\n\";\n\t\tPredictZTNBEmAlg1(hist, histLen, size, mu);\n\t\t//std::cout << \"Alg1 done: \" << index << \"\\n\";\n\t}\n\tcatch (std::exception&)\n\t{\n\t\t//std::cout << \"Alg2: \" << index << \"\\n\";\n\t\tPredictZTNBEmAlg2(hist, histLen, size, mu);\n\t\t//std::cout << \"Alg2 done: \" << index << \"\\n\";\n\t}\n\t\n\t//std::cout << \"Mu: \" << mu << \" Size: \" << size << \"\\n\";\n\n\t//estimate the total number of molecules\n\tdouble zeroProbability = DensityNegBin(0, size, mu);\n\tdouble totMol = histSum / (1 - zeroProbability); //L in the R code\n\n\t//The prediction is based on the assumption that the size parameter remains the same, while\n\t//the mean is scaled up with t. We then look at how many non-zero molecules we would get\n\tdouble zeroProbScaled = DensityNegBin(0, size, mu*t);\n\tdouble result = totMol * (1 - zeroProbScaled);\n\tif (result < histSum) { //safety check, we should never get fewer molecules than what we started with!\n\t\tresult = histSum;\n\t}\n\n\treturn result;\n}\n\n//This is a thread scheduler\nclass PredictionExecuter\n{\npublic:\n\tPredictionExecuter(const std::vector<double>& hists, const std::vector<size_t>& histLengths, double t, std::vector<double>& predVals, std::vector<double>& sizeVals, std::vector<double>& muVals, const uint32_t histmax) \n\t\t: m_hists(hists)\n\t\t, m_histLengths(histLengths)\n\t\t, m_t(t)\n\t\t, m_predVals(predVals)\n\t\t, m_sizeVals(sizeVals)\n\t\t, m_muVals(muVals)\n\t\t, m_histmax(histmax)\n\t{}\n\tvoid Execute(int numThreads) {\n\t\t//Some test code:\n\t\t//std::cout << \"Predicting 1345 \\n\";\n\t\t//double size = 0;\n\t\t//double mu = 0;\n\t\t//PredictZTNBForGene(&m_hists[1345 * m_histmax], m_histLengths[1345], m_t, size, mu, 1345);\n\t\t//std::cout << \"End Predicting 1345 \\n\";\n\n\t\t//create the threads\n\t\tfor (int i = 0; i < numThreads; ++i) {\n\t\t\tm_threads.push_back(std::shared_ptr<std::thread> (new std::thread(&PredictionExecuter::ThreadFunc, this)));\n\t\t}\n\t\t//wait for them to finish\n\t\tfor (int i = 0; i < numThreads; ++i) {\n\t\t\tm_threads[i]->join();\n\t\t}\n\t\tstd::cerr << \"\\n\";\n\t}\nprivate:\n\tvoid ThreadFunc() {\n\t\tsize_t i = 0;\n\t\twhile (GetNextIndex(i)) {\n\t\t\tdouble size = 0;\n\t\t\tdouble mu = 0;\n\t\t\tm_predVals[i] = PredictZTNBForGene(&m_hists[i * m_histmax], m_histLengths[i], m_t, size, mu, i);\n\t\t\tm_sizeVals[i] = size;\n\t\t\tm_muVals[i] = mu;\n\t\t}\n\t}\n\tbool GetNextIndex(size_t& index) {\n\t\tstd::lock_guard<std::mutex> lg(m_mutex);\n\t\tif (m_nextIndex == m_histLengths.size()) {\n\t\t\treturn false;\n\t\t} else {\n\t\t\tstd::cerr << \"\\rProcessing gene: \" << m_nextIndex + 1 << \" of \" << m_histLengths.size();//so, we use indexes starting at 1 in the printout\n\t\t\tindex = m_nextIndex++;\n\t\t\treturn true;\n\t\t}\n\t}\n\tstd::mutex m_mutex;\n\tsize_t m_nextIndex = 0;\n\tconst std::vector<double>& m_hists;\n\tconst std::vector<size_t>& m_histLengths;\n\tdouble m_t;\n\tstd::vector<double>& m_predVals;\n\tstd::vector<double>& m_sizeVals;\n\tstd::vector<double>& m_muVals;\n\tconst uint32_t m_histmax;\n\tstd::vector<std::shared_ptr<std::thread>> m_threads;\n};\n\nvoid bustools_predict(Bustools_opt &opt) {\n\n\t//Prepare and load histograms\n\t//////////////////\n\n\t//read the hist file\n\tstd::string hist_ifn = opt.predict_input + \".hist.txt\";\n\tstd::string counts_ifn = opt.predict_input + \".mtx\";\n\tstd::string gene_ifn = opt.predict_input + \".genes.txt\";\n\tstd::string barcode_ifn = opt.predict_input + \".barcodes.txt\";\n\n\tstd::string corr_counts_ofn = opt.output + \".mtx\";\n\tstd::string nb_params_ofn = opt.output + \".nb_params.txt\";\n\tstd::string corr_gene_ofn = opt.output + \".genes.txt\";\n\tstd::string corr_barcode_ofn = opt.output + \".barcodes.txt\";\n\n\t//just copy the genes and barcodes files, they don't change\n\tcopy_file(gene_ifn, corr_gene_ofn);\n\tcopy_file(barcode_ifn, corr_barcode_ofn);\n\n\t//Get gene list associated with count matrix and histograms\n\tstd::vector<std::string> genes;\n\tparseGenesList(gene_ifn, genes);\n\n\t//Allocate histograms\n\t//Indexed as gene*histmax + histIndex\n\tsize_t n_genes = genes.size();\n\tconst uint32_t histmax = 100;//set molecules with more than histmax copies to histmax \n\tstd::vector<double> histograms = std::vector<double>(n_genes * histmax, 0);\n\tstd::vector<size_t> histogramLengths = std::vector<size_t>(n_genes, 0);\n\tstd::string line;\n\n\t//load histograms file\n\t{\n\t\tstd::ifstream inf(hist_ifn);\n\t\tsize_t geneIndex = 0;\n\t\twhile (std::getline(inf, line)) {\n\t\t\tstd::stringstream ss(line);\n\t\t\tdouble num = 0;\n\t\t\tsize_t histIndex = 0;\n\t\t\twhile (ss >> num) {\n\t\t\t\thistograms[geneIndex * histmax + histIndex++] = num;\n\t\t\t}\n\t\t\thistogramLengths[geneIndex] = histIndex;\n\t\t\t++geneIndex;\n\t\t}\n\t}\n\n\t//fix the histograms if they have only a single non-zero value (i.e. for example looks like this: 1 0 0 0)\n\t//however, do not fix completely empty histograms\n\t//the strategy is to always add a one after the last item in the histogram \n\t//(this will be next to the only non-zero number, which will be last)\n\t//the strategy may lead to that a gene gets more counts. This, however, doesn't matter since we only calculate \n\t//a scaling factor for the gene, so that will be normalized out.\n\tfor (size_t i = 0; i < histogramLengths.size(); ++i) {\n\t\tsize_t nonZeros = 0;\n\t\tfor (size_t j = 0; j < histogramLengths[i]; ++j) {\n\t\t\tif (histograms[i * histmax + j] != 0) {\n\t\t\t\t++nonZeros;\n\t\t\t\tif (nonZeros > 1) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (nonZeros == 1) {\n\t\t\tif (histogramLengths[i] == histmax) { //rare case, add a count before instead of after\n\t\t\t\thistograms[i * histmax + histmax - 2] = 1;\n\t\t\t} else {\n\t\t\t\thistograms[i * histmax + histogramLengths[i]] = 1;\n\t\t\t\thistogramLengths[i]++;//also extend the histogram one step;\n\t\t\t}\n\t\t\t//so, if we can, remove one count from the current value\n\t\t\tif (histograms[i * histmax + histogramLengths[i] - 1] > 1) {\n\t\t\t\thistograms[i * histmax + histogramLengths[i] - 1] -= 1.0;\n\t\t\t}\n\t\t}\n\t}\n\n\t//Predict\n\t//////////////////\n\t\n\tstd::vector<double> predVals(n_genes, 0);\n\tstd::vector<double> sizeVals(n_genes, 0);\n\tstd::vector<double> muVals(n_genes, 0);\n\tint numThreads = std::thread::hardware_concurrency();\n\tstd::cerr << \"Using \" << numThreads << \" threads\\n\";\n\tPredictionExecuter pe(histograms, histogramLengths, opt.predict_t, predVals, sizeVals, muVals, histmax);\n\tpe.Execute(numThreads);\n\t\n\t//calculate the sum of all histograms and all predvals:\n\tdouble histSum = 0;\n\tstd::vector<double> umisPerGene(n_genes, 0);\n\tstd::vector<double> countsPerGene(n_genes, 0);\n\tdouble predSum = 0;\n\n\tfor (size_t i = 0; i < predVals.size(); ++i) {\n\t\tfor (size_t j = 0; j < histogramLengths[i]; ++j) {\n\t\t\tumisPerGene[i] += histograms[i * histmax + j];\n\t\t\tcountsPerGene[i] += histograms[i * histmax + j]*(j+1);\n\t\t}\n\t\thistSum += umisPerGene[i];\n\t\tpredSum += predVals[i];\n\t}\n\n\t//so the genes should be scaled according to the following:\n\t//geneScaling = histSum/predSum * predVal/umisPerGene;\n\tstd::vector<double> geneScaling(n_genes, 1.0);//1.0 for all empty genes\n\tdouble globScale = histSum / predSum;\n\tfor (size_t i = 0; i < predVals.size(); ++i) {\n\t\tif (umisPerGene[i] > 0) {\n\t\t\tgeneScaling[i] = globScale * predVals[i] / umisPerGene[i];\n\t\t}\n\t}\n\t\n\t//Modify counts\n\t//////////////////\n\t\n\tstd::cerr << \"Creating corrected counts matrix...\\n\";\n\n\t//read and write the counts matrix\n\t{\n\t\tstd::ifstream inf(counts_ifn);\n\t\tstd::string test;\n\t\tstd::ofstream of(corr_counts_ofn);\n\t\t//first number is cells, second genes\n\t\t//first handle header, we just leave that untouched\n\t\twhile (std::getline(inf, line)) {\n\t\t\tof << line << '\\n';\n\t\t\tif ((!line.empty()) && line[0] != '%') {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t//now all data with scaling\n\t\tsize_t cell = 0, gene = 0;\n\t\tdouble count = 0;\n\t\twhile (std::getline(inf, line)) {\n\t\t\tif ((!line.empty()) && line[0] == '%') {\n\t\t\t\tof << line << '\\n';\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tstd::stringstream ss(line);\n\t\t\tif (ss >> cell >> gene >> count) {\n\t\t\t\tof << cell << \" \" << gene << \" \" << count * geneScaling[gene-1] << '\\n';\n\t\t\t}\n\t\t}\n\t}\n\t\n\t//write negative binomial params (file with header)\n\tstd::cerr << \"Writing negative binomial params...\\n\";\n\t{\n\t\tstd::ofstream of(nb_params_ofn);\n\t\t\n\t\t//header\n\t\tof << \"gene\\tmu\\tsize\\tUMIs\\tcounts\\n\";\n\n\t\tfor (size_t i = 0; i < genes.size(); ++i) {\n\t\t\tof << genes[i] << '\\t' << muVals[i] << '\\t' << sizeVals[i] << '\\t' << umisPerGene[i] << '\\t' << countsPerGene[i] << '\\n';\n\t\t}\n\t}\n\t\n}\n", "meta": {"hexsha": "27e5f038bdba6cf4242dbefffcb04c55e706ee0e", "size": 22257, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/bustools_predict.cpp", "max_stars_repo_name": "Yenaled/bustools", "max_stars_repo_head_hexsha": "6fa0731f7f32c68645f0f60b1c1c89771b1c8061", "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": "src/bustools_predict.cpp", "max_issues_repo_name": "Yenaled/bustools", "max_issues_repo_head_hexsha": "6fa0731f7f32c68645f0f60b1c1c89771b1c8061", "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/bustools_predict.cpp", "max_forks_repo_name": "Yenaled/bustools", "max_forks_repo_head_hexsha": "6fa0731f7f32c68645f0f60b1c1c89771b1c8061", "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": 30.6993103448, "max_line_length": 219, "alphanum_fraction": 0.6606011592, "num_tokens": 7028, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632896242074, "lm_q2_score": 0.787931185683219, "lm_q1q2_score": 0.7306984563526921}}
{"text": "// Copyright (c) 2018 by University Paris-Est Marne-la-Vallee\r\n// MetricTools.hpp\r\n// This file is part of the Garamon Generator.\r\n// Authors: Stephane Breuils and Vincent Nozick\r\n// Conctact: vincent.nozick@u-pem.fr\r\n//\r\n// Licence MIT\r\n// A a copy of the MIT License is given along with this program\r\n\r\n\r\n#include \"MetricTools.hpp\"\r\n\r\n\r\n#include <Eigen/Eigenvalues>\r\n#include <cmath>\r\n#include <iostream>\r\n\r\n\r\nbool isMatrixDiagonal(const Eigen::MatrixXd &A, const double epsilon){\r\n\r\n    for(unsigned int i=0; i<(unsigned int)A.rows(); ++i)\r\n        for(unsigned int j=0; j<(unsigned int)A.cols(); ++j) {\r\n            if(i==j) continue;\r\n            if(fabs(A(i,j)) > epsilon)\r\n                return false;\r\n        }\r\n    return true;\r\n}\r\n\r\n\r\nbool isMatrixIdentity(const Eigen::MatrixXd &A, const double epsilon){\r\n\r\n    if(A.rows() != A.cols())\r\n        return false;\r\n\r\n    for(unsigned int i=0; i<(unsigned int)A.rows(); ++i)\r\n        for(unsigned int j=0; j<(unsigned int)A.cols(); ++j) {\r\n            if( (i==j) && (fabs(A(i,j)-1) > epsilon) )\r\n                return false;\r\n\r\n            if( (i!=j) && (fabs(A(i,j)) > epsilon) )\r\n                return false;\r\n        }\r\n\r\n    return true;\r\n}\r\n\r\n\r\nbool isMatrixPermutationOfDiagonal(const Eigen::MatrixXd &metric, const double epsilon){\r\n\r\n return isMatrixDiagonal(metric.transpose()*metric,epsilon);\r\n}\r\n\r\n\r\nunsigned int getRank(const Eigen::MatrixXd &metric){\r\n\r\n    Eigen::FullPivLU<Eigen::MatrixXd> lu(metric);\r\n    return lu.rank();\r\n}\r\n\r\n\r\nvoid eigenDecomposition(const Eigen::MatrixXd &M, Eigen::MatrixXd &P, Eigen::MatrixXd &A){\r\n\r\n    Eigen::EigenSolver<Eigen::MatrixXd> eigensolv;\r\n    eigensolv.compute(M,true);\r\n    P = eigensolv.eigenvectors().real();\r\n    A = Eigen::MatrixXd::Zero(M.rows(), M.cols());\r\n    A.diagonal() = eigensolv.eigenvalues().real();\r\n}\r\n\r\n\r\ndouble minAbsNonZeroValue(Eigen::VectorXd x){\r\n\r\n    // deal only with positive values\r\n    x = x.cwiseAbs();\r\n\r\n    // for first min value\r\n    bool firstValue = true;\r\n    double minVal = 0.0; //std::numeric_limits<double>::infinity();\r\n    for(unsigned int i=0; i<(unsigned int)x.size(); ++i){\r\n\r\n        // zero values should be ignored\r\n        if(x(i) < std::numeric_limits<double>::epsilon())\r\n            continue;\r\n\r\n        // if it is the first non zero value\r\n        if(firstValue){\r\n            minVal = x(i);\r\n            firstValue = false;\r\n        }else{\r\n            // looking for the lowest value\r\n            if(x(i) < minVal)\r\n                minVal = x(i);      \r\n        }   \r\n    }\r\n\r\n    return minVal; // negative if only zero values in the vector\r\n}\r\n\r\n\r\n// put the per column smallest element of P equal to 1 and update A consequently\r\n// if P initially contains many sqrt(0.5), they will (probably) be transform to 1\r\n// at the end, P is not an othrogonal matrix anymore.\r\nEigen::MatrixXd eigenRefinement(Eigen::MatrixXd &P, Eigen::MatrixXd &D, Eigen::MatrixXd &Pinv){\r\n\r\n    // initialize the scale matrix to Identity\r\n    Eigen::MatrixXd scaleMatrix = Eigen::MatrixXd::Identity(D.rows(),D.cols());\r\n\r\n    // when possible, put integers in P, update Pinv consequently\r\n    for(int i=0; i<P.rows(); ++i){\r\n\r\n        // convert the per line smallest non-zero value to 1\r\n        double minVal = minAbsNonZeroValue(P.col(i));\r\n        P.col(i)    /= minVal;\r\n        Pinv.row(i) *= minVal;\r\n        //D(i,i) = 1.0 / (minVal*minVal);\r\n        scaleMatrix(i,i) = 1.0/minVal;\r\n    }\r\n    return scaleMatrix;\r\n}\r\n\r\n\r\n// check if the clean up of the matrices still leads to a set of matrices whose product is equal to the initial metric.\r\nbool checkNumericalCleanUp(const Eigen::MatrixXd &M, const Eigen::MatrixXd &P, const Eigen::MatrixXd & A, const double epsilon){\r\n\r\n    Eigen::MatrixXd M2 = P * A * P.transpose();\r\n    Eigen::MatrixXd nullMatrix = (M - M2).cwiseAbs();\r\n\r\n    for(unsigned int i=0; i<(unsigned int)M.rows(); ++i)\r\n        for(unsigned int j=0; j<(unsigned int)M.cols(); ++j)\r\n            if(nullMatrix(i,j) > epsilon)\r\n                return false;\r\n\r\n    return true;\r\n}\r\n\r\n\r\n// check if the clean up of the matrices still leads to a set of matrices whose product is equal to the initial metric.\r\nbool checkNumericalCleanUp(const Eigen::MatrixXd &M,\r\n                           const Eigen::MatrixXd &P,\r\n                           const Eigen::MatrixXd &A,\r\n                           const Eigen::MatrixXd &Pinv,\r\n                           const double epsilon){\r\n\r\n    Eigen::MatrixXd M2 = P * A * Pinv;\r\n    Eigen::MatrixXd identity = (M - M2).cwiseAbs();\r\n\r\n    for(unsigned int i=0; i<(unsigned int)M.rows(); ++i)\r\n        for(unsigned int j=0; j<(unsigned int)M.cols(); ++j)\r\n            if(identity(i,j) > epsilon)\r\n                return false;\r\n\r\n    return true;\r\n}\r\n\r\n\r\n// when pertinent, replace a supposed integer value by the nearby int, etc.\r\nEigen::SparseMatrix<double> numericalCleanUpSparse(const Eigen::MatrixXd &M, const double epsilon){\r\n\r\n    Eigen::SparseMatrix<double> N(M.rows(),M.cols());\r\n\r\n    for(unsigned int i=0; i<(unsigned int)M.rows(); ++i)\r\n        for(unsigned int j=0; j<(unsigned int)M.cols(); ++j){\r\n\r\n            // ignore the zero\r\n            if(fabs(M(i,j)) < epsilon)\r\n                continue;\r\n\r\n            // round near integers to integers\r\n            int val = std::lround(M(i,j));\r\n            if( fabs(val - M(i,j)) < epsilon ){\r\n                N.insert(i,j) = val;\r\n                continue;\r\n            }\r\n\r\n            // if failed to round with integer\r\n            // round with decimal\r\n            for(double d=0; d<=10; ++d){\r\n                double decimal = -0.5 + d/10.0;\r\n                if( fabs(val + decimal - M(i,j)) < epsilon ){\r\n                    N.insert(i,j) = val + decimal;\r\n                    continue;\r\n                }\r\n            }\r\n        }\r\n\r\n    return N;\r\n}\r\n\r\n\r\n// for vectors: when pertinent, replace a supposed integer value by the nearby int, etc.\r\nEigen::VectorXd vectorNumericalCleanUp(const Eigen::VectorXd& original, const double epsilon){\r\n    Eigen::VectorXd outputVector(original);\r\n    for(unsigned int j=0; j<(unsigned int)outputVector.size(); ++j) {\r\n\r\n        // ignore the zero\r\n        if (fabs(original(j)) < epsilon) {\r\n            outputVector(j) = 0.0;\r\n            continue;\r\n        }\r\n\r\n        // round near integers to integers\r\n        int val = std::lround(original(j));\r\n        if (fabs(val - original(j)) < epsilon) {\r\n            outputVector(j) = val;\r\n            continue;\r\n        }\r\n\r\n        // some negative power of 2\r\n        const int maxNegPower = 7; // 2^{-6} = 0.015625 or the algebra dimension\r\n        const double step = pow(2,-maxNegPower);\r\n        for(double x=val-0.5; x<=val+0.5; x+=step)\r\n            if(fabs(x - original(j)) < epsilon) {\r\n                outputVector(j) = x;\r\n                continue;\r\n            }\r\n\r\n        // if failed to round with integer\r\n        // round with decimal\r\n        for(int d=0; d<=10; ++d) {\r\n            double decimal = -0.5 + d / 10.0;\r\n            if (fabs(val + decimal - original(j)) < epsilon) {\r\n                outputVector(j) = val + decimal;\r\n                continue;\r\n            }\r\n        }\r\n    }\r\n    return outputVector;\r\n}\r\n\r\n\r\n// for matrices: when pertinent, replace a supposed integer value by the nearby int, etc.\r\nEigen::MatrixXd numericalCleanUp(const Eigen::MatrixXd &M, const double epsilon){\r\n\r\n    Eigen::MatrixXd N = M; //Eigen::MatrixXd::Zero(M.rows(),M.cols());\r\n\r\n    for(unsigned int i=0; i<(unsigned int)M.rows(); ++i)\r\n        N.row(i) = vectorNumericalCleanUp(N.row(i), epsilon);\r\n\r\n    return N;\r\n}\r\n\r\n\r\n\r\nEigen::SparseMatrix<double, Eigen::ColMajor> computePerGradeTransformationMatrix(const Eigen::MatrixXd &vectorTransformationMatrix,\r\n                                                                                 const unsigned int dimension,\r\n                                                                                 const unsigned int grade,\r\n                                                                                 const double epsilon){\r\n    // Generate grade-vectors\r\n    // i.e. dimension=3\r\n    // generate: (e1+e2+e3) (e1+e2+e3) (e1+e2+e3)\r\n    std::vector<std::vector<unsigned int> > listOfVectors;\r\n    for(unsigned int j=0;j<dimension;++j){\r\n        std::vector<unsigned int> oneVector;\r\n        for(unsigned int i=0; i<dimension; ++i)\r\n            oneVector.push_back((unsigned int) 1 << i);\r\n        listOfVectors.push_back(oneVector);\r\n    }\r\n\r\n\r\n    // Compute the set of combination whose length is grade, in dimension space (i.e. for grade 2, dim 3: (1,2) (1,3) (2,3) )\r\n    std::vector<std::vector<unsigned int> > sequence = generateCombinations(dimension, grade);\r\n\r\n    // init the resulting transformation matrix\r\n    Eigen::SparseMatrix<double, Eigen::ColMajor> resultSparse(sequence.size(), sequence.size());\r\n//    Eigen::MatrixXd kVectorMetric = Eigen::MatrixXd::Zero(sequence.size(), sequence.size()); // to remove\r\n\r\n\r\n    // link the indices used for the XOR wedge with the index in the sequence of combinations using an array\r\n    // i.e. for grade 2, dim 3 :                (1,2) (1,3) (2,3)\r\n    // order induced by the xor:                scal, 1, 2, 12, 3, 13, 23, 123\r\n    // return their position in the sequence:      -, -, -,  0, -,  1,  2, -\r\n    std::vector<unsigned int> xorIndex2Combination = getSetOfCombinationsFromXorIndexation(dimension, sequence);\r\n\r\n    // generate the transformation matrix\r\n    for(unsigned int l=0; l<sequence.size(); ++l) { // for each element of grade \"grade'\r\n\r\n        std::vector<unsigned int> currentVector = listOfVectors[0];\r\n        std::vector<double>       currentCoeffs; // first line of the transformation matrix\r\n\r\n        // fill the currentCoeffs using the transformation\r\n        for(int idxTMat=0; idxTMat<vectorTransformationMatrix.cols(); ++idxTMat)\r\n            currentCoeffs.push_back(vectorTransformationMatrix(sequence[l][0],idxTMat));\r\n\r\n\r\n        std::vector<unsigned int> nextVector;\r\n        std::vector<unsigned int> result;\r\n\r\n        for(unsigned int j=0;j<sequence[l].size()-1;++j) {\r\n            // Contains the number of wedge to be computed,\r\n            // (v1^v2)^v3 for example\r\n\r\n            nextVector = listOfVectors[j+1];\r\n            std::vector<unsigned int> resultIdxTmp; // result = mv1 ^ mvss2\r\n            std::vector<double> resultCoeffTmp;     // coefficient of the result\r\n\r\n            // wedge between the last k-vector and a vector to make a (k+1)-vector up to 'grade'\r\n            for(unsigned int i=0; i<currentVector.size(); ++i) {\r\n                for(unsigned int k=0; k<nextVector.size(); ++k) {\r\n\r\n                    // index initialisation\r\n                    unsigned int mvC = 0;\r\n                    unsigned int mvA = currentVector[i];\r\n                    unsigned int mvB = nextVector[k];\r\n\r\n                    // coefficient computation\r\n                    double coeffA = currentCoeffs[i];\r\n                    double coeffB = vectorTransformationMatrix(sequence[l][j+1],k);\r\n                    double coeffC = 0.0; // To be changed with the transformation matrix\r\n                    if((coeffA != 0.0) && (coeffB != 0.0)){\r\n                        getSignAndBladeOuterProduct(mvC, mvA, mvB, coeffC, coeffA, coeffB);\r\n                        // update the results\r\n                        if(coeffC !=0.0) {\r\n                            resultIdxTmp.push_back(mvC);\r\n                            resultCoeffTmp.push_back(coeffC);\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n\r\n            currentVector = resultIdxTmp;\r\n            currentCoeffs = resultCoeffTmp;\r\n            resultIdxTmp.clear();\r\n            resultCoeffTmp.clear();\r\n        }\r\n\r\n        for(unsigned int idxRes=0; idxRes<currentVector.size(); ++idxRes){\r\n            if(fabs(currentCoeffs[idxRes])>epsilon)\r\n                resultSparse.coeffRef(l,xorIndex2Combination[currentVector[idxRes]]) += currentCoeffs[idxRes];\r\n        }\r\n\r\n    }\r\n    return resultSparse;\r\n}\r\n\r\n\r\n// convert the grade transformation matrix (inverse or not) to a vector of values (row, colums,value). no interpretation are done\r\nstd::vector<double> transformationMatricesToVectorOfComponents(\r\n        const Eigen::SparseMatrix<double, Eigen::ColMajor> &transformationMatrix, const int grade, const bool isInverse) {\r\n    std::vector<double> outputVector;\r\n    for (int k = 0; k < transformationMatrix.outerSize(); ++k)\r\n        for (Eigen::SparseMatrix<double, Eigen::ColMajor>::InnerIterator it(transformationMatrix,k); it; ++it) {\r\n            outputVector.push_back((double)it.row());\r\n            outputVector.push_back((double)it.col());\r\n            outputVector.push_back((double)it.value());\r\n        }\r\n    return outputVector;\r\n}\r\n\r\n\r\n// Compute the inverse of a transformation matrix given by transformationMatrix\r\nEigen::SparseMatrix<double, Eigen::ColMajor>  computeInverseTransformationMatrix(const Eigen::SparseMatrix<double, Eigen::ColMajor>& transformationMatrix, const double epsilon){\r\n    Eigen::SparseMatrix<double, Eigen::ColMajor> inverseTransformationMatrix(transformationMatrix.rows(),transformationMatrix.rows());\r\n    Eigen::SparseLU<Eigen::SparseMatrix<double, Eigen::ColMajor>> solver;\r\n    solver.analyzePattern(transformationMatrix);\r\n    solver.factorize(transformationMatrix);\r\n    // compute the inverse M.M-1 = Id\r\n    // i.e. solve all system where the unknown vector is a column of M-1\r\n    for(unsigned int j=0; j<(unsigned int)inverseTransformationMatrix.cols(); ++j){\r\n        Eigen::SparseVector<double> vecId(inverseTransformationMatrix.rows());\r\n        vecId.insert(j) = 1.0;\r\n        Eigen::VectorXd x = solver.solve(vecId);\r\n        // recopy into sparse matrix\r\n        for(unsigned i=0; i<(unsigned int)x.size(); ++i)\r\n            if(fabs(x(i)) > epsilon)\r\n                inverseTransformationMatrix.insert(i,j) = x(i);\r\n    }\r\n\r\n    return inverseTransformationMatrix;\r\n}\r\n\r\n\r\n// Compute the transformation matrices for grades ranging from 1 to d\r\n// For each per-grade transformation matrix, we construct a string containing the list of its non-zero elements.\r\n// We also pick up the number of non zero elements of each sparse matrices, the result is put into transformationMatricesSize\r\nstd::pair<std::vector<double>,std::vector<double>> computeTransformationMatricesToVector(const Eigen::MatrixXd &P, const double epsilon, std::vector<unsigned int>& transformationMatricesSizes,\r\n                                                                                       std::vector<Eigen::SparseMatrix<double, Eigen::ColMajor> >& allTransformationMatrices,\r\n                                                                                       std::vector<Eigen::SparseMatrix<double, Eigen::ColMajor> >& allInverseTransformationMatrices){\r\n    std::pair<std::vector<double>,std::vector<double>> transformationMatrices; // contains non-inverse and inverse transformation matrices\r\n\r\n    // push the scalar transformation matrix\r\n    Eigen::SparseMatrix<double, Eigen::ColMajor> spscalarTransformationMatrix(1, 1);\r\n    spscalarTransformationMatrix.insert(0,0)=1.0;\r\n    allTransformationMatrices.push_back(spscalarTransformationMatrix);\r\n\r\n    // The number of non-zeros elements of the grade 0 transformation matrix is simply 1\r\n    transformationMatricesSizes.push_back(1);\r\n\r\n    // SCALAR transformation matrix to a list of triplets (here only 1) which will be generated afterwards\r\n    std::vector<double> currentBasisTransformComponents = transformationMatricesToVectorOfComponents(spscalarTransformationMatrix, 0, false);\r\n    transformationMatrices.first.insert(std::end(transformationMatrices.first), std::begin(currentBasisTransformComponents), std::end(currentBasisTransformComponents));\r\n    currentBasisTransformComponents = transformationMatricesToVectorOfComponents(spscalarTransformationMatrix, 0, true); // inverse transformation matrices\r\n    transformationMatrices.second.insert(std::end(transformationMatrices.second), std::begin(currentBasisTransformComponents), std::end(currentBasisTransformComponents));\r\n    allInverseTransformationMatrices.push_back(spscalarTransformationMatrix);\r\n\r\n    // push the transformation matrix to the vector of transformation matrices\r\n    Eigen::SparseMatrix<double, Eigen::ColMajor> spVectorTransformationMatrix(P.rows(), P.cols());\r\n    for(unsigned int j=0; j<(unsigned int)P.cols(); ++j)\r\n        for(unsigned int i=0; i<(unsigned int)P.rows(); ++i)\r\n            if(fabs(P(i,j)) >epsilon) // if non-zero value, insert it\r\n                spVectorTransformationMatrix.insert(i,j)=P(i,j);\r\n    allTransformationMatrices.push_back(spVectorTransformationMatrix);\r\n\r\n    // extract the number of non-zeros elements of the grade 1transformation matrix\r\n    transformationMatricesSizes.push_back((unsigned int)spVectorTransformationMatrix.nonZeros());\r\n\r\n    // convert the grade 1 transformation matrix to a list of triplets which will be generated afterwards\r\n    currentBasisTransformComponents = transformationMatricesToVectorOfComponents(spVectorTransformationMatrix, 0, false);\r\n    transformationMatrices.first.insert(std::end(transformationMatrices.first), std::begin(currentBasisTransformComponents), std::end(currentBasisTransformComponents));\r\n\r\n    // compute also the inverse transformation matrix\r\n    Eigen::SparseMatrix<double, Eigen::ColMajor> spVectorInverseTransformation = computeInverseTransformationMatrix(spVectorTransformationMatrix, epsilon);\r\n\r\n    // and convert it to a list of triplets\r\n    currentBasisTransformComponents = transformationMatricesToVectorOfComponents(spVectorInverseTransformation, 0, true);\r\n    transformationMatrices.second.insert(std::end(transformationMatrices.second), std::begin(currentBasisTransformComponents), std::end(currentBasisTransformComponents));\r\n    allInverseTransformationMatrices.push_back(spVectorInverseTransformation);\r\n\r\n    // remaining transformation matrices\r\n    for(unsigned int i=2;i<=(unsigned int)P.cols();++i){\r\n\r\n        Eigen::SparseMatrix<double, Eigen::ColMajor> spPerGradeTransformation = computePerGradeTransformationMatrix(P, (unsigned int) P.rows(), i, epsilon); // resultMatrix, inputMatrix, dimension, nb vectors to wedge\r\n\r\n        // extract the number of non-zeros elements of the current transformation matrix\r\n        transformationMatricesSizes.push_back((unsigned int)spPerGradeTransformation.nonZeros());\r\n\r\n        // convert the current transformation matrix to a list of triplets which will be generated afterwards\r\n        currentBasisTransformComponents = transformationMatricesToVectorOfComponents(spPerGradeTransformation, 0, false);\r\n        transformationMatrices.first.insert(std::end(transformationMatrices.first), std::begin(currentBasisTransformComponents), std::end(currentBasisTransformComponents));\r\n        allTransformationMatrices.push_back(spPerGradeTransformation);\r\n\r\n        // compute also the inverse of the current transformation matrix\r\n        Eigen::SparseMatrix<double, Eigen::ColMajor> spPerGradeInverseTransformation = computeInverseTransformationMatrix(spPerGradeTransformation, epsilon);\r\n\r\n        // convert the current transformation matrix to a list of triplets which will be generated afterwards\r\n        currentBasisTransformComponents = transformationMatricesToVectorOfComponents(spPerGradeInverseTransformation, 0, true);\r\n        transformationMatrices.second.insert(std::end(transformationMatrices.second), std::begin(currentBasisTransformComponents), std::end(currentBasisTransformComponents));\r\n        allInverseTransformationMatrices.push_back(spPerGradeInverseTransformation);\r\n    }\r\n    return transformationMatrices;\r\n}\r\n", "meta": {"hexsha": "a3d43f27cdc04e77232cc07eb75a15a00ce8ccd9", "size": 19735, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/MetricTools.cpp", "max_stars_repo_name": "hugohadfield/garamon", "max_stars_repo_head_hexsha": "0dc40c7790eac887d41532503cd5ac74ce5d3216", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 53.0, "max_stars_repo_stars_event_min_datetime": "2019-07-23T10:56:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T22:18:04.000Z", "max_issues_repo_path": "src/MetricTools.cpp", "max_issues_repo_name": "hugohadfield/garamon", "max_issues_repo_head_hexsha": "0dc40c7790eac887d41532503cd5ac74ce5d3216", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2020-04-03T08:06:39.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-10T07:01:55.000Z", "max_forks_repo_path": "src/MetricTools.cpp", "max_forks_repo_name": "hugohadfield/garamon", "max_forks_repo_head_hexsha": "0dc40c7790eac887d41532503cd5ac74ce5d3216", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2019-10-22T12:41:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-14T12:17:15.000Z", "avg_line_length": 44.649321267, "max_line_length": 218, "alphanum_fraction": 0.629946795, "num_tokens": 4367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467611766711, "lm_q2_score": 0.8311430436757313, "lm_q1q2_score": 0.7306967149220397}}
{"text": "#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// object for output files\r\nofstream ofile;\r\n// Functions used\r\ninline double f(double x) {return 100.0*exp(-10.0*x);}\r\ninline double exact(double x) {return 1.0-(1-exp(-10))*x-exp(-10*x);}\r\n\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      // Set up arrays for the simple case\r\n      vec d(n+1);  vec solution(n+1);  vec b(n+1);  vec x(n+1);\r\n      // Quick setup of updated diagonal elements and enpoint values of x and b\r\n      x(0) = 0.0; x(n) = 1.0;  b(0) = hh*f(x(0)); b(n) = hh*f(x(n)); d(0) = 2.0;  d(n) = 2.0;\r\n      for (int i = 1; i < n; i++){ \r\n\td(i) = (i+1.0)/( (double) i);  \r\n        x(i) = i*h;\r\n\tb(i) = hh*f(x(i));\r\n      }\r\n     // Forward substitution\r\n      for (int i = 2; i < n; i++) b(i) = b(i) + b(i-1)/d(i-1);\r\n      // Backward substitution\r\n      solution(n-1) = b(n-1)/d(n-1);\r\n      for (int i = n-2; i > 0; i--) solution(i) = (b(i)+solution(i+1))/d(i);\r\n      // Now open file and write out results\r\n      ofile.open(fileout);\r\n      ofile << setiosflags(ios::showpoint | ios::uppercase);\r\n      ofile << \"       x:             approx:          exact:       relative error\" << endl;\r\n      for (int i = 1; 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", "meta": {"hexsha": "6ed53004eec82391afa1cedde73a5931102f9e1c", "size": 2570, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/Projects/2018/Project1/CodeExamples/TridiagonalArma.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/Project1/CodeExamples/TridiagonalArma.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/Project1/CodeExamples/TridiagonalArma.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": 35.2054794521, "max_line_length": 94, "alphanum_fraction": 0.5369649805, "num_tokens": 775, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473614033683, "lm_q2_score": 0.837619961306541, "lm_q1q2_score": 0.7306955631045525}}
{"text": "#include \"writer.hpp\"\n#include <Eigen/Core>\n#include <cmath>\n#include <functional>\n#include <iostream>\n#include <stdexcept>\n\nvoid apply_boundary_conditions(Eigen::ArrayXXd &u, int k) {\n    auto N = u.rows();\n    u(0, k) = u(1, k);\n    u(N - 1, k) = u(N - 2, k);\n}\n\n//----------------upwindFDBegin----------------\n/// Uses forward Euler and upwind finite differences to compute u from time 0 to\n/// time T\n///\n/// @param[in] u0 the initial conditions in the physical domain, excluding\n/// ghost-points.\n/// @param[in] dt the time step size\n/// @param[in] T the solution is computed for the interval [0, T]. T is assumed\n/// to be a multiple of of dt.\n/// @param[in] a the advection velocity\n/// @param[in] domain left & right limit of the domain\n///\n/// @return returns the solution 'u' at every time-step and the corresponding\n/// time-steps. The solution `u` includes the ghost-points.\nstd::pair<Eigen::ArrayXXd, Eigen::VectorXd>\nupwindFD(const Eigen::VectorXd &u0,\n         double dt,\n         double T,\n         const std::function<double(double)> &a,\n         const std::pair<double, double> &domain) {\n\n    auto N = u0.size();\n    auto nsteps = int(round(T / dt));\n\n    auto u = Eigen::ArrayXXd(N + 2, nsteps + 1);\n    auto time = Eigen::VectorXd(nsteps + 1);\n\n    auto [xL, xR] = domain;\n    double dx = (xR - xL) / (N - 1.0);\n\n    /* Initialize u */\n// (write your solution here)\n\n    /* Main loop */\n// (write your solution here)\n\n    return {std::move(u), std::move(time)};\n}\n//----------------upwindFDEnd----------------\n\n//----------------centeredFDBegin----------------\n/// Uses forward Euler and centered finite differences to compute u from time 0\n/// to time T\n///\n/// @param[in] u0 the initial conditions, as column vector\n/// @param[in] dt the time step size\n/// @param[in] T the solution is computed for the interval [0, T]. T is assumed\n/// to be a multiple of of dt.\n/// @param[in] a the advection velocity\n/// @param[in] domain left & right limit of the domain\n///\n/// @return returns the solution 'u' at every time-step and the corresponding\n/// time-steps. The solution `u` includes the ghost-points.\nstd::pair<Eigen::ArrayXXd, Eigen::VectorXd>\ncenteredFD(const Eigen::VectorXd &u0,\n           double dt,\n           double T,\n           const std::function<double(double)> &a,\n           const std::pair<double, double> &domain) {\n\n    auto N = u0.size();\n    auto nsteps = int(round(T / dt));\n    auto u = Eigen::ArrayXXd(N + 2, nsteps + 1);\n    auto time = Eigen::VectorXd(nsteps + 1);\n\n    auto [xL, xR] = domain;\n    double dx = (xR - xL) / (N - 1.0);\n\n    /* Initialize u */\n// (write your solution here)\n\n    /* Main loop */\n// (write your solution here)\n\n    return {std::move(u), std::move(time)};\n}\n//----------------centeredFDEnd----------------\n\n/* Initial condition: rectangle */\ndouble ic(double x) {\n    if (x < 0.25 || x > 0.75)\n        return 0.0;\n    else\n        return 2.0;\n}\n\nint main() {\n    double T = 2.0;\n    double dt = 0.002; // Change this for timestep comparison\n    int N = 101;\n\n    double xL = 0.0;\n    double xR = 5.0;\n    auto domain = std::pair<double, double>{xL, xR};\n\n    auto a = [](double x) { return std::sin(2.0 * M_PI * x); };\n\n    Eigen::VectorXd u0(N);\n    double h = (xR - xL) / (N - 1.0);\n    /* Initialize u0 */\n    for (int i = 0; i < u0.size(); i++) {\n        u0[i] = ic(xL + h * i);\n    }\n\n    const auto &[u_upwind, time_upwind] = upwindFD(u0, dt, T, a, domain);\n    writeToFile(\"time_upwind.txt\", time_upwind);\n    writeMatrixToFile(\"u_upwind.txt\", u_upwind);\n\n    const auto &[u_centered, time_centered] = centeredFD(u0, dt, T, a, domain);\n    writeToFile(\"time_centered.txt\", time_centered);\n    writeMatrixToFile(\"u_centered.txt\", u_centered);\n}\n", "meta": {"hexsha": "95ef9fd7f7f25ef4aa064d86a9a5c3437d5d3c67", "size": 3724, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "series0_handout/linear-transp-1d/linear_transport.cpp", "max_stars_repo_name": "BeatHubmann/19H-AdvNCSE", "max_stars_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-05T22:38:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-05T22:38:47.000Z", "max_issues_repo_path": "series0_handout/linear-transp-1d/linear_transport.cpp", "max_issues_repo_name": "BeatHubmann/19H-AdvNCSE", "max_issues_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "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": "series0_handout/linear-transp-1d/linear_transport.cpp", "max_forks_repo_name": "BeatHubmann/19H-AdvNCSE", "max_forks_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-08T20:43:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-08T20:43:27.000Z", "avg_line_length": 29.5555555556, "max_line_length": 80, "alphanum_fraction": 0.5942534909, "num_tokens": 1074, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.8499711737573762, "lm_q1q2_score": 0.7306894070575821}}
{"text": "#pragma once\n\n#include <vector>\n#include <cassert>\n\n#include <iostream>\n#include <iomanip>\n\n#include <Eigen/Dense>\n\n//! \\file tylorintegrator.hpp Solution for Problem 3, implementing TaylorIntegrator class\n\n//! \\brief Implements an autonomous ODE integrator based on Taylor expansion\n//! \\tparam State a type representing the space in which the solution lies, e.g. R^d, represented by e.g. Eigen::VectorXd.\ntemplate <class State>\nclass TaylorIntegrator {\npublic:\n    //! \\brief Perform the solution of the ODE\n    //! Solve an autonomous ODE y' = f(y), y(0) = y0, using a Taylor expansion method\n    //! constructor. Performs N equidistant steps upto time T with initial data y0\n    //! \\tparam Function type for function implementing the rhs function (and its derivatives).\n    //! \\param[in] odefun function handle for rhs f and its derivatives\n    //! \\param[in] T final time T\n    //! \\param[in] y0 initial data y(0) = y0 for y' = f(y)\n    //! \\param[in] N number of steps to perform. Step size is h = T / N. Steps are equidistant.\n    //! \\return vector containing all steps y^n (for each n) including initial and final value\n    template <class Function>\n    std::vector<State> solve(const Function &odefun, double T, const State & y0, unsigned int N) const {\n        // Iniz step size\n        double h = T / N;\n        \n        // Will contain all steps, reserve memory for efficiency\n        std::vector<State> res;\n        res.reserve(N);\n        \n        // Store initial data\n        res.push_back(y0);\n        \n        // Initialize some memory to store temporary values\n        State ytemp1 = y0;\n        State ytemp2 = y0;\n        // Pointers to swap previous value\n        State * yold = &ytemp1;\n        State * ynew = &ytemp2;\n        \n        // Loop over all fixed steps\n        for(unsigned int k = 0; k < N; ++k) {\n            // Compute, save and swap next step\n            step(odefun, h, *yold, *ynew);\n            res.push_back(*ynew);\n            std::swap(yold, ynew);\n        }\n        \n        return res;\n    }\n    \nprivate:\n    \n    //! \\brief Perform a single step of the Taylor expansion for the solution of the autonomous ODE\n    //! Compute a single explicit step y^{n+1} = y_n + \\sum ... starting from value y0 and storing next value in y1\n    //! \\tparam Function type for function implementing the rhs and its derivatives.\n    //! \\param[in] odefun function handle for rhs f and the derivatives\n    //! \\param[in] h step size\n    //! \\param[in] y0 initial state \n    //! \\param[out] y1 next step y^{n+1} = y^n + ...\n    template <class Function>\n    void step(const Function &odefun, double h, const State & y0, State & y1) const {\n        // Compute values for Taylor expansion, including Jacobian and Hessian matrix\n        auto fy0 =  odefun.f(y0);\n        auto dfy0fy0 =  odefun.df(y0, fy0);\n        auto df2y0fy0 =  odefun.df(y0, dfy0fy0);\n        auto d2fy0fy0 = odefun.d2f(y0, fy0);\n        \n        // Plug values into Taylor expansion for next step\n        y1 = y0 + fy0*h + dfy0fy0*h*h/2. + (df2y0fy0 + d2fy0fy0)*h*h*h/6.;\n    }\n    \n};\n", "meta": {"hexsha": "965395d928add2fbb443fda9ac3973b4e0d31b2f", "size": 3085, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/PS12/solutions_ps12/taylorintegrator.hpp", "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/PS12/solutions_ps12/taylorintegrator.hpp", "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/PS12/solutions_ps12/taylorintegrator.hpp", "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.0506329114, "max_line_length": 122, "alphanum_fraction": 0.6230145867, "num_tokens": 824, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637541053281, "lm_q2_score": 0.8499711699569787, "lm_q1q2_score": 0.7306894068465143}}
{"text": "#include <boost/math/special_functions/fpclassify.hpp>\n#include <boost/math/special_functions/round.hpp>\n#include <sm/assert_macros.hpp>\n#include <sm/kinematics/rotations.hpp>\n\nnamespace sm {\nnamespace kinematics {\n\n// Euler angle rotations.\nEigen::Matrix3d Rx(double radians) {\n    Eigen::Matrix3d C;\n    double c = cos(radians);\n    double s = sin(radians);\n    C(0, 0) = 1;\n    C(0, 1) = 0.0;\n    C(0, 2) = 0;\n    C(1, 0) = 0.0;\n    C(1, 1) = c;\n    C(1, 2) = -s;\n    C(2, 0) = 0.0;\n    C(2, 1) = s;\n    C(2, 2) = c;\n\n    return C;\n}\n\nEigen::Matrix3d Ry(double radians) {\n    Eigen::Matrix3d C;\n    double c = cos(radians);\n    double s = sin(radians);\n    C(0, 0) = c;\n    C(0, 1) = 0.0;\n    C(0, 2) = s;\n    C(1, 0) = 0.0;\n    C(1, 1) = 1;\n    C(1, 2) = 0.0;\n    C(2, 0) = -s;\n    C(2, 1) = 0.0;\n    C(2, 2) = c;\n\n    return C;\n}\nEigen::Matrix3d Rz(double radians) {\n    Eigen::Matrix3d C;\n    double c = cos(radians);\n    double s = sin(radians);\n    C(0, 0) = c;\n    C(0, 1) = -s;\n    C(0, 2) = 0.0;\n    C(1, 0) = s;\n    C(1, 1) = c;\n    C(1, 2) = 0.0;\n    C(2, 0) = 0.0;\n    C(2, 1) = 0.0;\n    C(2, 2) = 1;\n\n    return C;\n}\n\nEigen::Matrix3d rph2R(double x, double y, double z) {\n    Eigen::Matrix3d C;\n    double cx = cos(x);\n    double sx = sin(x);\n    double cy = cos(y);\n    double sy = sin(y);\n    double cz = cos(z);\n    double sz = sin(z);\n    //[cos(z)*cos(y), -sin(z)*cos(x)+cos(z)*sin(y)*sin(x),  sin(z)*sin(x)+cos(z)*sin(y)*cos(x)]\n    //[sin(z)*cos(y),  cos(z)*cos(x)+sin(z)*sin(y)*sin(x), -cos(z)*sin(x)+sin(z)*sin(y)*cos(x)]\n    //[      -sin(y),                       cos(y)*sin(x),                       cos(y)*cos(x)]\n    C(0, 0) = cz * cy;\n    C(0, 1) = -sz * cx + cz * sy * sx;\n    C(0, 2) = sz * sx + cz * sy * cx;\n    C(1, 0) = sz * cy;\n    C(1, 1) = cz * cx + sz * sy * sx;\n    C(1, 2) = -cz * sx + sz * sy * cx;\n    C(2, 0) = -sy;\n    C(2, 1) = cy * sx;\n    C(2, 2) = cy * cx;\n\n    return C;\n}\nEigen::Matrix3d rph2R(Eigen::Vector3d const& x) { return rph2R(x[0], x[1], x[2]); }\n\nEigen::Vector3d R2rph(Eigen::Matrix3d const& C) {\n    double phi = asin(C(2, 0));\n    double theta = atan2(C(2, 1), C(2, 2));\n    double psi = atan2(C(1, 0), C(0, 0));\n\n    Eigen::Vector3d ret;\n    ret[0] = theta;\n    ret[1] = -phi;\n    ret[2] = psi;\n\n    return ret;\n}\n\n//// Small angle approximation.\ntemplate <typename Scalar_>\nEigen::Matrix<Scalar_, 3, 3> crossMx(Scalar_ x, Scalar_ y, Scalar_ z) {\n    Eigen::Matrix<Scalar_, 3, 3> C;\n    C(0, 0) = 0.0;\n    C(0, 1) = -z;\n    C(0, 2) = y;\n    C(1, 0) = z;\n    C(1, 1) = 0.0;\n    C(1, 2) = -x;\n    C(2, 0) = -y;\n    C(2, 1) = x;\n    C(2, 2) = 0.0;\n    return C;\n}\ntemplate Eigen::Matrix<double, 3, 3> crossMx(double x, double y, double z);\ntemplate Eigen::Matrix<float, 3, 3> crossMx(float x, float y, float z);\n\ntemplate Eigen::Matrix<double, 3, 3> crossMx(Eigen::MatrixBase<Eigen::Matrix<double, 3, 1> > const&);\ntemplate Eigen::Matrix<float, 3, 3> crossMx(Eigen::MatrixBase<Eigen::Matrix<float, 3, 1> > const&);\n\ntemplate Eigen::Matrix<double, 3, 3> crossMx(Eigen::MatrixBase<Eigen::Matrix<double, Eigen::Dynamic, 1> > const&);\ntemplate Eigen::Matrix<float, 3, 3> crossMx(Eigen::MatrixBase<Eigen::Matrix<float, Eigen::Dynamic, 1> > const&);\n\n// Axis Angle rotation.\nEigen::Matrix3d axisAngle2R(double a, double ax, double ay, double az) {\n    SM_ASSERT_LT_DBG(std::runtime_error, fabs(sqrt(ax * ax + ay * ay + az * az) - 1.0), 1e-4,\n                     \"The axis is not a unit vector. ||a|| = \" << (sqrt(ax * ax + ay * ay + az * az)));\n\n    if (a < 1e-12) return Eigen::Matrix3d::Identity();\n    // e = [ax ay az]\n    // e*(e') + (eye(3) - e*(e'))*cos(a) - crossMx(e) * sin(a) =\n    //[         ax^2+ca*(1-ax^2), ax*ay-ca*ax*ay+sa*az, ax*az-ca*ax*az-sa*ay]\n    //[ ax*ay-ca*ax*ay-sa*az,         ay^2+ca*(1-ay^2), ay*az-ca*ay*az+sa*ax]\n    //[ ax*az-ca*ax*az+sa*ay, ay*az-ca*ay*az-sa*ax,         az^2+ca*(1-az^2)]\n    double sa = sin(a);\n    double ca = cos(a);\n    double ax2 = ax * ax;\n    double ay2 = ay * ay;\n    double az2 = az * az;\n    double const one = double(1);\n\n    Eigen::Matrix3d C;\n    C(0, 0) = ax2 + ca * (one - ax2);\n    C(0, 1) = ax * ay - ca * ax * ay + sa * az;\n    C(0, 2) = ax * az - ca * ax * az - sa * ay;\n    C(1, 0) = ax * ay - ca * ax * ay - sa * az;\n    C(1, 1) = ay2 + ca * (one - ay2);\n    C(1, 2) = ay * az - ca * ay * az + sa * ax;\n    C(2, 0) = ax * az - ca * ax * az + sa * ay;\n    C(2, 1) = ay * az - ca * ay * az - sa * ax;\n    C(2, 2) = az2 + ca * (one - az2);\n\n    return C;\n}\nEigen::Matrix3d axisAngle2R(double x, double y, double z) {\n    double a = sqrt(x * x + y * y + z * z);\n    if (a < 1e-12) return Eigen::Matrix3d::Identity();\n\n    double d = 1 / a;\n    return axisAngle2R(a, x * d, y * d, z * d);\n}\n\nEigen::Matrix3d axisAngle2R(Eigen::Vector3d const& x) { return axisAngle2R(x[0], x[1], x[2]); }\n\nEigen::Vector3d R2AxisAngle(Eigen::Matrix3d const& C) {\n    // Sometimes, because of roundoff error, the value of tr ends up outside\n    // the valid range of arccos. Truncate to the valid range.\n    double tr = std::max(-1.0, std::min((C(0, 0) + C(1, 1) + C(2, 2) - 1.0) * 0.5, 1.0));\n    double a = acos(tr);\n\n    Eigen::Vector3d axis;\n\n    if (fabs(a) < 1e-10) {\n        return Eigen::Vector3d::Zero();\n    }\n\n    axis[0] = (C(2, 1) - C(1, 2));\n    axis[1] = (C(0, 2) - C(2, 0));\n    axis[2] = (C(1, 0) - C(0, 1));\n    double n2 = axis.norm();\n    if (fabs(n2) < 1e-10) return Eigen::Vector3d::Zero();\n\n    double scale = -a / n2;\n    axis = scale * axis;\n\n    return axis;\n}\n\n// Utility functions\ndouble angleMod(double radians) { return (double)(radians - (SM_2PI * boost::math::round(radians / SM_2PI))); }\ndouble deg2rad(double degrees) { return (double)(degrees * SM_DEG2RAD); }\ndouble rad2deg(double radians) { return (double)(radians * SM_RAD2DEG); }\n\nEigen::Matrix3d Cx(double radians) { return Rx(-radians); }\nEigen::Matrix3d Cy(double radians) { return Ry(-radians); }\nEigen::Matrix3d Cz(double radians) { return Rz(-radians); }\n\nEigen::Matrix3d rph2C(double x, double y, double z) { return rph2R(-x, -y, -z); }\n\nEigen::Matrix3d rph2C(Eigen::Vector3d const& x) { return rph2C(x[0], x[1], x[2]); }\nEigen::Matrix3d rph2C(Eigen::VectorXd const& x) {\n    SM_ASSERT_EQ_DBG(std::runtime_error, x.size(), 3, \"The input vector must have 3 components\");\n    return rph2C(x[0], x[1], x[2]);\n}\n\nEigen::Matrix3d rph2C(Eigen::MatrixXd const& A, unsigned column) {\n    SM_ASSERT_EQ_DBG(std::runtime_error, A.rows(), 3, \"The input matrix must have 3 rows\");\n    SM_ASSERT_LT_DBG(std::runtime_error, column, A.cols(), \"The requested column is out of bounds\");\n    return rph2C(A(0, column), A(1, column), A(2, column));\n}\n\nEigen::Vector3d C2rph(Eigen::MatrixXd const& C) {\n    SM_ASSERT_EQ_DBG(std::runtime_error, C.rows(), 3, \"The input matrix must be 3x3\");\n    SM_ASSERT_EQ_DBG(std::runtime_error, C.cols(), 3, \"The input matrix must be 3x3\");\n\n    Eigen::Vector3d rph;\n\n    rph[1] = asin(C(2, 0));\n    rph[2] = atan2(-C(1, 0), C(0, 0));\n    rph[0] = atan2(-C(2, 1), C(2, 2));\n\n    return rph;\n}\n\nEigen::Vector3d C2rph(Eigen::Matrix3d const& C) {\n    Eigen::Vector3d rph;\n\n    rph[1] = asin(C(2, 0));\n    rph[2] = atan2(-C(1, 0), C(0, 0));\n    rph[0] = atan2(-C(2, 1), C(2, 2));\n\n    return rph;\n}\n\n}  // namespace kinematics\n}  // namespace sm\n", "meta": {"hexsha": "51f48d8ce82814d297a22bd409f64ef35753b9c7", "size": 7257, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Schweizer-Messer/sm_kinematics/src/rotations.cpp", "max_stars_repo_name": "chengfzy/kalibr", "max_stars_repo_head_hexsha": "fe9705b380b160dc939607135f7d30efa64ea2e9", "max_stars_repo_licenses": ["BSD-4-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": "Schweizer-Messer/sm_kinematics/src/rotations.cpp", "max_issues_repo_name": "chengfzy/kalibr", "max_issues_repo_head_hexsha": "fe9705b380b160dc939607135f7d30efa64ea2e9", "max_issues_repo_licenses": ["BSD-4-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": "Schweizer-Messer/sm_kinematics/src/rotations.cpp", "max_forks_repo_name": "chengfzy/kalibr", "max_forks_repo_head_hexsha": "fe9705b380b160dc939607135f7d30efa64ea2e9", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8808510638, "max_line_length": 114, "alphanum_fraction": 0.5474714069, "num_tokens": 2895, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912913, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7306532334865828}}
{"text": "#include \"problemes.h\"\n#include \"arithmetique.h\"\n#include \"matrice.h\"\n\n#include <boost/numeric/ublas/assignment.hpp>\n\ntypedef long long nombre;\ntypedef std::vector<nombre> vecteur;\n\nENREGISTRER_PROBLEME(237, \"Tours on a 4 x n playing board\") {\n    // Let T(n) be the number of tours over a 4 \u00d7 n playing board such that:\n    //\n    // The tour starts in the top left corner.\n    // The tour consists of moves that are up, down, left, or right one square.\n    // The tour visits each square exactly once.\n    // The tour ends in the bottom left corner.\n    // The diagram shows one tour over a 4 \u00d7 10 board:\n    //\n    //\t\t\t\t\thttps://projecteuler.net/project/images/p237.gif\n    //\n    //T(10) is 2329. What is T(1012) modulo 108?\n    size_t n = 1000000000000LL;\n    // T[n]=2*T[n-1]+2*T[n-2]-2*T[n-3]+T[n-4]\n    matrice::matrice<nombre> m(4, 4, 0);\n    m <<= 2, 2, -2, 1,\n            1, 0, 0, 0,\n            0, 1, 0, 0,\n            0, 0, 1, 0;\n\n    matrice::vecteur<nombre> i(4);\n    i <<= 8, 4, 1, 1;\n\n    auto m_n = matrice::puissance_matrice(m, n - 4, 100000000LL);\n    nombre resultat = boost::numeric::ublas::prod(m_n, i)(0);\n\n    return std::to_string(resultat);\n}\n", "meta": {"hexsha": "21a1f767f0396d30422ff37cc165fec1a2ce8121", "size": 1171, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problemes/probleme2xx/probleme237.cpp", "max_stars_repo_name": "ZongoForSpeed/ProjectEuler", "max_stars_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-10-13T17:07:21.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-08T11:50:22.000Z", "max_issues_repo_path": "problemes/probleme2xx/probleme237.cpp", "max_issues_repo_name": "ZongoForSpeed/ProjectEuler", "max_issues_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "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": "problemes/probleme2xx/probleme237.cpp", "max_forks_repo_name": "ZongoForSpeed/ProjectEuler", "max_forks_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "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.8157894737, "max_line_length": 79, "alphanum_fraction": 0.6054654142, "num_tokens": 400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966702001758, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.7306244899380743}}
{"text": "/// @file bealab/extensions/control/baytrack.hpp\n/// Implementation of Bayesian tracking techniques.\n\n#ifndef _BEALAB_BAYTRACK_\n#define\t_BEALAB_BAYTRACK_\n\n#include <bealab/core/blas.hpp>\n#include <bealab/scilib/stats.hpp>\n#include <bealab/scilib/optimization.hpp>\n#include <bealab/extensions/control/linsys.hpp>\n#include <boost/circular_buffer.hpp>\n\nnamespace bealab\n{\nnamespace control\n{\n//------------------------------------------------------------------------------\n/// @defgroup baytrack Bayesian tracking\n/// Implementation of Bayesian tracking techniques.\n/// @{\n\nusing boost::circular_buffer;\n\n/// Kalman filter\nclass kalman_filter : public state_space {\npublic:\n\n\trvec x;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t///< Initial state mean\n\trmat P;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t///< Initial state covariance\n\n\t/// Constructor\n\tkalman_filter( const rmat& A, const rmat& B, const rmat& C, const rmat& D,\n\t\t\tconst rmat& Q, const rmat& R, const rmat& P_ = rmat() ) :\n\t\t\t\tstate_space(A,B,C,D,Q,R)\n\t{\n\t\tint N = A.size1();\n\t\tx     = zeros(N);\n\t\tif( P_.size1() == 0 )\n\t\t\tP = zeros(N,N);\n\t\telse\n\t\t\tP = P_;\n\t}\n\n\t/// Constructor\n\tkalman_filter( const state_space& ss, const rmat& P = rmat() ) :\n\t\tkalman_filter( ss.A, ss.B, ss.C, ss.D, ss.Q, ss.R, P) {}\n\n\t/// Prediction step\n\trvec prediction( const rvec& u )\n\t{\n\t\tx = A * x + B * u;\n\t\tP = noproxy(A * P) * trans(A) + Q;\n\t\treturn x;\n\t}\n\n\t/// Update step\n\trvec update( const rvec& y )\n\t{\n\t\tint N  = A.size1();\n\t\trmat K = trans( linsolve( noproxy(C * P) * trans(C) + R, C * P ) );\n\t\tx      = x + K * ( y - C * x );\n\t\tP      = (eye(N) - K * C) * P;\n\t\treturn x;\n\t}\n\n\t/// Filter one pair of input and output samples\n\trvec operator()( const rvec& u, const rvec& y )\n\t{\n\t\tprediction( u );\n\t\tupdate( y );\n\t\treturn x;\n\t}\n\n\t/// Filter an output sample, assuming zero input.\n\trvec operator()( const rvec& y )\n\t{\n\t\tint M  = B.size2();\n\t\trvec u = zeros(M);\n\t\treturn (*this)( u, y );\n\t}\n\n\t/// Filter one pair of sequences of input and output samples\n\tvec<rvec> operator()( const vec<rvec>& U, const vec<rvec>& Y )\n\t{\n\t\tassert( U.size() == Y.size() );\n\t\tint T = U.size();\n\t\tvec<rvec> Xh(T);\n\t\tfor( int t = 0; t < T; t++ )\n\t\t\tXh(t) = (*this)( U(t), Y(t) );\n\t\treturn Xh;\n\t}\n\n\t/// Filter a sequences of output samples, assuming zero input.\n\tvec<rvec> operator()( const vec<rvec>& Y )\n\t{\n\t\tint T = Y.size();\n\t\tvec<rvec> Xh(T);\n\t\tfor( int t = 0; t < T; t++ )\n\t\t\tXh(t) = (*this)( Y(t) );\n\t\treturn Xh;\n\t}\n};\n\n/// Base class for implementing a particle filter.\n/// The virtual member functions  need to be implemented in a derived class.\n/// Need to implement either state_transition() or particle_prediction(), and\n/// either likelihood_function() or particle_update().\ntemplate< class state_t = rvec, class obs_t = state_t, class out_t = obs_t >\nclass particle_filter_b {\nprotected:\n\n\t/// A particles path with it's associated weight\n\tstruct particle_path {\n\t\tcircular_buffer<state_t> trajectory;\n\t\tdouble weight;\n\t};\n\n\trvec old_weights;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t///< Weights before the last update step\n\tbool init_f = false;\t\t\t\t\t\t\t\t\t\t\t\t\t\t///< Flag to indicate that the filter was initialized\n\tint time    = 0;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t///< The current time used when running the filter\n\n\t/// A particles with it's associated weight\n\tstruct particle {\n\t\tstate_t state;\n\t\tdouble weight;\n\t};\n\n\t/// Draw a sample from the initial distribution\n\tvirtual\n\tstate_t draw_initial_sample() = 0;\n\n\t/// State transition function\n\tvirtual\n\tstate_t state_transition( const state_t& state ) { return state; }\n\n\t/// Likelihood of the state given the observation\n\tvirtual\n\tdouble likelihood_function( const obs_t& obs, const state_t& state ) { return 1; }\n\n\t/// Default particle prediction function. Uses state_transition().\n\tvirtual\n\tparticle particle_prediction( const particle& p )\n\t{\n\t\tparticle pp = p;\n\t\tpp.state    = state_transition( p.state );\n\t\treturn pp;\n\t}\n\n\t/// Default particle update function. Uses likelihood_function().\n\tvirtual\n\tparticle particle_update( const obs_t& obs, const particle& p )\n\t{\n\t\tparticle pu = p;\n\t\tpu.weight  *= likelihood_function( obs, p.state );\n\t\treturn pu;\n\t}\n\n\t/// Output function\n\tvirtual\n\tout_t output_function( const state_t& state ) = 0;\n\npublic:\n\n\tvector<particle_path> x;\t\t\t\t\t\t\t\t\t\t\t\t\t///< Particles of the current predicted or updated state\n\tconst int I;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t///< Number of particles\n\tconst int lag;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t///< Amount of lag used for smoothing.\n\tdouble resample_period = 1;\n\n\t/// Constructor\n\tparticle_filter_b( int I_, int lag_=0 ) :\n\t\told_weights(I_), x(I_), I(I_), lag(lag_)\n\t{\n\t\tassert( I > 0 );\n\t\tfor( int i = 0; i < I; i++ )\n\t\t\tx[i].trajectory = circular_buffer<state_t>(lag+1);\n\t}\n\n\t/// Destructor\n\tvirtual\n\t~particle_filter_b() {}\n\n\t/// Implements the prediction step\n\tvirtual\n\tvoid prediction()\n\t{\n\t\t#pragma omp parallel for schedule(dynamic)\n\t\tfor( int i = 0; i < I; i++ ) {\n\t\t\tparticle p  = { x[i].trajectory.back(), x[i].weight };\n\t\t\tparticle pp = particle_prediction( p );\n\t\t\tx[i].trajectory.push_back( pp.state );\n\t\t\tx[i].weight = pp.weight;\n\t\t}\n\t}\n\n\t/// Implements the update step\n\tvirtual\n\tvoid update( const obs_t& z )\n\t{\n\t\t#pragma omp parallel for schedule(dynamic)\n\t\tfor( int i = 0; i < I; i++ ) {\n\t\t\tparticle p             = { x[i].trajectory.back(), x[i].weight };\n\t\t\tparticle pu            = particle_update( z, p );\n\t\t\tx[i].trajectory.back() = pu.state;\n\t\t\told_weights(i)         = x[i].weight;\n\t\t\tx[i].weight            = pu.weight;\n\t\t}\n\t\tnormalize();\n\t}\n\n\t/// Implements the normalization step\n\tvirtual\n\tvoid normalize()\n\t{\n\t\tdouble K = 0;\n\t\tfor( int i = 0; i < I; i++ )\n\t\t\tK += x[i].weight;\n//\t\tif( K == 0 ) {\n//\t\t\twarning(\"Ran out of particles\");\n//\t\t\tfor( int i = 0; i < I; i++ )\n//\t\t\t\tx[i].weight = old_weights(i);\n//\t\t}\n//\t\telse {\n//\t\t\tfor( int i = 0; i < I; i++ )\n//\t\t\t\tx[i].weight /= K;\n//\t\t}\n\t\tfor( int i = 0; i < I; i++ )\n\t\t\tx[i].weight /= K;\n\t\tif( K == 0 )\n\t\t\twarning(\"Ran out of particles\");\n\t}\n\n\t/// Implements the re-sampling step\n\tvirtual\n\tvoid resample()\n\t{\n\t\t// Store current particles\n\t\tauto x0 = x;\n\n\t\t// Build the distribution\n\t\trvec weights(I);\n\t\tfor( int i = 0; i < I; i++ )\n\t\t\tweights(i) = x[i].weight;\n\t\tstd::discrete_distribution<> d( weights.begin(), weights.end() );\n\n\t\t// Re-sample\n\t\tfor( int i = 0; i < I; i++ ) {\n\t\t\tint idx = d(_stats::engine);\n\t\t\tx[i].trajectory = x0[idx].trajectory;\n\t\t\tx[i].weight     = 1./I;\n\t\t}\n\t}\n\n\t/// Generates the output\n\tvirtual\n\tout_t output()\n\t{\n\t\tvec<out_t> o(I);\n\t\t#pragma omp parallel for schedule(dynamic)\n\t\tfor( int i = 0; i < I; i++ )\n\t\t\to(i) = output_function( x[i].trajectory.front() ) * x[i].weight;\n\t\treturn sum(o);\n\t}\n\n\t/// Draw the particles of the initial state\n\tvoid initialize()\n\t{\n\t\tinit_f = true;\n\t\tfor( int i = 0; i < I; i++ ) {\n\t\t\tx[i].trajectory.push_back( draw_initial_sample() );\n\t\t\tx[i].weight = 1./I;\n\t\t}\n\t}\n\n\t/// Filter one sample\n\tout_t operator()( const obs_t& z )\n\t{\n\t\tif( !init_f )\n\t\t\tinitialize();\n\t\tupdate( z );\n\t\tout_t o = output();\n\t\tif( mod( time+1, resample_period ) == 0 )\n\t\t\tresample();\n\t\tprediction();\n\t\ttime++;\n\t\treturn o;\n\t}\n\n\t/// Filter a vector of samples\n\tvec<out_t> operator()( const vec<obs_t>& Z )\n\t{\n\t\tint T = Z.size();\n\t\tvec<out_t> Yh(T);\n\t\tfor( int t = 0; t < T; t++ )\n\t\t\tYh(t) = (*this)( Z(t) );\n\t\treturn Yh;\n\t}\n};\n\n/// Particle approximation to a Kalman filter (for testing purposes)\nclass particle_kalman_filter : public particle_filter_b<rvec,rvec,rvec>, public kalman_filter {\n\n\tint N;\n\trmat Qh, Rh, Ph;\n\n\trvec draw_initial_sample() override\n\t{\n\t\treturn Ph * randn(N);\n\t}\n\n\trvec state_transition( const rvec& x ) override\n\t{\n\t\treturn A * x + Qh * randn(N);\n\t}\n\n\tdouble likelihood_function( const rvec& y, const rvec& x ) override\n\t{\n\t\treturn pdf( multivariate_normal( C*x, Rh ), y );\n\t}\n\n\trvec output_function( const rvec& x ) override\n\t{\n\t\treturn C*x;\n\t}\n\npublic:\n\n\tusing particle_filter_b::prediction;\n\tusing particle_filter_b::update;\n\tusing particle_filter_b::operator();\n\n\tparticle_kalman_filter( int I, const rmat& A, const rmat& B, const rmat& C, const rmat& D,\n\t\t\tconst rmat& Q, const rmat& R, const rmat& P_ = rmat() ) :\n\t\t\t\tparticle_filter_b(I),\n\t\t\t\tkalman_filter(A,B,C,D,Q,R,P_)\n\t{\n\t\tN  = A.size1();\n\t\tQh = real(msqrt(Q));\n\t\tRh = real(msqrt(R));\n\t\tPh = real(msqrt(P));\n\t}\n\n\tparticle_kalman_filter( int I, const state_space& ss, const rmat& P = rmat() ) :\n\t\tparticle_kalman_filter(I,ss.A,ss.B,ss.C,ss.D,ss.Q,ss.R,P)\n\t{}\n};\n\n/// State associated to a Rao-Blackwellized particle filter.\nstruct RB_state_t {\n\trvec position;\n\trvec mean;\n\trmat covariance;\n};\n\n/// Base class for implementing Rao-Blackwellized particle filters.\n/// The virtual member functions  need to be implemented in a derived class.\nclass RB_particle_filter_b : public particle_filter_b< RB_state_t, rvec, rvec > {\n\n\t/// Non-linear state transition function\n\tvirtual\n\trvec f( const rvec& x ) = 0;\n\n\t/// Linear state transition function\n\tvirtual\n\trvec g( const rvec& x ) = 0;\n\n\t/// Measurement non-linear component\n\tvirtual\n\trvec h( const rvec& x ) = 0;\n\n\t/// Output non-linear component\n\tvirtual\n\trvec o( const rvec& x ) = 0;\n\n\t/// Non-linear state transition matrix\n\tvirtual\n\trmat F( const rvec& x ) = 0;\n\n\t/// Linear state transition matrix\n\tvirtual\n\trmat G( const rvec& x ) = 0;\n\n\t/// Measurement linear component\n\tvirtual\n\trmat H( const rvec& x ) = 0;\n\n\t/// Output linear component\n\tvirtual\n\trmat O( const rvec& x ) = 0;\n\n\t/// Non-linear process noise covariance\n\tvirtual\n\trmat U( const rvec& x ) = 0;\n\n\t/// Linear process noise covariance\n\tvirtual\n\trmat V( const rvec& x ) = 0;\n\n\t/// Output noise covariance\n\tvirtual\n\trmat W( const rvec& x ) = 0;\n\n\t/// Override\n\tparticle particle_prediction( const particle& p ) override\n\t{\n\t\t// Predicted state\n\t\tparticle pp;\n\n\t\t// Non-linear elements\n\t\trvec f_ = f( p.state.position );\n\t\trmat F_ = F( p.state.position );\n\t\trmat U_ = U( p.state.position );\n\t\trvec g_ = g( p.state.position );\n\t\trmat G_ = G( p.state.position );\n\t\trmat V_ = V( p.state.position );\n\n\t\t// Non-linear prediction\n\t\trvec nlp_mean   = f_ + F_ * p.state.mean;\n\t\trmat nlp_cov    = noproxy(F_ * p.state.covariance) * trans(F_) + U_;\n\t\trmat nlp_cov_h  = real(msqrt(nlp_cov));\n\t\trvec nlp        = rand( multivariate_normal( nlp_mean, nlp_cov_h ) );\n\t\tpp.state.position = nlp;\n\n\t\t// Linear prediction\n\t\tif( det(nlp_cov) != 0 ) {\n\n\t\t\t// Linear false update\n\t\t\trvec lfu_obs  = nlp - f_;\n\t\t\trmat K        = trans( linsolve( nlp_cov, F_ * p.state.covariance ) );\n\t\t\trvec lfu_mean = p.state.mean + K * ( lfu_obs - F_ * p.state.mean );\n\t\t\trmat lfu_cov  = (eye(K.size1()) - K * F_) * p.state.covariance;\n\n\t\t\t// Prediction\n\t\t\tpp.state.mean       = g_ + G_ * lfu_mean;\n\t\t\tpp.state.covariance = noproxy(G_ * lfu_cov) * trans(G_) + V_;\n\t\t}\n\t\telse {\n\t\t\tpp.state.mean       = g_ + G_ * p.state.mean;\n\t\t\tpp.state.covariance = noproxy(G_ * p.state.covariance) * trans(G_) + V_;\n\t\t}\n\n\t\t// Weight\n\t\tpp.weight = p.weight;\n\n\t\treturn pp;\n\t}\n\n\t/// Override\n\tparticle particle_update( const rvec& obs, const particle& p ) override\n\t{\n\t\t// Update particles\n\t\tparticle pu;\n\n\t\t// Non-linear elements\n\t\trvec h_ = h( p.state.position );\n\t\trmat H_ = H( p.state.position );\n\t\trmat W_ = W( p.state.position );\n\n\t\t// Linear output prediction\n\t\trvec lop_mean = H_ * p.state.mean + h_;\n\t\trmat lop_cov  = noproxy(H_ * p.state.covariance) * trans(H_) + W_;\n\n\t\t// Check the singularity of lop_cov\n\t\tdouble singular = (det(lop_cov) == 0);\n\n\t\t// Non-linear state update\n\t\tpu.state.position = p.state.position;\n\t\trvec delta        = obs - lop_mean;\n\t\tif( !singular ) {\n\t\t\tint N     = lop_mean.size();\n\t\t\tdouble a  = inner_prod( delta, linsolve( lop_cov, delta ) );\n\t\t\tdouble b  = log( pow(2*pi,N) * det(lop_cov) );\n\t\t\tpu.weight = exp( -0.5 * (a+b) ) * p.weight;\n\t\t\tif( isnan(pu.weight) )\n\t\t\t\terror(\"Weight is nan\");\n\t\t}\n\t\telse\n\t\t\tpu.weight = ( norm(delta) == 0 ? 1 : 0) * p.weight;\n\n\t\t// Linear state update\n\t\tif( !singular ) {\n\t\t\trvec lsu_obs        = obs - h_;\n\t\t\trmat K              = trans( linsolve( lop_cov, H_ * p.state.covariance ) );\n\t\t\tpu.state.mean       = p.state.mean + K * ( lsu_obs - H_ * p.state.mean );\n\t\t\tpu.state.covariance = (eye(K.size1()) - K * H_) * p.state.covariance;\n\t\t}\n\t\telse {\n\t\t\tpu.state.mean       = p.state.mean;\n\t\t\tpu.state.covariance = p.state.covariance;\n\t\t}\n\n\t\treturn pu;\n\t}\n\n\t/// Override\n\trvec output_function( const RB_state_t& state ) override\n\t{\n\t\trvec o_ = o( state.position );\n\t\trmat O_ = O( state.position );\n\t\treturn O_ * state.mean + o_;\n\t}\n\npublic:\n\n\t/// Constructor\n\tRB_particle_filter_b( int I, int lag=0 ) :\n\t\tparticle_filter_b<RB_state_t,rvec,rvec>( I, lag ) {}\n\n\t/// Destructor\n\tvirtual\n\t~RB_particle_filter_b() {}\n};\n\n/// Base class for implementing a particle smoother.\n/// The virtual member functions  need to be implemented in a derived class.\n//template< class pos_t = rvec >\n//class particle_smoother_b : public particle_filter_b<pos_t> {\n//\n//\tint L;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t///< Lag size\n//\tparticles current;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t///< Current updated particles\n//\tdeque<particles> lagbuffer;\t\t\t\t\t\t\t\t\t\t\t\t\t///< Buffer with the updated particles within the lag\n//\n//\t/// Run one lag step\n//\tparticles smooth_one_step( const particles& filtered, const particles& lagged )\n//\t{\n////\t\tparticles rv = filtered;\n////\t\tfor( int i = 0; i < I; i++ )\n////\t\t\trv[i].weight *=\n//\t\treturn lagged;\n//\t}\n//\n//\t/// Run the backwards smoothing process\n//\tparticles smooth_backwards()\n//\t{\n//\t\tparticles lagged = current;\n//\t\tfor( int l = 0; l < L; l++ )\n//\t\t\tlagged = smooth_one_step( lagbuffer[l], lagged );\n//\t\treturn lagged;\n//\t}\n//\n//public:\n//\n//\t/// Constructor\n//\tparticle_smoother_b( int I_, int L_ ) :\n//\t\tparticle_filter_b(I_), L(L_) {};\n//\n//\t/// Filter one sample\n//\tpos_t operator()( const rvec& z ) override\n//\t{\n//\t\t// Initialize\n//\t\tif( !init_f )\n//\t\t\tinitialize();\n//\n//\t\t// Update buffer\n//\t\tif( (int)lagbuffer.size() == L )\n//\t\t\tlagbuffer.pop_back();\n//\t\tlagbuffer.emplace_front( current );\n//\n//\t\t// Filter\n//\t\tcurrent             = update( x, z );\n//\t\tparticles resampled = resample( current );\n//\t\tx                   = prediction( resampled );\n//\t\ttime++;\n//\n//\t\t// Smoothing\n//\t\tparticles xs = smooth_backwards();\n//\t\treturn mean( output(xs) );\n//\t}\n//};\n\n/// ML Kalman filter\nclass maximum_likelihood_kalman_filter_b {\n\n\t/// State type\n\tstruct state {\n\t\trvec x;\n\t\trmat P;\n\t};\n\n\trmat C;\n\trmat C_pseudoinverse;\n\n\tvirtual\n\tdouble logLF( const rvec& z, const rvec& x ) = 0;\n\n\tvirtual\n\trvec logLF_gradient( const rvec& z, const rvec& x )\n\t{\n\t\tauto loglf = [this,&z](const rvec&x){return logLF(z,x);};\n\t\treturn gradient( loglf, x );\n\t}\n\n\tvirtual\n\trvec output( const rvec& x )\n\t{\n\t\treturn x;\n\t}\n\n\t/// Maximum likelihood estimation.\n\t/// Returns the ML estimate in rv.x and the Hessian of the logLF in rv.P\n\tstate ml_estimate( const rvec& z, const rvec& guess=rvec() )\n\t{\n\t\t// Detect Rao-Blackwellization\n\t\tint L = s.x.size();\n\t\tint N = s.x.size();\n\t\tif( C_pseudoinverse.size1() * C_pseudoinverse.size2() > 0 )\n\t\t\tN = C_pseudoinverse.size2();\n\n\t\t// ML Estimation\n\t\tauto objfun  = [this,&z](const rvec&x){return -logLF(z,x);};\n\t\tauto objgrad = [this,&z](const rvec&x){return -logLF_gradient(z,x);};\n\t\toptimization::bfgs opt(N);\n\t\topt.set_objective( objfun, objgrad );\n\t\tif( guess.size() == 0 )\n\t\t\topt.guess = zeros(N);\n\t\telse\n\t\t\topt.guess = guess;\n\n//\t\t// Test derivatives\n//\t\trvec xt = randn(N);\n//\t\tcout << \"xtest = \" << xt << endl;\n//\t\topt.test_derivatives( xt );\n//\t\tcin.get();\n\n//\t\topt.stop_fincrement_relative = 1e-2;\n//\t\topt.stop_xincrement_relative = 1e-2;\n\t\trvec xh = opt.optimize();\n\n\t\t// Return value\n\t\tstate ml;\n\t\tml.x = { xh, zeros(L-N) };\n\t\tml.P = jacobian( objgrad, xh );\n\t\tml.P = ( ml.P + trans(ml.P) ) / 2;\n\t\tml.P = { { ml.P,         zeros(N,L-N)   },\n\t\t\t\t { zeros(L-N,N), zeros(L-N,L-N) } };\n\t\treturn ml;\n\t}\n\n\t/// Prediction step\n\tstate prediction( const state& s )\n\t{\n\t\tstate p;\n\t\tp.x = A * s.x;\n\t\tp.P = noproxy(A * s.P) * trans(A) + Q;\n\t\treturn p;\n\t}\n\n\t/// Update step\n\tstate update( const state& s, const rvec& z )\n\t{\n\t\t// ML estimate\n\t\tstate ml = ml_estimate( z, C*s.x );\n\n\t\t// Update the state\n\t\tstate u;\n\t\tu.P = inv( inv(s.P) + ml.P );\n\t\tu.x = u.P * ( linsolve( s.P, s.x ) + ml.P * ml.x );\n\t\treturn u;\n\t}\n\npublic:\n\n\tstate s;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t///< Current state\n\trmat A;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t///< State transition matrix\n\trmat Q;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t///< Process noise covariance\n\n\t/// Destructor\n\tvirtual\n\t~maximum_likelihood_kalman_filter_b() {}\n\n\tvoid set_C( const rmat& C_ )\n\t{\n\t\tC = C_;\n\t\tC_pseudoinverse = real(pinv(C));\n\t}\n\n\t/// Filter the sample z\n\trvec operator()( const rvec& z )\n\t{\n\t\ts = prediction( s );\n\t\ts = update( s, z );\n\t\treturn output(s.x);\n\t}\n\n\t/// Filter a vector of samples\n\tvec<rvec> operator()( const vec<rvec>& Z )\n\t{\n\t\tint T = Z.size();\n\t\tvec<rvec> Yh(T);\n\t\tfor( int t = 0; t < T; t++ )\n\t\t\tYh(t) = (*this)( Z(t) );\n\t\treturn Yh;\n\t}\n};\n\n/// @}\n}\n}\n#endif\n", "meta": {"hexsha": "ff56ec962e58872f876521a36aeee46279554f7e", "size": 16639, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/bealab/extensions/control/baytrack.hpp", "max_stars_repo_name": "damianmarelli/bealab", "max_stars_repo_head_hexsha": "3357a0b0fd836c3557f39863471680cc99721729", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-04-17T13:45:21.000Z", "max_stars_repo_stars_event_max_datetime": "2018-04-17T13:45:21.000Z", "max_issues_repo_path": "include/bealab/extensions/control/baytrack.hpp", "max_issues_repo_name": "damianmarelli/bealab", "max_issues_repo_head_hexsha": "3357a0b0fd836c3557f39863471680cc99721729", "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": "include/bealab/extensions/control/baytrack.hpp", "max_forks_repo_name": "damianmarelli/bealab", "max_forks_repo_head_hexsha": "3357a0b0fd836c3557f39863471680cc99721729", "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.8040057225, "max_line_length": 96, "alphanum_fraction": 0.6098323217, "num_tokens": 5148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147439, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.7305803323039742}}
{"text": "#include <iostream>\n#include <fstream>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include \"ceres/ceres.h\"\n#include \"glog/logging.h\"\n\nusing ceres::AutoDiffCostFunction;\nusing ceres::CostFunction;\nusing ceres::Problem;\nusing ceres::Solve;\nusing ceres::Solver;\n\nconst double DT = 1.0;\nconst Eigen::Vector3d GRAVITY{0, 0, -9.8};\n\nstruct State {\n  Eigen::Vector3d pos = Eigen::Vector3d::Random(); // position \n  Eigen::Vector3d vel = Eigen::Vector3d::Random(); // velocity\n  Eigen::Quaterniond q = Eigen::Quaterniond::UnitRandom(); // pose Qwr\n\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n};\n\nstruct Measurement{\n  Eigen::Matrix3d Rwr;\n  Eigen::Quaterniond qwr;\n  Eigen::Vector3d twr;\n  Eigen::Vector3d acc;\n  Eigen::Vector3d omega; \n\n  Measurement(Eigen::Matrix3d Rwr,                \n              Eigen::Quaterniond qwr,\n              Eigen::Vector3d twr,\n              Eigen::Vector3d acc,\n              Eigen::Vector3d omega)\n    : Rwr(Rwr), qwr(qwr), twr(twr), acc(acc), omega(omega) {}\n\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n};\n\nstruct PositionError {\n\tPositionError(const Eigen::Vector3d& pos_measured) \n\t\t: pos_measured_(pos_measured) {}\n\n\ttemplate <typename T>\n\tbool operator()(const T* const pos_hat_ptr,\n\t\t\t\t\t\t\t\t\tT* residuals_ptr) const {\n\t\tEigen::Matrix<T, 3, 1> pos_hat(pos_hat_ptr);\n\t\t// Eigen::Matrix<T, 3, 1> residuals(residuals_ptr);\n\t\t// residuals.template block<3, 1>(0, 0) = pos_hat - pos_measured_.template cast<T>();\n\t\tEigen::Matrix<T, 3, 1> pos_delta = pos_hat - pos_measured_.template cast<T>();\t\n\n    for (int i = 0; i < 3; i++) {\n      residuals_ptr[i] = pos_delta[i];\n    }\n\t\treturn true;\n\t}\n\n\tstatic CostFunction* Create(const Eigen::Vector3d& pos_measured) {\n\t\treturn new AutoDiffCostFunction<PositionError, 3, 3>(\n\t\t\tnew PositionError(pos_measured)\n\t\t);\n\t}\n\nEIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\nprivate:\n\tconst Eigen::Vector3d pos_measured_;\n};\n\nstruct PoseError {\n  PoseError(const Eigen::Vector3d& pos_measured,\n            const Eigen::Quaterniond& q_measured)\n    : pos_measured_(pos_measured), q_measured_(q_measured) {}\n\n  template <typename T>\n  bool operator()(const T* const pos_hat_ptr,\n                  const T* const q_hat_ptr,\n                  T* residuals_ptr) const {      \n    // Eigen::Matrix<T, 3, 1> pos_hat(pos_hat_ptr);\n\t\t// Eigen::Matrix<T, 3, 1> pos_delta = pos_hat - pos_measured_.template cast<T>();\n\n    // Eigen::Quaternion<T> q_hat(q_hat_ptr);\n    // Eigen::Quaternion<T> q_delta = q_hat.conjugate() * q_measured_.template cast<T>();\n\t\t// residuals_ptr[0] = pos_delta.norm() + T(2.0) * q_delta.vec().norm();\n\n\t\tEigen::Matrix<T, 6, 1> residuals;\n    Eigen::Matrix<T, 3, 1> pos_hat(pos_hat_ptr);\n\t\tresiduals.template block<3, 1>(0, 0) = pos_hat - pos_measured_.template cast<T>();\n\n    Eigen::Quaternion<T> q_hat(q_hat_ptr);\n    Eigen::Quaternion<T> q_delta = q_hat.conjugate() * q_measured_.template cast<T>();\n\t\tresiduals.template block<3, 1>(3, 0) = T(2.0) * q_delta.vec();\n    for (int i = 0; i < 6; i++) {\n      residuals_ptr[i] = residuals[i];\n    }\n\t\t\n\t\treturn true;\n  } \n  \n  static CostFunction* Create(const Eigen::Vector3d& pos_measured,\n                              const Eigen::Quaterniond& q_measured) {\n    return new AutoDiffCostFunction<PoseError, 6, 3, 4>(\n      new PoseError(pos_measured, q_measured));\n  }\n\nEIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\nprivate:\n  const Eigen::Vector3d pos_measured_;\n  const Eigen::Quaterniond q_measured_;\n};\n\n\nstd::vector<Measurement, Eigen::aligned_allocator<Measurement>> readSensorData(std::string path) {\n  std::vector<Measurement, Eigen::aligned_allocator<Measurement>> ret;\n\n  std::ifstream csvFile;\n  csvFile.open(path);\n\n  std::string line;\n  while(std::getline(csvFile, line)) {\n    std::vector<double> row;\n    std::cout << \"line:\" << line << std::endl;\n    std::istringstream s(line);\n    std::string field;\n    while (std::getline(s, field,',')) {\n      std::cout << \"field: \" << field << std::endl;\n      row.push_back(std::stod(field));\n    }  \n    Eigen::Matrix3d Rwr;\n    Eigen::Quaterniond qwr;\n    Eigen::Vector3d twr;\n    Eigen::Vector3d acc;\n    Eigen::Vector3d omega; \n    Rwr << row[0], row[1], row[2],\n          row[4], row[5], row[6],\n          row[8], row[9], row[10];\n    qwr = Rwr;\n    twr << row[3], row[7], row[11];\n    acc << row[16], row[17], row[18];\n    omega << row[19], row[20], row[21];\n    std::cout << \"Rwr: \" << Rwr << std::endl;\n    std::cout << \"qwr: \" << qwr.w() << \" \" << qwr.vec() << std::endl; \n    std::cout << \"twr: \" << twr << std::endl;\n    std::cout << \"acc: \" << acc << std::endl;\n    std::cout << \"omega: \" << omega << std::endl;\n    \n    ret.push_back(Measurement(Rwr, qwr, twr, acc, omega));\n  }\n\n  return ret;\n}\n\n\nvoid output_pose(const Eigen::Vector3d& pos, \n\t\t\t\t\t\t\t\t const Eigen::Quaterniond& q) {\n\tEigen::AngleAxisd ori(q);\n\n\tstd::cout << \"Location: \" << pos << std::endl;\n\tstd::cout << \"Orientation: \" << ori.angle() << \" * \" << std::endl << ori.axis() << std::endl;\n}\n\nvoid output_measurement(const Measurement& data) {\n  std::cout << \"\\nData State: \\n\" << \"R: \\n\" << data.Rwr << \"\\nt: \\n\" << data.twr \\\n            << \"\\nacc: \\n\" << data.acc << \"\\nomega: \\n\" << data.omega << std::endl;\n} \n\nint main(int argc, char** argv) {\n  if(argc < 2) {\n    std::cout << \"missing arg for the csv file\" << std::endl;\n  }\n\n  std::string path = argv[1];\n  std::vector<Measurement, Eigen::aligned_allocator<Measurement>> data = readSensorData(path);    \n\n   \n  output_measurement(data[0]);\n  output_measurement(data[1]);\n  output_measurement(data[2]);\n\n  return 0; \n\n  // int cnt = data.size();\n  int cnt = 2;\n\n  Eigen::Vector3d bias = Eigen::Vector3d::Random();\n  std::vector<State, Eigen::aligned_allocator<State>> states(cnt);\n  std::cout << \"states size: \" << states.size() << std::endl;\n  Problem problem;\n  \n  ceres::LossFunction* loss_function = nullptr;\n  ceres::LocalParameterization* quaternion_local_parameterization =\n      new ceres::EigenQuaternionParameterization;\n\n  cnt = 0;\n\n  Eigen::Vector3d pos1 = Eigen::Vector3d::Random(); // position \n\tEigen::Quaterniond q1 = Eigen::Quaterniond::UnitRandom(); // orientation\n\n\tstd::cout << \"Initial state: \" << std::endl;\n\toutput_pose(pos1, q1);\n\n\tceres::CostFunction* pose_cost_function = PoseError::Create(data[0].twr, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdata[0].qwr);\n\tproblem.AddResidualBlock(pose_cost_function, \n\t\t\t\t\t\t\t\t\t\t\t\t\t loss_function, \n\t\t\t\t\t\t\t\t\t\t\t\t\t pos1.data(), \n\t\t\t\t\t\t\t\t\t\t\t\t\t q1.coeffs().data());\n\t\n\t// for (auto& measure : data) {\n  //   ceres::CostFunction* pos_cost_function = PoseError::Create(measure.twr, measure.qwr);\n  //   problem.AddResidualBlock(pos_cost_function,\n  //                            loss_function,\n  //                            states[cnt].pos.data(),\n  //                            states[cnt].q.coeffs().data());\n  //   problem.SetParameterization(states[cnt].q.coeffs().data(),\n  //                               quaternion_local_parameterization);      \n\n\t// \t// ceres::CostFunction* position_cost_function = PositionError::Create(measure.twr);\n\t// \t// problem.AddResidualBlock(position_cost_function, loss_function, states[cnt].pos.data());\n\t//   cnt++;\n  //   if (cnt >= states.size()) {\n  //     break;\n  //   }\n  // } \n\n  ceres::Solver::Options options;\n\toptions.max_num_iterations = 20;\n  options.linear_solver_type = ceres::DENSE_SCHUR;\n  // options.linear_solver_type = ceres::SPARSE_NORMAL_CHOLESKY;\n  options.minimizer_progress_to_stdout = true;\n\n  ceres::Solver::Summary summary;\n  ceres::Solve(options, &problem, &summary);\n  std::cout << summary.FullReport() << \"\\n\";\n\n\tstd::cout << \"Ground Truth: \" << std::endl;\n\toutput_pose(data[0].twr, data[0].qwr);\n\tstd::cout << \"Final State: \" << std::endl;\n\toutput_pose(pos1, q1);\n\n  output_measurement(data[0]);\n  output_measurement(data[1]);\n  output_measurement(data[2]);\n\n  return 0;\n}", "meta": {"hexsha": "a8e30ccce21bd2c80f4d78d6231a41f02db77057", "size": 7774, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "experimental/simple_solver.cpp", "max_stars_repo_name": "yimuw/expriment", "max_stars_repo_head_hexsha": "5c4185d969556e7ec007aceaf0eb82f7e79f8abb", "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": "experimental/simple_solver.cpp", "max_issues_repo_name": "yimuw/expriment", "max_issues_repo_head_hexsha": "5c4185d969556e7ec007aceaf0eb82f7e79f8abb", "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": "experimental/simple_solver.cpp", "max_forks_repo_name": "yimuw/expriment", "max_forks_repo_head_hexsha": "5c4185d969556e7ec007aceaf0eb82f7e79f8abb", "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": 31.096, "max_line_length": 98, "alphanum_fraction": 0.628505274, "num_tokens": 2252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418283357703, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.7305621294895845}}
{"text": "\n#include <cmath>\n#include <cassert>\n#include <boost/math/special_functions/gamma.hpp>\n\n#include \"StudentTPrior.h\"\n\nnamespace Grante {\n\nconst double StudentTPrior::pi = 3.14159265358979323846;\n\nStudentTPrior::StudentTPrior(double dof, double sigma, unsigned int dim)\n\t: dof(dof), sigma(sigma) {\n\t// Precompute two constants\n\tdouble d = static_cast<double>(dim);\n\tlogp_constant1 = -boost::math::lgamma(0.5*(dof+d))\n\t\t+ boost::math::lgamma(0.5*dof) + 0.5*d*std::log(dof*pi)\n\t\t+ d*log(sigma);\n\tlogp_constant2 = dof + d;\n}\n\nStudentTPrior::~StudentTPrior() {\n}\n\n// -log p(w) = -log Gamma((dof + dim)/2) + log Gamma(dof/2)\n//             + (dim/2)*log(dof * pi) + dim*log(sigma)\n//             + ((dof + dim)/2)*log(1 + (1/(dof*sigma^2))*w'*w)\n// \\nabla_w -log p(w) = ((dof+dim)/(dof*sigma^2))\n//             * (1/(1+(1/(dof*sigma^2))*w'*w)) * w.\ndouble StudentTPrior::EvaluateNegLogP(const std::vector<double>& w,\n\tstd::vector<double>& grad, double scale) const {\n\tif (grad.empty() == false) {\n\t\tassert(w.size() == grad.size());\n\t}\n\tdouble xnorm = 0.0;\n\tfor (unsigned int d = 0; d < w.size(); ++d)\n\t\txnorm += w[d]*w[d];\n\n\tdouble nlogp = 1.0 + xnorm/(dof*sigma*sigma);\n\tdouble scale2 = (logp_constant2 / (dof*sigma*sigma)) / nlogp;\n\tif (grad.empty() == false) {\n\t\tfor (unsigned int d = 0; d < w.size(); ++d)\n\t\t\tgrad[d] += scale * scale2 * w[d];\n\t}\n\n\tdouble res = 0.5*logp_constant2*std::log(nlogp) + logp_constant1;\n\treturn (scale * res);\n}\n\n}\n\n", "meta": {"hexsha": "bc58c285313cc2e33ec1b3b71b09ac0fc1798ca0", "size": 1439, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "grante/StudentTPrior.cpp", "max_stars_repo_name": "pantonante/grante-bazel", "max_stars_repo_head_hexsha": "e3f22ec111463a7ae0686494422ab09f86b4d39a", "max_stars_repo_licenses": ["DOC"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "grante/StudentTPrior.cpp", "max_issues_repo_name": "pantonante/grante-bazel", "max_issues_repo_head_hexsha": "e3f22ec111463a7ae0686494422ab09f86b4d39a", "max_issues_repo_licenses": ["DOC"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "grante/StudentTPrior.cpp", "max_forks_repo_name": "pantonante/grante-bazel", "max_forks_repo_head_hexsha": "e3f22ec111463a7ae0686494422ab09f86b4d39a", "max_forks_repo_licenses": ["DOC"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6730769231, "max_line_length": 72, "alphanum_fraction": 0.6136205698, "num_tokens": 498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418158002492, "lm_q2_score": 0.7905303162021596, "lm_q1q2_score": 0.730562121860209}}
{"text": "// find_root_example.cpp\r\n\r\n// Copyright Paul A. Bristow 2007, 2010.\r\n\r\n// Use, modification and distribution are subject to the\r\n// Boost Software License, Version 1.0.\r\n// (See accompanying file LICENSE_1_0.txt\r\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n// Example of using root finding.\r\n\r\n// Note that this file contains Quickbook mark-up as well as code\r\n// and comments, don't change any of the special comment mark-ups!\r\n\r\n//[root_find1\r\n/*`\r\nFirst we need some includes to access the normal distribution\r\n(and some std output of course).\r\n*/\r\n\r\n#include <boost/math/tools/roots.hpp> // root finding.\r\n\r\n#include <boost/math/distributions/normal.hpp> // for normal_distribution\r\n  using boost::math::normal; // typedef provides default type is double.\r\n\r\n#include <iostream>\r\n  using std::cout; using std::endl; using std::left; using std::showpoint; using std::noshowpoint;\r\n#include <iomanip>\r\n  using std::setw; using std::setprecision;\r\n#include <limits>\r\n  using std::numeric_limits;\r\n#include <stdexcept>\r\n  using std::exception;\r\n\r\n//] //[/root_find1]\r\n  \r\nint main()\r\n{\r\n  cout << \"Example: Normal distribution, root finding.\";\r\n  try\r\n  {\r\n\r\n//[root_find2\r\n\r\n/*`A machine is set to pack 3 kg of ground beef per pack.  \r\nOver a long period of time it is found that the average packed was 3 kg\r\nwith a standard deviation of 0.1 kg.  \r\nAssuming the packing is normally distributed,\r\nwe can find the fraction (or %) of packages that weigh more than 3.1 kg.\r\n*/\r\n\r\ndouble mean = 3.; // kg\r\ndouble standard_deviation = 0.1; // kg\r\nnormal packs(mean, standard_deviation);\r\n\r\ndouble max_weight = 3.1; // kg\r\ncout << \"Percentage of packs > \" << max_weight << \" is \"\r\n<< cdf(complement(packs, max_weight)) << endl; // P(X > 3.1)\r\n\r\ndouble under_weight = 2.9;\r\ncout <<\"fraction of packs <= \" << under_weight << \" with a mean of \" << mean \r\n  << \" is \" << cdf(complement(packs, under_weight)) << endl;\r\n// fraction of packs <= 2.9 with a mean of 3 is 0.841345\r\n// This is 0.84 - more than the target 0.95\r\n// Want 95% to be over this weight, so what should we set the mean weight to be?\r\n// KK StatCalc says:\r\ndouble over_mean = 3.0664;\r\nnormal xpacks(over_mean, standard_deviation);\r\ncout << \"fraction of packs >= \" << under_weight\r\n<< \" with a mean of \" << xpacks.mean() \r\n  << \" is \" << cdf(complement(xpacks, under_weight)) << endl;\r\n// fraction of packs >= 2.9 with a mean of 3.06449 is 0.950005\r\ndouble under_fraction = 0.05;  // so 95% are above the minimum weight mean - sd = 2.9\r\ndouble low_limit = standard_deviation;\r\ndouble offset = mean - low_limit - quantile(packs, under_fraction);\r\ndouble nominal_mean = mean + offset;\r\n\r\nnormal nominal_packs(nominal_mean, standard_deviation);\r\ncout << \"Setting the packer to \" << nominal_mean << \" will mean that \"\r\n  << \"fraction of packs >= \" << under_weight \r\n  << \" is \" << cdf(complement(nominal_packs, under_weight)) << endl;\r\n\r\n/*`\r\nSetting the packer to 3.06449 will mean that fraction of packs >= 2.9 is 0.95.\r\n\r\nSetting the packer to 3.13263 will mean that fraction of packs >= 2.9 is 0.99,\r\nbut will more than double the mean loss from 0.0644 to 0.133.\r\n\r\nAlternatively, we could invest in a better (more precise) packer with a lower standard deviation.\r\n\r\nTo estimate how much better (how much smaller standard deviation) it would have to be,\r\nwe need to get the 5% quantile to be located at the under_weight limit, 2.9\r\n*/\r\ndouble p = 0.05; // wanted p th quantile.\r\ncout << \"Quantile of \" << p << \" = \" << quantile(packs, p)\r\n  << \", mean = \" << packs.mean() << \", sd = \" << packs.standard_deviation() << endl; // \r\n/*`\r\nQuantile of 0.05 = 2.83551, mean = 3, sd = 0.1\r\n\r\nWith the current packer (mean = 3, sd = 0.1), the 5% quantile is at 2.8551 kg,\r\na little below our target of 2.9 kg.\r\nSo we know that the standard deviation is going to have to be smaller.\r\n\r\nLet's start by guessing that it (now 0.1) needs to be halved, to a standard deviation of 0.05\r\n*/\r\nnormal pack05(mean, 0.05); \r\ncout << \"Quantile of \" << p << \" = \" << quantile(pack05, p) \r\n  << \", mean = \" << pack05.mean() << \", sd = \" << pack05.standard_deviation() << endl;\r\n\r\ncout <<\"Fraction of packs >= \" << under_weight << \" with a mean of \" << mean \r\n  << \" and standard deviation of \" << pack05.standard_deviation()\r\n  << \" is \" << cdf(complement(pack05, under_weight)) << endl;\r\n// \r\n/*`\r\nFraction of packs >= 2.9 with a mean of 3 and standard deviation of 0.05 is 0.9772\r\n\r\nSo 0.05 was quite a good guess, but we are a little over the 2.9 target,\r\nso the standard deviation could be a tiny bit more. So we could do some\r\nmore guessing to get closer, say by increasing to 0.06\r\n*/\r\n\r\nnormal pack06(mean, 0.06); \r\ncout << \"Quantile of \" << p << \" = \" << quantile(pack06, p) \r\n  << \", mean = \" << pack06.mean() << \", sd = \" << pack06.standard_deviation() << endl;\r\n\r\ncout <<\"Fraction of packs >= \" << under_weight << \" with a mean of \" << mean \r\n  << \" and standard deviation of \" << pack06.standard_deviation()\r\n  << \" is \" << cdf(complement(pack06, under_weight)) << endl;\r\n/*`\r\nFraction of packs >= 2.9 with a mean of 3 and standard deviation of 0.06 is 0.9522\r\n\r\nNow we are getting really close, but to do the job properly,\r\nwe could use root finding method, for example the tools provided, and used elsewhere,\r\nin the Math Toolkit, see\r\n[link math_toolkit.toolkit.internals1.roots2  Root Finding Without Derivatives].\r\n\r\nBut in this normal distribution case, we could be even smarter and make a direct calculation.\r\n*/\r\n//] [/root_find2]\r\n\r\n  }\r\n  catch(const std::exception& e)\r\n  { // Always useful to include try & catch blocks because default policies \r\n    // are to throw exceptions on arguments that cause errors like underflow, overflow. \r\n    // Lacking try & catch blocks, the program will abort without a message below,\r\n    // which may give some helpful clues as to the cause of the exception.\r\n    std::cout <<\r\n      \"\\n\"\"Message from thrown exception was:\\n   \" << e.what() << std::endl;\r\n  }\r\n  return 0;\r\n}  // int main()\r\n\r\n/*\r\nOutput is:\r\n\r\n//[root_find_output\r\n\r\nAutorun \"i:\\boost-06-05-03-1300\\libs\\math\\test\\Math_test\\debug\\find_root_example.exe\"\r\nExample: Normal distribution, root finding.Percentage of packs > 3.1 is 0.158655\r\nfraction of packs <= 2.9 with a mean of 3 is 0.841345\r\nfraction of packs >= 2.9 with a mean of 3.0664 is 0.951944\r\nSetting the packer to 3.06449 will mean that fraction of packs >= 2.9 is 0.95\r\nQuantile of 0.05 = 2.83551, mean = 3, sd = 0.1\r\nQuantile of 0.05 = 2.91776, mean = 3, sd = 0.05\r\nFraction of packs >= 2.9 with a mean of 3 and standard deviation of 0.05 is 0.97725\r\nQuantile of 0.05 = 2.90131, mean = 3, sd = 0.06\r\nFraction of packs >= 2.9 with a mean of 3 and standard deviation of 0.06 is 0.95221\r\n\r\n//] [/root_find_output]\r\n*/\r\n", "meta": {"hexsha": "d53cc93ebdd61cbb7a20ee058fccfea9a7e456d0", "size": 6752, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/example/find_root_example.cpp", "max_stars_repo_name": "jmuskaan72/Boost", "max_stars_repo_head_hexsha": "047e36c01841a8cd6a5c74d4e3034da46e327bc1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "libs/math/example/find_root_example.cpp", "max_issues_repo_name": "xiaoliang2121/Boost", "max_issues_repo_head_hexsha": "fc90c3fde129c62565c023f091eddc4a7ed9902b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-03-19T08:23:23.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-24T07:48:47.000Z", "max_forks_repo_path": "libs/math/example/find_root_example.cpp", "max_forks_repo_name": "xiaoliang2121/Boost", "max_forks_repo_head_hexsha": "fc90c3fde129c62565c023f091eddc4a7ed9902b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 39.485380117, "max_line_length": 99, "alphanum_fraction": 0.6713566351, "num_tokens": 1929, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.8615382058759129, "lm_q1q2_score": 0.7305566211934517}}
{"text": "#ifndef MLT_UTILS_LINEAR_ALGEBRA_HPP\n#define MLT_UTILS_LINEAR_ALGEBRA_HPP\n\n#include <algorithm>\n#include <limits>\n\n#include <Eigen/Core>\n#include <Eigen/SVD>\n\n#include \"../defs.hpp\"\n\nnamespace mlt {\nnamespace utils {\nnamespace linear_algebra {\n\t// Moore-Penrose pseudoinverse\n\tinline auto pseudo_inverse(MatrixXdRef x) {\n\t\tauto svd = x.jacobiSvd(ComputeThinU | ComputeThinV);\n\n\t\tauto tolerance = numeric_limits<double>::epsilon() * max(x.rows(), x.cols()) * svd.singularValues().maxCoeff();\n\t\t\n\t\treturn (svd.matrixV() * svd.singularValues().unaryExpr([=](double s) { return (s < tolerance) ? 0 : 1 / s; }).eval().asDiagonal() * svd.matrixU().transpose()).eval();\n\t}\n\n\tinline auto covariance(MatrixXdRef x, MatrixXdRef y) {\n\t\tassert(x.cols() == y.cols());\n\t\tconst auto num_observations = static_cast<double>(x.cols());\n\t\treturn ((x.colwise() - (x.rowwise().sum() / num_observations)) * (y.colwise() - (y.rowwise().sum() / num_observations)).transpose() / num_observations).eval();\n\t}\n\n\tinline auto linear_transformation(MatrixXdRef x, MatrixXdRef w) {\n\t\treturn (w * x).eval();\n\t}\n\n\tinline auto linear_transformation(MatrixXdRef x, MatrixXdRef w, VectorXdRef b) {\n\t\treturn ((w * x).colwise() + b).eval();\n\t}\n}\n}\n}\n#endif", "meta": {"hexsha": "3a7c366f4b1093436a043fe49a56e7f3d4645e14", "size": 1218, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/mlt/utils/linear_algebra.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/linear_algebra.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/linear_algebra.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": 30.45, "max_line_length": 168, "alphanum_fraction": 0.6954022989, "num_tokens": 342, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693674025231, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.7303719522735002}}
{"text": "// Copyright (c) 2005-2009  INRIA Sophia-Antipolis (France).\n// All rights reserved.\n//\n// This file is part of CGAL (www.cgal.org)\n//\n// $URL$\n// $Id$\n// SPDX-License-Identifier: LGPL-3.0-or-later OR LicenseRef-Commercial\n//\n//\n// Author(s)     : Sebastien Loriot, Sylvain Pion\n\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <boost/format.hpp>\n#include <CGAL/CGAL_Ipelet_base.h>\n#include <algorithm>\n#include <CGAL/point_generators_2.h>\n#include <CGAL/copy_n.h>\n#include <CGAL/random_selection.h>\n#include <CGAL/random_convex_set_2.h>\n#include <CGAL/random_polygon_2.h>\n#include <CGAL/Polygon_2.h>\n#include <CGAL/Join_input_iterator.h>\n#include <CGAL/function_objects.h>\n#include <CGAL/copy_n.h>\n\n\nnamespace CGAL_generator{\n\n\nconst std::string sublabel[] ={\n  \"Points in a disk\",\"Points on a grid\",\"Points in a square\",\"Points on a convex hull\",\"Polygon\",\"Segments in a square\", \"Circles (center in a square)\",\"Help\"\n};\n\nconst std::string hlpmsg[] ={\n\"Generate random inputs. You have to specify the size of the bounding box and the number of elements\"};\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel               Kernel;\n\nstruct generator\n  : CGAL::Ipelet_base<Kernel,8>\n{\n  typedef CGAL::Creator_uniform_2<Kernel::FT,Point_2>                     Creator;\n  typedef CGAL::Random_points_in_square_2<Point_2,Creator>                Point_generator;\n  typedef CGAL::Creator_uniform_2<Kernel::FT,Point_2>                     Pt_creator;\n\n  generator()\n    : CGAL::Ipelet_base<Kernel,8>(\"Generators\",sublabel, hlpmsg){};\n  void protected_run(int);\n};\n\n\nvoid generator::protected_run(int fn)\n{\n  if (fn==7) {\n    show_help(false);\n    return;\n  }\n\n  std::list<Point_2> pt_list;\n  std::list<Circle_2> cir_list;\n\n  Iso_rectangle_2 bbox=\n  read_active_objects(\n                      CGAL::dispatch_or_drop_output<Point_2,Circle_2>(\n      std::back_inserter(pt_list),\n      std::back_inserter(cir_list)\n    )\n  );\n\n  Kernel::Vector_2 origin;\n  double size=200;\n  int ret_val;\n\n\n  if (fn==0){\n    if (cir_list.size()==0) { print_error_message((\"Selection must be a circle\")); return;}\n    Circle_2  circ=*cir_list.begin();\n    size =  sqrt(circ.squared_radius());\n    origin= circ.center()-CGAL::ORIGIN;\n  }else{\n    size = (bbox.xmax()-bbox.xmin())/2;\n    origin= Kernel::Vector_2((bbox.xmin()+bbox.xmax())/2,(bbox.ymin()+bbox.ymax())/2);\n    if (size<1){\n      size=200;\n      //boost::tie(ret_val,size)=request_value_from_user<int>((boost::format(\"Size (default : %1%)\") % size).str());\n      //if (ret_val == -1) return;\n      //if (ret_val == 0) size=200;\n      origin =  Kernel::Vector_2(200,200);\n    }\n  }\n\n  int nbelements=30;\n\n  boost::tie(ret_val,nbelements)=request_value_from_user<int>((boost::format(\"Number of elements (default : %1%)\") % nbelements).str() );\n  if (ret_val == -1) return;\n  if (ret_val == 0) nbelements=30;\n\n\n  if(nbelements < 3){\n    print_error_message(\"Not a good value\");\n    return;\n  }\n\n  std::vector<Point_2> points;\n  std::vector<Segment_2> segments;\n\n  if (fn==5)\n    points.reserve(nbelements);\n  else\n    segments.reserve(nbelements);\n\n  get_IpePage()->deselectAll();\n\n  switch(fn){\n    case 0:{//random point in a circle\n      CGAL::Random_points_in_disc_2<Point_2,Creator> gs( size);\n      std::copy_n( gs, nbelements, std::back_inserter(points));\n      }\n    break;\n\n    case 1://random point on a grid\n    points_on_square_grid_2( size, nbelements, std::back_inserter(points),Creator());\n    break;\n\n    case 6:\n    case 2://points in a square : side =\n    {CGAL::Random_points_in_square_2<Point_2, Creator> gc (size);\n    std::copy_n( gc, nbelements, std::back_inserter(points));\n    }\n    break;\n\n    case 3:{//draw random set of point on a convex hull\n       CGAL::random_convex_set_2(nbelements, std::back_inserter(points),\n        Point_generator( size));\n    }\n    break;\n\n\n    case 4:\n      // create k-gon and write it into a window:\n      CGAL::random_polygon_2(nbelements, std::back_inserter(points),Point_generator(size));\n      for ( std::vector<Point_2>::iterator it=points.begin(); it!=points.end(); ++it) *it = *it + origin;\n      draw_polyline_in_ipe(points.begin(),points.end(),true);\n      return;\n\n    case 5://Random segments\n    typedef CGAL::Random_points_in_square_2<Point_2, Creator> P1;\n    typedef CGAL::Random_points_in_square_2<Point_2, Creator> P2;\n\n    P1 p1 (size);\n    P2 p2 (size);\n    typedef CGAL::Creator_uniform_2< Point_2, Segment_2> Seg_creator;\n    typedef CGAL::Join_input_iterator_2< P1, P2, Seg_creator> Seg_iterator;\n    Seg_iterator g( p1, p2);\n    std::copy_n( g, nbelements, std::back_inserter(segments) );\n    break;\n  };\n\n  if (fn==6){\n    CGAL::Random random;\n    for (std::vector<Point_2>::iterator it_pt=points.begin();it_pt!=points.end();++it_pt)\n      draw_in_ipe(Circle_2(*it_pt+origin,pow(random.get_double(size/20.,size/2.),2) ));\n    group_selected_objects_();\n  }\n  else\n    if (!points.empty()){// Translate and draw points\n      for ( std::vector<Point_2>::iterator it=points.begin(); it!=points.end(); ++it) *it = *it + origin;\n      draw_in_ipe(points.begin(),points.end());\n    }\n    else\n      if (!segments.empty()){// Translate and draw segments\n        for ( std::vector<Segment_2>::iterator it=segments.begin(); it!=segments.end(); ++it)\n          *it = Segment_2( it->source() + origin, it->target() + origin);\n        draw_in_ipe(segments.begin(),segments.end());\n      }\n}\n\n}\n\nCGAL_IPELET(CGAL_generator::generator)\n", "meta": {"hexsha": "92104a15cffe98bc0279f8cead1af6172e4bf038", "size": 5469, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CGAL_ipelets/demo/CGAL_ipelets/generator.cpp", "max_stars_repo_name": "ffteja/cgal", "max_stars_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 3227.0, "max_stars_repo_stars_event_min_datetime": "2015-03-05T00:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:20:35.000Z", "max_issues_repo_path": "CGAL_ipelets/demo/CGAL_ipelets/generator.cpp", "max_issues_repo_name": "ffteja/cgal", "max_issues_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 5574.0, "max_issues_repo_issues_event_min_datetime": "2015-03-05T00:01:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:08:11.000Z", "max_forks_repo_path": "CGAL_ipelets/demo/CGAL_ipelets/generator.cpp", "max_forks_repo_name": "ffteja/cgal", "max_forks_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1274.0, "max_forks_repo_forks_event_min_datetime": "2015-03-05T00:01:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:47:56.000Z", "avg_line_length": 30.0494505495, "max_line_length": 158, "alphanum_fraction": 0.6624611446, "num_tokens": 1569, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.89330940889474, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7303469740413108}}
{"text": "#include <Eigen/Eigen>\n#include <iostream>\n\n#ifndef M_PI\n#define M_PI 3.1415926535897932384626433832795\n#endif\n\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  Matrix3f m = Matrix3f::Random();\nMatrix3f y = Matrix3f::Random();\ncout << \"Here is the matrix m:\" << endl << m << endl;\ncout << \"Here is the matrix y:\" << endl << y << endl;\nMatrix3f x;\nx = m.fullPivHouseholderQr().solve(y);\nassert(y.isApprox(m*x));\ncout << \"Here is a solution x to the equation mx=y:\" << endl << x << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "112e6b9ad766752d2e4abe834093b37204d29677", "size": 545, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "third_party/eigen-eigen-50812b426b7c/build_dir/doc/snippets/compile_FullPivHouseholderQR_solve.cpp", "max_stars_repo_name": "shishaochen/TensorFlow-0.8-Win", "max_stars_repo_head_hexsha": "63221dfc4f1a1d064308e632ba12e6a54afe1fd8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-09-14T23:59:05.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-14T23:59:05.000Z", "max_issues_repo_path": "third_party/eigen-eigen-50812b426b7c/build_dir/doc/snippets/compile_FullPivHouseholderQR_solve.cpp", "max_issues_repo_name": "shishaochen/TensorFlow-0.8-Win", "max_issues_repo_head_hexsha": "63221dfc4f1a1d064308e632ba12e6a54afe1fd8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-10-19T02:43:04.000Z", "max_issues_repo_issues_event_max_datetime": "2016-10-31T14:53:06.000Z", "max_forks_repo_path": "third_party/eigen-eigen-50812b426b7c/build_dir/doc/snippets/compile_FullPivHouseholderQR_solve.cpp", "max_forks_repo_name": "shishaochen/TensorFlow-0.8-Win", "max_forks_repo_head_hexsha": "63221dfc4f1a1d064308e632ba12e6a54afe1fd8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2016-10-23T00:50:02.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-21T11:11:57.000Z", "avg_line_length": 20.9615384615, "max_line_length": 74, "alphanum_fraction": 0.6660550459, "num_tokens": 164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9207896715436483, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.7302837727930047}}
{"text": "#ifndef MOCHIMOCHI_SCW_HPP_\n#define MOCHIMOCHI_SCW_HPP_\n\n#include <Eigen/Dense>\n#include <boost/math/special_functions/erf.hpp>\n#include <boost/serialization/serialization.hpp>\n#include <boost/serialization/nvp.hpp>\n#include <boost/serialization/split_member.hpp>\n#include <boost/serialization/vector.hpp>\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n#include <fstream>\n#include \"../../functions/enumerate.hpp\"\n\nclass SCW {\nprivate :\n  const std::size_t kDim;\n  const double kC;\n  const double kPhi;\n\nprivate :\n  Eigen::VectorXd _covariances;\n  Eigen::VectorXd _means;\n\nprivate :\n  inline double cdf(const double x) const {\n    return 0.5 * (1.0 + boost::math::erf(x / std::sqrt(2.0)));\n  }\n\npublic :\n  SCW(const std::size_t dim, const double c, const double eta)\n    : kDim(dim),\n      kC(c),\n      kPhi(cdf(eta)),\n      _covariances(Eigen::VectorXd::Ones(kDim)),\n      _means(Eigen::VectorXd::Zero(kDim)) {\n\n    static_assert(std::numeric_limits<decltype(dim)>::max() > 0, \"Dimension Error. (Dimension > 0)\");\n    static_assert(std::numeric_limits<decltype(c)>::max() > 0, \"Hyper Parameter Error. (c > 0)\");\n    static_assert(std::numeric_limits<decltype(eta)>::max() > 0, \"Hyper Parameter Error. (\u03b7 > 0)\");\n    assert(dim > 0);\n    assert(c > 0);\n    assert(eta > 0);\n  }\n\n  virtual ~SCW() { }\n\nprivate :\n\n  double suffer_loss(const Eigen::VectorXd& f, const int label) const {\n    const auto confidence = compute_confidence(f);\n    return std::max(0.0, kPhi * std::sqrt(confidence) - label * _means.dot(f));\n  }\n\n  //Proposition 1\n  double compute_alpha(const double m, const double n, const double v, const double ganma) const {\n    const auto psi = 1.0 + kPhi * kPhi / 2.0;\n    const auto zeta = 1.0 + kPhi * kPhi;\n    const auto tmp1 = -m * psi + std::sqrt(m * m * std::pow(kPhi, 4.0) / 4.0 + v * kPhi * kPhi * zeta);\n    const auto tmp2 = 1.0 / v * zeta * tmp1;\n    return std::min(kC, std::max(0.0, tmp2));\n  }\n\n  double compute_beta(const double alpha, const double v) const {\n    const auto u = std::pow(-alpha * v * kPhi + std::sqrt(alpha * alpha * v * v * kPhi * kPhi + 4.0 * v), 2.0) / 4.0;\n    return alpha * kPhi / (std::sqrt(u) + v * alpha * kPhi);\n  }\n\n  double compute_confidence(const Eigen::VectorXd& f) const {\n    auto confidence = 0.0;\n    functions::enumerate(f.data(), f.data() + f.size(), 0,\n                       [&](const int index, const double value) {\n                         confidence += _covariances[index] * value * value;\n                       });\n    return confidence;\n  }\n\npublic :\n\n  bool update(const Eigen::VectorXd& feature, const int label) {\n    const auto v = compute_confidence(feature);\n    const auto m = label * _means.dot(feature);\n    const auto n = v + 1.0 / 2.0 * kC;\n    const auto ganma = kPhi * std::sqrt(kPhi * kPhi * m * m * v * v + 4.0 * n * v * (n + v * kPhi * kPhi));\n    const auto alpha = compute_alpha(m, n, v, ganma);\n    const auto beta = compute_beta(alpha, ganma);\n\n    if (suffer_loss(feature, label) <= 0.0) { return false; }\n\n    functions::enumerate(feature.data(), feature.data() + feature.size(), 0,\n                       [&](const int index, const double value) {\n                         const auto v = _covariances[index] * value;\n                         _means[index] += alpha * label * v;\n                         _covariances[index] -= beta * v * v;\n                       });\n\n    return true;\n  }\n\n  int predict(const Eigen::VectorXd& x) {\n    return _means.dot(x) < 0.0 ? -1 : 1;\n  }\n\n  Eigen::VectorXd get_means(void) const {\n    return _means;\n  }\n\n  void save(const std::string& filename) {\n    std::ofstream ofs(filename);\n    assert(ofs);\n    boost::archive::text_oarchive oa(ofs);\n    oa << *this;\n    ofs.close();\n  }\n\n  void load(const std::string& filename) {\n    std::ifstream ifs(filename);\n    assert(ifs);\n    boost::archive::text_iarchive ia(ifs);\n    ia >> *this;\n    ifs.close();\n  }\n\nprivate :\n  friend class boost::serialization::access;\n  BOOST_SERIALIZATION_SPLIT_MEMBER();\n  template <class Archive>\n  void save(Archive& ar, const unsigned int version) const {\n    std::vector<double> covariances_vector(_covariances.data(), _covariances.data() + _covariances.size());\n    std::vector<double> means_vector(_means.data(), _means.data() + _means.size());\n    ar & boost::serialization::make_nvp(\"covariances\", covariances_vector);\n    ar & boost::serialization::make_nvp(\"means\", means_vector);\n    ar & boost::serialization::make_nvp(\"dimension\", const_cast<std::size_t&>(kDim));\n    ar & boost::serialization::make_nvp(\"phi\", const_cast<double&>(kPhi));\n    ar & boost::serialization::make_nvp(\"c\", const_cast<double&>(kC));\n  }\n\n  template <class Archive>\n  void load(Archive& ar, const unsigned int version) {\n    std::vector<double> covariances_vector;\n    std::vector<double> means_vector;\n    ar & boost::serialization::make_nvp(\"covariances\", covariances_vector);\n    ar & boost::serialization::make_nvp(\"means\", means_vector);\n    ar & boost::serialization::make_nvp(\"dimension\", const_cast<std::size_t&>(kDim));\n    ar & boost::serialization::make_nvp(\"phi\", const_cast<double&>(kPhi));\n    ar & boost::serialization::make_nvp(\"c\", const_cast<double&>(kC));\n    _covariances = Eigen::Map<Eigen::VectorXd>(&covariances_vector[0], covariances_vector.size());\n    _means = Eigen::Map<Eigen::VectorXd>(&means_vector[0], means_vector.size());\n  }\n\n};\n\n#endif //MOCHIMOCHI_SCW_HPP_\n", "meta": {"hexsha": "3e4b4983a630822a4ff703293001d2e004aa6693", "size": 5436, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mochimochi/classifier/binary/scw.hpp", "max_stars_repo_name": "olanleed/MochiMochi", "max_stars_repo_head_hexsha": "830d361fa352f6ac336ec97a80588018c8164916", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2015-05-17T04:33:04.000Z", "max_stars_repo_stars_event_max_datetime": "2016-07-02T11:18:58.000Z", "max_issues_repo_path": "mochimochi/classifier/binary/scw.hpp", "max_issues_repo_name": "olanleed/MochiMochi", "max_issues_repo_head_hexsha": "830d361fa352f6ac336ec97a80588018c8164916", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2015-05-24T10:14:03.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-23T14:40:08.000Z", "max_forks_repo_path": "mochimochi/classifier/binary/scw.hpp", "max_forks_repo_name": "olanleed/MochiMochi", "max_forks_repo_head_hexsha": "830d361fa352f6ac336ec97a80588018c8164916", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-30T13:10:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-30T13:10:29.000Z", "avg_line_length": 35.2987012987, "max_line_length": 117, "alphanum_fraction": 0.6372332597, "num_tokens": 1519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896715436482, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.7302837682901311}}
{"text": "#include <iostream>\n#include <numeric>\n#include <type.hpp>\n\n#include <Eigen/Eigen>\n\n#include \"FEM/FEM1DApp.hpp\"\n#include \"imgui/implot.h\"\n#include \"Visualization/Visualizer.h\"\n\n#include <numeric>\n\nusing Linear = PolynomialFEMApp<1>;\nusing Quadratic = PolynomialFEMApp<2>;\n\nusing LinearDG = PolynomialFEMAppSD<1>;\nusing QuadraticDG = PolynomialFEMAppSD<2>;\n\nclass FEM1DVisualizer :public Visualizer\n{\nprotected:\n\n\tvoid evaluate()\n\t{\n\t\tint segement_ = segemnt;\n\n\t\t//Homework 2\n\t\t//auto rhs = [](Float x) {return  -4 - x + Power(x, 2) - Power(x, 3) + Power(x, 4) + Cos(x) - 2 * x * Cos(x) - 2 * Sin(x); };\n\t\t//auto a = [](Float x) {return sin(x) + 2; };\n\t\t//auto c = [](Float x) {return x * x + 1; };\n\t\tauto rhs = [](Float x) {return  x; };\n\t\tauto d = [this](Float x) {return epsilon; };\n\t\tauto b = [](Float x) {return 1;\t};\n\t\tauto c = [](Float x) {return 0; };\n\n\t\tInterval interval(0.0, 1.0);\n\n\t\tif (use_shishkin)\n\t\t{\n\t\t\tInterval interval1(0.0, 1 - 2 * epsilon * log(segement_));\n\t\t\tinterval1.SetPartitionCount(segement_);\n\t\t\tInterval interval2(1 - 2 * epsilon * log(segement_), 1.0);\n\t\t\tinterval2.SetPartitionCount(segement_);\n\n\t\t\tstd::vector<Float> knot_vector(2 * segement_ - 1);\n\n\t\t\tfor (int i = 0; i < segement_ - 1; ++i)\n\t\t\t{\n\t\t\t\tknot_vector[i] = interval1.SubInterval(i).lerp(1.0);\n\t\t\t\tknot_vector[segement_ + i] = interval2.SubInterval(i).lerp(1.0);\n\t\t\t}\n\t\t\tif (segement_ > 1)\n\t\t\t\tknot_vector[segement_ - 1] = interval1.SubInterval(segement_ - 1).lerp(1.0);\n\n\t\t\tinterval.SetSubIntervalKnots(knot_vector);\n\t\t}\n\t\telse\n\t\t\tinterval.SetPartitionCount(segement_);\n\n\t\tLinearDG linear(rhs, d, b, c, interval);\n\t\tQuadraticDG quadratic(rhs, d, b, c, interval);\n\t\tlinear.evaluate();\n\t\tquadratic.evaluate();\n\t\tfor (int i = 0; i < Length; ++i)\n\t\t{\n\t\t\tquadratic_val[i] = quadratic.Value(1.0 / (Length - 1) * i);\n\t\t\tlinear_val[i] = linear.Value(1.0 / (Length - 1) * i);\n\n\t\t\tquadratic_diff[i] = quadratic_val[i] - precise_val[i];\n\t\t\tlinear_diff[i] = linear_val[i] - precise_val[i];\n\t\t}\n\t}\n\n\tvoid Control_UI();\n\tvoid draw(bool* p_open) override;\n\n\tstd::vector<Point2d> points;\n\tbool updated = true;\n\tint segemnt = 16;\n\tfloat epsilon = 1E-7;\n\tbool use_shishkin = false;\n\n\tvoid error(std::vector<float>& ref, std::vector<float>& eval, Float& L_1, Float& L_2, Float& L_inf)\n\t{\n\t\tassert(ref.size() == eval.size());\n\n\t\tstd::vector<Float> minus(ref.size());\n\n\t\tfor (int i = 0; i < ref.size(); ++i)\n\t\t{\n\t\t\tminus[i] = abs(ref[i] - eval[i]);\n\t\t}\n\n\t\tL_inf = *std::max_element(minus.begin(), minus.end(), [](Float a, Float b) {return a < b; });\n\t\tL_2 = sqrt(std::accumulate(minus.begin(), minus.end(), static_cast<Float>(0), [](Float r, Float a) {return r + a * a; }) / Float(ref.size()));\n\t\tL_1 = std::accumulate(minus.begin(), minus.end(), static_cast<Float>(0), [](Float r, Float a) {return r + a; }) / Float(ref.size());\n\t}\n\npublic:\n\tvoid CalcAccurateRst()\n\t{\n\t\tFloat h = 1.0 / (Length - 1);\n\t\tfor (int i = 0; i < Length; ++i)\n\t\t{\n\t\t\txs[i] = i * h;\n\n\t\t\tauto accurate_func = [this](Float x) {return -(-1 + exp(x / epsilon) + pow(x, 2) - exp(1 / epsilon) * pow(x, 2) + 2 * epsilon * (-1 + exp(x / epsilon) + x - exp(1 / epsilon) * x)) / (2. * (-1 + exp(1 / epsilon))); };\n\n\t\t\tif (epsilon < 1E-2)\n\t\t\t{\n\t\t\t\tauto accurate_func = [this](Float x) {return -exp(1 / epsilon * (x - 1)) / 2. + x * epsilon + x * x / 2.; };\n\t\t\t\tprecise_val[i] = accurate_func(xs[i]);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tprecise_val[i] = accurate_func(xs[i]);\n\t\t\t}\n\t\t}\n\t}\n\n\tFEM1DVisualizer() {\n\t\tCalcAccurateRst();\n\t\tsegemnt = 16;\n\t\tFloat L1, L2, L_inf;\n\t\tdo\n\t\t{\n\t\t\tevaluate();\n\n\t\t\terror(precise_val, linear_val, L1, L2, L_inf);\n\n\t\t\tusing std::cout;\n\t\t\tusing std::endl;\n\n\t\t\tif (segemnt == 16)\n\t\t\t{\n\t\t\t\tcout << segemnt << '&' << L1 << '&' << '-' << '&' << L2 << '&' << '-' << '&' << L_inf << '&' << '-' << \"\\\\\\\\\" << endl;\n\t\t\t}\n\t\t\telse\n\t\t\t\tcout << segemnt << '&' << L1 << '&' <<- log2(L1 / linear_L1.back()) << '&' << L2 << '&' << -log2(L2 / linear_L2.back()) << '&' << L_inf << '&' << -log2(L_inf / linear_Linf.back()) << \"\\\\\\\\\" << endl;\n\n\t\t\tpointcount.push_back(segemnt);\n\t\t\tlinear_L1.push_back(L1);\n\t\t\tlinear_L2.push_back(L2);\n\t\t\tlinear_Linf.push_back(L_inf);\n\t\t\terror(precise_val, quadratic_val, L1, L2, L_inf);\n\n\t\t\t//if (segemnt == 16)\n\t\t\t//{\n\t\t\t//\tcout << segemnt << '&' << L1 << '&' << '-' << '&' << L2 << '&' << '-' << '&' << L_inf << '&' << '-' << \"\\\\\\\\\" << endl;\n\t\t\t//}\n\t\t\t//else\n\t\t\t//\tcout << segemnt << '&' << L1 << '&' << -log2(L1 / quadratic_L1.back()) << '&' << L2 << '&' << -log2(L2 / quadratic_L2.back()) << '&' << L_inf << '&' << -log2(L_inf / quadratic_Linf.back()) << \"\\\\\\\\\" << endl;\n\n\t\t\tquadratic_L1.push_back(L1);\n\t\t\tquadratic_L2.push_back(L2);\n\t\t\tquadratic_Linf.push_back(L_inf);\n\n\t\t\tsegemnt *= 2;\n\t\t} while (segemnt != 8192);\n\t\tsegemnt = 16;\n\n\t\tevaluate();\n\t}\n\tconst size_t Length = 20001;\n\n\tstd::vector<float> xs = std::vector<float>(Length);\n\tstd::vector<float> precise_val = std::vector<float>(Length);\n\tstd::vector<float> quadratic_val = std::vector<float>(Length);\n\tstd::vector<float> linear_val = std::vector<float>(Length);\n\tstd::vector<float> quadratic_diff = std::vector<float>(Length);\n\tstd::vector<float> linear_diff = std::vector<float>(Length);\n\n\tstd::vector<float> pointcount;\n\tstd::vector<float> linear_L1;\n\tstd::vector<float> linear_L2;\n\tstd::vector<float> linear_Linf;\n\n\tstd::vector<float> quadratic_L1;\n\tstd::vector<float> quadratic_L2;\n\tstd::vector<float> quadratic_Linf;\n};\n\nstatic inline ImVec2 operator-(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x - rhs.x, lhs.y - rhs.y); }\n\nvoid FEM1DVisualizer::Control_UI()\n{\n\tif (ImGui::SliderInt(\"Number of segments\", &segemnt, 2, 200))\n\t{\n\t\tsegemnt = segemnt < 2 ? 2 : segemnt;\n\t\tevaluate();\n\t}\n\tif (ImGui::SliderFloat(\"Epsilon\", &epsilon, 1E-7, 1E-1, \"%.8f\", ImGuiSliderFlags_Logarithmic))\n\t{\n\t\tevaluate();\n\t\tCalcAccurateRst();\n\t}\n\tif (ImGui::Checkbox(\"Use Shishkin\", &use_shishkin))\n\t{\n\t\tevaluate();\n\t}\n}\n\nvoid FEM1DVisualizer::draw(bool* p_open)\n{\n\tif (ImGui::BeginTabBar(\"FEM 1D App\")) {\n\t\tif (ImGui::BeginTabItem(\"FEM1D\"))\n\t\t{\n\t\t\tif (ImPlot::BeginPlot(\"Line Plot\", \"x\", \"f(x)\", ImGui::GetContentRegionAvail() - ImVec2(0, 100), ImPlotFlags_NoBoxSelect | ImPlotFlags_NoMenus)) {\n\t\t\t\tImPlot::PlotLine(\"Precise solution\", &xs[0], &precise_val[0], Length);\n\t\t\t\tImPlot::PlotLine(\"FEM Quadratic\", &xs[0], &quadratic_val[0], Length);\n\t\t\t\tImPlot::PlotLine(\"FEM Linear\", &xs[0], &linear_val[0], Length);\n\n\t\t\t\tImPlot::EndPlot();\n\t\t\t}\n\t\t\tControl_UI();\n\t\t\tImGui::EndTabItem();\n\t\t}\n\t\tif (ImGui::BeginTabItem(\"FEM1D difference\"))\n\t\t{\n\t\t\tif (ImPlot::BeginPlot(\"Line Plot\", \"x\", \"f(x)\", ImGui::GetContentRegionAvail() - ImVec2(0, 100), ImPlotFlags_NoBoxSelect | ImPlotFlags_NoMenus)) {\n\t\t\t\tImPlot::PlotLine(\"FEM diff Linear\", &xs[0], &linear_diff[0], Length);\n\t\t\t\tImPlot::PlotLine(\"FEM diff Quadratic\", &xs[0], &quadratic_diff[0], Length);\n\n\t\t\t\tImPlot::EndPlot();\n\t\t\t}\n\t\t\tControl_UI();\n\t\t\tImGui::EndTabItem();\n\t\t}\n\n\t\tif (ImGui::BeginTabItem(\"Error Plot\"))\n\t\t{\n\t\t\tif (ImPlot::BeginPlot(\"Line Plot\", \"x\", \"f(x)\", ImGui::GetContentRegionAvail() - ImVec2(0, 100), ImPlotFlags_NoBoxSelect | ImPlotFlags_NoMenus, ImPlotAxisFlags_LogScale, ImPlotAxisFlags_LogScale)) {\n\t\t\t\tImPlot::PlotLine(\"Linear L1    Error\", &pointcount[0], &linear_L1[0], pointcount.size());\n\t\t\t\tImPlot::PlotLine(\"Linear L2    Error\", &pointcount[0], &linear_L2[0], pointcount.size());\n\t\t\t\tImPlot::PlotLine(\"Linear L_inf Error\", &pointcount[0], &linear_Linf[0], pointcount.size());\n\n\t\t\t\tImPlot::PlotLine(\"Quadratic L1    Error\", &pointcount[0], &quadratic_L1[0], pointcount.size());\n\t\t\t\tImPlot::PlotLine(\"Quadratic L2    Error\", &pointcount[0], &quadratic_L2[0], pointcount.size());\n\t\t\t\tImPlot::PlotLine(\"Quadratic L_inf Error\", &pointcount[0], &quadratic_Linf[0], pointcount.size());\n\n\t\t\t\tImPlot::EndPlot();\n\t\t\t}\n\n\t\t\tImGui::EndTabItem();\n\t\t}\n\t\tImGui::EndTabBar();\n\t}\n\n\tImGui::End();\n}\n\nint main()\n{\n\tFEM1DVisualizer visualizer;\n\tvisualizer.RenderLoop();\n}", "meta": {"hexsha": "b39e8b38e946a6769e29a1156d14b97a1e65b907", "size": 7846, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/FEM/FEM1DAppShishskin/test.cpp", "max_stars_repo_name": "Jerry-Shen0527/Numerical", "max_stars_repo_head_hexsha": "0bd6b630ac450caa0642029792ab348867d2390d", "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/test/FEM/FEM1DAppShishskin/test.cpp", "max_issues_repo_name": "Jerry-Shen0527/Numerical", "max_issues_repo_head_hexsha": "0bd6b630ac450caa0642029792ab348867d2390d", "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/test/FEM/FEM1DAppShishskin/test.cpp", "max_forks_repo_name": "Jerry-Shen0527/Numerical", "max_forks_repo_head_hexsha": "0bd6b630ac450caa0642029792ab348867d2390d", "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.6484375, "max_line_length": 219, "alphanum_fraction": 0.6138159572, "num_tokens": 2664, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436395, "lm_q2_score": 0.8198933293122507, "lm_q1q2_score": 0.7299463018957637}}
{"text": "#pragma once\n#include \"settings.hpp\"\n#if USE_EIGEN == 1\n#include <Eigen/Dense>\n#endif\n\nnamespace nn\n{\n\tenum class CostType\n\t{\n\t\tkQuadratic,\n\t\tkCrossEntropy\n\t};\n\n#if USE_EIGEN == 1\n\tusing MatrixType = Eigen::Matrix<real, Eigen::Dynamic, Eigen::Dynamic>;\n\tusing CostFunction = real(*)(const MatrixType& output, const MatrixType& truth);\n\tusing CostDerivativeFunction = MatrixType(*)(const MatrixType& output, const MatrixType& truth);\n\n\ttemplate<CostType t> real cost(const MatrixType& output, const MatrixType& truth);\n\ttemplate<CostType t> MatrixType cost_derivative(const MatrixType& output, const MatrixType& truth);\n\n\t// mse\n\ttemplate<>\n\treal cost<CostType::kQuadratic>(const MatrixType& output, const MatrixType& truth)\n\t{\n\t\tif (output.rows() != truth.rows() || output.cols() != truth.cols())\n\t\t\tthrow std::logic_error(\"Cost functions require equally sized matrices\");\n\t\tconst real c = real((truth - output).squaredNorm());\n\t\treturn real(0.5) * c;\n\t}\n\ttemplate<>\n\tMatrixType cost_derivative<CostType::kQuadratic>(const MatrixType& output, const MatrixType& truth)\n\t{\n\t\tif (output.rows() != truth.rows() || output.cols() != truth.cols())\n\t\t\tthrow std::logic_error(\"Cost functions require equally sized matrices\");\n\t\treturn output - truth;\n\t}\n\n\t// cross-entropy\n\ttemplate<>\n\treal cost<CostType::kCrossEntropy>(const MatrixType& output, const MatrixType& truth)\n\t{\n\t\tif (output.rows() != truth.rows() || output.cols() != truth.cols())\n\t\t\tthrow std::logic_error(\"Cost functions require equally sized matrices\");\n\t\tconst MatrixType one = MatrixType::Ones(truth.rows(), truth.cols());\n\t\tMatrixType tmp = -truth.array() * output.unaryExpr(&logf).array() - (one - truth).array() * ((one - output).unaryExpr(&logf).array());\n\t\tauto& arr = tmp.array();\n\t\tfor (int i = 0; i < arr.size(); ++i)\n\t\t\tif (!std::isfinite(arr(i)))\n\t\t\t\tarr(i) = 0.0f;\n\t\treturn tmp.sum();\n\t}\n\ttemplate<>\n\tMatrixType cost_derivative<CostType::kCrossEntropy>(const MatrixType& output, const MatrixType& truth)\n\t{\n\t\tif (output.rows() != truth.rows() || output.cols() != truth.cols())\n\t\t\tthrow std::logic_error(\"Cost functions require equally sized matrices\");\n\t\treturn (output - truth);\n\t}\n#endif\n}", "meta": {"hexsha": "4778f4b6e3fc9b70172a5ae58fe0801a73cd8f4b", "size": 2162, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/cost.hpp", "max_stars_repo_name": "dmitryduka/nn", "max_stars_repo_head_hexsha": "301bf81f68b9db564d01076303dac635b0ea6957", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-08-07T19:40:16.000Z", "max_stars_repo_stars_event_max_datetime": "2016-08-07T19:40:16.000Z", "max_issues_repo_path": "include/cost.hpp", "max_issues_repo_name": "dmitryduka/nn", "max_issues_repo_head_hexsha": "301bf81f68b9db564d01076303dac635b0ea6957", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-09-23T14:00:59.000Z", "max_issues_repo_issues_event_max_datetime": "2016-09-23T14:01:47.000Z", "max_forks_repo_path": "include/cost.hpp", "max_forks_repo_name": "dmitryduka/nn", "max_forks_repo_head_hexsha": "301bf81f68b9db564d01076303dac635b0ea6957", "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.8709677419, "max_line_length": 136, "alphanum_fraction": 0.6993524514, "num_tokens": 564, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403999037782, "lm_q2_score": 0.7853085909370422, "lm_q1q2_score": 0.7298975308083971}}
{"text": "#include <iostream>\n#include <ql/quantlib.hpp>\n#include <boost/format.hpp>\n#include <functional>\n#include <numeric>\n#include <fstream>\n\nusing namespace QuantLib;\n\ndouble calculatePortfolioReturn (double proportionA, double expectedReturnA,\n                                 double expectedReturnB) {\n  return proportionA * expectedReturnA +\n         (1 - proportionA) * expectedReturnB;\n}\n\nVolatility\ncalculatePortfolioRisk (double proportionA, Volatility volatilityA,\n                        Volatility volatilityB,\n                        double covarianceAB) {\n  return std::sqrt (std::pow (proportionA, 2) * std::pow (volatilityA, 2) +\n                    std::pow (1 - proportionA, 2) *\n                    std::pow (volatilityB, 2) +\n                    (2 * proportionA * (1 - proportionA) * covarianceAB));\n}\n\nint main () {\n\n  Matrix covarianceMatrix (4, 4);\n\n//row 1\n  covarianceMatrix[0][0] = .40;  //Equity1-Equity1\n  covarianceMatrix[0][1] = .03;  //Equity1-Equity2\n  covarianceMatrix[0][2] = .02;  //Equity1-Equity3\n  covarianceMatrix[0][3] = .06;  //Equity1-Equity4\n//row 2\n  covarianceMatrix[1][0] = .03;  //Equity2-Equity1\n  covarianceMatrix[1][1] = .20;  //Equity2-Equity2\n  covarianceMatrix[1][2] = .01;  //Equity2-Equity3\n  covarianceMatrix[1][3] = -.06; //Equity2-Equity4\n//row 3\n  covarianceMatrix[2][0] = .02;  //Equity3-Equity1\n  covarianceMatrix[2][1] = .01;  //Equity3-Equity2\n  covarianceMatrix[2][2] = .30;  //Equity3-Equity3\n  covarianceMatrix[2][3] = .03;  //Equity3-Equity4\n//row 4\n  covarianceMatrix[3][0] = .06;  //Equity4-Equity1\n  covarianceMatrix[3][1] = -.06; //Equity4-Equity2\n  covarianceMatrix[3][2] = .03;  //Equity4-Equity3\n  covarianceMatrix[3][3] = .15;  //Equity4-Equity4\n\n  std::cout << \"Covariance matrix of returns: \" << std::endl;\n  std::cout << covarianceMatrix << std::endl;\n\n//portfolio return vector         \n  Matrix portfolioReturnVector (4, 1);\n  portfolioReturnVector[0][0] = .19; //Equity1\n  portfolioReturnVector[1][0] = .11; //Equity2\n  portfolioReturnVector[2][0] = .07; //Equity3\n  portfolioReturnVector[3][0] = .08; //Equity4\n\n  std::cout << \"Portfolio return vector\" << std::endl;\n  std::cout << portfolioReturnVector << std::endl;\n\n// Constant\n  Rate c = .05;\n\n// Portfolio return vector minus constant rate\n  Matrix portfolioReturnVectorMinusC (4, 1);\n  for (int i = 0; i < 4; ++i) {\n    portfolioReturnVectorMinusC[i][0] = portfolioReturnVector[i][0] - c;\n  }\n\n  std::cout\n    << boost::format (\"Portfolio return vector minus constantrate (c = %f)\") % c\n    << std::endl;\n  std::cout << portfolioReturnVectorMinusC << std::endl;\n\n// Inverse of covariance matrix\n  const Matrix &inverseOfCovarienceMatrix = inverse (covarianceMatrix);\n\n// Z vectors\n  const Matrix &portfolioAz = inverseOfCovarienceMatrix * portfolioReturnVector;\n  std::cout << \"Portfolio A z vector\" << std::endl;\n  std::cout << portfolioAz << std::endl;\n  double sumOfPortfolioAz = 0.0;\n  std::for_each (portfolioAz.begin (), portfolioAz.end (), [&] (Real n) {\n      sumOfPortfolioAz += n;\n  });\n\n  const Matrix &portfolioBz =\n    inverseOfCovarienceMatrix * portfolioReturnVectorMinusC;\n  std::cout << \"Portfolio B z vector\" << std::endl;\n  std::cout << portfolioBz << std::endl;\n  double sumOfPortfolioBz = 0.0;\n  std::for_each (portfolioBz.begin (), portfolioBz.end (), [&] (Real n) {\n      sumOfPortfolioBz += n;\n  });\n\n// Portfolio weights\n  Matrix weightsPortfolioA (4, 1);\n  for (int i = 0; i < 4; ++i) {\n    weightsPortfolioA[i][0] = portfolioAz[i][0] / sumOfPortfolioAz;\n  }\n\n  std::cout << \"Portfolio A weights\" << std::endl;\n  std::cout << weightsPortfolioA << std::endl;\n\n  Matrix weightsPortfolioB (4, 1);\n  for (int i = 0; i < 4; ++i) {\n    weightsPortfolioB[i][0] = portfolioBz[i][0] / sumOfPortfolioBz;\n  }\n\n  std::cout << \"Portfolio B weights\" << std::endl;\n  std::cout << weightsPortfolioB << std::endl;\n\n// Portfolio risk and return\n  const Matrix &expectedReturnPortfolioAMatrix =\n    transpose (weightsPortfolioA) * portfolioReturnVector;\n  double expectedReturnPortfolioA = expectedReturnPortfolioAMatrix[0][0];\n  const Matrix &variancePortfolioAMatrix =\n    transpose (weightsPortfolioA) * covarianceMatrix * weightsPortfolioA;\n  double variancePortfolioA = variancePortfolioAMatrix[0][0];\n  double stdDeviationPortfolioA = std::sqrt (variancePortfolioA);\n  std::cout << boost::format (\"Portfolio A expected return: %f\") %\n               expectedReturnPortfolioA << std::endl;\n  std::cout << boost::format (\"Portfolio A variance: %f\") % variancePortfolioA\n            << std::endl;\n  std::cout << boost::format (\"Portfolio A standard deviation: %f\") %\n               stdDeviationPortfolioA << std::endl;\n\n  const Matrix &expectedReturnPortfolioBMatrix =\n    transpose (weightsPortfolioB) * portfolioReturnVector;\n  double expectedReturnPortfolioB = expectedReturnPortfolioBMatrix[0][0];\n  const Matrix &variancePortfolioBMatrix =\n    transpose (weightsPortfolioB) * covarianceMatrix * weightsPortfolioB;\n  double variancePortfolioB = variancePortfolioBMatrix[0][0];\n  double stdDeviationPortfolioB = std::sqrt (variancePortfolioB);\n  std::cout << boost::format (\"Portfolio B expected return: %f\") %\n               expectedReturnPortfolioB << std::endl;\n  std::cout << boost::format (\"Portfolio B variance: %f\") % variancePortfolioB\n            << std::endl;\n  std::cout << boost::format (\"Portfolio B standard deviation: %f\") %\n               stdDeviationPortfolioB << std::endl;\n\n// Covariance and correlation of returns\n  const Matrix &covarianceABMatrix =\n    transpose (weightsPortfolioA) * covarianceMatrix * weightsPortfolioB;\n  double covarianceAB = covarianceABMatrix[0][0];\n  double correlationAB =\n    covarianceAB / (stdDeviationPortfolioA * stdDeviationPortfolioB);\n  std::cout\n    << boost::format (\"Covariance of portfolio A and B: %f\") % covarianceAB\n    << std::endl;\n  std::cout\n    << boost::format (\"Correlation of portfolio A and B: %f\") % correlationAB\n    << std::endl;\n\n// Generate envelope set of portfolios\n  double startingProportion = -.40;\n  double increment = .10;\n  std::map<double, std::pair<Volatility, double> > mapOfProportionToRiskAndReturn;\n  std::map<Volatility, double> mapOfVolatilityToReturn;\n  for (int i = 0; i < 21; ++i) {\n    double proportionA = startingProportion + i * increment;\n    Volatility risk_frontier = calculatePortfolioRisk (proportionA,\n                                                       stdDeviationPortfolioA,\n                                                       stdDeviationPortfolioB,\n                                                       covarianceAB);\n    double returnEF = calculatePortfolioReturn (proportionA,\n                                                expectedReturnPortfolioA,\n                                                expectedReturnPortfolioB);\n    mapOfProportionToRiskAndReturn[proportionA] = std::make_pair (risk_frontier,\n                                                                  returnEF);\n    mapOfVolatilityToReturn[risk_frontier] = returnEF;\n  }\n\n// Write data to a file for plotting latter\n  std::ofstream envelopeSetFile;\n  envelopeSetFile.open (\"./envelope.dat\", std::ios::out);\n  for (std::map<double, std::pair<Volatility, double> >::const_iterator i = mapOfProportionToRiskAndReturn.begin ();\n       i != mapOfProportionToRiskAndReturn.end (); ++i) {\n    envelopeSetFile << boost::format (\"%f %f %f\") % i->first % i->second.first %\n                       i->second.second << std::endl;\n  }\n  envelopeSetFile.close ();\n\n// Find minimum risk portfolio on efficient frontier\n  std::pair<Volatility, double> minimumVariancePortfolioRiskAndReturn = *mapOfVolatilityToReturn.begin ();\n  Volatility minimumRisk = minimumVariancePortfolioRiskAndReturn.first;\n  double maximumReturn = minimumVariancePortfolioRiskAndReturn.second;\n  std::cout << boost::format (\"Maximum portfolio return for risk of %f is %f\") %\n               minimumRisk % maximumReturn << std::endl;\n\n// Generate efficient frontier\n  std::map<Volatility, double> efficientFrontier;\n  for (std::map<double, std::pair<Volatility, double> >::const_iterator i = mapOfProportionToRiskAndReturn.begin ();\n       i != mapOfProportionToRiskAndReturn.end (); ++i) {\n    efficientFrontier[i->second.first] = i->second.second;\n    if (i->second.first == minimumRisk) break;\n  }\n\n// Write efficient frontier to file\n  std::ofstream efficient_frontier_file;\n  efficient_frontier_file.open (\"./efficient_frontier.dat\", std::ios::out);\n  for (std::map<Volatility, double>::const_iterator i = efficientFrontier.begin ();\n       i != efficientFrontier.end (); ++i) {\n    efficient_frontier_file << boost::format (\"%f %f\") % i->first % i->second\n                            << std::endl;\n  }\n  efficient_frontier_file.close ();\n  return 0;\n}\n\n", "meta": {"hexsha": "5ac2793d8623a49a165cd308683b800a7a8d9789", "size": 8751, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "raghavkhanna18/Efficient-Frontier", "max_stars_repo_head_hexsha": "b24f417e4dd68d9dd4cd8f284d919f4531617380", "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": "raghavkhanna18/Efficient-Frontier", "max_issues_repo_head_hexsha": "b24f417e4dd68d9dd4cd8f284d919f4531617380", "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": "raghavkhanna18/Efficient-Frontier", "max_forks_repo_head_hexsha": "b24f417e4dd68d9dd4cd8f284d919f4531617380", "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.8925233645, "max_line_length": 116, "alphanum_fraction": 0.6591246715, "num_tokens": 2350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404018582427, "lm_q2_score": 0.7853085708384736, "lm_q1q2_score": 0.7298975136628332}}
{"text": "#ifndef HBM_PERIODICITY_HPP\n#define HBM_PERIODICITY_HPP\n\n#include \"ukp_common.hpp\"\n#include \"wrapper.hpp\"\n#include \"type_name.hpp\"\n\n#include <type_traits>  // For is_integral, is_same\n#include <limits> // for numeric_limits\n#include <boost/multiprecision/cpp_int.hpp> // For cpp_rational (infinite\n                                            // precision boost rational)\n                                            // used at y_star\n#include <boost/math/common_factor_rt.hpp>  // For boost::math::lcm used\n                                            // at huangtang\n\nnamespace hbm {\n  template <typename W, typename P, typename I>\n  struct per_extra_info_t : extra_info_t {\n    W original_cap;\n    W y_cap;\n\n    per_extra_info_t(W original_cap, W y_cap) :\n                     original_cap(original_cap),  y_cap(y_cap) { }\n\n    virtual std::string gen_info(void) {\n      return std::string(\"algorithm_name: y_star_periodicity_bound\\n\")\n           + \"git_head_at_compilation: \" + HBM_GIT_HEAD_AT_COMPILATION + \"\\n\"\n           + \"type_W: \" + hbm::type_name<W>::get() + \"\\n\"\n           + \"type_P: \" + hbm::type_name<P>::get() + \"\\n\"\n           + \"type_I: \" + hbm::type_name<I>::get() + \"\\n\"\n           + \"Original capacity: \" + std::to_string(original_cap) + \"\\n\"\n           + \"y* capacity: \" + std::to_string(y_cap) + \"\\n\";\n    }\n  };\n\n  namespace hbm_periodicity_impl {\n    using namespace std;\n    using namespace boost;\n    using namespace boost::multiprecision;\n\n    // From \"A constructive periodicity bound for the unbounded\n    //  knapsack problem\"\n    // Its complexity is bigger than O(n^2), and it seems worse than\n    // y*. The overall impression is that it is terrible.\n    template <typename W, typename P>\n    W huangtang(instance_t<W, P> &ukpi, bool already_sorted = false) {\n      auto &items = ukpi.items;\n      if (!already_sorted) sort_by_eff(items);\n\n      size_t n = items.size();\n      W h0 = 0;\n      for (size_t j = 1; j < n; ++j) {\n        W min = boost::math::lcm(items[0].w, items[j].w) - items[j].w;\n        for (size_t i = 1; i < j; ++i) {\n          W x = boost::math::lcm(items[i].w, items[j].w) - items[j].w;\n          if (x < min) min = x;\n        }\n        h0 += min;\n      }\n\n      return h0 + 1;\n    }\n\n    template <typename W, typename P>\n    W y_star(const item_t<W, P> &b, const item_t<W, P> &b2) {\n      assert(b < b2);\n      if (std::is_integral<W>::value && std::is_same<W, P>::value) {\n        // Without the castings, the compiler gives conversion warnings\n        // that don't will ever happen. If P is a floating point number\n        // this 'if' never executes. The castings have literally no\n        // effect since inside this if W and P are the same type.\n        W w1 = b.w, w2 = b2.w;\n        W p1 = static_cast<W>(b.p), p2 = static_cast<W>(b2.p);\n\n        cpp_rational r_p1 = static_cast<W>(b.p);\n        cpp_rational r1(p1, w1);\n        cpp_rational r2(p2, w2);\n\n        // If the two numbers are equal we would divide by\n        // zero later. The closest value we have to infinity\n        // is the best return.\n        if (r1 == r2) return numeric_limits<W>::max();\n\n        // Always positive: the r1 efficiency is bigger than the r2 efficiency\n        cpp_rational d = r1 - r2;\n        // Final value, the \"plus one\" is to avoid getting 1 less\n        // than the real value when we cast back to W\n        cpp_rational y = (r_p1 / d) + 1;\n\n        return y <= numeric_limits<W>::max() ? static_cast<W>(y) : numeric_limits<W>::max();\n      } else if (std::is_floating_point<P>::value) {\n        W w1 = b.w, w2 = b2.w;\n        P p1 = b.p, p2 = b2.p;\n\n        P e1 = p1 / static_cast<P>(w1);\n        P e2 = p2 / static_cast<P>(w2);\n\n        if (e1 - e2 < numeric_limits<P>::epsilon())\n          return numeric_limits<W>::max();\n\n        return static_cast<W>(p1/(e1 - e2)) + 1;\n      } else {\n        cerr << __func__ << \": W and P aren't valid types. \" << endl;\n        exit(EXIT_FAILURE);\n      }\n    }\n\n    template <typename W>\n    W refine_y_star(W y_, W c, W w_b) {\n      if (y_ > c) return c;\n      W qt_b = ((c - y_) / w_b) + 1;\n      return c - qt_b*w_b;\n    }\n\n    template <typename W, typename P>\n    W y_star(vector< item_t<W, P> > &items, bool already_sorted = false) {\n      if (!already_sorted) sort_by_eff(items, 2u);\n\n      return hbm_periodicity_impl::y_star(items[0], items[1]);\n    }\n\n    template <typename W, typename P>\n    W y_star(instance_t<W, P> &ukpi, bool already_sorted = false) {\n      return y_star(ukpi.items, already_sorted);\n    }\n\n//    template <typename W, typename P, typename I>\n//    W run_with_y_star(void(*ukp_solver)(instance_t<W, P> &, solution_t<W, P, I> &, void*),\n//      instance_t<W, P> &ukpi, solution_t<W, P, I> &sol, void* ukp_solver_extra_params) {\n//      W y_ = y_star(ukpi, false);\n//\n//      if (y_ >= ukpi.c) {\n//        (*ukp_solver)(ukpi, sol, ukp_solver_extra_params);\n//        return y_;\n//      }\n//\n//      vector< item_t<W, P> > &items(ukpi.items);\n//\n//      W old_c = ukpi.c;\n//\n//      W w1, p1;\n//      w1 = items[0].w;\n//      p1 = items[0].p;\n//\n//      W qt_best_item_used = (old_c - y_)/w1;\n//      P profit_generated_by_best_item = static_cast<P>(qt_best_item_used)*p1;\n//      W space_used_by_best_item = qt_best_item_used*w1;\n//\n//      ukpi.c = old_c - space_used_by_best_item;\n//\n//      (*ukp_solver)(ukpi, sol, true);\n//\n//      sol.opt += profit_generated_by_best_item;\n//\n//      return y_;\n//    }\n\n    template <typename W, typename P, typename I>\n    void y_star_wrapper(instance_t<W, P> &ukpi, solution_t<W, P, I> &sol, bool already_sorted = false) {\n      sol.show_only_extra_info = true;\n      I y_star_cap = hbm_periodicity_impl::y_star(ukpi, already_sorted);\n\n      per_extra_info_t<W, P, I>* ptr =\n        new per_extra_info_t<W, P, I>(ukpi.c, y_star_cap);\n\n      extra_info_t* upcast_ptr = dynamic_cast<extra_info_t*>(ptr);\n      sol.extra_info = std::shared_ptr<extra_info_t>(upcast_ptr);\n\n      return;\n    }\n\n    template<typename W, typename P, typename I>\n    struct y_star_wrap : wrapper_t<W, P, I> {\n      virtual void operator()(instance_t<W, P> &ukpi, solution_t<W, P, I> &sol, bool already_sorted) const {\n        // Calls the overloaded version with the third argument as a bool\n        hbm_periodicity_impl::y_star_wrapper(ukpi, sol, already_sorted);\n\n        return;\n      }\n\n      virtual const std::string& name(void) const {\n        static const std::string name = \"y_star\";\n        return name;\n      }\n    };\n\n    template<typename W, typename P, typename I = size_t>\n    void y_star_wrapper(instance_t<W, P> &ukpi, solution_t<W, P, I> &sol, int argc, argv_t argv) {\n      simple_wrapper(y_star_wrap<W, P, I>(), ukpi, sol, argc, argv);\n    }\n  }\n\n  /// Computes the y* periodicity bound. It's guaranteed that any optimal\n  /// solution for a capacity bigger than this bound have at least one copy of\n  /// the best item. Taken from Garfinkel and Nemhauser at \"Integer\n  /// Programming\", p. 223.\n  ///\n  /// @param b The best item, i.e. the most efficient one.\n  /// @param b2 The second best item, i.e. the second\n  ///   most efficient one.\n  ///\n  /// @return The first capacity value that have guarantee that any optimal\n  ///   solution will contain a copy of the best item.\n  template <typename W, typename P>\n  W y_star(const item_t<W, P> &b, const item_t<W, P> &b2) {\n    return hbm_periodicity_impl::y_star(b, b2);\n  }\n\n  /// Based on the y* bound, gives you the capacity for what you\n  /// should compute the UKP solution, to after fill with remaining\n  /// space with copies of the best item.\n  ///\n  /// Don't use the y* bound as capacity. Use the value\n  /// returned by this function. This value is guaranteed to be\n  /// equal to or smaller than y*, and the difference between it\n  /// and c is always a multiple of w_b (if y_ > c it will be c,\n  /// and the difference will be zero, that is a multiple of any\n  /// number). This way, to know how many copies of the best item\n  /// you should add to the solution you only need to compute this\n  /// value divided by w_b.\n  ///\n  /// @param y_ The value obtained by y_star.\n  /// @param c The original capacity value of the instance.\n  /// @param w_b The weight of the best item, i.e the most\n  ///   efficient one.\n  ///\n  /// @return A safe capacity to compute the result, and then fill the\n  ///   remaining space with exactly (c - <this return value>)/best_item.w\n  ///   copies of the best item.\n  template <typename W>\n  W refine_y_star(W y_, W c, W w_b) {\n    return hbm_periodicity_impl::refine_y_star(y_, c, w_b);\n  }\n\n  /// A terrible bound only implemented to access that it is indeed\n  /// terrible. Kept only for comparison.\n  template <typename W, typename P>\n  W huangtang(instance_t<W, P> &ukpi, bool already_sorted = false) {\n    return hbm_periodicity_impl::huangtang(ukpi, already_sorted);\n  }\n\n  /// Executes y_star over the two best items of ukpi.items. Assumes that ukpi\n  /// has at least two items, and that if already_sorted is true, the items are\n  /// ordered by non-increasing efficiency.\n  ///\n  /// @see y_star(const item_t<W, P> &b, const item_t<W, P> &b2)\n  template <typename W, typename P>\n  W y_star(instance_t<W, P> &ukpi, bool already_sorted = false) {\n    return hbm_periodicity_impl::y_star(ukpi, already_sorted);\n  }\n\n//  template <typename W, typename P, typename I = size_t>\n//  W run_with_y_star(void(*ukp_solver)(instance_t<W, P> &, solution_t<W, P, I> &, bool),\n//    instance_t<W, P> &ukpi, solution_t<W, P, I> &sol, bool already_sorted = false) {\n//    return hbm_periodicity_impl::run_with_y_star(ukp_solver, ukpi, sol, already_sorted);\n//  }\n\n  /// Convenience overload, executes y_star over ukpi.items and saves the\n  /// \"solution\" (the result of y_star, not an optimal solution) to sol. A hack\n  /// used to allow y_star to make use of main_take_path and benchmark_pyasukp\n  /// procedures.\n  ///\n  /// @see main_take_path\n  /// @see benchmark_pyasukp\n  /// @see per_extra_info_t\n  template <typename W, typename P, typename I = size_t>\n  void y_star_wrapper(instance_t<W, P> &ukpi, solution_t<W, P, I> &sol, bool already_sorted = false) {\n    hbm_periodicity_impl::y_star_wrapper(ukpi, sol, already_sorted);\n  }\n\n  /// Other convenience overload, executes y_star over ukpi.items and saves the\n  /// \"solution\" (the result of y_star, not an optimal solution) to sol. A hack\n  /// used to allow y_star to make use of main_take_path and benchmark_pyasukp\n  /// procedures.\n  ///\n  /// @see main_take_path\n  /// @see benchmark_pyasukp\n  /// @see per_extra_info_t\n  template<typename W, typename P, typename I = size_t>\n  void y_star_wrapper(instance_t<W, P> &ukpi, solution_t<W, P, I> &sol, int argc, argv_t argv) {\n    hbm_periodicity_impl::y_star_wrapper(ukpi, sol, argc, argv);\n  }\n}\n\n#endif //HBM_PERIODICITY_HPP\n", "meta": {"hexsha": "e2e1ee5277a6a10d60cdf230ec5005e798756538", "size": 10800, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "codes/cpp/lib/periodicity.hpp", "max_stars_repo_name": "henriquebecker91/masters", "max_stars_repo_head_hexsha": "1783c05b6f916cc4eb883df26fd4eb3460f98816", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-18T23:01:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-18T23:01:41.000Z", "max_issues_repo_path": "codes/cpp/lib/periodicity.hpp", "max_issues_repo_name": "henriquebecker91/masters", "max_issues_repo_head_hexsha": "1783c05b6f916cc4eb883df26fd4eb3460f98816", "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": "codes/cpp/lib/periodicity.hpp", "max_forks_repo_name": "henriquebecker91/masters", "max_forks_repo_head_hexsha": "1783c05b6f916cc4eb883df26fd4eb3460f98816", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-08-13T15:24:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-06T00:20:48.000Z", "avg_line_length": 37.7622377622, "max_line_length": 108, "alphanum_fraction": 0.6265740741, "num_tokens": 3074, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898127684334, "lm_q2_score": 0.8056321913146128, "lm_q1q2_score": 0.7298945581693488}}
{"text": "#include <stdexcept>\n#include <string>\n#include <utility>\n#include <vector>\n\n#include <NTL/ZZ.h>\n#include <NTL/ZZX.h>\n#include <NTL/ZZXFactoring.h>\n\n#include \"RSAkey.h\"\n\nusing namespace std;\nusing namespace NTL;\n\n\n// Create RSA public key from modulus and public exponent\nRSAkey::RSAkey (ZZ modulus, ZZ pub_exp) {\n\tn = modulus;\n\te = pub_exp;\n}\n\n// Create RSA private key from modulus' factors and public exponent\nRSAkey::RSAkey (vector<ZZ> factors, ZZ pub_exp) {\n\tvector<ZZ>::iterator iter;\n\n\tf = factors;\n\tn = 1;\n\tfor(iter = f.begin(); iter != f.end(); iter++)\n\t\tn *= (*iter);\n\n\te = pub_exp;\n\n\t// get phi and set it as modulus for e*d = 1 (mod phi)\n\tphi = 1;\n\tfor(iter = f.begin(); iter != f.end(); iter++)\n\t\tphi *= ((*iter) - 1);\n\tInvMod(d, pub_exp, phi);\n}\n\n// Create RSA private key from modulus, public exponent and private exponent\nRSAkey::RSAkey (ZZ modulus, ZZ pub_exp, ZZ priv_exp) {\n\tn = modulus;\n\te = pub_exp;\n\td = priv_exp;\n\n\n\t// Calculate factors from d\n\t// Based on a generalization of pycryptodome's implementation:\n\t// https://github.com/Legrandin/pycryptodome/blob/master/lib/Crypto/PublicKey/RSA.py\n\tZZ x, t, g, cand, fac, r;\n\tvector<ZZ>::iterator iter;\n\tx = e * d - 1;\n\tg = 2;\n\n\tt = x;\n\twhile(t % 2 == 0) t/=2;\n\n\t// r: remaining composite factors\n\tr = n;\n\n\twhile(!ProbPrime(r) && g < 100) {\n\t\tZZ k = t;\n\t\twhile(k < x) {\n\t\t\tPowerMod(cand, g, k, r);\n\t\t\tif(cand != 1 && cand != (r - 1) && SqrMod(cand, r) == 1) {\n\t\t\t\tfac = GCD(cand + 1, r);\n\t\t\t\tif(ProbPrime(fac)) {\n\t\t\t\t\tf.push_back(fac);\n\t\t\t\t\tr = r / fac;\n\t\t\t\t\tg = 2;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tk*=2;\n\t\t}\n\t\tg += 2;\n\t}\n\tif(!ProbPrime(r)) throw domain_error(\"Unable to compute p and q from d.\");\n\n\tf.push_back(r);\n\n\t// phi = (f1 - 1)*(f2 - 1)*...*(fk - 1) for all k factors of n\n\tphi = 1;\n\tfor(iter = f.begin(); iter < f.end(); iter++)\n\t\tmul(phi, phi, (*iter) - 1);\n}\n\nbool RSAkey::is_private() const {\n\tif (!IsZero(phi)) {\n\t\treturn true;\n\t} else {\n\t\treturn false;\n\t}\n}\n\nZZ RSAkey::get_param(string param) const {\n\tchar ch = param[0];\n\tif(param == \"phi\") {\n\t\t// o for order\n\t\tch = 'o';\n\t}\n\n\tswitch(ch) {\n\t\tcase 'n':\n\t\t\treturn n;\n\t\t\tbreak;\n\t\tcase 'e':\n\t\t\treturn e;\n\t\t\tbreak;\n\t\tcase 'd':\n\t\t\treturn d;\n\t\t\tbreak;\n\t\tcase 'o':\n\t\t\treturn phi;\n\t\t\tbreak;\n\t}\n\tthrow domain_error(\"Invalid RSA parameter specified!\");\n}\n\n\nvector<ZZ> RSAkey::get_factors() const {\n\treturn f;\n}\n", "meta": {"hexsha": "87d90dee68bf1d5cc2002917e96308483ef360a9", "size": 2328, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RSAkey.cpp", "max_stars_repo_name": "tacopeland/forty-years-of-RSA-attacks", "max_stars_repo_head_hexsha": "d556e20880525cfa4666e23c6b50f0906d67fdce", "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": "RSAkey.cpp", "max_issues_repo_name": "tacopeland/forty-years-of-RSA-attacks", "max_issues_repo_head_hexsha": "d556e20880525cfa4666e23c6b50f0906d67fdce", "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": "RSAkey.cpp", "max_forks_repo_name": "tacopeland/forty-years-of-RSA-attacks", "max_forks_repo_head_hexsha": "d556e20880525cfa4666e23c6b50f0906d67fdce", "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.7741935484, "max_line_length": 85, "alphanum_fraction": 0.5966494845, "num_tokens": 760, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.905989815306765, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7298945517583181}}
{"text": "/*\nProblem 28 - Number spiral diagonals\nStarting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows:\n\n21 22 23 24 25\n20  7  8  9 10\n19  6  1  2 11\n18  5  4  3 12\n17 16 15 14 13\n\nIt can be verified that the sum of the numbers on the diagonals is 101.\n\nWhat is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way?\n*/\n\n#include <iostream>\n#include <Eigen/Dense>\nusing namespace std;\n\nlong long int table_size = 1001;\nlong long int current_step = 1;\n\n\nint main() {\n\n\tEigen::Matrix<long long int, Eigen::Dynamic, Eigen::Dynamic> table(table_size, table_size);\n\tfor (int i = 0; i < table_size; i++) {\n\t\tfor (int j = 0; j < table_size; j++) {\n\t\t\ttable(i, j) = 0;\n\t\t}\n\t}\n\tEigen::Matrix<bool, Eigen::Dynamic, Eigen::Dynamic> is_visited(table_size, table_size);\n\tfor (int i = 0; i < table_size; i++) {\n\t\tfor (int j = 0; j < table_size; j++) {\n\t\t\tis_visited(i, j) = false;\n\t\t}\n\t}\n\t\n\t\n\t// We populate the matrix\n\tlong long int last_i = table_size / 2, last_j = table_size / 2;\n\ttable(last_i, last_j) = current_step;\n\tis_visited(last_i, last_j) = true;\n\tlong long int current_i = last_i, current_j = last_j + 1;\n\twhile ((current_j < table_size - 1) || (current_i >0)) { // The last number is in the upper right corner\n\t\tcurrent_step += 1;\n\t\ttable(current_i, current_j) = current_step;\n\t\tis_visited(current_i, current_j) = true;\n\t\t// std::cout << current_step << \" i: \" << current_i << \" j: \" << current_j << endl;\n\t\tif ((current_j - last_j) == 1) {\n\t\t\tif (is_visited(current_i + 1, current_j)) {\n\t\t\t\tlast_i = current_i;\n\t\t\t\tlast_j = current_j;\n\t\t\t\tcurrent_j += 1;\n\t\t\t\t// std::cout << \"Right\" << endl;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlast_i = current_i;\n\t\t\t\tlast_j = current_j;\n\t\t\t\tcurrent_i += 1;\n\t\t\t\t// std::cout << \"Down\" << endl;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif ((current_i - last_i) == 1) {\n\t\t\tif (is_visited(current_i, current_j - 1)) {\n\t\t\t\tlast_i = current_i;\n\t\t\t\tlast_j = current_j;\n\t\t\t\tcurrent_i += 1;\n\t\t\t\t// std::cout << \"Down\" << endl;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlast_i = current_i;\n\t\t\t\tlast_j = current_j;\n\t\t\t\tcurrent_j -= 1;\n\t\t\t\t// std::cout << \"Left\" << endl;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif ((current_j - last_j) == -1) {\n\t\t\tif (is_visited(current_i - 1, current_j)) {\n\t\t\t\tlast_i = current_i;\n\t\t\t\tlast_j = current_j;\n\t\t\t\tcurrent_j -= 1;\n\t\t\t\t// std::cout << \"Left\" << endl;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlast_i = current_i;\n\t\t\t\tlast_j = current_j;\n\t\t\t\tcurrent_i -= 1;\n\t\t\t\t// std::cout << \"Up\" << endl;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif ((current_i - last_i) == -1) {\n\t\t\tif (is_visited(current_i, current_j + 1)) {\n\t\t\t\tlast_i = current_i;\n\t\t\t\tlast_j = current_j;\n\t\t\t\tcurrent_i -= 1;\n\t\t\t\t// std::cout << \"Up\" << endl;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlast_i = current_i;\n\t\t\t\tlast_j = current_j;\n\t\t\t\tcurrent_j += 1;\n\t\t\t\t// std::cout << \"Right\" << endl;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t}\n\tcurrent_step += 1;\n\ttable(current_i, current_j) = current_step;\n\tis_visited(current_i, current_j) = true;\n\t// std::cout << current_step << \" i: \" << current_i << \" j: \" << current_j << endl;\n\n\n\t//Summation\n\tlong long int result = 0;\n\tfor (int i = 0; i < table_size; i++) {\n\t\tresult += table(i, i);\n\t}\n\t// std::cout << \"OK\" << endl;\n\tfor (int i = 0; i < table_size; i++) {\n\t\tresult += table(table_size - i - 1, i);\n\t}\n\t// std::cout << \"OK\" << endl;\n\tresult -= 1;\n\n\tstd::cout << result << endl;\n\n}", "meta": {"hexsha": "54524cc70be672f25356c64ef899f2cbc0a48f6b", "size": 3297, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problem_028.cpp", "max_stars_repo_name": "JlnZhou/ProjtecEuler", "max_stars_repo_head_hexsha": "6bbc4cbed2bf6596346d6d84e07b5355a36304c9", "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": "problem_028.cpp", "max_issues_repo_name": "JlnZhou/ProjtecEuler", "max_issues_repo_head_hexsha": "6bbc4cbed2bf6596346d6d84e07b5355a36304c9", "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": "problem_028.cpp", "max_forks_repo_name": "JlnZhou/ProjtecEuler", "max_forks_repo_head_hexsha": "6bbc4cbed2bf6596346d6d84e07b5355a36304c9", "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.1679389313, "max_line_length": 113, "alphanum_fraction": 0.593266606, "num_tokens": 1093, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952811593496, "lm_q2_score": 0.8128673110375457, "lm_q1q2_score": 0.7297071493270941}}
{"text": "#include <gtest/gtest.h>\n\n#include <Eigen/Dense>\n#include <iostream>\n#include <ancse/model.hpp>\n\nTEST(TestModelEuler, SimpleExample)\n{\n    auto model = Euler();\n    auto u = Eigen::Vector3d(1,1,1);\n    auto gamma = model.get_gamma();\n    auto c = std::sqrt(0.5*gamma*(gamma-1));\n    auto p = 0.5 * (gamma - 1);\n    auto H = 0.5 * (gamma + 1);\n\n    // Make sure we get the right values for u = (1,1,1)\n    //Fluxes\n    ASSERT_DOUBLE_EQ(model.flux(u)(0), 1.);\n    ASSERT_DOUBLE_EQ(model.flux(u)(1), 1. + p);\n    ASSERT_DOUBLE_EQ(model.flux(u)(2), 1. + p);\n\n    // Eigenvalues\n    ASSERT_DOUBLE_EQ(model.eigenvalues(u)(0), 1. - c);\n    ASSERT_DOUBLE_EQ(model.eigenvalues(u)(1), 1.);\n    ASSERT_DOUBLE_EQ(model.eigenvalues(u)(2), 1. + c);\n\n    // Eigenvectors\n    auto evs = Eigen::Matrix3d();\n    evs <<\n    1.,     1.,   1.,\n    1. - c, 1.,   1. + c,\n    H - c,  0.5,  H + c;\n    ASSERT_DOUBLE_EQ((model.eigenvectors(u) - evs).norm(), 0);\n}\n\nTEST(TestModelEuler, Prim2Cons2PrimConversions)\n{\n    auto model = Euler();\n    Eigen::VectorXd u;\n    u = Eigen::Vector3d(1,1,1);\n\n    ASSERT_DOUBLE_EQ(u(0), model.cons_to_prim(model.prim_to_cons(u))(0));\n    ASSERT_DOUBLE_EQ(u(1), model.cons_to_prim(model.prim_to_cons(u))(1));\n    ASSERT_DOUBLE_EQ(u(2), model.cons_to_prim(model.prim_to_cons(u))(2));\n\n    u = Eigen::Vector3d(1,0,0);\n\n    ASSERT_DOUBLE_EQ(u(0), model.cons_to_prim(model.prim_to_cons(u))(0));\n    ASSERT_DOUBLE_EQ(u(1), model.cons_to_prim(model.prim_to_cons(u))(1));\n    ASSERT_DOUBLE_EQ(u(2), model.cons_to_prim(model.prim_to_cons(u))(2));\n\n    u = Eigen::Vector3d(M_PI, -12.34, 42);\n\n    ASSERT_DOUBLE_EQ(u(0), model.cons_to_prim(model.prim_to_cons(u))(0));\n    ASSERT_DOUBLE_EQ(u(1), model.cons_to_prim(model.prim_to_cons(u))(1));\n    ASSERT_DOUBLE_EQ(u(2), model.cons_to_prim(model.prim_to_cons(u))(2));\n\n    ASSERT_DOUBLE_EQ(model.cons_to_prim(u)(0), u(0));\n    ASSERT_DOUBLE_EQ(model.cons_to_prim(u)(1), u(1) / u(0));\n    ASSERT_DOUBLE_EQ(model.cons_to_prim(u)(2), (u(2) - .5 * u(1) * u(1) / u(0)) * (model.get_gamma() - 1));\n\n    ASSERT_DOUBLE_EQ(model.prim_to_cons(u)(0), u(0));\n    ASSERT_DOUBLE_EQ(model.prim_to_cons(u)(1), u(0) * u(1));\n    ASSERT_DOUBLE_EQ(model.prim_to_cons(u)(2), u(2) / (model.get_gamma() - 1) + 0.5 * u(0) * u(1) * u(1));\n}", "meta": {"hexsha": "95f4b2c26c1369a0eaeddb41f99871b020513c2e", "size": 2265, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "series2_workbench/hyp_sys_1d/tests/test_model.cpp", "max_stars_repo_name": "BeatHubmann/19H-AdvNCSE", "max_stars_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-05T22:38:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-05T22:38:47.000Z", "max_issues_repo_path": "series2_workbench/hyp_sys_1d/tests/test_model.cpp", "max_issues_repo_name": "BeatHubmann/19H-AdvNCSE", "max_issues_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "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": "series2_workbench/hyp_sys_1d/tests/test_model.cpp", "max_forks_repo_name": "BeatHubmann/19H-AdvNCSE", "max_forks_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-08T20:43:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-08T20:43:27.000Z", "avg_line_length": 34.8461538462, "max_line_length": 107, "alphanum_fraction": 0.6317880795, "num_tokens": 762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391706552538, "lm_q2_score": 0.7905303260722198, "lm_q1q2_score": 0.7296904565555291}}
{"text": "//\n// Created by tr on 21-10-14.\n//\n#include <iostream>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <vector>\n\nusing namespace std;\n\nint main(){\n    Eigen::Matrix3d R=Eigen::Matrix3d::Identity();\n    Eigen::AngleAxisd rotationVector(M_PI/4, Eigen::Vector3d(0,0,1));\n    R=rotationVector.toRotationMatrix();\n    cout<<\"R: \"<<R<<endl;\n    \n    //3points\n    Eigen::Vector3d p1 =Eigen::Vector3d(1,2,3);\n    Eigen::Vector3d p2 =Eigen::Vector3d(6,5,4);\n    Eigen::Vector3d p3 =Eigen::Vector3d(8,7,9);\n\n    vector<Eigen::Vector3d> points1={p1,p2,p3};\n\n    vector<Eigen::Vector3d> points2;\n\n    for(auto p:points1)\n    {\n        points2.push_back(R*p);\n        cout<<\"p1:\"<<p<<endl;\n    }\n\n//    for (auto p2:points2)\n//    {\n//        cout<<\"p2: \"<<p2<<endl;\n//    }\n\nEigen::Vector3d qa=Eigen::Vector3d(0,0,0);\n    Eigen::Vector3d qb=Eigen::Vector3d(0,0,0);\n\n    for(int i =0; i<points1.size();i++)\n    {\n        for(int j=0;j<3; j++)\n        {\n            qa[j]+=points1[i][j];\n            qb[j]+=points2[i][j];\n        }\n    }\nqa=qa/points1.size();qb=qb/points2.size();\ncout<<\"qa:\"<<qa<<endl;\ncout<<\"qb\"<<qb<<endl;\n\n    for (int i=0; i<points1.size();i++)\n    {\npoints1[i]=points1[i]-qa;\npoints2[i]=points2[i]-qb;\n    }\n    Eigen::Matrix3d W=Eigen::Matrix3d::Zero();\n    for(int i=0;i<points1.size();i++)\n    {\n        W+=points1[i]*points2[i].transpose();\n    }\n    cout<<\"W:\"<<W<<endl;\n//svd\n\n\nEigen::JacobiSVD<Eigen::Matrix3d> svd (W,Eigen::ComputeFullU|Eigen::ComputeFullV);\n    Eigen::Matrix3d U= svd.matrixU();\n    Eigen::Matrix3d V=svd.matrixV();\n\n    Eigen::Matrix3d Rr=U*V.transpose();\n    cout <<\"Rr\"<<Rr<<endl;\n\n    return 0;\n\n\n\n}\n", "meta": {"hexsha": "f509db5b28950d5d542464179ce11dd410061f1b", "size": 1650, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "icp.cpp", "max_stars_repo_name": "TianXiaoRui/slam_book_self", "max_stars_repo_head_hexsha": "dd30bd0bbd0944b060d658e5af0eab0c492e17d3", "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": "icp.cpp", "max_issues_repo_name": "TianXiaoRui/slam_book_self", "max_issues_repo_head_hexsha": "dd30bd0bbd0944b060d658e5af0eab0c492e17d3", "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": "icp.cpp", "max_forks_repo_name": "TianXiaoRui/slam_book_self", "max_forks_repo_head_hexsha": "dd30bd0bbd0944b060d658e5af0eab0c492e17d3", "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.1538461538, "max_line_length": 82, "alphanum_fraction": 0.5703030303, "num_tokens": 573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391706552538, "lm_q2_score": 0.7905303162021596, "lm_q1q2_score": 0.7296904474450769}}
{"text": "// negative_binomial_example1.cpp\n\n// Copyright Paul A. Bristow 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 negative_binomial distribution.\n\n//[negative_binomial_eg1_1\n\n/*`\nBased on [@http://en.wikipedia.org/wiki/Negative_binomial_distribution\na problem by Dr. Diane Evans,\nProfessor of Mathematics at Rose-Hulman Institute of Technology].\n\nPat is required to sell candy bars to raise money for the 6th grade field trip.\nThere are thirty houses in the neighborhood,\nand Pat is not supposed to return home until five candy bars have been sold.\nSo the child goes door to door, selling candy bars.\nAt each house, there is a 0.4 probability (40%) of selling one candy bar\nand a 0.6 probability (60%) of selling nothing.\n\nWhat is the probability mass (density) function (pdf) for selling the last (fifth)\ncandy bar at the nth house?\n\nThe Negative Binomial(r, p) distribution describes the probability of k failures\nand r successes in k+r Bernoulli(p) trials with success on the last trial.\n(A [@http://en.wikipedia.org/wiki/Bernoulli_distribution Bernoulli trial]\nis one with only two possible outcomes, success of failure,\nand p is the probability of success).\nSee also [@ http://en.wikipedia.org/wiki/Bernoulli_distribution Bernoulli distribution]\nand [@http://www.math.uah.edu/stat/bernoulli/Introduction.xhtml Bernoulli applications].\n\nIn this example, we will deliberately produce a variety of calculations\nand outputs to demonstrate the ways that the negative binomial distribution\ncan be implemented with this library: it is also deliberately over-commented.\n\nFirst we need to #define macros to control the error and discrete handling policies.\nFor this simple example, we want to avoid throwing\nan exception (the default policy) and just return infinity.\nWe want to treat the distribution as if it was continuous,\nso we choose a discrete_quantile policy of real,\nrather than the default policy integer_round_outwards.\n*/\n#define BOOST_MATH_OVERFLOW_ERROR_POLICY ignore_error\n#define BOOST_MATH_DISCRETE_QUANTILE_POLICY real\n/*`\nAfter that we need some includes to provide easy access to the negative binomial distribution,\n[caution It is vital to #include distributions etc *after* the above #defines]\nand we need some std library iostream, of course.\n*/\n#include <boost/math/distributions/negative_binomial.hpp>\n  // for negative_binomial_distribution\n  using boost::math::negative_binomial; // typedef provides default type is double.\n  using  ::boost::math::pdf; // Probability mass function.\n  using  ::boost::math::cdf; // Cumulative density function.\n  using  ::boost::math::quantile;\n\n#include <iostream>\n  using std::cout; using std::endl;\n  using std::noshowpoint; using std::fixed; using std::right; using std::left;\n#include <iomanip>\n  using std::setprecision; using std::setw; \n\n#include <limits>\n  using std::numeric_limits;\n//] [negative_binomial_eg1_1]\n\nint main()\n{\n  cout <<\"Selling candy bars - using the negative binomial distribution.\" \n    << \"\\nby Dr. Diane Evans,\"\n    \"\\nProfessor of Mathematics at Rose-Hulman Institute of Technology,\"\n    << \"\\nsee http://en.wikipedia.org/wiki/Negative_binomial_distribution\\n\"\n    << endl;\n  cout << endl;\n  cout.precision(5); \n  // None of the values calculated have a useful accuracy as great this, but\n  // INF shows wrongly with < 5 !\n  // https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=240227\n//[negative_binomial_eg1_2\n/*`\nIt is always sensible to use try and catch blocks because defaults policies are to\nthrow an exception if anything goes wrong.\n\nA simple catch block (see below) will ensure that you get a\nhelpful error message instead of an abrupt program abort.\n*/\n  try\n  {\n/*`\nSelling five candy bars means getting five successes, so successes r = 5.\nThe total number of trials (n, in this case, houses visited) this takes is therefore\n  = sucesses + failures or k + r = k + 5.\n*/\n    double sales_quota = 5; // Pat's sales quota - successes (r).\n/*`\nAt each house, there is a 0.4 probability (40%) of selling one candy bar\nand a 0.6 probability (60%) of selling nothing.\n*/\n    double success_fraction = 0.4; // success_fraction (p) - so failure_fraction is 0.6.\n/*`\nThe Negative Binomial(r, p) distribution describes the probability of k failures\nand r successes in k+r Bernoulli(p) trials with success on the last trial.\n(A [@http://en.wikipedia.org/wiki/Bernoulli_distribution Bernoulli trial]\nis one with only two possible outcomes, success of failure,\nand p is the probability of success).\n\nWe therefore start by constructing a negative binomial distribution\nwith parameters sales_quota (required successes) and probability of success.\n*/\n    negative_binomial nb(sales_quota, success_fraction); // type double by default.\n/*`\nTo confirm, display the success_fraction & successes parameters of the distribution.\n*/\n    cout << \"Pat has a sales per house success rate of \" << success_fraction\n      << \".\\nTherefore he would, on average, sell \" << nb.success_fraction() * 100\n      << \" bars after trying 100 houses.\" << endl;\n\n    int all_houses = 30; // The number of houses on the estate.\n\n    cout << \"With a success rate of \" << nb.success_fraction() \n      << \", he might expect, on average,\\n\"\n        \"to need to visit about \" << success_fraction * all_houses\n        << \" houses in order to sell all \" << nb.successes() << \" bars. \" << endl;\n/*`\n[pre\nPat has a sales per house success rate of 0.4.\nTherefore he would, on average, sell 40 bars after trying 100 houses.\nWith a success rate of 0.4, he might expect, on average,\nto need to visit about 12 houses in order to sell all 5 bars. \n]\n\nThe random variable of interest is the number of houses\nthat must be visited to sell five candy bars,\nso we substitute k = n - 5 into a negative_binomial(5, 0.4)\nand obtain the [link math.dist.pdf probability mass (density) function (pdf or pmf)]\nof the distribution of houses visited.\nObviously, the best possible case is that Pat makes sales on all the first five houses.\n\nWe calculate this using the pdf function:\n*/\n    cout << \"Probability that Pat finishes on the \" << sales_quota << \"th house is \"\n      << pdf(nb, 5 - sales_quota) << endl; // == pdf(nb, 0)\n/*`\nOf course, he could not finish on fewer than 5 houses because he must sell 5 candy bars.\nSo the 5th house is the first that he could possibly finish on.\n\nTo finish on or before the 8th house, Pat must finish at the 5th, 6th, 7th or 8th house.\nThe probability that he will finish on *exactly* ( == ) on any house\nis the Probability Density Function (pdf).\n*/\n    cout << \"Probability that Pat finishes on the 6th house is \"\n      << pdf(nb, 6 - sales_quota) << endl;\n    cout << \"Probability that Pat finishes on the 7th house is \"\n      << pdf(nb, 7 - sales_quota) << endl;\n    cout << \"Probability that Pat finishes on the 8th house is \"\n      << pdf(nb, 8 - sales_quota) << endl;\n/*`\n[pre\nProbability that Pat finishes on the 6th house is 0.03072\nProbability that Pat finishes on the 7th house is 0.055296\nProbability that Pat finishes on the 8th house is 0.077414\n]\n\nThe sum of the probabilities for these houses is the Cumulative Distribution Function (cdf).\nWe can calculate it by adding the individual probabilities.\n*/\n    cout << \"Probability that Pat finishes on or before the 8th house is sum \"\n      \"\\n\" << \"pdf(sales_quota) + pdf(6) + pdf(7) + pdf(8) = \"\n      // Sum each of the mass/density probabilities for houses sales_quota = 5, 6, 7, & 8.\n      << pdf(nb, 5 - sales_quota) // 0 failures.\n        + pdf(nb, 6 - sales_quota) // 1 failure.\n        + pdf(nb, 7 - sales_quota) // 2 failures.\n        + pdf(nb, 8 - sales_quota) // 3 failures.\n      << endl;\n/*`[pre\npdf(sales_quota) + pdf(6) + pdf(7) + pdf(8) = 0.17367\n]\n\nOr, usually better, by using the negative binomial *cumulative* distribution function.\n*/    \n    cout << \"\\nProbability of selling his quota of \" << sales_quota\n      << \" bars\\non or before the \" << 8 << \"th house is \"\n      << cdf(nb, 8 - sales_quota) << endl;\n/*`[pre\nProbability of selling his quota of 5 bars on or before the 8th house is 0.17367\n]*/\n    cout << \"\\nProbability that Pat finishes exactly on the 10th house is \"\n      << pdf(nb, 10 - sales_quota) << endl;\n    cout << \"\\nProbability of selling his quota of \" << sales_quota\n      << \" bars\\non or before the \" << 10 << \"th house is \"\n      << cdf(nb, 10 - sales_quota) << endl;\n/*`\n[pre\nProbability that Pat finishes exactly on the 10th house is 0.10033\nProbability of selling his quota of 5 bars on or before the 10th house is 0.3669\n]*/\n    cout << \"Probability that Pat finishes exactly on the 11th house is \"\n      << pdf(nb, 11 - sales_quota) << endl;\n    cout << \"\\nProbability of selling his quota of \" << sales_quota\n      << \" bars\\non or before the \" << 11 << \"th house is \"\n      << cdf(nb, 11 - sales_quota) << endl;\n/*`[pre\nProbability that Pat finishes on the 11th house is 0.10033\nProbability of selling his quota of 5 candy bars\non or before the 11th house is 0.46723\n]*/\n    cout << \"Probability that Pat finishes exactly on the 12th house is \"\n      << pdf(nb, 12 - sales_quota) << endl;\n\n    cout << \"\\nProbability of selling his quota of \" << sales_quota\n      << \" bars\\non or before the \" << 12 << \"th house is \"\n      << cdf(nb, 12 - sales_quota) << endl;\n/*`[pre\nProbability that Pat finishes on the 12th house is 0.094596\nProbability of selling his quota of 5 candy bars\non or before the 12th house is 0.56182\n]\nFinally consider the risk of Pat not selling his quota of 5 bars\neven after visiting all the houses.\nCalculate the probability that he /will/ sell on \nor before the last house:\nCalculate the probability that he would sell all his quota on the very last house.\n*/\n    cout << \"Probability that Pat finishes on the \" << all_houses\n      << \" house is \" << pdf(nb, all_houses - sales_quota) << endl;\n/*`\nProbability of selling his quota of 5 bars on the 30th house is \n[pre\nProbability that Pat finishes on the 30 house is 0.00069145\n]\nwhen he'd be very unlucky indeed!\n\nWhat is the probability that Pat exhausts all 30 houses in the neighborhood,\nand *still* doesn't sell the required 5 candy bars?\n*/  \n    cout << \"\\nProbability of selling his quota of \" << sales_quota\n      << \" bars\\non or before the \" << all_houses << \"th house is \"\n      << cdf(nb, all_houses - sales_quota) << endl;\n/*`\n[pre\nProbability of selling his quota of 5 bars\non or before the 30th house is 0.99849\n]\n\n/*`So the risk of failing even after visiting all the houses is 1 - this probability,\n  ``1 - cdf(nb, all_houses - sales_quota``\nBut using this expression may cause serious inaccuracy,\nso it would be much better to use the complement of the cdf:\nSo the risk of failing even at, or after, the 31th (non-existent) houses is 1 - this probability,\n  ``1 - cdf(nb, all_houses - sales_quota)`` \nBut using this expression may cause serious inaccuracy. \nSo it would be much better to use the complement of the cdf.\n[link why_complements Why complements?]\n*/\n    cout << \"\\nProbability of failing to sell his quota of \" << sales_quota\n      << \" bars\\neven after visiting all \" << all_houses << \" houses is \"\n      << cdf(complement(nb, all_houses - sales_quota)) << endl;\n/*`\n[pre\nProbability of failing to sell his quota of 5 bars\neven after visiting all 30 houses is 0.0015101\n]\nWe can also use the quantile (percentile), the inverse of the cdf, to\npredict which house Pat will finish on.  So for the 8th house:\n*/\n double p = cdf(nb, (8 - sales_quota)); \n cout << \"Probability of meeting sales quota on or before 8th house is \"<< p << endl;\n/*`\n[pre\nProbability of meeting sales quota on or before 8th house is 0.174\n]\n*/\n    cout << \"If the confidence of meeting sales quota is \" << p\n        << \", then the finishing house is \" << quantile(nb, p) + sales_quota << endl;\n\n    cout<< \" quantile(nb, p) = \" << quantile(nb, p) << endl;\n/*`\n[pre\nIf the confidence of meeting sales quota is 0.17367, then the finishing house is 8\n]\nDemanding absolute certainty that all 5 will be sold,\nimplies an infinite number of trials.\n(Of course, there are only 30 houses on the estate,\nso he can't ever be *certain* of selling his quota).\n*/\n    cout << \"If the confidence of meeting sales quota is \" << 1.\n        << \", then the finishing house is \" << quantile(nb, 1) + sales_quota << endl;\n    //  1.#INF == infinity.\n/*`[pre\nIf the confidence of meeting sales quota is 1, then the finishing house is 1.#INF\n]\nAnd similarly for a few other probabilities:\n*/\n    cout << \"If the confidence of meeting sales quota is \" << 0.\n        << \", then the finishing house is \" << quantile(nb, 0.) + sales_quota << endl;\n\n    cout << \"If the confidence of meeting sales quota is \" << 0.5\n        << \", then the finishing house is \" << quantile(nb, 0.5) + sales_quota << endl;\n\n    cout << \"If the confidence of meeting sales quota is \" << 1 - 0.00151 // 30 th\n        << \", then the finishing house is \" << quantile(nb, 1 - 0.00151) + sales_quota << endl;\n/*`\n[pre\nIf the confidence of meeting sales quota is 0, then the finishing house is 5\nIf the confidence of meeting sales quota is 0.5, then the finishing house is 11.337\nIf the confidence of meeting sales quota is 0.99849, then the finishing house is 30\n]\n\nNotice that because we chose a discrete quantile policy of real,\nthe result can be an 'unreal' fractional house.\n\nIf the opposite is true, we don't want to assume any confidence, then this is tantamount\nto assuming that all the first sales_quota trials will be successful sales.\n*/\n    cout << \"If confidence of meeting quota is zero\\n(we assume all houses are successful sales)\" \n      \", then finishing house is \" << sales_quota << endl;\n/*`\n[pre\nIf confidence of meeting quota is zero (we assume all houses are successful sales), then finishing house is 5\nIf confidence of meeting quota is 0, then finishing house is 5\n]\nWe can list quantiles for a few probabilities:\n*/\n\n    double ps[] = {0., 0.001, 0.01, 0.05, 0.1, 0.5, 0.9, 0.95, 0.99, 0.999, 1.};\n    // Confidence as fraction = 1-alpha, as percent =  100 * (1-alpha[i]) %\n    cout.precision(3);\n    for (int i = 0; i < sizeof(ps)/sizeof(ps[0]); i++)\n    {\n      cout << \"If confidence of meeting quota is \" << ps[i]\n        << \", then finishing house is \" << quantile(nb, ps[i]) + sales_quota\n        << endl;\n   }\n\n/*`\n[pre\nIf confidence of meeting quota is 0, then finishing house is 5\nIf confidence of meeting quota is 0.001, then finishing house is 5\nIf confidence of meeting quota is 0.01, then finishing house is 5\nIf confidence of meeting quota is 0.05, then finishing house is 6.2\nIf confidence of meeting quota is 0.1, then finishing house is 7.06\nIf confidence of meeting quota is 0.5, then finishing house is 11.3\nIf confidence of meeting quota is 0.9, then finishing house is 17.8\nIf confidence of meeting quota is 0.95, then finishing house is 20.1\nIf confidence of meeting quota is 0.99, then finishing house is 24.8\nIf confidence of meeting quota is 0.999, then finishing house is 31.1\nIf confidence of meeting quota is 1, then finishing house is 1.#INF\n]\n\nWe could have applied a ceil function to obtain a 'worst case' integer value for house.\n``ceil(quantile(nb, ps[i]))``\n\nOr, if we had used the default discrete quantile policy, integer_outside, by omitting\n``#define BOOST_MATH_DISCRETE_QUANTILE_POLICY real``\nwe would have achieved the same effect.\n\nThe real result gives some suggestion which house is most likely.\nFor example, compare the real and integer_outside for 95% confidence.\n\n[pre\nIf confidence of meeting quota is 0.95, then finishing house is 20.1\nIf confidence of meeting quota is 0.95, then finishing house is 21\n]\nThe real value 20.1 is much closer to 20 than 21, so integer_outside is pessimistic.\nWe could also use integer_round_nearest policy to suggest that 20 is more likely.\n\nFinally, we can tabulate the probability for the last sale being exactly on each house.\n*/\n   cout << \"\\nHouse for \" << sales_quota << \"th (last) sale.  Probability (%)\" << endl;\n   cout.precision(5);\n   for (int i = (int)sales_quota; i < all_houses+1; i++)\n   {\n     cout << left << setw(3) << i << \"                             \" << setw(8) << cdf(nb, i - sales_quota)  << endl;\n   }\n   cout << endl;\n/*`\n[pre\nHouse for 5 th (last) sale.  Probability (%)\n5                               0.01024 \n6                               0.04096 \n7                               0.096256\n8                               0.17367 \n9                               0.26657 \n10                              0.3669  \n11                              0.46723 \n12                              0.56182 \n13                              0.64696 \n14                              0.72074 \n15                              0.78272 \n16                              0.83343 \n17                              0.874   \n18                              0.90583 \n19                              0.93039 \n20                              0.94905 \n21                              0.96304 \n22                              0.97342 \n23                              0.98103 \n24                              0.98655 \n25                              0.99053 \n26                              0.99337 \n27                              0.99539 \n28                              0.99681 \n29                              0.9978  \n30                              0.99849\n]\n\nAs noted above, using a catch block is always a good idea, even if you do not expect to use it.\n*/\n  }\n  catch(const std::exception& e)\n  { // Since we have set an overflow policy of ignore_error,\n    // an overflow exception should never be thrown.\n     std::cout << \"\\nMessage from thrown exception was:\\n \" << e.what() << std::endl;\n/*`\nFor example, without a ignore domain error policy, if we asked for ``pdf(nb, -1)`` for example, we would get:\n[pre\nMessage from thrown exception was:\n Error in function boost::math::pdf(const negative_binomial_distribution<double>&, double):\n Number of failures argument is -1, but must be >= 0 !\n]\n*/\n//] [/ negative_binomial_eg1_2]\n  }\n   return 0;\n}  // int main()\n\n\n/*\n\nOutput is:\n\nSelling candy bars - using the negative binomial distribution.\nby Dr. Diane Evans,\nProfessor of Mathematics at Rose-Hulman Institute of Technology,\nsee http://en.wikipedia.org/wiki/Negative_binomial_distribution\nPat has a sales per house success rate of 0.4.\nTherefore he would, on average, sell 40 bars after trying 100 houses.\nWith a success rate of 0.4, he might expect, on average,\nto need to visit about 12 houses in order to sell all 5 bars. \nProbability that Pat finishes on the 5th house is 0.01024\nProbability that Pat finishes on the 6th house is 0.03072\nProbability that Pat finishes on the 7th house is 0.055296\nProbability that Pat finishes on the 8th house is 0.077414\nProbability that Pat finishes on or before the 8th house is sum \npdf(sales_quota) + pdf(6) + pdf(7) + pdf(8) = 0.17367\nProbability of selling his quota of 5 bars\non or before the 8th house is 0.17367\nProbability that Pat finishes exactly on the 10th house is 0.10033\nProbability of selling his quota of 5 bars\non or before the 10th house is 0.3669\nProbability that Pat finishes exactly on the 11th house is 0.10033\nProbability of selling his quota of 5 bars\non or before the 11th house is 0.46723\nProbability that Pat finishes exactly on the 12th house is 0.094596\nProbability of selling his quota of 5 bars\non or before the 12th house is 0.56182\nProbability that Pat finishes on the 30 house is 0.00069145\nProbability of selling his quota of 5 bars\non or before the 30th house is 0.99849\nProbability of failing to sell his quota of 5 bars\neven after visiting all 30 houses is 0.0015101\nProbability of meeting sales quota on or before 8th house is 0.17367\nIf the confidence of meeting sales quota is 0.17367, then the finishing house is 8\n quantile(nb, p) = 3\nIf the confidence of meeting sales quota is 1, then the finishing house is 1.#INF\nIf the confidence of meeting sales quota is 0, then the finishing house is 5\nIf the confidence of meeting sales quota is 0.5, then the finishing house is 11.337\nIf the confidence of meeting sales quota is 0.99849, then the finishing house is 30\nIf confidence of meeting quota is zero\n(we assume all houses are successful sales), then finishing house is 5\nIf confidence of meeting quota is 0, then finishing house is 5\nIf confidence of meeting quota is 0.001, then finishing house is 5\nIf confidence of meeting quota is 0.01, then finishing house is 5\nIf confidence of meeting quota is 0.05, then finishing house is 6.2\nIf confidence of meeting quota is 0.1, then finishing house is 7.06\nIf confidence of meeting quota is 0.5, then finishing house is 11.3\nIf confidence of meeting quota is 0.9, then finishing house is 17.8\nIf confidence of meeting quota is 0.95, then finishing house is 20.1\nIf confidence of meeting quota is 0.99, then finishing house is 24.8\nIf confidence of meeting quota is 0.999, then finishing house is 31.1\nIf confidence of meeting quota is 1, then finishing house is 1.#J\nHouse for 5th (last) sale.  Probability (%)\n5                               0.01024 \n6                               0.04096 \n7                               0.096256\n8                               0.17367 \n9                               0.26657 \n10                              0.3669  \n11                              0.46723 \n12                              0.56182 \n13                              0.64696 \n14                              0.72074 \n15                              0.78272 \n16                              0.83343 \n17                              0.874   \n18                              0.90583 \n19                              0.93039 \n20                              0.94905 \n21                              0.96304 \n22                              0.97342 \n23                              0.98103 \n24                              0.98655 \n25                              0.99053 \n26                              0.99337 \n27                              0.99539 \n28                              0.99681 \n29                              0.9978  \n30                              0.99849 \n\n*/\n\n\n\n\n\n\n", "meta": {"hexsha": "ce5c50999f8056bfe0cd4e3dcde2a412772d75b1", "size": 22251, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/example/negative_binomial_example1.cpp", "max_stars_repo_name": "mike-code/boost_1_38_0", "max_stars_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-06-25T23:20:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-14T19:38:34.000Z", "max_issues_repo_path": "libs/math/example/negative_binomial_example1.cpp", "max_issues_repo_name": "boost-cmake/vintage", "max_issues_repo_head_hexsha": "dcfb7da3177134eddaee6789d6f582259cb0d6ee", "max_issues_repo_licenses": ["BSL-1.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/math/example/negative_binomial_example1.cpp", "max_forks_repo_name": "boost-cmake/vintage", "max_forks_repo_head_hexsha": "dcfb7da3177134eddaee6789d6f582259cb0d6ee", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-07-26T08:07:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-25T23:20:21.000Z", "avg_line_length": 42.6264367816, "max_line_length": 117, "alphanum_fraction": 0.6680598625, "num_tokens": 5752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267694452331, "lm_q2_score": 0.8397339736884711, "lm_q1q2_score": 0.7295833555531627}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <iostream>\n\n#include <boost/numeric/mtl/mtl.hpp>\n \nusing namespace std;  \n\ntemplate <typename Matrix, typename Vector>\nvoid inline power_iteration(const Matrix& A, Vector& v, double tau)\n{\n    assert(num_rows(A) == num_cols(A));               // A should be square    \n    v*= 1. / two_norm(v);                             // Normalize v\n    Vector v2(size(v));\n    do {\t \n\tswap(v, v2);                                  // Keep old value in v2    \n\tv= A * v2;           \t\n\tv*= 1. / two_norm(v);                         // Normalize \n    } while (two_norm(Vector(v - v2)) >= tau);\n}\n\ntemplate <typename Matrix, typename Vector>\nbool inline check_eigenvector(const Matrix& A, Vector& v, double tau)\n{    \n    Vector w(A * v);\n    std::cout << \"A * v is \" << w << endl;\n\n    typename mtl::Collection<Vector>::value_type alpha= two_norm(w) / two_norm(v);\n    std::cout << \"Eigenvalue alpha for v is \" << alpha << endl;\n    Vector w2(alpha * v);\n    std::cout << \"alpha * v is \" << w2 << endl;\n\n    bool close= two_norm(Vector(w - w2)) / two_norm(Vector(w + w2)) < tau;\n    std::cout << \"The results are \" << (close ? \"similar.\\n\" : \"different.\\n\") << endl;\n    return close;\n}\n\nint main(int, char**)\n{\n    double a_value[4][4] = {{0, 0, 1, .5},\n\t\t\t    {1/3., 0, 0, 0},\n\t\t\t    {1/3., .5, 0, .5},\n\t\t\t    {1/3., .5, 0, 0}};\n    mtl::dense2D<double> A(a_value);\n    mtl::dense_vector<double> v(4, 1.0);\n\n    power_iteration(A, v, 0.00001);\n    check_eigenvector(A, v, 0.001);\n\n    mtl::compressed2D<double> B(9, 9);\n    {\n\tmtl::mat::inserter<mtl::compressed2D<double> > ins(B);\n\tins[0][1] << .2; ins[0][4] << .5;\n\tins[1][0] << .5; ins[1][3] << 1; ins[1][4] << .5; ins[1][5] << .25; ins[1][6] << 1/3.;\n\tins[2][2] << .1; ins[2][5] << .25;\n\tins[3][1] << .2;\n\tins[4][0] << .5; ins[4][1] << .2;\n\tins[5][1] << .2; ins[5][6] << 1/3.; ins[5][8] << 1; \n\tins[6][1] << .2; ins[6][5] << .25; ins[6][7] << 1; \n\tins[7][6] << 1/3.; \n\tins[8][5] << .25; \n    }\n    mtl::dense_vector<double> w(9, 1.0);\n\n    power_iteration(B, w, 0.00001);\n    check_eigenvector(B, w, 0.001);\n\n    return 0;\n}\n", "meta": {"hexsha": "64dc0b9c7846e7cf1070f43bd5ea906053fc68eb", "size": 2520, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/page_rank_test.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/test/page_rank_test.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/test/page_rank_test.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 31.5, "max_line_length": 94, "alphanum_fraction": 0.544047619, "num_tokens": 871, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797100118214, "lm_q2_score": 0.8006920092299293, "lm_q1q2_score": 0.7295743127789096}}
{"text": "    #include <Eigen/Dense>\n    #include <Eigen/Sparse>\n    #include <unsupported/Eigen/AutoDiff>\n\n    #include <iostream>\n    #include <cmath>\n\n    template <typename T>\n    T fun(Eigen::Matrix<T,Eigen::Dynamic,1> const &x){\n       T y;\n       y = x(0)*x(0)*x(0)*x(1) + x(0)*x(0)*x(1)*x(1)*x(1)*x(1); // f(x) = x[0]^3 * x[1]  + x[0]^2 * x[1]^4\n       return y;\n    }\n\n    template <typename T>\n\tT dist(Eigen::Matrix<T,Eigen::Dynamic,1> const &x, Eigen::Matrix<T,Eigen::Dynamic,1> const &y){\n\tT r;\n\tr =x.dot(y);\n\treturn r;\n    }\n\n\n    int main(){\n       //normal use of fun\n       {\n        \n\t  typedef double scalar_t;\n          typedef Eigen::Matrix<scalar_t,Eigen::Dynamic,1> input_t;\n          input_t x(2);\n          x.setConstant(1);\n          scalar_t y = fun(x);\n\t  std::cout << \"Normal use of function\" << std::endl;\n\t  std::cout << y << std::endl;\n       }\n\tstd::cout << std::endl;\n       //autodiff use of dist\n       {\n\ttypedef Eigen::Matrix<double,Eigen::Dynamic,1> vec;\n\ttypedef Eigen::AutoDiffScalar<vec> AD;\n\ttypedef Eigen::Matrix<AD,Eigen::Dynamic,1> ADvec;\n\n\tvec vec1, vec2;\n\tvec1 = vec::Random(3).normalized(); \n\tvec2 = vec::Random(3).normalized();\n\n\tint s1 = vec1.size();\n\tint s2 = vec2.size();\n\n\tADvec ax(s1);\n\tADvec ay(s2);\n\tax = vec1.cast<AD>();\n\tay = vec2.cast<AD>();\n\n\tax.setZero(s1);\n\tay.setZero(s2);\n\n\tfor(int i=0; i<s1; i++){\n\t    ax(i).derivatives().resize(s1);\n\t    ax(i).derivatives()(i)=1;\n\t    ay(i).derivatives().resize(s2);\n\t    ay(i).derivatives()(i)=1;\n\t}\n\n\tAD res = dist(ax,ay);\n\tstd::cout << \"\\n Autodiff Dist function value: \\n\" << res.value() << std::endl;\n        std::cout << \"\\n x-Derivatives\\n \" << res.derivatives() << std::endl;\n//        std::cout << \"\\n y-Derivatives\\n \" << res.derivatives()(1) << std::endl;\n       }\n\n\n\tstd::cout << std::endl;\n       //autodiff use of fun\n       {\n          typedef Eigen::Matrix<double,Eigen::Dynamic,1> derivative_t;\n          typedef Eigen::AutoDiffScalar<derivative_t> scalar_t;\n          typedef Eigen::Matrix<scalar_t,Eigen::Dynamic,1> input_t;\n          input_t x(2);\n          x.setConstant(1);\n          \n          //set unit vectors for the derivative directions (partial derivatives of the input vector)\n          x(0).derivatives().resize(2);\n          x(0).derivatives()(0)=1;\n          x(1).derivatives().resize(2);\n          x(1).derivatives()(1)=1;\n\n          scalar_t y = fun(x);\n\t  std::cout << \"Autodiff use of function\" << std::endl;\n          std::cout << \"\\nFunction:\\n \" << y.value() << std::endl;\n          std::cout << \"\\nDerivatives\\n \" << y.derivatives() << std::endl;\n       }\n\tstd::cout << std::endl;\n       //autodiff second derivative of fun\n       {\n          typedef Eigen::Matrix<double,Eigen::Dynamic,1> inner_derivative_t;\n          typedef Eigen::AutoDiffScalar<inner_derivative_t> inner_scalar_t;\n          typedef Eigen::Matrix<inner_scalar_t,Eigen::Dynamic,1> derivative_t;\n          typedef Eigen::AutoDiffScalar<derivative_t> scalar_t;\n          typedef Eigen::Matrix<scalar_t,Eigen::Dynamic,1> input_t;\n          input_t x(2);\n          x(0).value()=1;\n          x(1).value()=1;\n          \n          //set unit vectors for the derivative directions (partial derivatives of the input vector)\n          x(0).derivatives().resize(2);\n          x(0).derivatives()(0)=1;\n          x(1).derivatives().resize(2);\n          x(1).derivatives()(1)=1;\n\n          //repeat partial derivatives for the inner AutoDiffScalar\n          x(0).value().derivatives() = inner_derivative_t::Unit(2,0);\n          x(1).value().derivatives() = inner_derivative_t::Unit(2,1);\n\n          //set the hessian matrix to zero\n          for(int idx=0;idx<2;idx++){\n             x(0).derivatives()(idx).derivatives()  = inner_derivative_t::Zero(2);\n             x(1).derivatives()(idx).derivatives()  = inner_derivative_t::Zero(2);\n          }\n\n          scalar_t y = fun(x);\n          //std::cout << y.value().value() << std::endl;\n          //std::cout << y.value().derivatives() << std::endl;\n          //std::cout << y.derivatives()(0).value() << std::endl;\n          std::cout << y.derivatives()(0).derivatives() << std::endl;\n         // std::cout << y.derivatives()(1).value() << std::endl;\n          std::cout << y.derivatives()(1).derivatives() << std::endl;\n       }\n    }\n", "meta": {"hexsha": "0d6f0ffccd4ed8dc1be1a4deedb4d538f6d8c3aa", "size": 4276, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/autodiff_test.cpp", "max_stars_repo_name": "pdebus/MTVMTL", "max_stars_repo_head_hexsha": "65a7754b34d1f6a1e86d15e3c2d4346b9418414f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-05-08T12:40:46.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-02T05:11:01.000Z", "max_issues_repo_path": "test/autodiff_test.cpp", "max_issues_repo_name": "pdebus/MTVMTL", "max_issues_repo_head_hexsha": "65a7754b34d1f6a1e86d15e3c2d4346b9418414f", "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/autodiff_test.cpp", "max_forks_repo_name": "pdebus/MTVMTL", "max_forks_repo_head_hexsha": "65a7754b34d1f6a1e86d15e3c2d4346b9418414f", "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.40625, "max_line_length": 106, "alphanum_fraction": 0.5598690365, "num_tokens": 1253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465062370313, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.7295636389259144}}
{"text": "// Implements non-natives linear algebra classes (Mat and Vec) - Felipe Figueredo Rocha\n#ifndef _linalg_hpp\n#define _linalg_hpp\n\n#include <iostream>\n#include <iomanip>\n#include <string>\n#include <fstream>\n#include <vector>\n#include <stdlib.h>  \n#include <sstream>\n#include <cmath>\n//~ #include <gsl/gsl_matrix.h>\n//~ #include <gsl/gsl_vector.h>\n//~ #include <gsl/gsl_blas.h>\n//~ #include <gsl/gsl_linalg.h>\n#include <armadillo>\n\n//~ using namespace arma;\nusing namespace std;\n\n#define PRECISAO 12 \n\n\n// defines shortcuts for some most useds object types\ntemplate <class T> class Vec;\ntemplate <class T> class Mat;\ntypedef double SGPreal; // long double is not supported by GSL\ntypedef Vec<SGPreal> SGPrealVec;\ntypedef Mat<SGPreal> SGPrealMat;\ntypedef Vec<int> intVec;\ntypedef Mat<int> intMat;\n\n// class numerical vector\ntemplate <class T> class Vec{\n\tpublic:\n\tT *v;\n\tint n;\n\tVec() { n = 0; }\n\tVec(int nn) { n= nn; v = new T[n]; (*this)=0.0; }\t\n\tvoid readNumberBlock(ifstream &file); // reads a block of n (size of the vector) numbers in a file\n\tvoid writeNumberBlock(ofstream &file); // idem to the last, but writes\n\tvoid writeNumberBlockRect(ofstream &file, int m);\n\tvoid print();\n\tvoid printH();\n\tT max();\n\tT min();\n\tT sum();\n\tT amax();\n\tT& operator()(int i) {return v[i];}\n\tT& operator[](int i) {return v[i];}\n\tvoid operator=(T a) { for(int i=0; i<n ; i++) v[i]=a;}\n\tvoid operator=(Vec &w) { for(int i=0; i<n ; i++) v[i]=w[i];}\n\tvoid operator=(arma::vec &w) { for(int i=0; i<n ; i++) v[i]=w[i];}\n};\n\ntemplate<class T> void Vec<T>:: print(){\t\n\tfor(int i = 0; i<n ; i++) cout << v[i] << endl;\n}\n\ntemplate<class T> void Vec<T>:: printH(){\t\n\tfor(int i = 0; i<n ; i++) cout << v[i] << \" \";\n\tcout << endl;\n}\n\n\ntemplate <class T> void Vec<T> :: readNumberBlock(ifstream &file){\t\n\t//~ file << fixed << setprecision(PRECISAO);\n\tfor(int i = 0; i<n ; i++) file  >> v[i] ;\t\n}\n\ntemplate <class T> void Vec<T> :: writeNumberBlock(ofstream &file){\t\n\tfile << scientific << setprecision(PRECISAO);\n\tfor(int i = 0; i<n ; i++) file  << v[i] << endl ;\t\n}\n\ntemplate <class T> void Vec<T> :: writeNumberBlockRect(ofstream &file,int m){\t\n\tif(n%m==0){\n\t\tint nn = n/m;\n\t\tint ip = 0;\n\t\tfile << scientific << setprecision(PRECISAO);\n\t\tfor(int i = 0; i<nn ; i++){ \n\t\t\tip = i*m;\n\t\t\tfor(int j = 0; j<m ; j++){\n\t\t\t\tfile  << v[ip + j] << \" \" ;\n\t\t\t}\n\t\t\tfile << endl ;\n\t\t}\n\t} else {\n\t\twriteNumberBlock(file);\n\t}\n}\t\n\ntemplate <class T> T Vec<T> :: max(){\t\n\tT vmax = -9999.0;\n\t\n\tfor(int i = 0; i<n ; i++){\n\t\tif(v[i]>vmax) vmax = v[i];\n\t}\t\n\t\n\treturn vmax;\n}\n\ntemplate <class T> T Vec<T> :: sum(){\t\n\tT vsum = 0.0;\n\t\n\tfor(int i = 0; i<n ; i++) vsum += v[i];\n\t\n\treturn vsum;\n}\n\ntemplate <class T> T Vec<T> :: amax(){\t\n\tT vmax = 0.0;\n\tT aux;\n\t\n\tfor(int i = 0; i<n ; i++){\n\t\taux = abs(v[i]);\n\t\tif(aux>vmax) vmax = aux;\n\t}\t\n\t\n\treturn vmax;\n}\n\n\n// class numerical matrix as a spelization of the Vec. All the elements are in a Vec, but can be acessed with two indices. Row-major convention (C convention)\ntemplate <class T> class Mat : public Vec<T>{\n\tpublic:\n\tint m1,m2; // m1 is Nrows, m2 is Ncolumns \n\tMat() {}\n\tMat(int mm1, int mm2):Vec<T>(mm1*mm2) { m1 = mm1; m2 = mm2;  }\n\tMat(Vec<T> &V, int mm1, int mm2) { m1 = mm1; m2 = mm2; this->v = V.v; }\n\t\n\t//~ T& operator()(int i,int j) {return this->v[j*m1 + i];} Fortran style\n\tT& operator()(int i,int j) {return this->v[i*m2 + j];} // C style, compatibility with GSL\n\tvoid operator=(T a) { for(int i=0; i<this->n ; i++) this->v[i]=a;}\n\tvoid operator=(Mat &w) { for(int i=0; i<this->n ; i++) this->v[i]=w->v[i];}\n\tvoid prettyPrint();\n\tvoid prettyPrintClean();\n\tvoid solve(SGPrealVec &x,SGPrealVec &b); // solves linear system using GSL\n};\n\ntemplate<class T> void Mat<T> :: prettyPrint(){\n\t//~ cout << m1 << \" \" << m2 << endl;\n\tfor (int i=0;i<m1;i++){ \n        for (int j=0;j<m2;j++) cout << \"a[\" << i << \"][\" << j << \"]=\" << (*this)(i,j) << \"  \" ;\n        cout << endl; \n    }\n}\n\ntemplate<class T> void Mat<T> :: prettyPrintClean(){\n\t//~ cout << m1 << \" \" << m2 << endl;\n\tfor (int i=0;i<m1;i++){ \n        for (int j=0;j<m2;j++) cout << (*this)(i,j) << \"  \" ;\n        cout << endl; \n    }\n}\n\ntemplate<class T> T dot_product(Vec<T> &u,Vec<T> &w){\n\tT dot = 0.0;\n\t\n\tfor(int i=0; i<u.n ; i++) dot += u(i)*w(i);\n\t\n\treturn dot;\n}\n\ntemplate<class T> void Mat<T> :: solve(SGPrealVec &x,SGPrealVec &b){ \n\t// creates GSL objects\n\t//~ gsl_matrix_view gslA=gsl_matrix_view_array(this->v,this->m1,this->m2); \n\t//~ gsl_vector_view gslB=gsl_vector_view_array(b.v,b.n);\n\t//~ gsl_vector_view gslX=gsl_vector_view_array(x.v,x.n);\n\t//~ gsl_permutation *gslP=gsl_permutation_alloc(b.n);\n\t//~ \n\t//~ int sig;\n      //~ \n    //~ // solve system\n\t//~ gsl_linalg_LU_decomp(&gslA.matrix,gslP,&sig);\n    //~ gsl_linalg_LU_solve(&gslA.matrix,gslP,&gslB.vector,&gslX.vector);\n}\n\ndouble computeError(arma::vec &v, SGPrealVec &v0){\n\tdouble error = 0.0;\t\n\tarma::vec e(v0.n);\n\t\n\tfor(int i=0;i<v0.n;i++) e(i) = v(i) - v0(i);\n\t\n\tdouble emax = arma::abs(e).max();\n\tdouble v0max = v0.amax();\n\t\n\tif(v0max >0.0){\n\t\terror = emax/v0max;\n\t}\n\telse{\n\t\terror = emax;\n\t}\n\t\n\treturn error;\n}\n\ndouble computeError(SGPrealVec &v,SGPrealVec &v0){\n\t\n\tSGPrealVec e(v.n);\n\tdouble error = 0.0;\t\n\t\n\tfor(int i=0; i<v.n ; i++) e(i) = v(i) - v0(i);\n\t\n\tdouble emax = e.amax();\n\tdouble v0max = v0.amax();\n\t\n\tif(v0max >0.0){\n\t\terror = emax/v0max;\n\t}\n\telse{\n\t\terror = emax;\n\t}\n\t\n\treturn error;\n}\n\n\n#endif\n", "meta": {"hexsha": "aea70d7d83560ec52de8ad5dbb0237d3f0da52ed", "size": 5349, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/linAlg.hpp", "max_stars_repo_name": "felipefr/Piola", "max_stars_repo_head_hexsha": "2189b0a4d214f99cd550ee780f0b439e0763825f", "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/linAlg.hpp", "max_issues_repo_name": "felipefr/Piola", "max_issues_repo_head_hexsha": "2189b0a4d214f99cd550ee780f0b439e0763825f", "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/linAlg.hpp", "max_forks_repo_name": "felipefr/Piola", "max_forks_repo_head_hexsha": "2189b0a4d214f99cd550ee780f0b439e0763825f", "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.2036199095, "max_line_length": 158, "alphanum_fraction": 0.5933819405, "num_tokens": 1849, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544911, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.729513528382042}}
{"text": "/**\n * @file matode_main.cc\n * @brief NPDE homework MatODE code\n * @copyright Developed at ETH Zurich\n */\n\n#include <Eigen/Dense>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\n#include \"matode.h\"\n\nint main(int /*argc*/, char** /*argv*/) {\n  /* SAM_LISTING_BEGIN_6 */\n  double h = 0.01;  // stepsize\n  //Eigen::Vector3d norms;\n  // Build M\n  Eigen::Matrix3d M;\n  M << 8, 1, 6, 3, 5, 7, 9, 9, 2;\n  // Build A\n  Eigen::Matrix3d A;\n  A << 0, 1, 1, -1, 0, 1, -1, -1, 0;\n  Eigen::MatrixXd I = Eigen::Matrix3d::Identity();\n  //====================\n  // Your code goes here\n  //====================\n  \n  using namespace MatODE;\n\n  // y0 is Q in M = QR\n  Eigen::MatrixXd Y01, Y02, Y03;\n  Eigen::HouseholderQR<Eigen::MatrixXd> qr(M);\n  Y01 = Y02 = Y03 = qr.householderQ();\n\n  Eigen::MatrixXd norms = Eigen::MatrixXd::Zero(20, 3); // stores frobenius norms using 3 different methods\n  // perform 20 steps using the implemented methods\n  for(int i = 0; i < 20; ++i) {\n    // explicit Euler step\n    Eigen::MatrixXd Y1 = eeulstep(A, Y01, h);\n    norms(i, 0) = (Y1.transpose()*Y1 - I).norm();\n    Y01 = Y1;\n    // implicit Euler step\n    Y1 = ieulstep(A, Y02, h);\n    norms(i, 1) = (Y1.transpose()*Y1 - I).norm();\n    Y02 = Y1;\n    // implicit Euler step\n    Y1 = impstep(A, Y03, h);\n    norms(i, 2) = (Y1.transpose()*Y1 - I).norm();\n    Y03 = Y1;\n  }\n\n  std::cout << \"Norms:\" << std::endl;\n  std::cout << norms << std::endl;\n  /* SAM_LISTING_END_6 */\n  return 0;\n}\n", "meta": {"hexsha": "a97a8ccd0547c2f5ac491e3bf164f9bd0c36ecba", "size": 1464, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/MatODE/mysolution/matode_main.cc", "max_stars_repo_name": "rjs02/NPDECODES", "max_stars_repo_head_hexsha": "e15e492f7fd5a0a02a6c27c31673d2afc925b7d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-22T10:59:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T10:59:19.000Z", "max_issues_repo_path": "homeworks/MatODE/mysolution/matode_main.cc", "max_issues_repo_name": "rjs02/NPDECODES", "max_issues_repo_head_hexsha": "e15e492f7fd5a0a02a6c27c31673d2afc925b7d5", "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": "homeworks/MatODE/mysolution/matode_main.cc", "max_forks_repo_name": "rjs02/NPDECODES", "max_forks_repo_head_hexsha": "e15e492f7fd5a0a02a6c27c31673d2afc925b7d5", "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.2413793103, "max_line_length": 107, "alphanum_fraction": 0.5703551913, "num_tokens": 513, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278695464501, "lm_q2_score": 0.8267117940706735, "lm_q1q2_score": 0.729513527170708}}
{"text": "/**\n * @file exponentialintegrator.cc\n * @brief NPDE homework ExponentialIntegrator code\n * @author Unknown, Oliver Rietmann\n * @date 04.04.2021\n * @copyright Developed at ETH Zurich\n */\n\n#include \"exponentialintegrator.h\"\n\n#include <Eigen/Core>\n#include <cassert>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <unsupported/Eigen/MatrixFunctions>\n#include <vector>\n\nnamespace ExponentialIntegrator {\n\n// Function $\\phi$ used in the Exponential Euler\n// single step method for an autonomous ODE.\nEigen::MatrixXd phim(const Eigen::MatrixXd &Z) {\n  int n = Z.cols();\n  assert(n == Z.rows() && \"Matrix must be square.\");\n  Eigen::MatrixXd C(2 * n, 2 * n);\n  C << Z, Eigen::MatrixXd::Identity(n, n), Eigen::MatrixXd::Zero(n, 2 * n);\n  return C.exp().block(0, n, n, n);\n}\n\nvoid testExpEulerLogODE() {\n  /* SAM_LISTING_BEGIN_0 */\n  // Final time\n  double T = 1.0;\n  // Initial value\n  Eigen::VectorXd y0(1);\n  y0 << 0.1;\n  // Function and Jacobian and exact solution\n  auto f = [](const Eigen::VectorXd &y) { return y(0) * (1.0 - y(0)); };\n  auto df = [](const Eigen::VectorXd &y) {\n    Eigen::MatrixXd dfy(1, 1);\n    dfy << 1.0 - 2.0 * y(0);\n    return dfy;\n  };\n  double exactyT = y0(0) / (y0(0) + (1.0 - y0(0)) * std::exp(-T));\n\n  // Container for errors\n  std::vector<double> error(15);\n\n  // Test many step sizes\n  for (int j = 0; j < 15; ++j) {\n    int M = std::pow(2, j + 1);\n    Eigen::VectorXd y = y0;\n    double h = T / M;\n    //====================\n    // Your code goes here\n    // TODO: Perform N timesteps with inital data y0 and store the result in y.\n    //====================\n\n    error[j] = std::abs(y(0) - exactyT);\n    std::cout << std::left << std::setfill(' ') << std::setw(3)\n              << \"M = \" << std::setw(7) << M << std::setw(8)\n              << \"Error = \" << std::setw(13) << error[j];\n    if (j > 0) {\n      std::cout << std::left << std::setfill(' ') << std::setw(10)\n                << \"Approximated order = \" << std::log2(error[j - 1] / error[j])\n                << std::endl;\n    } else\n      std::cout << std::endl;\n  }\n  /* SAM_LISTING_END_0 */\n}\n\n}  // namespace ExponentialIntegrator\n", "meta": {"hexsha": "4033308f24aab28097c42c6c2a529c1fe782a43d", "size": 2138, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/ExponentialIntegrator/templates/exponentialintegrator.cc", "max_stars_repo_name": "0xBachmann/NPDECODES", "max_stars_repo_head_hexsha": "70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea", "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/ExponentialIntegrator/templates/exponentialintegrator.cc", "max_issues_repo_name": "0xBachmann/NPDECODES", "max_issues_repo_head_hexsha": "70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea", "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/ExponentialIntegrator/templates/exponentialintegrator.cc", "max_forks_repo_name": "0xBachmann/NPDECODES", "max_forks_repo_head_hexsha": "70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea", "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": 28.5066666667, "max_line_length": 80, "alphanum_fraction": 0.5687558466, "num_tokens": 674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117983401364, "lm_q2_score": 0.8824278571786139, "lm_q1q2_score": 0.729513520713565}}
{"text": "#pragma once\n\n#include <tuple>\n#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\n\n#include \"geometry.hpp\"\n\nnamespace rt {\n\tclass OnlineCovarianceMatrix2x2 {\n\tpublic:\n\t\tvoid addSample(Vec2 x) {\n\t\t\t_00.addSample(x[0], x[0]);\n\t\t\t_11.addSample(x[1], x[1]);\n\t\t\t_01.addSample(x[0], x[1]);\n\t\t}\n\t\tEigen::Matrix2d sampleCovarianceMatrix() const {\n\t\t\tEigen::Matrix2d cov;\n\t\t\tcov(0, 0) = _00.sampleCovariance();\n\t\t\tcov(1, 1) = _11.sampleCovariance();\n\t\t\tcov(0, 1) = cov(1, 0) = _01.sampleCovariance();\n\t\t\treturn cov;\n\t\t}\n\tprivate:\n\t\tOnlineCovariance _00;\n\t\tOnlineCovariance _11;\n\t\tOnlineCovariance _01;\n\t};\n\tclass OnlineCovarianceMatrix3x3 {\n\tpublic:\n\t\tvoid addSample(Vec3 x) {\n\t\t\t_00.addSample(x[0], x[0]);\n\t\t\t_11.addSample(x[1], x[1]);\n\t\t\t_22.addSample(x[2], x[2]);\n\t\t\t_01.addSample(x[0], x[1]);\n\t\t\t_02.addSample(x[0], x[2]);\n\t\t\t_12.addSample(x[1], x[2]);\n\t\t}\n\t\tEigen::Matrix3d sampleCovarianceMatrix() const {\n\t\t\tEigen::Matrix3d cov;\n\t\t\tcov(0, 0) = _00.sampleCovariance();\n\t\t\tcov(1, 1) = _11.sampleCovariance();\n\t\t\tcov(2, 2) = _22.sampleCovariance();\n\t\t\tcov(0, 1) = cov(1, 0) = _01.sampleCovariance();\n\t\t\tcov(0, 2) = cov(2, 0) = _02.sampleCovariance();\n\t\t\tcov(1, 2) = cov(2, 1) = _12.sampleCovariance();\n\t\t\treturn cov;\n\t\t}\n\tprivate:\n\t\tOnlineCovariance _00;\n\t\tOnlineCovariance _11;\n\t\tOnlineCovariance _22;\n\t\tOnlineCovariance _01;\n\t\tOnlineCovariance _02;\n\t\tOnlineCovariance _12;\n\t};\n\n\t/*\n\t\u4e3b\u6210\u5206\u5206\u6790 2x2 mat\n\t*/\n\tinline std::tuple<Vec2, Vec2> PCA(const Eigen::Matrix2d covarianceMatrix) {\n\t\tEigen::EigenSolver<Eigen::Matrix2d> es(covarianceMatrix);\n\t\tauto eigenvectors = es.eigenvectors();\n\t\tVec2 xaxis(\n\t\t\teigenvectors(0, 0).real(),\n\t\t\teigenvectors(1, 0).real()\n\t\t);\n\t\tVec2 yaxis(\n\t\t\teigenvectors(0, 1).real(),\n\t\t\teigenvectors(1, 1).real()\n\t\t);\n\t\treturn{ xaxis, yaxis };\n\t}\n\n\t/*\n\t\u4e3b\u6210\u5206\u5206\u6790 3x3 mat\n\t*/\n\tinline std::tuple<Vec3, Vec3, Vec3> PCA(const Eigen::Matrix3d covarianceMatrix) {\n\t\tEigen::EigenSolver<Eigen::Matrix3d> es(covarianceMatrix);\n\t\tauto eigenvectors = es.eigenvectors();\n\t\tVec3 xaxis(\n\t\t\teigenvectors(0, 0).real(),\n\t\t\teigenvectors(1, 0).real(),\n\t\t\teigenvectors(2, 0).real()\n\t\t);\n\t\tVec3 yaxis(\n\t\t\teigenvectors(0, 1).real(),\n\t\t\teigenvectors(1, 1).real(),\n\t\t\teigenvectors(2, 1).real()\n\t\t);\n\t\tVec3 zaxis(\n\t\t\teigenvectors(0, 2).real(),\n\t\t\teigenvectors(1, 2).real(),\n\t\t\teigenvectors(2, 2).real()\n\t\t);\n\n\t\treturn{ xaxis , yaxis, zaxis };\n\t}\n}", "meta": {"hexsha": "a2ba3e19a63acab2c7c84c28129dbc380f16d856", "size": 2332, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/pca.hpp", "max_stars_repo_name": "Ushio/MofuMofuRender", "max_stars_repo_head_hexsha": "3236dea301d0d809e28fde83b51cce9b4b089f3d", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2017-09-10T16:46:52.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-20T05:10:08.000Z", "max_issues_repo_path": "src/pca.hpp", "max_issues_repo_name": "Ushio/MofuMofuRender", "max_issues_repo_head_hexsha": "3236dea301d0d809e28fde83b51cce9b4b089f3d", "max_issues_repo_licenses": ["Zlib"], "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/pca.hpp", "max_forks_repo_name": "Ushio/MofuMofuRender", "max_forks_repo_head_hexsha": "3236dea301d0d809e28fde83b51cce9b4b089f3d", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.5555555556, "max_line_length": 82, "alphanum_fraction": 0.6462264151, "num_tokens": 916, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541544761566, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.7293896567871058}}
{"text": "/* @copyright The code is licensed under the MIT License\n *            <https://opensource.org/licenses/MIT>,\n *            Copyright (c) 2020 Christian Eskil Vaugelade Berg\n * @author Christian Eskil Vaugelade Berg\n*/\n#pragma once\n\n#include <orient/axis.hpp>\n\n#include <Eigen/Dense>\n\nnamespace orient {\n\ntemplate<Axis axis, typename Scalar>\nEigen::Matrix<Scalar,3,3> rotationMatrixFromEuler(Scalar angle)\n{\n  const auto s = std::sin(angle);\n  const auto c = std::cos(angle);\n\n  constexpr auto i1 = asIndex<axis>;\n  constexpr auto i2 = (i1 + 1) % 3;\n  constexpr auto i3 = (i2 + 1) % 3;\n  Eigen::Matrix<Scalar,3,3> R = Eigen::Matrix<Scalar,3,3>::Zero();\n  R(i1, i1) = 1.0;\n  R(i2, i2) = c;\n  R(i3, i3) = c;\n  R(i2, i3) = -s; \n  R(i3, i2) = s; \n  return R;\n}\n\ntemplate<Axis axis, typename Scalar>\nstd::pair<Eigen::Matrix<Scalar,3,3>, Eigen::Matrix<Scalar,3,3>> rotationMatrixFromEulerWD(Scalar angle)\n{\n  const auto s = std::sin(angle);\n  const auto c = std::cos(angle);\n\n  constexpr auto i1 = asIndex<axis>;\n  constexpr auto i2 = (i1 + 1) % 3;\n  constexpr auto i3 = (i2 + 1) % 3;\n  Eigen::Matrix<Scalar,3,3> J = Eigen::Matrix<Scalar,3,3>::Zero();\n  Eigen::Matrix<Scalar,3,3> R = Eigen::Matrix<Scalar,3,3>::Zero();\n  R(i1, i1) = 1.0;\n  R(i2, i2) = c;\n  J(i2, i2) = -s; \n\n  R(i3, i3) = c;\n  J(i3, i3) = -s;\n\n  R(i2, i3) = -s; \n  J(i2, i3) = -c;\n\n  R(i3, i2) = s; \n  J(i3, i2) = c;\n  return std::make_pair(R, J);\n}\n\ntemplate<Axis A1, Axis A2, Axis A3, typename Scalar>\nEigen::Matrix<Scalar,3,3> rotationMatrixFromEuler(Eigen::Matrix<Scalar,3,1> const& angles)\n{\n  return \n    rotationMatrixFromEuler<A1>(angles[0]) *\n    rotationMatrixFromEuler<A2>(angles[1]) *\n    rotationMatrixFromEuler<A3>(angles[2]);\n}\n\ntemplate<Axis A1, Axis A2, Axis A3, typename Scalar>\nstd::pair<Eigen::Matrix<Scalar,3,3>, Eigen::Matrix<Scalar, 9, 3>> rotationMatrixFromEulerWD(Eigen::Matrix<Scalar,3,1> const& angles)\n{\n  const auto [R1, J1] = rotationMatrixFromEulerWD<A1>(angles[0]);\n  const auto [R2, J2] = rotationMatrixFromEulerWD<A2>(angles[1]);\n  const auto [R3, J3] = rotationMatrixFromEulerWD<A3>(angles[2]);\n\n  Eigen::Matrix<Scalar, 9, 3> J;\n  Eigen::Map<Eigen::Matrix<Scalar,3,3>>(J.template block<9,1>(0,0).data(), 3, 3) = J1 * R2 * R3;\n  Eigen::Map<Eigen::Matrix<Scalar,3,3>>(J.template block<9,1>(0,1).data(), 3, 3) = R1 * J2 * R3;\n  Eigen::Map<Eigen::Matrix<Scalar,3,3>>(J.template block<9,1>(0,2).data(), 3, 3) = R1 * R2 * J3;\n  return std::make_pair(R1 * R2 * R3, J);\n}\n\n}\n", "meta": {"hexsha": "872558ac09e2077da8523fdd5f6a81ab3f5c0e66", "size": 2463, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/orient/impl/from_euler.hpp", "max_stars_repo_name": "Eskilade/orient", "max_stars_repo_head_hexsha": "d73e9459155e991539c20bfd92c04cb487b65538", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2020-05-11T07:27:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-10T09:23:29.000Z", "max_issues_repo_path": "include/orient/impl/from_euler.hpp", "max_issues_repo_name": "Eskilade/orient", "max_issues_repo_head_hexsha": "d73e9459155e991539c20bfd92c04cb487b65538", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-09-20T02:22:15.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-21T01:42:47.000Z", "max_forks_repo_path": "include/orient/impl/from_euler.hpp", "max_forks_repo_name": "Eskilade/orient", "max_forks_repo_head_hexsha": "d73e9459155e991539c20bfd92c04cb487b65538", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-09-14T11:11:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-10T04:26:22.000Z", "avg_line_length": 30.0365853659, "max_line_length": 132, "alphanum_fraction": 0.6366220057, "num_tokens": 915, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947086083138, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.7293880262912001}}
{"text": "#include <Eigen/Eigen>\n#include <iostream>\n\nint main(int argc, char **argv) {\n\n  // Simple initialization.\n  Eigen::Matrix<double, 3, 3> square3;\n  square3 << 2, 1, 3, 5, 7, 8, 9, 12, 11;\n  std::cout << square3 << std::endl;\n  std::cout << \"Trace: \";\n  std::cout << square3.trace() << std::endl;\n\n  std::cout << \"Max: \";\n  int mr, mc;\n  std::cout << square3.maxCoeff(&mr, &mc) << std::endl;\n  std::cout << mr << \" , \" << mc << std::endl;\n\n  std::cout << \"Min: \";\n  std::cout << square3.minCoeff(&mr, &mc) << \" at \" << std::endl;\n  std::cout << mr << \" , \" << mc << std::endl;\n\n  // Invert it.\n  Eigen::Matrix3d inv_square3 = square3.inverse();\n  std::cout << inv_square3 << std::endl;\n  std::cout << \"Trace: \";\n  std::cout << inv_square3.trace() << std::endl;\n\n  // Example of solve.\n  Eigen::Matrix2f A, b;\n  A << 2, -1, -1, 3;\n  b << 1, 2, 3, 1;\n  std::cout << \"Here is the matrix A:\\n\" << A << std::endl;\n  std::cout << \"Here is the right hand side b:\\n\" << b << std::endl;\n  Eigen::Matrix2f x = A.llt().solve(b);\n  std::cout << \"The solution is:\\n\" << x << std::endl;\n\n  return 0;\n}", "meta": {"hexsha": "4578b45bac97b40620b9845019c64e0dd4a773d1", "size": 1086, "ext": "cc", "lang": "C++", "max_stars_repo_path": "eigen_practice.cc", "max_stars_repo_name": "sahilshah/cpp_practice", "max_stars_repo_head_hexsha": "c8b460a567e2ed603da24688c04bf4725da158a7", "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": "eigen_practice.cc", "max_issues_repo_name": "sahilshah/cpp_practice", "max_issues_repo_head_hexsha": "c8b460a567e2ed603da24688c04bf4725da158a7", "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": "eigen_practice.cc", "max_forks_repo_name": "sahilshah/cpp_practice", "max_forks_repo_head_hexsha": "c8b460a567e2ed603da24688c04bf4725da158a7", "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.5789473684, "max_line_length": 68, "alphanum_fraction": 0.544198895, "num_tokens": 395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765187126079, "lm_q2_score": 0.798186775339273, "lm_q1q2_score": 0.7292845141744294}}
{"text": "#define BOOST_TEST_MODULE kinetic energy multivar normal\n#define BOOST_TEST_DYN_LINK\n#include <cmath>\n#include <random>\n#include <limits>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/test/unit_test.hpp>\n#include <mpp/hamiltonian/kinetic_energy_multivar_normal.hpp>\n\ntemplate<typename real_scalar_type>\nvoid test_multivariate_normal_diag()\n{\n    using namespace mpp::hamiltonian;\n    using namespace boost::numeric::ublas;\n\n    typedef multivariate_normal<real_scalar_type> multivariate_normal_type;\n    typedef vector<real_scalar_type> real_vector_type;\n    typedef std::mt19937 rng_type;\n\n    std::size_t const num_dims = 1000000;\n\n    real_vector_type sigma_inv(num_dims);\n    for(std::size_t i=0;i<num_dims;++i)\n    {\n        sigma_inv(i) = real_scalar_type(1);\n    }\n\n    multivariate_normal_type mlt_nr(sigma_inv);\n\n    // compute the log_posterior for a ones vector\n    real_vector_type p(num_dims);\n    for(std::size_t i=0;i<num_dims;++i)\n    {\n        p(i) = real_scalar_type(1);\n    }\n\n    real_scalar_type log_posterior_c = mlt_nr.log_posterior(p);\n\n    real_scalar_type log_posterior_e(0);\n    for(std::size_t i=0;i<num_dims;++i)\n    {\n        log_posterior_e -= p(i)*p(i)*sigma_inv(i);\n    }\n    log_posterior_e *= real_scalar_type(0.5);\n\n    real_scalar_type eps = std::numeric_limits<real_scalar_type>::epsilon();\n    BOOST_CHECK(\n        std::abs(log_posterior_c - log_posterior_e) <= eps\n    );\n\n    real_vector_type grad_p_c = mlt_nr.grad_log_posterior(p);\n\n    real_vector_type grad_p_e(num_dims);\n    for(std::size_t i=0;i<num_dims;++i)\n    {\n        grad_p_e(i) = -sigma_inv(i)*p(i);\n    }\n\n    for(std::size_t i=0;i<num_dims;++i)\n    {\n        BOOST_CHECK(\n            std::abs(grad_p_c(i) - grad_p_e(i) ) <= eps\n        );\n    }\n\n    rng_type rng;\n    real_vector_type samp_p = mlt_nr.generate_sample(rng);\n\n    real_scalar_type sum(0);\n    real_scalar_type sum2(0);\n    for(std::size_t i=0;i<num_dims;++i)\n    {\n        sum += samp_p(i);\n        sum2 += samp_p(i)*samp_p(i);\n    }\n    real_scalar_type mean = sum/real_scalar_type(num_dims);\n    real_scalar_type std = std::sqrt( sum2/real_scalar_type(num_dims)\n        - mean*mean );\n\n    BOOST_CHECK(\n        std::abs(mean) <=\n            real_scalar_type(1)/std::sqrt(real_scalar_type(num_dims))\n    );\n\n    BOOST_CHECK(\n        std::abs( std - real_scalar_type(1) ) <= real_scalar_type(1)/std::sqrt(real_scalar_type(num_dims))\n    );\n\n}\n\nBOOST_AUTO_TEST_CASE(kinetic_energy_multivar_normal_diag)\n{\n    test_multivariate_normal_diag<float>();\n    test_multivariate_normal_diag<double>();\n    test_multivariate_normal_diag<long double>();\n}\n", "meta": {"hexsha": "729f9a60cfbe9a8159c648bae4be6b245f10005b", "size": 2628, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/hamiltonian/kinetic_energy_multivar_normal.cpp", "max_stars_repo_name": "tbs1980/mpp", "max_stars_repo_head_hexsha": "5a704b48d5ab2386588c71987a7616a276380a99", "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/hamiltonian/kinetic_energy_multivar_normal.cpp", "max_issues_repo_name": "tbs1980/mpp", "max_issues_repo_head_hexsha": "5a704b48d5ab2386588c71987a7616a276380a99", "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/hamiltonian/kinetic_energy_multivar_normal.cpp", "max_forks_repo_name": "tbs1980/mpp", "max_forks_repo_head_hexsha": "5a704b48d5ab2386588c71987a7616a276380a99", "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.0927835052, "max_line_length": 106, "alphanum_fraction": 0.6799847793, "num_tokens": 692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.7292296594313054}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace std;\nusing namespace Eigen;\n\nint main()\n{\n  MatrixXf m(4,4);\n  \n  m << 1, 2, 3, 4,\n       5, 6, 7, 8,\n       9, 10,11,12,\n       13,14,15,16;\n\n  //print first two columns\n  cout << \"-- leftCols(2) --\" << endl\n    << m.leftCols(2) << endl << endl;\n  \n  //print last two rows\n  cout << \"-- bottomRows(2) --\" << endl\n    << m.bottomRows(2) << endl << endl;\n    \n  //print top-left 2x3 corner\n  cout << \"-- topLeftCorner(2,3) --\" << endl\n    << m.topLeftCorner(2,3) << endl;\n}\n", "meta": {"hexsha": "96c6df62bf24119b9315b09fb55da706677e2a57", "size": 533, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "t1m1/include/eigen/doc/examples/Tutorial_BlockOperations_corner.cpp", "max_stars_repo_name": "dailysoap/CSMM.104x", "max_stars_repo_head_hexsha": "4515b30ab5f60827a9011b23ef155a3063584a9d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2017-04-01T17:18:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T05:23:23.000Z", "max_issues_repo_path": "t1m1/include/eigen/doc/examples/Tutorial_BlockOperations_corner.cpp", "max_issues_repo_name": "dailysoap/CSMM.104x", "max_issues_repo_head_hexsha": "4515b30ab5f60827a9011b23ef155a3063584a9d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-05-24T13:36:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T06:44:20.000Z", "max_forks_repo_path": "t1m1/include/eigen/doc/examples/Tutorial_BlockOperations_corner.cpp", "max_forks_repo_name": "dailysoap/CSMM.104x", "max_forks_repo_head_hexsha": "4515b30ab5f60827a9011b23ef155a3063584a9d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-09-20T01:07:39.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-22T14:55:38.000Z", "avg_line_length": 19.0357142857, "max_line_length": 44, "alphanum_fraction": 0.5328330206, "num_tokens": 194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.7291219443736007}}
{"text": "#ifndef VECTOR_MATH_HPP\n# define VECTOR_MATH_HPP\n\n#include <Eigen/Dense>\n\nusing Eigen::Matrix3d;\nusing Eigen::Vector3d;\n\nconst double ANGLE_SMALL = 1e-12;\n\nMatrix3d skew(const Vector3d& a) {\n  Matrix3d ax;\n  ax << 0.0, -a(2), a(1),\n    a(2), 0.0, -a(0),\n    -a(1), a(0), 0.0;\n  return ax;\n}\n\n/** @brief Convert a rotation vector to a DCM.\n *\n * @param[in]   v   rotation vector (unit rotation axis multiplied by\n *                  angle about that vector)\n *\n * @returns A 3D matrix.\n */\nMatrix3d rotvec_to_matrix(const Vector3d& v) {\n  double v_mag = v.norm();\n  double c     = std::cos(v_mag);\n  double s     = std::sin(v_mag);\n\n  Vector3d vu = v / v_mag;\n\n  Matrix3d T;\n  if (v_mag < ANGLE_SMALL) T = Matrix3d::Identity();\n  else {\n    // Reference: https://github.com/mohawkjohn/pyquat/blob/master/pyquat/pyquat.c\n    // Line 932\n    T << c + vu[0]*vu[0] * (1.0 - c),\n      vu[0]*vu[1] * (1.0 - c) + vu[2] * s,\n      vu[0]*vu[2] * (1.0 - c) - vu[1] * s,\n      vu[0]*vu[1] * (1.0 - c) - vu[2] * s,\n      c + vu[1]*vu[1] * (1.0 - c),\n      vu[1]*vu[2] * (1.0 - c) + vu[0] * s,\n      vu[0]*vu[2] * (1.0 - c) + vu[1] * s,\n      vu[1]*vu[2] * (1.0 - c) - vu[0] * s,\n      c + vu[2]*vu[2] * (1.0 - c);\n  }\n\n  return T;\n}\n\n#endif\n", "meta": {"hexsha": "4f525dc3ac056a47487afcda124445b35c20033e", "size": 1228, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/vector_math.hpp", "max_stars_repo_name": "openlunar/nav", "max_stars_repo_head_hexsha": "37240000c542f4d42979a83ac5bebb3ab2c01fe4", "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": "include/vector_math.hpp", "max_issues_repo_name": "openlunar/nav", "max_issues_repo_head_hexsha": "37240000c542f4d42979a83ac5bebb3ab2c01fe4", "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": "include/vector_math.hpp", "max_forks_repo_name": "openlunar/nav", "max_forks_repo_head_hexsha": "37240000c542f4d42979a83ac5bebb3ab2c01fe4", "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": 23.1698113208, "max_line_length": 82, "alphanum_fraction": 0.5276872964, "num_tokens": 490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625126757597, "lm_q2_score": 0.782662489091802, "lm_q1q2_score": 0.7290207686665143}}
{"text": "#pragma once\n#include \"coordinate_transform.hpp\"\n#include \"grad_shape.hpp\"\n#include \"integrate.hpp\"\n#include \"shape.hpp\"\n#include <Eigen/Core>\n\n//! Makes the matrix corresponding to the neumann boundary conditions\n//!\ntemplate <class MatrixType, class Point>\nvoid computeBoundaryMatrix(MatrixType & boundaryMatrix,\n                           const Point &a,\n                           const Point &b,\n                           double       gamma) {\n\t// (write your solution here)\n\tboundaryMatrix.resize(2, 2);\n\n\tfor (int i = 0; i < 2; ++i) {\n\t\tfor (int j = 0; j < 2; ++j) {\n\t\t\tauto f = [&](double t) -> double {\n\t\t\t\treturn lambda(i, t / 2.0 + 1, 0) * lambda(j, t / 2.0 + 1, 0);\n\t\t\t};\n\n\t\t\tdouble scaling_factor = (b - a).norm() / 2.0;\n\t\t\tboundaryMatrix(i, j) = scaling_factor * gamma * integrate1d(f);\n\t\t}\n\t}\n}\n", "meta": {"hexsha": "e625ae548fcec99f9033746190ab9278d6e1e43f", "size": 811, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "series4/2d-rad-cooling/neumann_boundary.hpp", "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": "series4/2d-rad-cooling/neumann_boundary.hpp", "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": "series4/2d-rad-cooling/neumann_boundary.hpp", "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": 27.9655172414, "max_line_length": 69, "alphanum_fraction": 0.5795314427, "num_tokens": 226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625031628428, "lm_q2_score": 0.782662489091802, "lm_q1q2_score": 0.7290207612211111}}
{"text": "///////////////////////////////////////////////////////////////////\n//  Copyright Eduardo Quintana 2021\n//  Copyright Janek Kozicki 2021\n//  Copyright Christopher Kormanyos 2021\n//  Distributed under the Boost Software License,\n//  Version 1.0. (See accompanying file LICENSE_1_0.txt\n//  or copy at http://www.boost.org/LICENSE_1_0.txt)\n/*\n    boost::math::fft example 07\n    \n    Real transforms with GSL, FFTW and Boost backends\n*/\n\n#include <boost/random.hpp>\n#include <boost/math/fft/bsl_backend.hpp>\n#include <boost/math/fft/fftw_backend.hpp>\n#include <boost/math/fft/gsl_backend.hpp>\n#include <boost/math/fft/real_algorithms.hpp>\n#include <iostream>\n#include <vector>\n#include <complex>\n\ntemplate<class T>\nvoid print(const std::vector<T>& V)\n{\n  std::cout << \"size(V) = \" << V.size() << \"\\n\";\n  std::cout << \"[\";\n  for(auto x: V)\n  {\n    std::cout << x << \", \";\n  }\n  std::cout << \"]\\n\";\n}\n\nvoid check(int n)\n{\n  boost::random::mt19937 rng;\n  boost::random::uniform_real_distribution<double> U(0.0,1.0);\n  \n  std::vector< double > V(n);\n  for(auto& x: V)\n      x = U(rng);\n  std::cout << \"Original data:\\n\";\n  print(V);\n  \n  std::vector<double> A,B,C;\n  \n  boost::math::fft::fftw_rdft< double > P1(V.size());\n  P1.real_to_halfcomplex(V.begin(),V.end(),std::back_inserter(A));\n  //std::cout << \"FFTW:\\n\";\n  //print(A);\n  \n  boost::math::fft::gsl_rdft< double > P2(V.size());\n  P2.real_to_halfcomplex(V.begin(),V.end(),std::back_inserter(B));\n  //std::cout << \"GSL:\\n\";\n  //print(B);\n  \n  \n  boost::math::fft::bsl_rdft< double > P3(V.size());\n  P3.real_to_halfcomplex(V.begin(),V.end(),std::back_inserter(C));\n  //std::cout << \"Boost:\\n\";\n  //print(C);\n  \n  std::cout << \"Boost inverse:\\n\";\n  P3.halfcomplex_to_real(C.begin(),C.end(),C.begin());\n  const double inv_n = 1.0/C.size();\n  for(auto &x : C) x *= inv_n;\n  print(C);\n  \n  std::vector< std::complex<double> > cplx_V(V.begin(),V.end()),cplx_C;\n  boost::math::fft::bsl_dft< std::complex<double> > P4(V.size());\n  P4.forward(cplx_V.begin(),cplx_V.end(),std::back_inserter(cplx_C));\n  //std::cout << \"Boost complex:\\n\";\n  //print(cplx_C);\n}\n\nint main()\n{\n  check(1);\n  \n  check(2);\n  check(3);\n  check(5);\n  check(7);\n  \n  check(4);\n  check(8);\n  check(16);\n  check(32);\n  \n  check(6);\n  check(9);\n  check(10);\n  check(12);\n  return 0;\n}\n\n\n\n", "meta": {"hexsha": "97cbee97234688b3606691eb36bcc33e40d03d48", "size": 2299, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/fft_ex07.cpp", "max_stars_repo_name": "BoostGSoC21/math", "max_stars_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_stars_repo_licenses": ["BSL-1.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": "example/fft_ex07.cpp", "max_issues_repo_name": "BoostGSoC21/math", "max_issues_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 30.0, "max_issues_repo_issues_event_min_datetime": "2021-06-22T12:59:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-02T09:27:49.000Z", "max_forks_repo_path": "example/fft_ex07.cpp", "max_forks_repo_name": "BoostGSoC21/math", "max_forks_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-07T21:15:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-07T21:15:02.000Z", "avg_line_length": 22.99, "max_line_length": 71, "alphanum_fraction": 0.5989560679, "num_tokens": 728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.931462503162843, "lm_q2_score": 0.7826624688140726, "lm_q1q2_score": 0.7290207423331666}}
{"text": "#pragma once\n\n#include <vector>\n\n#include <Eigen/Geometry>\n#include <common_robotics_utilities/math.hpp>\n#include <geometry_msgs/PointStamped.h>\n#include <geometry_msgs/PoseStamped.h>\n#include <geometry_msgs/TransformStamped.h>\n\nnamespace common_robotics_utilities\n{\nnamespace conversions\n{\nEigen::Quaterniond QuaternionFromRPY(const double R,\n                                     const double P,\n                                     const double Y);\n\n// URDF RPY IS ACTUALLY APPLIED Y*P*R\nEigen::Quaterniond QuaternionFromUrdfRPY(const double R,\n                                         const double P,\n                                         const double Y);\n\n// Returns XYZ Euler angles\nEigen::Vector3d EulerAnglesFromRotationMatrix(\n    const Eigen::Matrix3d& rot_matrix);\n\n// Returns XYZ Euler angles\nEigen::Vector3d EulerAnglesFromQuaternion(const Eigen::Quaterniond& quat);\n\n// Returns XYZ Euler angles\nEigen::Vector3d EulerAnglesFromIsometry3d(const Eigen::Isometry3d& trans);\n\nEigen::Isometry3d TransformFromXYZRPY(const double x,\n                                      const double y,\n                                      const double z,\n                                      const double roll,\n                                      const double pitch,\n                                      const double yaw);\n\nEigen::Isometry3d TransformFromRPY(const Eigen::Vector3d& translation,\n                                   const Eigen::Vector3d& rotation);\n\nEigen::Isometry3d TransformFromRPY(const Eigen::VectorXd& components);\n\n// URDF RPY IS ACTUALLY APPLIED Y*P*R\nEigen::Isometry3d TransformFromUrdfXYZRPY(const double x,\n                                          const double y,\n                                          const double z,\n                                          const double roll,\n                                          const double pitch,\n                                          const double yaw);\n\n// URDF RPY IS ACTUALLY APPLIED Y*P*R\nEigen::Isometry3d TransformFromUrdfRPY(const Eigen::Vector3d& translation,\n                                       const Eigen::Vector3d& rotation);\n\n// URDF RPY IS ACTUALLY APPLIED Y*P*R\nEigen::Isometry3d TransformFromUrdfRPY(const Eigen::VectorXd& components);\n\nEigen::VectorXd TransformToRPY(const Eigen::Isometry3d& transform);\n\nEigen::Vector3d StdVectorDoubleToEigenVector3d(\n    const std::vector<double>& vector);\n\nEigen::VectorXd StdVectorDoubleToEigenVectorXd(\n    const std::vector<double>& vector);\n\nstd::vector<double> EigenVector3dToStdVectorDouble(\n    const Eigen::Vector3d& point);\n\nstd::vector<double> EigenVectorXdToStdVectorDouble(\n    const Eigen::VectorXd& eigen_vector);\n\n// Takes <x, y, z, w> as is the ROS custom!\nEigen::Quaterniond StdVectorDoubleToEigenQuaterniond(\n    const std::vector<double>& vector);\n\n// Returns <x, y, z, w> as is the ROS custom!\nstd::vector<double> EigenQuaterniondToStdVectorDouble(\n    const Eigen::Quaterniond& quat);\n\nEigen::Vector3d GeometryPointToEigenVector3d(\n    const geometry_msgs::Point& point);\n\ngeometry_msgs::Point EigenVector3dToGeometryPoint(\n    const Eigen::Vector3d& point);\n\nEigen::Vector4d GeometryPointToEigenVector4d(\n    const geometry_msgs::Point& point);\n\ngeometry_msgs::Point EigenVector4dToGeometryPoint(\n    const Eigen::Vector4d& point);\n\ngeometry_msgs::PointStamped EigenVector3dToGeometryPointStamped(\n    const Eigen::Vector3d& point, const std::string& frame_id);\n\nEigen::Vector3d GeometryVector3ToEigenVector3d(\n    const geometry_msgs::Vector3& vector);\n\ngeometry_msgs::Vector3 EigenVector3dToGeometryVector3(\n    const Eigen::Vector3d& vector);\n\nEigen::Vector4d GeometryVector3ToEigenVector4d(\n    const geometry_msgs::Vector3& vector);\n\ngeometry_msgs::Vector3 EigenVector4dToGeometryVector3(\n    const Eigen::Vector4d& vector);\n\nEigen::Quaterniond GeometryQuaternionToEigenQuaterniond(\n    const geometry_msgs::Quaternion& quat);\n\ngeometry_msgs::Quaternion EigenQuaterniondToGeometryQuaternion(\n    const Eigen::Quaterniond& quat);\n\nEigen::Isometry3d GeometryPoseToEigenIsometry3d(\n    const geometry_msgs::Pose& pose);\n\ngeometry_msgs::Pose EigenIsometry3dToGeometryPose(\n    const Eigen::Isometry3d& transform);\n\ngeometry_msgs::PoseStamped EigenIsometry3dToGeometryPoseStamped(\n    const Eigen::Isometry3d& transform, const std::string& frame_id);\n\nEigen::Isometry3d GeometryTransformToEigenIsometry3d(\n    const geometry_msgs::Transform& transform);\n\ngeometry_msgs::Transform EigenIsometry3dToGeometryTransform(\n    const Eigen::Isometry3d& transform);\n\ngeometry_msgs::TransformStamped EigenIsometry3dToGeometryTransformStamped(\n    const Eigen::Isometry3d& transform, const std::string& frame_id,\n    const std::string& child_frame_id);\n\nEigen::Matrix3Xd VectorGeometryPointToEigenMatrix3Xd(\n    const std::vector<geometry_msgs::Point>& vector_geom);\n\nstd::vector<geometry_msgs::Point> EigenMatrix3XdToVectorGeometryPoint(\n    const Eigen::Matrix3Xd& eigen_matrix);\n\nstd::vector<geometry_msgs::Point>\nVectorEigenVector3dToVectorGeometryPoint(\n    const common_robotics_utilities::math::VectorVector3d& vector_eigen);\n\ncommon_robotics_utilities::math::VectorVector3d\nVectorGeometryPointToVectorEigenVector3d(\n    const std::vector<geometry_msgs::Point>& vector_geom);\n\ncommon_robotics_utilities::math::VectorVector3d\nVectorGeometryVector3ToEigenVector3d(\n    const std::vector<geometry_msgs::Vector3>& vector_geom);\n\ncommon_robotics_utilities::math::VectorIsometry3d\nVectorGeometryPoseToVectorIsometry3d(\n    const std::vector<geometry_msgs::Pose>& vector_geom);\n\ncommon_robotics_utilities::math::VectorIsometry3d\nVectorGeometryPoseToVectorIsometry3d(\n    const std::vector<geometry_msgs::Transform>& vector_geom);\n\nstd::vector<geometry_msgs::Pose> VectorIsometry3dToVectorGeometryPose(\n    const common_robotics_utilities::math::VectorIsometry3d& vector_eigen);\n\nstd::vector<geometry_msgs::Transform> VectorIsometry3dToVectorGeometryTransform(\n    const common_robotics_utilities::math::VectorIsometry3d& vector_eigen);\n}  // namespace conversions\n}  // namespace common_robotics_utilities\n", "meta": {"hexsha": "dd4e297632d388b64d69160f748888bfb0816cbe", "size": 6051, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/common_robotics_utilities/conversions.hpp", "max_stars_repo_name": "EricCousineau-TRI/common_robotics_utilities", "max_stars_repo_head_hexsha": "df2f0c68d92d93c919bb7401abe5e12bd5ca2345", "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": "include/common_robotics_utilities/conversions.hpp", "max_issues_repo_name": "EricCousineau-TRI/common_robotics_utilities", "max_issues_repo_head_hexsha": "df2f0c68d92d93c919bb7401abe5e12bd5ca2345", "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": "include/common_robotics_utilities/conversions.hpp", "max_forks_repo_name": "EricCousineau-TRI/common_robotics_utilities", "max_forks_repo_head_hexsha": "df2f0c68d92d93c919bb7401abe5e12bd5ca2345", "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": 36.0178571429, "max_line_length": 80, "alphanum_fraction": 0.7207073211, "num_tokens": 1370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096204605945, "lm_q2_score": 0.7956581024858786, "lm_q1q2_score": 0.7289100422847351}}
{"text": "#include \"problemes.h\"\n#include \"arithmetique.h\"\n#include \"timer.h\"\n\n#include <boost/range/adaptor/reversed.hpp>\n\ntypedef unsigned long long nombre;\ntypedef std::vector<nombre> vecteur;\n\nnamespace {\n    nombre maximum(const vecteur &fibonacci, const nombre &n) {\n        for (const auto &f: boost::adaptors::reverse(fibonacci)) {\n            if (f < n)\n                return f;\n        }\n\n        return fibonacci.back();\n    }\n\n    nombre Zeckendorf(const vecteur &fibonacci, const nombre n) {\n        if (n < 2)\n            return 0;\n\n        static std::map<nombre, nombre> cache;\n\n        if (auto it = cache.find(n);it != cache.end())\n            return it->second;\n\n        nombre m = maximum(fibonacci, n);\n\n        nombre resultat = n - m + Zeckendorf(fibonacci, m) + Zeckendorf(fibonacci, n - m);\n\n        cache[n] = resultat;\n        return resultat;\n    }\n}\n\nENREGISTRER_PROBLEME(297, \"Zeckendorf Representation\") {\n    // Each new term in the Fibonacci sequence is generated by adding the previous two terms. Starting with 1 and 2, the\n    // first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89.\n    //\n    // Every positive integer can be uniquely written as a sum of nonconsecutive terms of the Fibonacci sequence. For\n    // example, 100 = 3 + 8 + 89. Such a sum is called the Zeckendorf representation of the number.\n    //\n    // For any integer n>0, let z(n) be the number of terms in the Zeckendorf representation of n.\n    // Thus, z(5)\u2009=\u20091, z(14)\u2009=\u20092, z(100)\u2009=\u20093 etc.\n    // Also, for 0<n<10**6, \u2211\u2009z(n)\u2009=\u20097894453.\n    //\n    // Find \u2211\u2009z(n) for 0<n<10**17.\n    const auto limite = puissance::puissance<nombre, unsigned>(10, 17);\n    vecteur fibonacci{1, 1};\n    while (fibonacci.back() < limite) {\n        fibonacci.push_back(fibonacci.back() + fibonacci.at(fibonacci.size() - 2));\n    }\n\n    nombre resultat = Zeckendorf(fibonacci, limite);\n    return std::to_string(resultat);\n}\n", "meta": {"hexsha": "8a0d06ce7a32f8d8e62886b6fb373fdf7f6f2de0", "size": 1908, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problemes/probleme2xx/probleme297.cpp", "max_stars_repo_name": "ZongoForSpeed/ProjectEuler", "max_stars_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-10-13T17:07:21.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-08T11:50:22.000Z", "max_issues_repo_path": "problemes/probleme2xx/probleme297.cpp", "max_issues_repo_name": "ZongoForSpeed/ProjectEuler", "max_issues_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "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": "problemes/probleme2xx/probleme297.cpp", "max_forks_repo_name": "ZongoForSpeed/ProjectEuler", "max_forks_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "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.3389830508, "max_line_length": 120, "alphanum_fraction": 0.6184486373, "num_tokens": 571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096135894201, "lm_q2_score": 0.7956580976404296, "lm_q1q2_score": 0.728910032378667}}
{"text": "// \n// Helper functions for tests.\n//\n\n#pragma once\n\n#include <ilqr/ilqr_taylor_expansions.hh>\n\n#include <Eigen/Dense>\n\n#include <vector>\n\nilqr::DynamicsFunc create_linear_dynamics(const Eigen::MatrixXd &A, \n        const Eigen::MatrixXd &B);\n\n// Creates cost function of form 0.5*[(x-x_goal)^T Q (x-x_goal) + u^T R u]\nilqr::CostFunc create_quadratic_cost(const Eigen::MatrixXd &Q, \n        const Eigen::MatrixXd &R, \n        const Eigen::VectorXd &x_goal);\n\n\n// Creates cost function of form 0.5*[x^T Q x + u^T R u]\nilqr::CostFunc create_quadratic_cost(const Eigen::MatrixXd &Q, \n        const Eigen::MatrixXd &R);\n\n\n// Computes \\sum_i cost(x_i, u_i)\ndouble compute_total_cost(const ilqr::CostFunc &cost,  \n                          const std::vector<Eigen::VectorXd> &states, \n                          const std::vector<Eigen::VectorXd> &controls);\n\n// Returns a randomly generated [dim x dim] PSD matrix with specified \n// minimum eigen value.\nEigen::MatrixXd make_random_psd(const int dim, const double min_eig_val);\n\n\n// Linearly interpolate from x_t0 -> x_T corresponding to time steps t0->T.\nstd::vector<Eigen::VectorXd> linearly_interpolate(const int t0, \n        const Eigen::VectorXd& x_t0, const int T, const Eigen::VectorXd& x_T);\n\n", "meta": {"hexsha": "2022184e12d1535031115e1018f50539274a6cfe", "size": 1245, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/utils/helpers.hh", "max_stars_repo_name": "LAIRLAB/qr_trees", "max_stars_repo_head_hexsha": "66eb7310daa1d9978158198a508d02bf2128a377", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-16T08:42:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-16T08:42:33.000Z", "max_issues_repo_path": "src/utils/helpers.hh", "max_issues_repo_name": "LAIRLAB/qr_trees", "max_issues_repo_head_hexsha": "66eb7310daa1d9978158198a508d02bf2128a377", "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/utils/helpers.hh", "max_forks_repo_name": "LAIRLAB/qr_trees", "max_forks_repo_head_hexsha": "66eb7310daa1d9978158198a508d02bf2128a377", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-07-10T03:25:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-22T15:58:44.000Z", "avg_line_length": 30.3658536585, "max_line_length": 78, "alphanum_fraction": 0.6835341365, "num_tokens": 325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7288318810846667}}
{"text": "#include <iostream>\r\n#include <fstream>\r\n#include <sstream>\r\n#include <string>\r\n#include <boost/format.hpp>\r\n#include \"perceptron.h\"\r\n#include \"utils.h\"\r\n#include <omp.h>\r\n#include <ctime>\r\n\r\nusing namespace std;\r\nusing namespace Eigen;\r\n\r\nPerceptron::Perceptron(const int& n_iterations, const double& learning_rate, const double& tolerance, const int& seed, const int& early_stopping_round) : n_iterations(n_iterations), learning_rate(learning_rate), tolerance(tolerance), seed(seed), early_stopping_round(early_stopping_round) {}\r\n\r\nPerceptron::~Perceptron(){}\r\n\r\nvoid Perceptron::fit(const MatrixXd& X, const VectorXd& y, VectorXd (*activation)(Eigen::VectorXd x), double (*loss)(VectorXd y, VectorXd y_pred), double (*metric)(VectorXd y, VectorXd pred)){\r\n\tint n_features = X.cols();\r\n\tsrand(seed);\r\n\t// initialize weights between [-1/sqrt(n_features+1), 1/sqrt(n_features+1)]\r\n\tdouble limit = 1/sqrt(n_features+1);\r\n\tW = limit * VectorXd::Random(X.cols()+1);\r\n\tMatrixXd X_new(X.rows(), X.cols()+1);\r\n\tX_new<<X, MatrixXd::Ones(X.rows(), 1);\r\n\r\n\tdouble best_acc = 0.0;\r\n\tint become_worse_round = 0;\r\n\r\n\tfor(int iter = 0; iter < n_iterations; iter++){\r\n\t\t// calculate outputs\r\n\t\tVectorXd outputs = X_new*W;\r\n\t\t//cout << \"??\" << endl;\r\n\t\tVectorXd y_pred = predict_prob(X);\r\n\r\n\t\t//cout << \"??\" << endl;\r\n\t\tVectorXd E = y - y_pred;\r\n\r\n\t\t// calcalate the loss gradient w.r.t the input of the activation function\r\n\t\tVectorXd loss_gradient = (-E.array() * Utils::sigmoid(outputs).array()*(VectorXd::Ones(X.rows()) - Utils::sigmoid(outputs)).array()).matrix();\r\n\t\tW = W - learning_rate*X_new.transpose()*loss_gradient;\r\n\r\n\t\ty_pred = predict_prob(X);\r\n\r\n\r\n\t\tdouble loss = Utils::squareLoss(y, y_pred);\r\n\t\tdouble acc = metric(y, y_pred);\r\n\t\tcout << boost::format(\"Iteration: %d, squareloss:%.5f, accuracy:%.5f\") %iter %loss %acc << endl;\r\n\t\tif(loss <= tolerance) break;\r\n\r\n\t\tif(acc < best_acc){\r\n\t\t\tbecome_worse_round +=1;\r\n\t\t}else{\r\n\t\t\tbecome_worse_round = 0;\r\n\t\t\tbest_acc = acc;\r\n\t\t}\r\n\t\tif(become_worse_round >= early_stopping_round){\r\n\t\t\tcout << \"Early stopping. the best accuracy: \" << best_acc << endl;\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nVectorXd Perceptron::predict_prob(const MatrixXd& X){\r\n\tMatrixXd X_new(X.rows(), X.cols()+1);\r\n\tX_new << X, MatrixXd::Ones(X.rows(), 1);\r\n\tVectorXd y_pred_prob = Utils::sigmoid(X_new*W);\r\n\treturn y_pred_prob;\r\n}\r\n\r\nVectorXi Perceptron::predict(const MatrixXd& X){\r\n\tVectorXd ret_ = predict_prob(X);\r\n\tint n = ret_.size();\r\n\tVectorXi ret(n);\r\n\t#pragma omp parallel for\r\n\tfor(int i = 0; i < n; i++){\r\n\t\tret(i) = ret_(i)>0.5?1:0;\r\n\t}\r\n\treturn ret;\r\n}\r\n", "meta": {"hexsha": "93e793fb369331b106d84f929b4ab03085c28184", "size": 2576, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/perceptron.cc", "max_stars_repo_name": "KaiminLai/tiny-machine-learning-system", "max_stars_repo_head_hexsha": "e29625dfb513032b40712663b63f874e2ae6f924", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-09T16:03:50.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-09T16:03:50.000Z", "max_issues_repo_path": "src/perceptron.cc", "max_issues_repo_name": "KaiminLai/tiny-machine-learning-system", "max_issues_repo_head_hexsha": "e29625dfb513032b40712663b63f874e2ae6f924", "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/perceptron.cc", "max_forks_repo_name": "KaiminLai/tiny-machine-learning-system", "max_forks_repo_head_hexsha": "e29625dfb513032b40712663b63f874e2ae6f924", "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.8024691358, "max_line_length": 292, "alphanum_fraction": 0.6653726708, "num_tokens": 711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.8031737940012417, "lm_q1q2_score": 0.7287293991739068}}
{"text": "//####### Test module for vec functions ####################################\n\n//Define Module name\n #define BOOST_TEST_MODULE \"vector functions\"\n\n//Will automatically define a main for this test\n #define BOOST_TEST_DYN_LINK\n\n//Include Boost unit tests library & library for floating point comparison\n#include <boost/test/unit_test.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n\n//Units choice. Not relevant here, but avoids compile-time warning\n#define PXRMP_USE_SI_UNITS\n\n#include \"vec_functions.hpp\"\n\nusing namespace picsar::multi_physics;\n\n//Tolerance for double precision calculations\nconst double double_tolerance = 1.0e-10;\n\n//Tolerance for single precision calculations\nconst float float_tolerance = 1.0e-4;\n\n//Templated tolerance\ntemplate <typename T>\nT tolerance()\n{\n    if(std::is_same<T,float>::value)\n        return float_tolerance;\n    else\n        return double_tolerance;\n}\n\n// ------------- Tests --------------\n\n//Test norm2 generic\ntemplate<typename T>\nvoid vec_functions_norm2()\n{\n    vec3<T> vv{static_cast<T>(1.0),static_cast<T>(-2.0),static_cast<T>(3.0)};\n    T exp = static_cast<T>(1.0 + 4.0 + 9.0);\n    BOOST_CHECK_SMALL((norm2(vv)-exp)/exp, tolerance<T>());\n}\n\n//Test norm2 in double precision\nBOOST_AUTO_TEST_CASE( vec_functions_norm2_double_1 )\n{\n    vec_functions_norm2<double>();\n}\n\n//Test norm2 in single precision\nBOOST_AUTO_TEST_CASE( vec_functions_norm2_single_1 )\n{\n    vec_functions_norm2<float>();\n}\n\n//Test norm generic\ntemplate<typename T>\nvoid vec_functions_norm()\n{\n    vec3<T> vv{static_cast<T>(1.0),static_cast<T>(-2.0),static_cast<T>(3.0)};\n    T exp =  static_cast<T>(sqrt(1.0 + 4.0 + 9.0));\n    BOOST_CHECK_SMALL((norm(vv)-exp)/exp,  tolerance<T>());\n}\n\n//Test norm in double precision\nBOOST_AUTO_TEST_CASE( vec_functions_norm_double_1 )\n{\n    vec_functions_norm<double>();\n}\n\n//Test norm in single precision\nBOOST_AUTO_TEST_CASE( vec_functions_norm_single_1 )\n{\n    vec_functions_norm<float>();\n}\n\n//Test dot generic\ntemplate<typename T>\nvoid vec_functions_dot()\n{\n    vec3<T> vv1{static_cast<T>(1.0),static_cast<T>(-2.0),static_cast<T>(3.0)};\n    vec3<T> vv2{static_cast<T>(-1.0),static_cast<T>(0.0),static_cast<T>(5.0)};\n    T exp = static_cast<T>(14.0);\n    BOOST_CHECK_SMALL((dot(vv1, vv2)-exp)/exp, tolerance<T>());\n}\n\n//Test dot in double precision\nBOOST_AUTO_TEST_CASE( vec_functions_dot_double_1 )\n{\n    vec_functions_dot<double>();\n}\n\n//Test dot in single precision\nBOOST_AUTO_TEST_CASE( vec_functions_dot_single_1 )\n{\n    vec_functions_dot<float>();\n}\n\n//Test cross generic\ntemplate<typename T>\nvoid vec_functions_cross()\n{\n    vec3<T> vv1{static_cast<T>(1./3.),static_cast<T>(-1./4.),static_cast<T>(1./5.)};\n    vec3<T> vv2{static_cast<T>(-2./3.),static_cast<T>(-3./4.),static_cast<T>(4./5.)};\n    vec3<T> exp{static_cast<T>(-1./20.),static_cast<T>(-2./5.),static_cast<T>(-5./12.)};\n\n    vec3<T> res = cross(vv1,vv2);\n    BOOST_CHECK_SMALL((res[0]-exp[0])/exp[0], tolerance<T>());\n    BOOST_CHECK_SMALL((res[1]-exp[1])/exp[1], tolerance<T>());\n    BOOST_CHECK_SMALL((res[2]-exp[2])/exp[2], tolerance<T>());\n}\n\n//Test cross in double precision\nBOOST_AUTO_TEST_CASE( vec_functions_cross_double_1 )\n{\n    vec_functions_cross<double>();\n}\n\n//Test cross in single precision\nBOOST_AUTO_TEST_CASE( vec_functions_cross_single_1 )\n{\n    vec_functions_cross<float>();\n}\n\n//Test vector times scalar generic\ntemplate<typename T>\nvoid vec_functions_vsprod()\n{\n    vec3<T> vv{static_cast<T>(1.0),static_cast<T>(2.0),static_cast<T>(-3.0)};\n    T s = static_cast<T>(-2.0);\n    vec3<T> exp{static_cast<T>(-2.0),static_cast<T>(-4.0),static_cast<T>(6.0)};\n\n    vec3<T> r1 = s * vv;\n    vec3<T> r2 = vv * s;\n\n    BOOST_CHECK_SMALL((r1[0]-exp[0])/exp[0], tolerance<T>());\n    BOOST_CHECK_SMALL((r1[1]-exp[1])/exp[1], tolerance<T>());\n    BOOST_CHECK_SMALL((r1[2]-exp[2])/exp[2], tolerance<T>());\n    BOOST_CHECK_SMALL((r2[0]-exp[0])/exp[0], tolerance<T>());\n    BOOST_CHECK_SMALL((r2[1]-exp[1])/exp[1], tolerance<T>());\n    BOOST_CHECK_SMALL((r2[2]-exp[2])/exp[2], tolerance<T>());\n}\n\n//Test vector times scalar in double precision\nBOOST_AUTO_TEST_CASE( vec_functions_vsprod_double_1 )\n{\n    vec_functions_vsprod<double>();\n}\n\n//Test vector times scalar in single precision\nBOOST_AUTO_TEST_CASE( vec_functions_vsprod_float_1 )\n{\n    vec_functions_vsprod<float>();\n}\n\n//Test vector divided by scalar generic\ntemplate<typename T>\nvoid vec_functions_vsdiv()\n{\n    vec3<T> vv{static_cast<T>(2.0),static_cast<T>(4.0),static_cast<T>(-6.0)};\n    T s = static_cast<T>(-2.0);\n    vec3<T> exp{static_cast<T>(-1.0),static_cast<T>(-2.0),static_cast<T>(3.0)};\n\n    vec3<T> r = vv / s;\n\n    BOOST_CHECK_SMALL((r[0]-exp[0])/exp[0], tolerance<T>());\n    BOOST_CHECK_SMALL((r[1]-exp[1])/exp[1], tolerance<T>());\n    BOOST_CHECK_SMALL((r[2]-exp[2])/exp[2], tolerance<T>());\n}\n\n//Test vector divided by scalar in double precision\nBOOST_AUTO_TEST_CASE( vec_functions_vsdiv_double_1 )\n{\n    vec_functions_vsdiv<double>();\n}\n\n//Test vector divided by scalar in single precision\nBOOST_AUTO_TEST_CASE( vec_functions_vsdiv_float_1 )\n{\n    vec_functions_vsdiv<float>();\n}\n\n//Test vector add generic\ntemplate<typename T>\nvoid vec_functions_vadd()\n{\n    vec3<T> vv1{static_cast<T>(1.0),static_cast<T>(2.0),static_cast<T>(3.0)};\n    vec3<T> vv2{static_cast<T>(1.0),static_cast<T>(-1.0),static_cast<T>(-2.0)};\n\n    vec3<T> exp{static_cast<T>(2.0),static_cast<T>(1.0),static_cast<T>(1.0)};\n\n    vec3<T> r = vv1 + vv2;\n\n    BOOST_CHECK_SMALL((exp[0]-r[0])/exp[0], tolerance<T>());\n    BOOST_CHECK_SMALL((exp[1]-r[1])/exp[1], tolerance<T>());\n    BOOST_CHECK_SMALL((exp[2]-r[2])/exp[2], tolerance<T>());\n}\n\n//Test vector add in double precision\nBOOST_AUTO_TEST_CASE( vec_functions_vadd_double_1 )\n{\n    vec_functions_vadd<double>();\n}\n\n//Test vector add in single precision\nBOOST_AUTO_TEST_CASE( vec_functions_vadd_single_1 )\n{\n    vec_functions_vadd<float>();\n}\n\n//Test vector diff generic\ntemplate<typename T>\nvoid vec_functions_vdiff()\n{\n    vec3<T> vv1{static_cast<T>(1.0),static_cast<T>(2.0),static_cast<T>(3.0)};\n    vec3<T> vv2{static_cast<T>(2.0),static_cast<T>(-1.0),static_cast<T>(-2.0)};\n\n    vec3<T> exp{static_cast<T>(-1.0),static_cast<T>(3.0),static_cast<T>(5.0)};\n\n    vec3<T> r = vv1 - vv2;\n\n    BOOST_CHECK_SMALL((r[0]-exp[0])/exp[0], tolerance<T>());\n    BOOST_CHECK_SMALL((r[1]-exp[1])/exp[1], tolerance<T>());\n    BOOST_CHECK_SMALL((r[2]-exp[2])/exp[2], tolerance<T>());\n}\n\n//Test vector diff in double precision\nBOOST_AUTO_TEST_CASE( vec_functions_vdiff_double_1 )\n{\n    vec_functions_vdiff<double>();\n}\n\n//Test vector diff in single precision\nBOOST_AUTO_TEST_CASE( vec_functions_vdiff_single_1 )\n{\n    vec_functions_vdiff<float>();\n}\n", "meta": {"hexsha": "3ab3d8eac6e6335d4d2bbf0e70f899309350e28e", "size": 6670, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/multi_physics/QED_tests/test_vec_functions.cpp", "max_stars_repo_name": "thaisacs/PICSAR", "max_stars_repo_head_hexsha": "1e3840779f478a70417975feecd35814ef92bf9d", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "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/multi_physics/QED_tests/test_vec_functions.cpp", "max_issues_repo_name": "thaisacs/PICSAR", "max_issues_repo_head_hexsha": "1e3840779f478a70417975feecd35814ef92bf9d", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "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/multi_physics/QED_tests/test_vec_functions.cpp", "max_forks_repo_name": "thaisacs/PICSAR", "max_forks_repo_head_hexsha": "1e3840779f478a70417975feecd35814ef92bf9d", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6763485477, "max_line_length": 88, "alphanum_fraction": 0.6889055472, "num_tokens": 1952, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513620489619, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.7285334448400342}}
{"text": "#ifndef MATH_TYPES_HPP_INCLUDED\n#define MATH_TYPES_HPP_INCLUDED\n\n#include <Eigen/Core>\n\nnamespace gazeestimation {\n\n\t/// These types can be swapped out for anything that supports operators +,-,/,* with scalars\n\t/// and supplies a corresponding header file implementing the operations from Utils.cpp\n\t/// in addition they must define an operator <<= for matrics compliant with boost ubas's implementation\n\ttypedef Eigen::Vector2d Vec2;\n\ttypedef Eigen::Vector2i Vec2i;\n\ttypedef Eigen::Vector3d Vec3;\n\ttypedef Eigen::Matrix3d Mat3x3;\n\n\tinline Vec2 make_vec2(double a, double b)\n\t{\n\t\treturn Vec2(a, b);\n\t}\n\n\tinline Vec3 make_vec3(double a, double b, double c)\n\t{\n\t\treturn Vec3(a, b, c);\n\t}\n\n\tinline Mat3x3 mat_prod(const Mat3x3& a, const Mat3x3& b)\n\t{\n\t\treturn a * b;\n\t}\n\n\tinline double dot(const Vec3& a, const Vec3& b)\n\t{\n\t\treturn a.dot(b);\n\t}\n\n\tinline Vec3 mat3vec3_prod(const Mat3x3& a, const Vec3& b)\n\t{\n\t\treturn a * b;\n\t}\n\n\tinline Vec3 normalized(const Vec3& a)\n\t{\n\t\treturn a.normalized();\n\t}\n\n\tinline double length(const Vec3& a)\n\t{\n\t\treturn a.norm();\n\t}\n\n\tinline double length(const Vec2& a)\n\t{\n\t\treturn a.norm();\n\t}\n\n\tinline double squared_length(const Vec3& a)\n\t{\n\t\treturn a.squaredNorm();\n\t}\n\n\tinline double squared_length_vec2(const Vec2& a)\n\t{\n\t\treturn a.squaredNorm();\n\t}\n\n\tinline std::string vec3_to_string(const Vec3& a)\n\t{\n\t\tstd::stringstream s;\n\t\ts << \"(\" << a[0] << \", \" << a[1] << \", \" << a[2] << \")\";\n\t\treturn s.str();\n\t}\n\n\tinline std::string vec2_to_string(const Vec3& a)\n\t{\n\t\tstd::stringstream s;\n\t\ts << \"(\" << a[0] << \", \" << a[1] << \")\";\n\t\treturn s.str();\n\t}\n\n\tinline Mat3x3 identity_matrix3x3()\n\t{\n\t\treturn Eigen::Matrix3d::Identity();\n\t}\n\n\tinline Mat3x3 calculate_extrinsic_rotation_matrix(double alpha, double beta, double gamma)\n\t{\n\t\tMat3x3 Rx, Ry, Rz;\n\t\tRx << 1, 0, 0,\n\t\t\t0, std::cos(alpha), -std::sin(alpha),\n\t\t\t0, std::sin(alpha), std::cos(alpha);\n\t\tRy << std::cos(beta), 0, std::sin(beta),\n\t\t\t0, 1, 0,\n\t\t\t-std::sin(beta), 0, std::cos(beta);\n\t\tRz << std::cos(gamma), -std::sin(gamma), 0,\n\t\t\tstd::sin(gamma), std::cos(gamma), 0,\n\t\t\t0, 0, 1;\n\t\treturn mat_prod(Rz, mat_prod(Ry, Rx));\n\t}\n\n\tinline Vec3 cross_product(const Vec3& a, const Vec3& b)\n\t{\n\t\treturn a.cross(b);\n\t}\n\n\t/// Returns the midpoint of the shortest segment between the two lines o1+a * d1 and o2 + b * d2;\n\tVec3 shortest_line_segment(const Vec3& o1, const Vec3& d1, const Vec3& o2, const Vec3& d2);\n}\n\n#endif", "meta": {"hexsha": "53a4c8d50e93e9b5411b1199bfc35715d0580e15", "size": 2399, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "GazeEstimationCpp/MathTypes.hpp", "max_stars_repo_name": "dmikushin/RemoteEye", "max_stars_repo_head_hexsha": "f467594e8d0246d7cc87bf843da1d09e105fcca7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2020-05-10T15:40:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T19:58:55.000Z", "max_issues_repo_path": "GazeEstimationCpp/MathTypes.hpp", "max_issues_repo_name": "dmikushin/RemoteEye", "max_issues_repo_head_hexsha": "f467594e8d0246d7cc87bf843da1d09e105fcca7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2020-08-08T22:22:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-18T12:18:37.000Z", "max_forks_repo_path": "GazeEstimationCpp/MathTypes.hpp", "max_forks_repo_name": "dmikushin/RemoteEye", "max_forks_repo_head_hexsha": "f467594e8d0246d7cc87bf843da1d09e105fcca7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-08-08T09:31:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-14T05:49:33.000Z", "avg_line_length": 22.0091743119, "max_line_length": 104, "alphanum_fraction": 0.6544393497, "num_tokens": 761, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.7931059414036511, "lm_q1q2_score": 0.7284521385983257}}
{"text": "#ifndef __BS_PRICES_HPP\n#define __BS_PRICES_HPP\n\n#include <iostream>\n#include <cmath>\n#include <armadillo>\n\ndouble d_j(const int j, const double S, const double K, const double r, const double sigma, const double T) {\n  return (log(S/K) + (r + (pow(-1,j-1))*0.5*sigma*sigma)*T)/(sigma*(pow(T,0.5)));\n}\n\ndouble call_price(const double S, const double K, const double r, const double sigma, const double T) {\n  return S * arma::normcdf(d_j(1, S, K, r, sigma, T))-K*exp(-r*T) * arma::normcdf(d_j(2, S, K, r, sigma, T));\n}\n\ndouble call_vega(const double S, const double K, const double r, const double sigma, const double T){\n\treturn S*sqrt(T)*arma::normpdf(d_j(1, S, K, r, sigma, T));\n}\n\n\n\n\n\n#endif ", "meta": {"hexsha": "58dff1dd11b32702512131328b2abc192121c94d", "size": 696, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/bs_prices.hpp", "max_stars_repo_name": "NicolasMakaroff/implied-volatility-learning", "max_stars_repo_head_hexsha": "907dfe4496be35708881f7b40c1b543a8574d649", "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/bs_prices.hpp", "max_issues_repo_name": "NicolasMakaroff/implied-volatility-learning", "max_issues_repo_head_hexsha": "907dfe4496be35708881f7b40c1b543a8574d649", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-03-28T11:36:39.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-21T14:01:12.000Z", "max_forks_repo_path": "src/bs_prices.hpp", "max_forks_repo_name": "NicolasMakaroff/implied-volatility-learning", "max_forks_repo_head_hexsha": "907dfe4496be35708881f7b40c1b543a8574d649", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-27T17:47:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-27T17:47:36.000Z", "avg_line_length": 29.0, "max_line_length": 109, "alphanum_fraction": 0.6752873563, "num_tokens": 222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9724147193720648, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.7284234266791669}}
{"text": "#include <Eigen/Core>\n\nEigen::Vector3d reflect(const Eigen::Vector3d & in, const Eigen::Vector3d & n)\n{\n  ////////////////////////////////////////////////////////////////////////////\n  // Replace with your code here:\n  return -in + (2 * n.dot(in) * n);\n  ////////////////////////////////////////////////////////////////////////////\n}\n", "meta": {"hexsha": "b425755d1a781d4ed275e2c84fd694fd93083166", "size": 334, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/reflect.cpp", "max_stars_repo_name": "jackys-95/computer-graphics-final-image-competition", "max_stars_repo_head_hexsha": "65e7c041530f319d10faba177ef03963aad16e56", "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/reflect.cpp", "max_issues_repo_name": "jackys-95/computer-graphics-final-image-competition", "max_issues_repo_head_hexsha": "65e7c041530f319d10faba177ef03963aad16e56", "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/reflect.cpp", "max_forks_repo_name": "jackys-95/computer-graphics-final-image-competition", "max_forks_repo_head_hexsha": "65e7c041530f319d10faba177ef03963aad16e56", "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.4, "max_line_length": 78, "alphanum_fraction": 0.3413173653, "num_tokens": 60, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361700013356, "lm_q2_score": 0.7981867873410141, "lm_q1q2_score": 0.7282944951871054}}
{"text": "// Jacobi theta functions\n// Copyright Evan Miller 2020\n//\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// Four main theta functions with various flavors of parameterization,\n// floating-point policies, and bonus \"minus 1\" versions of functions 3 and 4\n// designed to preserve accuracy for small q. Twenty-four C++ functions are\n// provided in all.\n//\n// The functions take a real argument z and a parameter known as q, or its close\n// relative tau.\n//\n// The mathematical functions are best understood in terms of their Fourier\n// series. Using the q parameterization, and summing from n = 0 to INF:\n//\n// theta_1(z,q) = 2 SUM (-1)^n * q^(n+1/2)^2 * sin((2n+1)z)\n// theta_2(z,q) = 2 SUM q^(n+1/2)^2 * cos((2n+1)z)\n// theta_3(z,q) = 1 + 2 SUM q^n^2 * cos(2nz)\n// theta_4(z,q) = 1 + 2 SUM (-1)^n * q^n^2 * cos(2nz)\n//\n// Appropriately multiplied and divided, these four theta functions can be used\n// to implement the famous Jacabi elliptic functions - but this is not really\n// recommended, as the existing Boost implementations are likely faster and\n// more accurate.  More saliently, setting z = 0 on the fourth theta function\n// will produce the limiting CDF of the Kolmogorov-Smirnov distribution, which\n// is this particular implementation's raison d'etre.\n//\n// Separate C++ functions are provided for q and for tau. The main q functions are:\n//\n// template <class T> inline T jacobi_theta1(T z, T q);\n// template <class T> inline T jacobi_theta2(T z, T q);\n// template <class T> inline T jacobi_theta3(T z, T q);\n// template <class T> inline T jacobi_theta4(T z, T q);\n//\n// The parameter q, also known as the nome, is restricted to the domain (0, 1),\n// and will throw a domain error otherwise.\n//\n// The equivalent functions that use tau instead of q are:\n//\n// template <class T> inline T jacobi_theta1tau(T z, T tau);\n// template <class T> inline T jacobi_theta2tau(T z, T tau);\n// template <class T> inline T jacobi_theta3tau(T z, T tau);\n// template <class T> inline T jacobi_theta4tau(T z, T tau);\n//\n// Mathematically, q and tau are related by:\n//\n// q = exp(i PI*Tau)\n//\n// However, the tau in the equation above is *not* identical to the tau in the function\n// signature. Instead, `tau` is the imaginary component of tau. Mathematically, tau can\n// be complex - but practically, most applications call for a purely imaginary tau.\n// Rather than provide a full complex-number API, the author decided to treat the\n// parameter `tau` as an imaginary number. So in computational terms, the\n// relationship between `q` and `tau` is given by:\n//\n// q = exp(-constants::pi<T>() * tau)\n//\n// The tau versions are provided for the sake of accuracy, as well as conformance\n// with common notation. If your q is an exponential, you are better off using\n// the tau versions, e.g.\n//\n// jacobi_theta1(z, exp(-a)); // rather poor accuracy\n// jacobi_theta1tau(z, a / constants::pi<T>()); // better accuracy\n//\n// Similarly, if you have a precise (small positive) value for the complement\n// of q, you can obtain a more precise answer overall by passing the result of\n// `log1p` to the tau parameter:\n//\n// jacobi_theta1(z, 1-q_complement); // precision lost in subtraction\n// jacobi_theta1tau(z, -log1p(-q_complement) / constants::pi<T>()); // better!\n//\n// A third quartet of functions are provided for improving accuracy in cases\n// where q is small, specifically |q| < exp(-PI) = 0.04 (or, equivalently, tau\n// greater than unity). In this domain of q values, the third and fourth theta\n// functions always return values close to 1. So the following \"m1\" functions\n// are provided, similar in spirit to `expm1`, which return one less than their\n// regular counterparts:\n//\n// template <class T> inline T jacobi_theta3m1(T z, T q);\n// template <class T> inline T jacobi_theta4m1(T z, T q);\n// template <class T> inline T jacobi_theta3m1tau(T z, T tau);\n// template <class T> inline T jacobi_theta4m1tau(T z, T tau);\n//\n// Note that \"m1\" versions of the first and second theta would not be useful,\n// as their ranges are not confined to a neighborhood around 1 (see the Fourier\n// transform representations above).\n//\n// Finally, the twelve functions above are each available with a third Policy\n// argument, which can be used to define a custom epsilon value. These Policy\n// versions bring the total number of functions provided by jacobi_theta.hpp\n// to twenty-four.\n//\n// See:\n// https://mathworld.wolfram.com/JacobiThetaFunctions.html\n// https://dlmf.nist.gov/20\n\n#ifndef BOOST_MATH_JACOBI_THETA_HPP\n#define BOOST_MATH_JACOBI_THETA_HPP\n\n#include <boost/math/tools/complex.hpp>\n#include <boost/math/tools/precision.hpp>\n#include <boost/math/tools/promotion.hpp>\n#include <boost/math/policies/error_handling.hpp>\n#include <boost/math/constants/constants.hpp>\n\nnamespace boost{ namespace math{\n\n// Simple functions - parameterized by q\ntemplate <class T, class U>\ninline typename tools::promote_args<T, U>::type jacobi_theta1(T z, U q);\ntemplate <class T, class U>\ninline typename tools::promote_args<T, U>::type jacobi_theta2(T z, U q);\ntemplate <class T, class U>\ninline typename tools::promote_args<T, U>::type jacobi_theta3(T z, U q);\ntemplate <class T, class U>\ninline typename tools::promote_args<T, U>::type jacobi_theta4(T z, U q);\n\n// Simple functions - parameterized by tau (assumed imaginary)\n// q = exp(i*PI*TAU)\n// tau = -log(q)/PI\ntemplate <class T, class U>\ninline typename tools::promote_args<T, U>::type jacobi_theta1tau(T z, U tau);\ntemplate <class T, class U>\ninline typename tools::promote_args<T, U>::type jacobi_theta2tau(T z, U tau);\ntemplate <class T, class U>\ninline typename tools::promote_args<T, U>::type jacobi_theta3tau(T z, U tau);\ntemplate <class T, class U>\ninline typename tools::promote_args<T, U>::type jacobi_theta4tau(T z, U tau);\n\n// Minus one versions for small q / large tau\ntemplate <class T, class U>\ninline typename tools::promote_args<T, U>::type jacobi_theta3m1(T z, U q);\ntemplate <class T, class U>\ninline typename tools::promote_args<T, U>::type jacobi_theta4m1(T z, U q);\ntemplate <class T, class U>\ninline typename tools::promote_args<T, U>::type jacobi_theta3m1tau(T z, U tau);\ntemplate <class T, class U>\ninline typename tools::promote_args<T, U>::type jacobi_theta4m1tau(T z, U tau);\n\n// Policied versions - parameterized by q\ntemplate <class T, class U, class Policy>\ninline typename tools::promote_args<T, U>::type jacobi_theta1(T z, U q, const Policy& pol);\ntemplate <class T, class U, class Policy>\ninline typename tools::promote_args<T, U>::type jacobi_theta2(T z, U q, const Policy& pol);\ntemplate <class T, class U, class Policy>\ninline typename tools::promote_args<T, U>::type jacobi_theta3(T z, U q, const Policy& pol);\ntemplate <class T, class U, class Policy>\ninline typename tools::promote_args<T, U>::type jacobi_theta4(T z, U q, const Policy& pol);\n\n// Policied versions - parameterized by tau\ntemplate <class T, class U, class Policy>\ninline typename tools::promote_args<T, U>::type jacobi_theta1tau(T z, U tau, const Policy& pol);\ntemplate <class T, class U, class Policy>\ninline typename tools::promote_args<T, U>::type jacobi_theta2tau(T z, U tau, const Policy& pol);\ntemplate <class T, class U, class Policy>\ninline typename tools::promote_args<T, U>::type jacobi_theta3tau(T z, U tau, const Policy& pol);\ntemplate <class T, class U, class Policy>\ninline typename tools::promote_args<T, U>::type jacobi_theta4tau(T z, U tau, const Policy& pol);\n\n// Policied m1 functions\ntemplate <class T, class U, class Policy>\ninline typename tools::promote_args<T, U>::type jacobi_theta3m1(T z, U q, const Policy& pol);\ntemplate <class T, class U, class Policy>\ninline typename tools::promote_args<T, U>::type jacobi_theta4m1(T z, U q, const Policy& pol);\ntemplate <class T, class U, class Policy>\ninline typename tools::promote_args<T, U>::type jacobi_theta3m1tau(T z, U tau, const Policy& pol);\ntemplate <class T, class U, class Policy>\ninline typename tools::promote_args<T, U>::type jacobi_theta4m1tau(T z, U tau, const Policy& pol);\n\n// Compare the non-oscillating component of the delta to the previous delta.\n// Both are assumed to be non-negative.\ntemplate <class RealType>\ninline bool\n_jacobi_theta_converged(RealType last_delta, RealType delta, RealType eps) {\n    return delta == 0.0 || delta < eps*last_delta;\n}\n\ntemplate <class RealType>\ninline RealType\n_jacobi_theta_sum(RealType tau, RealType z_n, RealType z_increment, RealType eps) {\n    BOOST_MATH_STD_USING\n    RealType delta = 0, partial_result = 0;\n    RealType last_delta = 0;\n\n    do {\n        last_delta = delta;\n        delta = exp(-tau*z_n*z_n/constants::pi<RealType>());\n        partial_result += delta;\n        z_n += z_increment;\n    } while (!_jacobi_theta_converged(last_delta, delta, eps));\n\n    return partial_result;\n}\n\n// The following _IMAGINARY theta functions assume imaginary z and are for\n// internal use only. They are designed to increase accuracy and reduce the\n// number of iterations required for convergence for large |q|. The z argument\n// is scaled by tau, and the summations are rewritten to be double-sided\n// following DLMF 20.13.4 and 20.13.5. The return values are scaled by\n// exp(-tau*z^2/Pi)/sqrt(tau).\n//\n// These functions are triggered when tau < 1, i.e. |q| > exp(-Pi) = 0.043\n//\n// Note that jacobi_theta4 uses the imaginary version of jacobi_theta2 (and\n// vice-versa). jacobi_theta1 and jacobi_theta3 use the imaginary versions of\n// themselves, following DLMF 20.7.30 - 20.7.33.\ntemplate <class RealType, class Policy>\ninline RealType\n_IMAGINARY_jacobi_theta1tau(RealType z, RealType tau, const Policy&) {\n    BOOST_MATH_STD_USING\n    RealType eps = policies::get_epsilon<RealType, Policy>();\n    RealType result = RealType(0);\n\n    // n>=0 even\n    result -= _jacobi_theta_sum(tau, RealType(z + constants::half_pi<RealType>()), constants::two_pi<RealType>(), eps);\n    // n>0 odd\n    result += _jacobi_theta_sum(tau, RealType(z + constants::half_pi<RealType>() + constants::pi<RealType>()), constants::two_pi<RealType>(), eps);\n    // n<0 odd\n    result += _jacobi_theta_sum(tau, RealType(z - constants::half_pi<RealType>()), RealType (-constants::two_pi<RealType>()), eps);\n    // n<0 even\n    result -= _jacobi_theta_sum(tau, RealType(z - constants::half_pi<RealType>() - constants::pi<RealType>()), RealType (-constants::two_pi<RealType>()), eps);\n\n    return result * sqrt(tau);\n}\n\ntemplate <class RealType, class Policy>\ninline RealType\n_IMAGINARY_jacobi_theta2tau(RealType z, RealType tau, const Policy&) {\n    BOOST_MATH_STD_USING\n    RealType eps = policies::get_epsilon<RealType, Policy>();\n    RealType result = RealType(0);\n\n    // n>=0\n    result += _jacobi_theta_sum(tau, RealType(z + constants::half_pi<RealType>()), constants::pi<RealType>(), eps);\n    // n<0\n    result += _jacobi_theta_sum(tau, RealType(z - constants::half_pi<RealType>()), RealType (-constants::pi<RealType>()), eps);\n\n    return result * sqrt(tau);\n}\n\ntemplate <class RealType, class Policy>\ninline RealType\n_IMAGINARY_jacobi_theta3tau(RealType z, RealType tau, const Policy&) {\n    BOOST_MATH_STD_USING\n    RealType eps = policies::get_epsilon<RealType, Policy>();\n    RealType result = 0;\n\n    // n=0\n    result += exp(-z*z*tau/constants::pi<RealType>());\n    // n>0\n    result += _jacobi_theta_sum(tau, RealType(z + constants::pi<RealType>()), constants::pi<RealType>(), eps);\n    // n<0\n    result += _jacobi_theta_sum(tau, RealType(z - constants::pi<RealType>()), RealType(-constants::pi<RealType>()), eps);\n\n    return result * sqrt(tau);\n}\n\ntemplate <class RealType, class Policy>\ninline RealType\n_IMAGINARY_jacobi_theta4tau(RealType z, RealType tau, const Policy&) {\n    BOOST_MATH_STD_USING\n    RealType eps = policies::get_epsilon<RealType, Policy>();\n    RealType result = 0;\n\n    // n = 0\n    result += exp(-z*z*tau/constants::pi<RealType>());\n\n    // n > 0 odd\n    result -= _jacobi_theta_sum(tau, RealType(z + constants::pi<RealType>()), constants::two_pi<RealType>(), eps);\n    // n < 0 odd\n    result -= _jacobi_theta_sum(tau, RealType(z - constants::pi<RealType>()), RealType (-constants::two_pi<RealType>()), eps);\n    // n > 0 even\n    result += _jacobi_theta_sum(tau, RealType(z + constants::two_pi<RealType>()), constants::two_pi<RealType>(), eps);\n    // n < 0 even\n    result += _jacobi_theta_sum(tau, RealType(z - constants::two_pi<RealType>()), RealType (-constants::two_pi<RealType>()), eps);\n\n    return result * sqrt(tau);\n}\n\n// First Jacobi theta function (Parameterized by tau - assumed imaginary)\n// = 2 * SUM (-1)^n * exp(i*Pi*Tau*(n+1/2)^2) * sin((2n+1)z)\ntemplate <class RealType, class Policy>\ninline RealType\njacobi_theta1tau_imp(RealType z, RealType tau, const Policy& pol, const char *function)\n{\n    BOOST_MATH_STD_USING\n    unsigned n = 0;\n    RealType eps = policies::get_epsilon<RealType, Policy>();\n    RealType q_n = 0, last_q_n, delta, result = 0;\n\n    if (tau <= 0.0)\n        return policies::raise_domain_error<RealType>(function,\n                \"tau must be greater than 0 but got %1%.\", tau, pol);\n\n    if (abs(z) == 0.0)\n        return result;\n\n    if (tau < 1.0) {\n        z = fmod(z, constants::two_pi<RealType>());\n        while (z > constants::pi<RealType>()) {\n            z -= constants::two_pi<RealType>();\n        }\n        while (z < -constants::pi<RealType>()) {\n            z += constants::two_pi<RealType>();\n        }\n\n        return _IMAGINARY_jacobi_theta1tau(z, RealType(1/tau), pol);\n    }\n\n    do {\n        last_q_n = q_n;\n        q_n = exp(-tau * constants::pi<RealType>() * RealType(n + 0.5)*RealType(n + 0.5) );\n        delta = q_n * sin(RealType(2*n+1)*z);\n        if (n%2)\n            delta = -delta;\n\n        result += delta + delta;\n        n++;\n    } while (!_jacobi_theta_converged(last_q_n, q_n, eps));\n\n    return result;\n}\n\n// First Jacobi theta function (Parameterized by q)\n// = 2 * SUM (-1)^n * q^(n+1/2)^2 * sin((2n+1)z)\ntemplate <class RealType, class Policy>\ninline RealType\njacobi_theta1_imp(RealType z, RealType q, const Policy& pol, const char *function) {\n    BOOST_MATH_STD_USING\n    if (q <= 0.0 || q >= 1.0) {\n        return policies::raise_domain_error<RealType>(function,\n                \"q must be greater than 0 and less than 1 but got %1%.\", q, pol);\n    }\n    return jacobi_theta1tau_imp(z, RealType (-log(q)/constants::pi<RealType>()), pol, function);\n}\n\n// Second Jacobi theta function (Parameterized by tau - assumed imaginary)\n// = 2 * SUM exp(i*Pi*Tau*(n+1/2)^2) * cos((2n+1)z)\ntemplate <class RealType, class Policy>\ninline RealType\njacobi_theta2tau_imp(RealType z, RealType tau, const Policy& pol, const char *function)\n{\n    BOOST_MATH_STD_USING\n    unsigned n = 0;\n    RealType eps = policies::get_epsilon<RealType, Policy>();\n    RealType q_n = 0, last_q_n, delta, result = 0;\n\n    if (tau <= 0.0) {\n        return policies::raise_domain_error<RealType>(function,\n                \"tau must be greater than 0 but got %1%.\", tau, pol);\n    } else if (tau < 1.0 && abs(z) == 0.0) {\n        return jacobi_theta4tau(z, 1/tau, pol) / sqrt(tau);\n    } else if (tau < 1.0) { // DLMF 20.7.31\n        z = fmod(z, constants::two_pi<RealType>());\n        while (z > constants::pi<RealType>()) {\n            z -= constants::two_pi<RealType>();\n        }\n        while (z < -constants::pi<RealType>()) {\n            z += constants::two_pi<RealType>();\n        }\n\n        return _IMAGINARY_jacobi_theta4tau(z, RealType(1/tau), pol);\n    }\n\n    do {\n        last_q_n = q_n;\n        q_n = exp(-tau * constants::pi<RealType>() * RealType(n + 0.5)*RealType(n + 0.5));\n        delta = q_n * cos(RealType(2*n+1)*z);\n        result += delta + delta;\n        n++;\n    } while (!_jacobi_theta_converged(last_q_n, q_n, eps));\n\n    return result;\n}\n\n// Second Jacobi theta function, parameterized by q\n// = 2 * SUM q^(n+1/2)^2 * cos((2n+1)z)\ntemplate <class RealType, class Policy>\ninline RealType\njacobi_theta2_imp(RealType z, RealType q, const Policy& pol, const char *function) {\n    BOOST_MATH_STD_USING\n    if (q <= 0.0 || q >= 1.0) {\n        return policies::raise_domain_error<RealType>(function,\n                \"q must be greater than 0 and less than 1 but got %1%.\", q, pol);\n    }\n    return jacobi_theta2tau_imp(z, RealType (-log(q)/constants::pi<RealType>()), pol, function);\n}\n\n// Third Jacobi theta function, minus one (Parameterized by tau - assumed imaginary)\n// This function preserves accuracy for small values of q (i.e. |q| < exp(-Pi) = 0.043)\n// For larger values of q, the minus one version usually won't help.\n// = 2 * SUM exp(i*Pi*Tau*(n)^2) * cos(2nz)\ntemplate <class RealType, class Policy>\ninline RealType\njacobi_theta3m1tau_imp(RealType z, RealType tau, const Policy& pol)\n{\n    BOOST_MATH_STD_USING\n\n    RealType eps = policies::get_epsilon<RealType, Policy>();\n    RealType q_n = 0, last_q_n, delta, result = 0;\n    unsigned n = 1;\n\n    if (tau < 1.0)\n        return jacobi_theta3tau(z, tau, pol) - RealType(1);\n\n    do {\n        last_q_n = q_n;\n        q_n = exp(-tau * constants::pi<RealType>() * RealType(n)*RealType(n));\n        delta = q_n * cos(RealType(2*n)*z);\n        result += delta + delta;\n        n++;\n    } while (!_jacobi_theta_converged(last_q_n, q_n, eps));\n\n    return result;\n}\n\n// Third Jacobi theta function, parameterized by tau\n// = 1 + 2 * SUM exp(i*Pi*Tau*(n)^2) * cos(2nz)\ntemplate <class RealType, class Policy>\ninline RealType\njacobi_theta3tau_imp(RealType z, RealType tau, const Policy& pol, const char *function)\n{\n    BOOST_MATH_STD_USING\n    if (tau <= 0.0) {\n        return policies::raise_domain_error<RealType>(function,\n                \"tau must be greater than 0 but got %1%.\", tau, pol);\n    } else if (tau < 1.0 && abs(z) == 0.0) {\n        return jacobi_theta3tau(z, RealType(1/tau), pol) / sqrt(tau);\n    } else if (tau < 1.0) { // DLMF 20.7.32\n        z = fmod(z, constants::pi<RealType>());\n        while (z > constants::half_pi<RealType>()) {\n            z -= constants::pi<RealType>();\n        }\n        while (z < -constants::half_pi<RealType>()) {\n            z += constants::pi<RealType>();\n        }\n        return _IMAGINARY_jacobi_theta3tau(z, RealType(1/tau), pol);\n    }\n    return RealType(1) + jacobi_theta3m1tau_imp(z, tau, pol);\n}\n\n// Third Jacobi theta function, minus one (parameterized by q)\n// = 2 * SUM q^n^2 * cos(2nz)\ntemplate <class RealType, class Policy>\ninline RealType\njacobi_theta3m1_imp(RealType z, RealType q, const Policy& pol, const char *function) {\n    BOOST_MATH_STD_USING\n    if (q <= 0.0 || q >= 1.0) {\n        return policies::raise_domain_error<RealType>(function,\n                \"q must be greater than 0 and less than 1 but got %1%.\", q, pol);\n    }\n    return jacobi_theta3m1tau_imp(z, RealType (-log(q)/constants::pi<RealType>()), pol);\n}\n\n// Third Jacobi theta function (parameterized by q)\n// = 1 + 2 * SUM q^n^2 * cos(2nz)\ntemplate <class RealType, class Policy>\ninline RealType\njacobi_theta3_imp(RealType z, RealType q, const Policy& pol, const char *function) {\n    BOOST_MATH_STD_USING\n    if (q <= 0.0 || q >= 1.0) {\n        return policies::raise_domain_error<RealType>(function,\n                \"q must be greater than 0 and less than 1 but got %1%.\", q, pol);\n    }\n    return jacobi_theta3tau_imp(z, RealType (-log(q)/constants::pi<RealType>()), pol, function);\n}\n\n// Fourth Jacobi theta function, minus one (Parameterized by tau)\n// This function preserves accuracy for small values of q (i.e. tau > 1)\n// = 2 * SUM (-1)^n exp(i*Pi*Tau*(n)^2) * cos(2nz)\ntemplate <class RealType, class Policy>\ninline RealType\njacobi_theta4m1tau_imp(RealType z, RealType tau, const Policy& pol)\n{\n    BOOST_MATH_STD_USING\n\n    RealType eps = policies::get_epsilon<RealType, Policy>();\n    RealType q_n = 0, last_q_n, delta, result = 0;\n    unsigned n = 1;\n\n    if (tau < 1.0)\n        return jacobi_theta4tau(z, tau, pol) - RealType(1);\n\n    do {\n        last_q_n = q_n;\n        q_n = exp(-tau * constants::pi<RealType>() * RealType(n)*RealType(n));\n        delta = q_n * cos(RealType(2*n)*z);\n        if (n%2)\n            delta = -delta;\n\n        result += delta + delta;\n        n++;\n    } while (!_jacobi_theta_converged(last_q_n, q_n, eps));\n\n    return result;\n}\n\n// Fourth Jacobi theta function (Parameterized by tau)\n// = 1 + 2 * SUM (-1)^n exp(i*Pi*Tau*(n)^2) * cos(2nz)\ntemplate <class RealType, class Policy>\ninline RealType\njacobi_theta4tau_imp(RealType z, RealType tau, const Policy& pol, const char *function)\n{\n    BOOST_MATH_STD_USING\n    if (tau <= 0.0) {\n        return policies::raise_domain_error<RealType>(function,\n                \"tau must be greater than 0 but got %1%.\", tau, pol);\n    } else if (tau < 1.0 && abs(z) == 0.0) {\n        return jacobi_theta2tau(z, 1/tau, pol) / sqrt(tau);\n    } else if (tau < 1.0) { // DLMF 20.7.33\n        z = fmod(z, constants::pi<RealType>());\n        while (z > constants::half_pi<RealType>()) {\n            z -= constants::pi<RealType>();\n        }\n        while (z < -constants::half_pi<RealType>()) {\n            z += constants::pi<RealType>();\n        }\n        return _IMAGINARY_jacobi_theta2tau(z, RealType(1/tau), pol);\n    }\n\n    return RealType(1) + jacobi_theta4m1tau_imp(z, tau, pol);\n}\n\n// Fourth Jacobi theta function, minus one (Parameterized by q)\n// This function preserves accuracy for small values of q\n// = 2 * SUM q^n^2 * cos(2nz)\ntemplate <class RealType, class Policy>\ninline RealType\njacobi_theta4m1_imp(RealType z, RealType q, const Policy& pol, const char *function) {\n    BOOST_MATH_STD_USING\n    if (q <= 0.0 || q >= 1.0) {\n        return policies::raise_domain_error<RealType>(function,\n                \"q must be greater than 0 and less than 1 but got %1%.\", q, pol);\n    }\n    return jacobi_theta4m1tau_imp(z, RealType (-log(q)/constants::pi<RealType>()), pol);\n}\n\n// Fourth Jacobi theta function, parameterized by q\n// = 1 + 2 * SUM q^n^2 * cos(2nz)\ntemplate <class RealType, class Policy>\ninline RealType\njacobi_theta4_imp(RealType z, RealType q, const Policy& pol, const char *function) {\n    BOOST_MATH_STD_USING\n    if (q <= 0.0 || q >= 1.0) {\n        return policies::raise_domain_error<RealType>(function,\n            \"|q| must be greater than zero and less than 1, but got %1%.\", q, pol);\n    }\n    return jacobi_theta4tau_imp(z, RealType(-log(q)/constants::pi<RealType>()), pol, function);\n}\n\n// Begin public API\n\ntemplate <class T, class U, class Policy>\ninline typename tools::promote_args<T, U>::type jacobi_theta1tau(T z, U tau, const Policy&) {\n   BOOST_FPU_EXCEPTION_GUARD\n   typedef typename tools::promote_args<T, U>::type result_type;\n   typedef typename policies::normalise<\n      Policy,\n      policies::promote_float<false>,\n      policies::promote_double<false>,\n      policies::discrete_quantile<>,\n      policies::assert_undefined<> >::type forwarding_policy;\n\n   static const char* function = \"boost::math::jacobi_theta1tau<%1%>(%1%)\";\n\n   return policies::checked_narrowing_cast<result_type, Policy>(\n           jacobi_theta1tau_imp(static_cast<result_type>(z), static_cast<result_type>(tau),\n               forwarding_policy(), function), function);\n}\n\ntemplate <class T, class U>\ninline typename tools::promote_args<T, U>::type jacobi_theta1tau(T z, U tau) {\n    return jacobi_theta1tau(z, tau, policies::policy<>());\n}\n\ntemplate <class T, class U, class Policy>\ninline typename tools::promote_args<T, U>::type jacobi_theta1(T z, U q, const Policy&) {\n   BOOST_FPU_EXCEPTION_GUARD\n   typedef typename tools::promote_args<T, U>::type result_type;\n   typedef typename policies::normalise<\n      Policy,\n      policies::promote_float<false>,\n      policies::promote_double<false>,\n      policies::discrete_quantile<>,\n      policies::assert_undefined<> >::type forwarding_policy;\n\n   static const char* function = \"boost::math::jacobi_theta1<%1%>(%1%)\";\n\n   return policies::checked_narrowing_cast<result_type, Policy>(\n           jacobi_theta1_imp(static_cast<result_type>(z), static_cast<result_type>(q),\n               forwarding_policy(), function), function);\n}\n\ntemplate <class T, class U>\ninline typename tools::promote_args<T, U>::type jacobi_theta1(T z, U q) {\n    return jacobi_theta1(z, q, policies::policy<>());\n}\n\ntemplate <class T, class U, class Policy>\ninline typename tools::promote_args<T, U>::type jacobi_theta2tau(T z, U tau, const Policy&) {\n   BOOST_FPU_EXCEPTION_GUARD\n   typedef typename tools::promote_args<T, U>::type result_type;\n   typedef typename policies::normalise<\n      Policy,\n      policies::promote_float<false>,\n      policies::promote_double<false>,\n      policies::discrete_quantile<>,\n      policies::assert_undefined<> >::type forwarding_policy;\n\n   static const char* function = \"boost::math::jacobi_theta2tau<%1%>(%1%)\";\n\n   return policies::checked_narrowing_cast<result_type, Policy>(\n           jacobi_theta2tau_imp(static_cast<result_type>(z), static_cast<result_type>(tau),\n               forwarding_policy(), function), function);\n}\n\ntemplate <class T, class U>\ninline typename tools::promote_args<T, U>::type jacobi_theta2tau(T z, U tau) {\n    return jacobi_theta2tau(z, tau, policies::policy<>());\n}\n\ntemplate <class T, class U, class Policy>\ninline typename tools::promote_args<T, U>::type jacobi_theta2(T z, U q, const Policy&) {\n   BOOST_FPU_EXCEPTION_GUARD\n   typedef typename tools::promote_args<T, U>::type result_type;\n   typedef typename policies::normalise<\n      Policy,\n      policies::promote_float<false>,\n      policies::promote_double<false>,\n      policies::discrete_quantile<>,\n      policies::assert_undefined<> >::type forwarding_policy;\n\n   static const char* function = \"boost::math::jacobi_theta2<%1%>(%1%)\";\n\n   return policies::checked_narrowing_cast<result_type, Policy>(\n           jacobi_theta2_imp(static_cast<result_type>(z), static_cast<result_type>(q),\n               forwarding_policy(), function), function);\n}\n\ntemplate <class T, class U>\ninline typename tools::promote_args<T, U>::type jacobi_theta2(T z, U q) {\n    return jacobi_theta2(z, q, policies::policy<>());\n}\n\ntemplate <class T, class U, class Policy>\ninline typename tools::promote_args<T, U>::type jacobi_theta3m1tau(T z, U tau, const Policy&) {\n   BOOST_FPU_EXCEPTION_GUARD\n   typedef typename tools::promote_args<T, U>::type result_type;\n   typedef typename policies::normalise<\n      Policy,\n      policies::promote_float<false>,\n      policies::promote_double<false>,\n      policies::discrete_quantile<>,\n      policies::assert_undefined<> >::type forwarding_policy;\n\n   static const char* function = \"boost::math::jacobi_theta3m1tau<%1%>(%1%)\";\n\n   return policies::checked_narrowing_cast<result_type, Policy>(\n           jacobi_theta3m1tau_imp(static_cast<result_type>(z), static_cast<result_type>(tau),\n               forwarding_policy()), function);\n}\n\ntemplate <class T, class U>\ninline typename tools::promote_args<T, U>::type jacobi_theta3m1tau(T z, U tau) {\n    return jacobi_theta3m1tau(z, tau, policies::policy<>());\n}\n\ntemplate <class T, class U, class Policy>\ninline typename tools::promote_args<T, U>::type jacobi_theta3tau(T z, U tau, const Policy&) {\n   BOOST_FPU_EXCEPTION_GUARD\n   typedef typename tools::promote_args<T, U>::type result_type;\n   typedef typename policies::normalise<\n      Policy,\n      policies::promote_float<false>,\n      policies::promote_double<false>,\n      policies::discrete_quantile<>,\n      policies::assert_undefined<> >::type forwarding_policy;\n\n   static const char* function = \"boost::math::jacobi_theta3tau<%1%>(%1%)\";\n\n   return policies::checked_narrowing_cast<result_type, Policy>(\n           jacobi_theta3tau_imp(static_cast<result_type>(z), static_cast<result_type>(tau),\n               forwarding_policy(), function), function);\n}\n\ntemplate <class T, class U>\ninline typename tools::promote_args<T, U>::type jacobi_theta3tau(T z, U tau) {\n    return jacobi_theta3tau(z, tau, policies::policy<>());\n}\n\n\ntemplate <class T, class U, class Policy>\ninline typename tools::promote_args<T, U>::type jacobi_theta3m1(T z, U q, const Policy&) {\n   BOOST_FPU_EXCEPTION_GUARD\n   typedef typename tools::promote_args<T, U>::type result_type;\n   typedef typename policies::normalise<\n      Policy,\n      policies::promote_float<false>,\n      policies::promote_double<false>,\n      policies::discrete_quantile<>,\n      policies::assert_undefined<> >::type forwarding_policy;\n\n   static const char* function = \"boost::math::jacobi_theta3m1<%1%>(%1%)\";\n\n   return policies::checked_narrowing_cast<result_type, Policy>(\n           jacobi_theta3m1_imp(static_cast<result_type>(z), static_cast<result_type>(q),\n               forwarding_policy(), function), function);\n}\n\ntemplate <class T, class U>\ninline typename tools::promote_args<T, U>::type jacobi_theta3m1(T z, U q) {\n    return jacobi_theta3m1(z, q, policies::policy<>());\n}\n\ntemplate <class T, class U, class Policy>\ninline typename tools::promote_args<T, U>::type jacobi_theta3(T z, U q, const Policy&) {\n   BOOST_FPU_EXCEPTION_GUARD\n   typedef typename tools::promote_args<T, U>::type result_type;\n   typedef typename policies::normalise<\n      Policy,\n      policies::promote_float<false>,\n      policies::promote_double<false>,\n      policies::discrete_quantile<>,\n      policies::assert_undefined<> >::type forwarding_policy;\n\n   static const char* function = \"boost::math::jacobi_theta3<%1%>(%1%)\";\n\n   return policies::checked_narrowing_cast<result_type, Policy>(\n           jacobi_theta3_imp(static_cast<result_type>(z), static_cast<result_type>(q),\n               forwarding_policy(), function), function);\n}\n\ntemplate <class T, class U>\ninline typename tools::promote_args<T, U>::type jacobi_theta3(T z, U q) {\n    return jacobi_theta3(z, q, policies::policy<>());\n}\n\ntemplate <class T, class U, class Policy>\ninline typename tools::promote_args<T, U>::type jacobi_theta4m1tau(T z, U tau, const Policy&) {\n   BOOST_FPU_EXCEPTION_GUARD\n   typedef typename tools::promote_args<T, U>::type result_type;\n   typedef typename policies::normalise<\n      Policy,\n      policies::promote_float<false>,\n      policies::promote_double<false>,\n      policies::discrete_quantile<>,\n      policies::assert_undefined<> >::type forwarding_policy;\n\n   static const char* function = \"boost::math::jacobi_theta4m1tau<%1%>(%1%)\";\n\n   return policies::checked_narrowing_cast<result_type, Policy>(\n           jacobi_theta4m1tau_imp(static_cast<result_type>(z), static_cast<result_type>(tau),\n               forwarding_policy()), function);\n}\n\ntemplate <class T, class U>\ninline typename tools::promote_args<T, U>::type jacobi_theta4m1tau(T z, U tau) {\n    return jacobi_theta4m1tau(z, tau, policies::policy<>());\n}\n\ntemplate <class T, class U, class Policy>\ninline typename tools::promote_args<T, U>::type jacobi_theta4tau(T z, U tau, const Policy&) {\n   BOOST_FPU_EXCEPTION_GUARD\n   typedef typename tools::promote_args<T, U>::type result_type;\n   typedef typename policies::normalise<\n      Policy,\n      policies::promote_float<false>,\n      policies::promote_double<false>,\n      policies::discrete_quantile<>,\n      policies::assert_undefined<> >::type forwarding_policy;\n\n   static const char* function = \"boost::math::jacobi_theta4tau<%1%>(%1%)\";\n\n   return policies::checked_narrowing_cast<result_type, Policy>(\n           jacobi_theta4tau_imp(static_cast<result_type>(z), static_cast<result_type>(tau),\n               forwarding_policy(), function), function);\n}\n\ntemplate <class T, class U>\ninline typename tools::promote_args<T, U>::type jacobi_theta4tau(T z, U tau) {\n    return jacobi_theta4tau(z, tau, policies::policy<>());\n}\n\ntemplate <class T, class U, class Policy>\ninline typename tools::promote_args<T, U>::type jacobi_theta4m1(T z, U q, const Policy&) {\n   BOOST_FPU_EXCEPTION_GUARD\n   typedef typename tools::promote_args<T, U>::type result_type;\n   typedef typename policies::normalise<\n      Policy,\n      policies::promote_float<false>,\n      policies::promote_double<false>,\n      policies::discrete_quantile<>,\n      policies::assert_undefined<> >::type forwarding_policy;\n\n   static const char* function = \"boost::math::jacobi_theta4m1<%1%>(%1%)\";\n\n   return policies::checked_narrowing_cast<result_type, Policy>(\n           jacobi_theta4m1_imp(static_cast<result_type>(z), static_cast<result_type>(q),\n               forwarding_policy(), function), function);\n}\n\ntemplate <class T, class U>\ninline typename tools::promote_args<T, U>::type jacobi_theta4m1(T z, U q) {\n    return jacobi_theta4m1(z, q, policies::policy<>());\n}\n\ntemplate <class T, class U, class Policy>\ninline typename tools::promote_args<T, U>::type jacobi_theta4(T z, U q, const Policy&) {\n   BOOST_FPU_EXCEPTION_GUARD\n   typedef typename tools::promote_args<T, U>::type result_type;\n   typedef typename policies::normalise<\n      Policy,\n      policies::promote_float<false>,\n      policies::promote_double<false>,\n      policies::discrete_quantile<>,\n      policies::assert_undefined<> >::type forwarding_policy;\n\n   static const char* function = \"boost::math::jacobi_theta4<%1%>(%1%)\";\n\n   return policies::checked_narrowing_cast<result_type, Policy>(\n           jacobi_theta4_imp(static_cast<result_type>(z), static_cast<result_type>(q),\n               forwarding_policy(), function), function);\n}\n\ntemplate <class T, class U>\ninline typename tools::promote_args<T, U>::type jacobi_theta4(T z, U q) {\n    return jacobi_theta4(z, q, policies::policy<>());\n}\n\n}}\n\n#endif\n", "meta": {"hexsha": "39b1243913103fdae5d04e53b719117504786db8", "size": 33425, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/math/special_functions/jacobi_theta.hpp", "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": "include/boost/math/special_functions/jacobi_theta.hpp", "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": "include/boost/math/special_functions/jacobi_theta.hpp", "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": 39.9820574163, "max_line_length": 159, "alphanum_fraction": 0.6851757666, "num_tokens": 9285, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436167620237, "lm_q2_score": 0.7981867777396212, "lm_q1q2_score": 0.728294484525886}}
{"text": "\n#include <tiny_math_types.h>\n#include <tiny_matrix_functions.h>\n#include <tiny_eigen3x3.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n\n#include <cmath>                       // for fabs\n\ntemplate<typename vector3_type,typename matrix3x3_type>\ninline void eigen_value_decomposition_test(vector3_type d,matrix3x3_type R)\n{\n  using std::fabs;\n\n  typedef typename vector3_type::real_type     real_type;\n  typedef typename vector3_type::value_traits  value_traits;\n\n  real_type const tol = value_traits::numeric_cast( 0.0001 );\n  real_type const d0  = d(0);\n  real_type const d1  = d(1);\n  real_type const d2  = d(2);\n  \n  matrix3x3_type D = matrix3x3_type::make_diag(d);\n  matrix3x3_type A = R*D*tiny::trans(R);\n  BOOST_CHECK( tiny::is_symmetric(A,tol) );\n\n  matrix3x3_type V;\n  tiny::eigen(A, V, d);\n\n  real_type determinant = tiny::det(V);\n  BOOST_CHECK_CLOSE( fabs( determinant ), value_traits::one(), tol );\n\n  real_type epsilon = 10e-7;\n\n  matrix3x3_type Itest = tiny::trans(V)*V;\n\n  BOOST_CHECK_CLOSE( Itest(0,0), value_traits::one() , tol );\n  BOOST_CHECK_CLOSE( Itest(1,1), value_traits::one() , tol );\n  BOOST_CHECK_CLOSE( Itest(2,2), value_traits::one() , tol );\n  //--- The check close version behaves strange when rhs is exactly zero?, so we use the check-version instead...\n  BOOST_CHECK( fabs(Itest(0,1))<epsilon );\n  BOOST_CHECK( fabs(Itest(0,2))<epsilon );\n  BOOST_CHECK( fabs(Itest(1,0))<epsilon );\n  BOOST_CHECK( fabs(Itest(1,2))<epsilon );\n  BOOST_CHECK( fabs(Itest(2,0))<epsilon );\n  BOOST_CHECK( fabs(Itest(2,1))<epsilon );\n\n  matrix3x3_type Atest = A - V*matrix3x3_type::make_diag(d)*tiny::trans(V);\n  \n  BOOST_CHECK( fabs(Atest(0,0))<epsilon );\n  BOOST_CHECK( fabs(Atest(0,1))<epsilon );\n  BOOST_CHECK( fabs(Atest(0,2))<epsilon );\n  BOOST_CHECK( fabs(Atest(1,0))<epsilon );\n  BOOST_CHECK( fabs(Atest(1,1))<epsilon );\n  BOOST_CHECK( fabs(Atest(1,2))<epsilon );\n  BOOST_CHECK( fabs(Atest(2,0))<epsilon );\n  BOOST_CHECK( fabs(Atest(2,1))<epsilon );\n  BOOST_CHECK( fabs(Atest(2,2))<epsilon );\n\n  bool match1 = fabs( d0 - d(0) ) < epsilon &&  \n                fabs( d1 - d(1) ) < epsilon &&\n                fabs( d2 - d(2) ) < epsilon ;\n\n  bool match2 = fabs( d0 - d(0) )< epsilon &&\n                fabs( d1 - d(2) )< epsilon &&\n                fabs( d2 - d(1) )< epsilon ;\n\n  bool match3 = fabs( d0 - d(1) )< epsilon &&\n                fabs( d1 - d(0) )< epsilon &&\n                fabs( d2 - d(2) )< epsilon ;\n\n  bool match4 = fabs( d0 - d(1) )< epsilon &&\n                fabs( d1 - d(2) )< epsilon &&\n                fabs( d2 - d(0) )< epsilon ;\n\n  bool match5 = fabs( d0 - d(2) )< epsilon &&\n                fabs( d1 - d(0) )< epsilon &&\n                fabs( d2 - d(1) )< epsilon ;\n\n  bool match6 = fabs( d0 - d(2) )< epsilon &&\n                fabs( d1 - d(1) )< epsilon &&\n                fabs( d2 - d(0) )< epsilon ;\n\n  BOOST_CHECK( match1 || match2 || match3 || match4 || match5 || match6 );\n}\n\nBOOST_AUTO_TEST_SUITE(tiny_eigen);\n\n  BOOST_AUTO_TEST_CASE(random_testing)\n  {\n    typedef tiny::MathTypes<double>                    math_types;\n    typedef math_types::vector3_type                  vector3_type;\n    typedef math_types::matrix3x3_type                matrix3x3_type;\n\n    matrix3x3_type R;\n    vector3_type d;\n\n    for(int i= 0;i<100;++i)\n    {\n      //--- non-negative eigen-values\n      d = vector3_type::random(0,1);\n      R = matrix3x3_type::random();\n      R = tiny::ortonormalize(R);\n      eigen_value_decomposition_test(d,R);\n\n      //--- non-positive eigen-values\n      d = vector3_type::random(-1,0);\n      R = matrix3x3_type::random();\n      R = tiny::ortonormalize(R);\n      eigen_value_decomposition_test(d,R);\n\n      //--- one zero eigen-values\n      d = vector3_type::random(0,1);\n      d(0) = 0;\n      R = matrix3x3_type::random();\n      R = tiny::ortonormalize(R);\n      eigen_value_decomposition_test(d,R);\n\n      //--- one zero eigen-values\n      d = vector3_type::random(0,1);\n      d(1) = 0;\n      R = matrix3x3_type::random();\n      R = tiny::ortonormalize(R);\n      eigen_value_decomposition_test(d,R);\n\n      //--- one zero eigen-values\n      d = vector3_type::random(0,1);\n      d(2) = 0;\n      R = matrix3x3_type::random();\n      R = tiny::ortonormalize(R);\n      eigen_value_decomposition_test(d,R);\n\n      //--- two zero eigen-values\n      d = vector3_type::random(0,1);\n      d(0) = 0;\n      d(1) = 0;\n      R = matrix3x3_type::random();\n      R = tiny::ortonormalize(R);\n      eigen_value_decomposition_test(d,R);\n\n      //--- two zero eigen-values\n      d = vector3_type::random(0,1);\n      d(0) = 0;\n      d(2) = 0;\n      R = matrix3x3_type::random();\n      R = tiny::ortonormalize(R);\n      eigen_value_decomposition_test(d,R);\n\n      //--- two zero eigen-values\n      d = vector3_type::random(0,1);\n      d(1) = 0;\n      d(2) = 0;\n      R = matrix3x3_type::random();\n      R = tiny::ortonormalize(R);\n      eigen_value_decomposition_test(d,R);\n\n      //--- three zero eigen-values\n      d.clear();\n      R = matrix3x3_type::random();\n      R = tiny::ortonormalize(R);\n      eigen_value_decomposition_test(d,R);\n\n      //--- multiplicity of 3\n      d = vector3_type::random(0,1);\n      d(1) = d(0);\n      d(2) = d(0);\n      R = matrix3x3_type::random();\n      R = tiny::ortonormalize(R);\n      eigen_value_decomposition_test(d,R);\n\n      //--- multiplicity of 2\n      d = vector3_type::random(0,1);\n      d(1) = d(0);\n      R = matrix3x3_type::random();\n      R = tiny::ortonormalize(R);\n      eigen_value_decomposition_test(d,R);\n\n      //--- multiplicity of 2\n      d = vector3_type::random(0,1);\n      d(2) = d(0);\n      R = matrix3x3_type::random();\n      R = tiny::ortonormalize(R);\n      eigen_value_decomposition_test(d,R);\n\n      //--- multiplicity of 2\n      d = vector3_type::random(0,1);\n      d(2) = d(1);\n      R = matrix3x3_type::random();\n      R = tiny::ortonormalize(R);\n      eigen_value_decomposition_test(d,R);\n    }\n  }\n\n\nBOOST_AUTO_TEST_CASE(detailed_testing)\n{  \n  typedef tiny::MathTypes<double>           MT;\n  typedef MT::vector3_type                  V;\n  typedef MT::matrix3x3_type                M;\n  typedef MT::value_traits                  VT;\n\n  M A;\n  \n  // This test case is known to result in a R-matrix with det(R)=-1\n  A(0,0) =  10.0;  A(0,1) = -1.0;  A(0,2) = -1.0;\n  A(1,0) =  -1.0;  A(1,1) = 10.0;  A(1,2) = -1.0;\n  A(2,0) =  -1.0;  A(2,1) = -1.0;  A(2,2) = 10.0;\n    \n  M R;\n  V d;\n  tiny::eigen(A, R, d);\n  \n  double determinant = tiny::det(R);\n  BOOST_CHECK_CLOSE( determinant, -VT::one(), 0.01 );\n  \n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "02465a485bc2dc388ec36ddbdbc4906365f8f726", "size": 6706, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/FOUNDATION/TINY/unit_tests/tiny_eigen/tiny_eigen.cpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T09:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-13T00:24:21.000Z", "max_issues_repo_path": "PROX/FOUNDATION/TINY/unit_tests/tiny_eigen/tiny_eigen.cpp", "max_issues_repo_name": "erleben/matchstick", "max_issues_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "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": "PROX/FOUNDATION/TINY/unit_tests/tiny_eigen/tiny_eigen.cpp", "max_forks_repo_name": "erleben/matchstick", "max_forks_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "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.0717488789, "max_line_length": 113, "alphanum_fraction": 0.5881300328, "num_tokens": 2098, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147439, "lm_q2_score": 0.7981867849406659, "lm_q1q2_score": 0.7282944815935722}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\nusing namespace Eigen;\nusing namespace std;\n\nMatrixXcd bl_bicgstab(const MatrixXcd& A, const MatrixXcd& B, const double& tol, const int& itermax)\n{\n// Block BiCGSTAB [Tadano etal 2009 JSIAM letters]\n  double Bnorm= B.norm();\n  MatrixXcd X= MatrixXcd::Zero(B.rows(),B.cols()); // Initial guess of X (zeros)\n  MatrixXcd R= B-A*X;\n  MatrixXcd P= R;\n  MatrixXcd R0til= R; //MatrixXcd::Random(B.rows(),B.cols());\n  MatrixXcd R0til_H= R0til.adjoint();\n  for(int k= 0; k < itermax; ++k){\n      MatrixXcd V= A*P;\n      FullPivLU<MatrixXcd> lu(R0til_H*V);\n      MatrixXcd alfa= lu.solve(R0til_H*R);\n      MatrixXcd T= R-V*alfa;\n      MatrixXcd Z= A*T;\n      complex<double> qsi= (Z.adjoint()*T).trace()/(Z.adjoint()*Z).trace();\n      X= X+P*alfa+qsi*T;\n      R= T-qsi*Z;\n      double err= R.norm()/Bnorm;\n      cout << \"bl_bicgstab: \" << \"iter= \" << k << \" relative err= \" << err << endl;\n      if(err < tol) break;\n      MatrixXcd beta= lu.solve(-R0til_H*Z);\n      P= R+(P-qsi*V)*beta;\n  }\n  if((A*X-B).norm()/Bnorm > 10*tol){\n      cerr << \"bl_bicgstab did not converge to solution within error tolerance !\" << endl;\n     // exit(EXIT_FAILURE);\n  }\n\n  return X;\n}\n", "meta": {"hexsha": "e4d28bc285eddb405531e5cf9624cfd992f4ef82", "size": 1200, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bl_bicgstab.cpp", "max_stars_repo_name": "nmoteki/block-Krylov-linear-solvers", "max_stars_repo_head_hexsha": "0c123f474296219c1b944ad83f8e3c7abbf0c2b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-27T08:44:06.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-27T08:44:06.000Z", "max_issues_repo_path": "bl_bicgstab.cpp", "max_issues_repo_name": "nmoteki/block-Krylov-linear-solvers", "max_issues_repo_head_hexsha": "0c123f474296219c1b944ad83f8e3c7abbf0c2b0", "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": "bl_bicgstab.cpp", "max_forks_repo_name": "nmoteki/block-Krylov-linear-solvers", "max_forks_repo_head_hexsha": "0c123f474296219c1b944ad83f8e3c7abbf0c2b0", "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.4324324324, "max_line_length": 100, "alphanum_fraction": 0.6125, "num_tokens": 414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436167620237, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.7282944801455566}}
{"text": "#include <glog/logging.h>\n#include <math.h> /* sin */\n#include <omp.h>\n#include <pcl/common/angles.h>\n#include <v4r/common/color_comparison.h>\n#include <boost/algorithm/string.hpp>\n\nnamespace v4r {\n\nstd::istream &operator>>(std::istream &in, ColorComparisonMethod &cm) {\n  std::string token;\n  in >> token;\n  boost::to_upper(token);\n  if (token == \"CIE76\")\n    cm = ColorComparisonMethod::CIE76;\n  else if (token == \"CIE94\")\n    cm = ColorComparisonMethod::CIE94;\n  else if (token == \"CIEDE2000\")\n    cm = ColorComparisonMethod::CIEDE2000;\n  else if (token == \"CUSTOM\")\n    cm = ColorComparisonMethod::CUSTOM;\n  else\n    in.setstate(std::ios_base::failbit);\n  return in;\n}\n\nstd::ostream &operator<<(std::ostream &out, const ColorComparisonMethod &cm) {\n  switch (cm) {\n    case ColorComparisonMethod::CIE76:\n      out << \"CIE76\";\n      break;\n    case ColorComparisonMethod::CIE94:\n      out << \"CIE94\";\n      break;\n    case ColorComparisonMethod::CIEDE2000:\n      out << \"CIEDE2000\";\n      break;\n    case ColorComparisonMethod::CUSTOM:\n      out << \"CUSTOM\";\n      break;\n    default:\n      out.setstate(std::ios_base::failbit);\n  }\n  return out;\n}\n\nfloat computeCIE76(const Eigen::Vector3f &a, const Eigen::Vector3f &b) {\n  return (a - b).norm();\n}\n\nfloat computeCIE94_DEFAULT(const Eigen::Vector3f &a, const Eigen::Vector3f &b) {\n  return computeCIE94(a, b, 1.f, .045f, .015f);\n}\n\nfloat computeCIE94(const Eigen::Vector3f &a, const Eigen::Vector3f &b, float K1, float K2, float Kl) {\n  float deltaL = a(0) - b(0);\n  float deltaA = a(1) - b(1);\n  float deltaB = a(2) - b(2);\n\n  float c1 = sqrt(a(1) * a(1) + a(2) * a(2));\n  float c2 = sqrt(b(1) * b(1) + b(2) * b(2));\n  float deltaC = c1 - c2;\n\n  float deltaH = deltaA * deltaA + deltaB * deltaB - deltaC * deltaC;\n  deltaH = deltaH < 0 ? 0 : sqrt(deltaH);\n\n  const double sl = 1.0;\n  const double kc = 1.0;\n  const double kh = 1.0;\n\n  float sc = 1.0f + K1 * c1;\n  float sh = 1.0f + K2 * c1;\n\n  float deltaLKlsl = deltaL / (Kl * sl);\n  float deltaCkcsc = deltaC / (kc * sc);\n  float deltaHkhsh = deltaH / (kh * sh);\n  float i = deltaLKlsl * deltaLKlsl + deltaCkcsc * deltaCkcsc + deltaHkhsh * deltaHkhsh;\n  return i < 0 ? 0 : sqrt(i);\n}\n\nfloat computeCIEDE2000(const Eigen::Vector3f &a, const Eigen::Vector3f &b) {\n  // Set weighting factors to 1\n  double k_L = 1.0;\n  double k_C = 1.0;\n  double k_H = 1.0;\n\n  // Calculate Cprime1, Cprime2, Cabbar\n  double c_star_1_ab = sqrt(a(1) * a(1) + a(2) * a(2));\n  double c_star_2_ab = sqrt(b(1) * b(1) + b(2) * b(2));\n  double c_star_average_ab = (c_star_1_ab + c_star_2_ab) / 2;\n\n  double c_star_average_ab_pot7 = c_star_average_ab * c_star_average_ab * c_star_average_ab;\n  c_star_average_ab_pot7 *= c_star_average_ab_pot7 * c_star_average_ab;\n\n  double G = 0.5 * (1 - sqrt(c_star_average_ab_pot7 / (c_star_average_ab_pot7 + 6103515625)));  // 25^7\n  double a1_prime = (1. + G) * a(1);\n  double a2_prime = (1. + G) * b(1);\n\n  double C_prime_1 = sqrt(a1_prime * a1_prime + a(2) * a(2));\n  double C_prime_2 = sqrt(a2_prime * a2_prime + b(2) * b(2));\n  // Angles in Degree.\n  double h_prime_1 = fmod(((atan2(a(2), a1_prime) * 180. / M_PI) + 360.), 360.);\n  double h_prime_2 = fmod(((atan2(b(2), a2_prime) * 180. / M_PI) + 360.), 360.);\n\n  double delta_L_prime = b(0) - a(0);\n  double delta_C_prime = C_prime_2 - C_prime_1;\n\n  double h_bar = std::abs(h_prime_1 - h_prime_2);\n  double delta_h_prime;\n  if (C_prime_1 * C_prime_2 == 0)\n    delta_h_prime = 0;\n  else {\n    if (h_bar <= 180.) {\n      delta_h_prime = h_prime_2 - h_prime_1;\n    } else if (h_bar > 180. && h_prime_2 <= h_prime_1) {\n      delta_h_prime = h_prime_2 - h_prime_1 + 360.;\n    } else {\n      delta_h_prime = h_prime_2 - h_prime_1 - 360.;\n    }\n  }\n  double delta_H_prime = 2 * sqrt(C_prime_1 * C_prime_2) * sin(delta_h_prime * M_PI / 360.);\n\n  // Calculate CIEDE2000\n  double L_prime_average = (a(0) + b(0)) / 2.0;\n  double C_prime_average = (C_prime_1 + C_prime_2) / 2.0;\n\n  // Calculate h_prime_average\n\n  double h_prime_average;\n  if (C_prime_1 * C_prime_2 == 0)\n    h_prime_average = 0;\n  else {\n    if (h_bar <= 180) {\n      h_prime_average = (h_prime_1 + h_prime_2) / 2;\n    } else if (h_bar > 180. && (h_prime_1 + h_prime_2) < 360) {\n      h_prime_average = (h_prime_1 + h_prime_2 + 360) / 2;\n    } else {\n      h_prime_average = (h_prime_1 + h_prime_2 - 360) / 2;\n    }\n  }\n  double L_prime_average_minus_50_square = (L_prime_average - 50);\n  L_prime_average_minus_50_square *= L_prime_average_minus_50_square;\n\n  double S_L = 1 + ((.015 * L_prime_average_minus_50_square) / sqrt(20. + L_prime_average_minus_50_square));\n  double S_C = 1 + .045 * C_prime_average;\n  double T = 1 - .17 * cos(pcl::deg2rad(h_prime_average - 30)) + .24 * cos(pcl::deg2rad(h_prime_average * 2)) +\n             .32 * cos(pcl::deg2rad(h_prime_average * 3 + 6)) - .2 * cos(pcl::deg2rad(h_prime_average * 4 - 63));\n  double S_H = 1 + .015 * T * C_prime_average;\n  double h_prime_average_minus_275_div_25_square = (h_prime_average - 275) / (25);\n  h_prime_average_minus_275_div_25_square *= h_prime_average_minus_275_div_25_square;\n  double delta_theta = 30 * std::exp(-h_prime_average_minus_275_div_25_square);\n\n  double C_prime_average_pot_7 = C_prime_average * C_prime_average * C_prime_average;\n  C_prime_average_pot_7 *= C_prime_average_pot_7 * C_prime_average;\n  double R_C = 2 * sqrt(C_prime_average_pot_7 / (C_prime_average_pot_7 + 6103515625));\n\n  double R_T = -sin(pcl::deg2rad(2 * delta_theta)) * R_C;\n\n  double delta_L_prime_div_k_L_S_L = delta_L_prime / (S_L * k_L);\n  double delta_C_prime_div_k_C_S_C = delta_C_prime / (S_C * k_C);\n  double delta_H_prime_div_k_H_S_H = delta_H_prime / (S_H * k_H);\n\n  double CIEDE2000 = sqrt(delta_L_prime_div_k_L_S_L * delta_L_prime_div_k_L_S_L +\n                          delta_C_prime_div_k_C_S_C * delta_C_prime_div_k_C_S_C +\n                          delta_H_prime_div_k_H_S_H * delta_H_prime_div_k_H_S_H +\n                          R_T * delta_C_prime_div_k_C_S_C * delta_H_prime_div_k_H_S_H);\n\n  return CIEDE2000;\n}\n\n// Eigen::VectorXf computeCIE76(const Eigen::MatrixXf &a, const Eigen::MatrixXf &b)\n//{\n//    CHECK(a.rows() == b.rows() && a.cols() == b.cols());\n\n//    Eigen::VectorXf diff(a.rows());\n\n//#pragma omp parallel for schedule(dynamic)\n\n//    for(size_t i=0; i<a.rows(); i++)\n//        diff(i) = computeCIE76(a.row(i), b.row(i));\n\n//    return diff;\n//}\n}  // namespace v4r\n", "meta": {"hexsha": "6f238ed1bbf9dff264155ff7e6264cacfe1e204f", "size": 6388, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/common/src/color_comparison.cpp", "max_stars_repo_name": "v4r-tuwien/v4r", "max_stars_repo_head_hexsha": "ff3fbd6d2b298b83268ba4737868bab258262a40", "max_stars_repo_licenses": ["BSD-1-Clause", "BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-02-22T11:36:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-20T11:31:08.000Z", "max_issues_repo_path": "modules/common/src/color_comparison.cpp", "max_issues_repo_name": "v4r-tuwien/v4r", "max_issues_repo_head_hexsha": "ff3fbd6d2b298b83268ba4737868bab258262a40", "max_issues_repo_licenses": ["BSD-1-Clause", "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": "modules/common/src/color_comparison.cpp", "max_forks_repo_name": "v4r-tuwien/v4r", "max_forks_repo_head_hexsha": "ff3fbd6d2b298b83268ba4737868bab258262a40", "max_forks_repo_licenses": ["BSD-1-Clause", "BSD-2-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-10-19T10:39:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-07T13:39:03.000Z", "avg_line_length": 34.5297297297, "max_line_length": 113, "alphanum_fraction": 0.6548215404, "num_tokens": 2187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632876167045, "lm_q2_score": 0.7853085708384735, "lm_q1q2_score": 0.7282663380463424}}
{"text": "#include <iostream>\n#include <ctime>\nusing namespace std;\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#define MATRIX_SIZE 50\n\nint main( int argc, char** argv)\n{\n    Eigen::Matrix3d matrix_33 = Eigen::Matrix3d::Zero(); //\u521d\u59cb\u5316\u4e3a\u96f6\n\n    matrix_33 = Eigen::Matrix3d::Random();\n    cout << matrix_33 << endl << endl;\n\n    cout << matrix_33.transpose() << endl;\n    cout << matrix_33.sum() << endl;\n    cout << matrix_33.trace() << endl;\n    cout << 10*matrix_33 << endl;\n    cout << 10*matrix_33.inverse() << endl;\n    cout << matrix_33.determinant() << endl << endl;\n\n    Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> eigen_solver(matrix_33.transpose()*matrix_33);\n    cout << \"Eigen Value = \" << eigen_solver.eigenvalues() << endl;\n    cout << \"Eigen vectors = \" << eigen_solver.eigenvectors() << endl;\n\n}", "meta": {"hexsha": "386ab8b02ecb08f45e9eeed372628b2dca10a76e", "size": 803, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "my_implementation_1/ch3/useEigen/eigenMatrix.cpp", "max_stars_repo_name": "Mingrui-Yu/slambook2", "max_stars_repo_head_hexsha": "d31273192bd9fb5ac618f147105082022c87a005", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-09T14:18:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-09T14:18:15.000Z", "max_issues_repo_path": "my_implementation_1/ch3/useEigen/eigenMatrix.cpp", "max_issues_repo_name": "Mingrui-Yu/slambook2", "max_issues_repo_head_hexsha": "d31273192bd9fb5ac618f147105082022c87a005", "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": "my_implementation_1/ch3/useEigen/eigenMatrix.cpp", "max_forks_repo_name": "Mingrui-Yu/slambook2", "max_forks_repo_head_hexsha": "d31273192bd9fb5ac618f147105082022c87a005", "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.6785714286, "max_line_length": 97, "alphanum_fraction": 0.6475716065, "num_tokens": 226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094117351309, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.7282548595005375}}
{"text": "#include <Eigen/LU>\n#include <mathtoolbox/matrix-inversion.hpp>\n#include <memory>\n#include <timer.hpp>\n\nusing Eigen::MatrixXd;\n\ninline bool CheckInvertibleness(const MatrixXd& matrix)\n{\n    const Eigen::FullPivLU<MatrixXd> lu(matrix);\n    return lu.isInvertible();\n}\n\nint main(int argc, char** argv)\n{\n    constexpr int size = 500;\n\n    std::shared_ptr<timer::Timer> t;\n\n#if 1\n    // Generate a test matrix\n    const MatrixXd random_matrix = [](const int size) {\n        while (true)\n        {\n            const MatrixXd candidate = MatrixXd::Random(size, size);\n\n            if (CheckInvertibleness(candidate))\n            {\n                return candidate;\n            }\n        }\n    }(size);\n\n    constexpr int block_size = 495;\n\n    std::cout << \"Matrix size: \" << size << std::endl;\n    std::cout << \"Block size: \" << block_size << std::endl;\n\n    // Prepare the inverse of the upper left block\n    const Eigen::MatrixXd block_inv = random_matrix.block(0, 0, block_size, block_size).inverse();\n\n    // Perform matrix inversion in the naive direct approach\n    t = std::make_shared<timer::Timer>(\"Naive approach\");\n\n    const MatrixXd naive_result = random_matrix.inverse();\n\n    // Perform matrix inversion in the block matrix approach\n    t = std::make_shared<timer::Timer>(\"Block approach\");\n\n    const MatrixXd block_result = mathtoolbox::GetInverseUsingUpperLeftBlockInverse(random_matrix, block_inv);\n\n    // Stop the timer\n    t = nullptr;\n\n    // Error check\n    if (!naive_result.isApprox(block_result, 1e-06))\n    {\n        throw std::runtime_error(\"The results are not consistent.\");\n    }\n#else\n    const int start_size = 100;\n\n    MatrixXd test_matrix     = MatrixXd::Random(start_size, start_size);\n    MatrixXd test_matrix_inv = test_matrix.inverse();\n    for (int i = test_matrix.rows(); i < size; ++i)\n    {\n        const MatrixXd new_test_matrix = [&]() {\n            MatrixXd mat(i + 1, i + 1);\n\n            mat.block(0, 0, i, i) = test_matrix; // A\n            while (true)\n            {\n                mat.block(0, i, i, 1) = MatrixXd::Random(i, 1); // B\n                mat.block(i, 0, 1, i) = MatrixXd::Random(1, i); // C\n                mat.block(i, i, 1, 1) = MatrixXd::Random(1, 1); // D\n\n                const MatrixXd sub_matrix =\n                    mat.block(i, i, 1, 1) - mat.block(i, 0, 1, i) * test_matrix_inv * mat.block(0, i, i, 1);\n\n                if (CheckInvertibleness(sub_matrix))\n                {\n                    break;\n                }\n            }\n\n            return mat;\n        }();\n\n        std::cout << \"Matrix size: \" << std::to_string(i + 1) << std::endl;\n\n        // Perform matrix inversion in the naive direct approach\n        t = std::make_shared<timer::Timer>(\"Naive approach\");\n\n        const MatrixXd naive_result = new_test_matrix.inverse();\n\n        // Perform matrix inversion in the block matrix approach\n        t = std::make_shared<timer::Timer>(\"Block approach\");\n\n        const MatrixXd block_result =\n            mathtoolbox::GetInverseUsingUpperLeftBlockInverse(new_test_matrix, test_matrix_inv);\n\n        // Stop the timer\n        t = nullptr;\n\n        // Error check\n        if (!naive_result.isApprox(block_result, 1e-06))\n        {\n            throw std::runtime_error(\"The results are not consistent.\");\n        }\n\n        // Store the results for the next step\n        test_matrix     = new_test_matrix;\n        test_matrix_inv = naive_result;\n    }\n#endif\n\n    return 0;\n}\n", "meta": {"hexsha": "1d78de5c0308c1162cbd9951ce342d4c2917603f", "size": 3462, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/matrix-inversion/main.cpp", "max_stars_repo_name": "yuki-koyama/mathtoolbox", "max_stars_repo_head_hexsha": "eb7449c3c489f465849a74405e72aff016a296f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 195.0, "max_stars_repo_stars_event_min_datetime": "2018-04-28T16:12:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:52:56.000Z", "max_issues_repo_path": "examples/matrix-inversion/main.cpp", "max_issues_repo_name": "amazing89/mathtoolbox", "max_issues_repo_head_hexsha": "8904bb06ced2ac501594f9574ef1ba3454b8e38e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 52.0, "max_issues_repo_issues_event_min_datetime": "2018-04-15T01:24:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-02T09:14:23.000Z", "max_forks_repo_path": "examples/matrix-inversion/main.cpp", "max_forks_repo_name": "amazing89/mathtoolbox", "max_forks_repo_head_hexsha": "8904bb06ced2ac501594f9574ef1ba3454b8e38e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 21.0, "max_forks_repo_forks_event_min_datetime": "2018-06-05T04:11:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T13:28:12.000Z", "avg_line_length": 29.0924369748, "max_line_length": 110, "alphanum_fraction": 0.5883882149, "num_tokens": 858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582554941719, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.7282347695241894}}
{"text": "#ifndef SKYLARK_SPECTRAL_HPP\n#define SKYLARK_SPECTRAL_HPP\n\n#include <boost/math/constants/constants.hpp>\n\n#include <El.hpp>\n\nnamespace skylark { namespace nla {\n\n/**\n * Chebyshev points of the second kind.\n *\n * Returns the N Chebyshev points of the second kind, rescaled to [a,b].\n * That is, x_j = (cos(j* pi / N) + a + 1) * (b - a) / 2 for j=0,..N-1.\n */\ntemplate<typename T>\nvoid ChebyshevPoints(int N, El::Matrix<T>& X, double a = -1, double b = 1) {\n    const double s = (b - a) / 2.0;\n    const double pi = boost::math::constants::pi<double>();\n\n    N = N - 1;\n    X.Resize(N+1, 1);\n    for(int j = 0; j <= N; j++)\n        X.Set(j, 0,\n            (std::cos(j * pi / N) + a + 1) * s);\n\n    if (N % 2 == 0)\n        X.Set(N / 2, 0, 0.0);\n}\n\n/**\n * Differentation matrix associated with with interpolation on N Chebyshev\n * points of the second kind.\n *\n * Returns a NxN matrix with the following property:\n *\n * Suppose a vector p representes a polynomial p(x) of degree N-1 by keeping its\n * value at the N points x_j = (cos(j* pi / N) + a + 1) * (b - a) / 2\n * for j=0,..,N-1. That is p_i = p(x_j-1) for i = 1,..,N-1. There is a unique\n * degree N-1 polynomial interpolating those points, and that is p(x).\n *\n * ([a,b] is the range of values of x we are interested in.)\n *\n * The dervitative of p(x), p'(x), is a degree N polynomial as well, and it\n * can be represented in the same manner by a vector p'. D is built such that\n *                    p' = D * p\n *\n * \\param N degree of differentation matrix (i.e. degree of polynomials + 1).\n * \\param D matrix to be filled.\n * \\param X matrix containing the Chebyshev points used.\n * \\param a,b  range of the parameter we are interested in.\n */\ntemplate<typename T>\nvoid ChebyshevDiffMatrix(int N, El::Matrix<T>& D, El::Matrix<T> &X,\n    double a = -1, double b = 1) {\n\n    ChebyshevPoints(N, X);\n    N = N - 1;\n    double *x = X.Buffer();\n\n    D.Resize(N+1, N+1);\n    for(int j = 0; j <= N; j++)\n        for(int i = 0; i <= N; i++) {\n            int d = i - j;\n            double v = 2.0 / (b - a);\n\n            if (i == 0 && j == 0)\n                v *= (2.0 * N * N + 1.0) / 6.0;\n            else if (i == N && j == N)\n                v *= -(2.0 * N * N + 1.0) / 6.0;\n            else {\n                if (i == 0 || i == N)\n                    v *= 2.0;\n                if (j ==0 || j == N)\n                    v /= 2.0;\n\n                if (d == 0)\n                    v *= -x[j] / (2.0 * (1 - x[j] * x[j]));\n                else if (d % 2 == 0)\n                    v *= 1.0 / (x[i] - x[j]);\n                else\n                    v *= -1.0 / (x[i] - x[j]);\n            }\n\n            D.Set(i, j, v);\n        }\n\n    // Rescale points from [-1, 1] to [a, b]\n    if (a != -1 && b != 1)\n        for(int i = 0; i <= N; i++)\n            x[i] = a + (x[i] + 1.0) * (b - a) / 2.0;\n}\n\n} }\n\n#endif\n", "meta": {"hexsha": "f17a8be0710eb2739e4d7b090efeb9dca02afd2e", "size": 2852, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "nla/spectral.hpp", "max_stars_repo_name": "xdata-skylark/libskylark", "max_stars_repo_head_hexsha": "89c3736136a24d519c14fc0738c21f37f1e10360", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 86.0, "max_stars_repo_stars_event_min_datetime": "2015-01-20T03:12:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-10T04:05:21.000Z", "max_issues_repo_path": "nla/spectral.hpp", "max_issues_repo_name": "xdata-skylark/libskylark", "max_issues_repo_head_hexsha": "89c3736136a24d519c14fc0738c21f37f1e10360", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 48.0, "max_issues_repo_issues_event_min_datetime": "2015-05-12T09:31:23.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-05T14:45:46.000Z", "max_forks_repo_path": "nla/spectral.hpp", "max_forks_repo_name": "xdata-skylark/libskylark", "max_forks_repo_head_hexsha": "89c3736136a24d519c14fc0738c21f37f1e10360", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2015-01-18T23:02:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-12T07:30:35.000Z", "avg_line_length": 29.4020618557, "max_line_length": 80, "alphanum_fraction": 0.4807152875, "num_tokens": 959, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.7281653306670367}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n\nnamespace filter_bay\n{\n/*!\nA linear state space model for transitioning between states with explicit noise.\nThe equation ist:\n\\f[\n  x_{k+1} = F x_k + B u_k + G w_k\n\\f]\nWhere \\f$x_k\\f$ is the state, \\f$u_k\\f$ the input and \\f$w_k\\f$ the process\nnoise at step k.\nThe noise is not actually used in the state prediction but in the state \ncovariance prediction:\n\\f[\n  P_{k+1} = F P_k F^T + G Q_k G^T\n\\f]\nThe noise *\\f$w_k\\f$ is described via its covariance *\\f$Q_k\\f$.\n\nSee https://en.wikipedia.org/wiki/Kalman_filter#Example_application,_technical\nfor an example how \\f$G\\f% might be introduced into the state equation.\n*/\ntemplate <size_t state_size, size_t input_size, size_t noise_size>\nstruct LinearTransitionModel\n{\n  /*! \\f$F\\f$ */\n  using TransitionMatrix = Eigen::Matrix<double, state_size, state_size>;\n  /*! \\f$B\\f$ */\n  using InputMatrix = Eigen::Matrix<double, state_size, input_size>;\n  /*! \\f$G\\f$ */\n  using NoiseMatrix = Eigen::Matrix<double, state_size, noise_size>;\n  /*! \\f$x_k\\f$ */\n  using State = Eigen::Matrix<double, state_size, 1>;\n  /*! \\f$U_k\\f$ */\n  using Input = Eigen::Matrix<double, input_size, 1>;\n  /*! \\f$P_k\\f$ */\n  using StateCovariance = Eigen::Matrix<double, state_size, state_size>;\n  /*! \\f$Q_k\\f$ */\n  using NoiseCovariance = Eigen::Matrix<double, noise_size, noise_size>;\n\n  /*! Transition matrix of the model. */\n  TransitionMatrix F;\n  /*! Control input matrix of the model. */\n  InputMatrix B;\n  /*! Explicit noise input matrix of the model. */\n  NoiseMatrix G;\n\n  LinearTransitionModel() {}\n\n  LinearTransitionModel(TransitionMatrix f, InputMatrix b,\n                        NoiseMatrix g) : F(std::move(f)), B(std::move(b)),\n                                         G(std::move(g)) {}\n\n  /*!\n  Predict the new state via this model.\n  \\param x the last state\n  \\param u the last control input\n  */\n  State predict_state(const State &x, const Input &u) const\n  {\n    return F * x + B * u;\n  }\n\n  /*!\n  Predict the new covariance of the state via this model.\n  \\param x the last state\n  \\param u the last control input\n  */\n  StateCovariance predict_covariance(const StateCovariance &P,\n                                     const NoiseCovariance &Q) const\n  {\n    return F * P * F.transpose() + G * Q * G.transpose();\n  }\n};\n} // namespace filter_bay", "meta": {"hexsha": "9292fd56a3b2660059c333ac0fde08106f70a25f", "size": 2328, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/filter_bay/model/linear_transition_model.hpp", "max_stars_repo_name": "Tuebel/filter_bay", "max_stars_repo_head_hexsha": "43728be441c3db0f3001b0d31068ce3c3e01d579", "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/filter_bay/model/linear_transition_model.hpp", "max_issues_repo_name": "Tuebel/filter_bay", "max_issues_repo_head_hexsha": "43728be441c3db0f3001b0d31068ce3c3e01d579", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-08-10T14:36:16.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-21T10:10:08.000Z", "max_forks_repo_path": "include/filter_bay/model/linear_transition_model.hpp", "max_forks_repo_name": "Tuebel/filter_bay", "max_forks_repo_head_hexsha": "43728be441c3db0f3001b0d31068ce3c3e01d579", "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.2337662338, "max_line_length": 80, "alphanum_fraction": 0.654209622, "num_tokens": 637, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418262465169, "lm_q2_score": 0.7879311856832191, "lm_q1q2_score": 0.7281601648938735}}
{"text": "/*\n   For more information, please see: http://software.sci.utah.edu\n\n   The MIT License\n\n   Copyright (c) 2020 Scientific Computing and Imaging Institute,\n   University of Utah.\n\n   Permission is hereby granted, free of charge, to any person obtaining a\n   copy of this software and associated documentation files (the \"Software\"),\n   to deal in the Software without restriction, including without limitation\n   the rights to use, copy, modify, merge, publish, distribute, sublicense,\n   and/or sell copies of the Software, and to permit persons to whom the\n   Software is furnished to do so, subject to the following conditions:\n\n   The above copyright notice and this permission notice shall be included\n   in all copies or substantial portions of the Software.\n\n   THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n   DEALINGS IN THE SOFTWARE.\n*/\n\n\n#include <Core/Algorithms/Base/AlgorithmPreconditions.h>\n#include <Core/Algorithms/Math/ComputeSVD.h>\n#include <Core/Datatypes/DenseMatrix.h>\n#include <Core/Datatypes/DenseColumnMatrix.h>\n#include <Core/Datatypes/MatrixTypeConversions.h>\n#include <Eigen/SVD>\n\n#include <Core/Algorithms/Base/AlgorithmVariableNames.h>\n\nusing namespace SCIRun;\nusing namespace SCIRun::Core::Algorithms;\nusing namespace SCIRun::Core::Datatypes;\nusing namespace SCIRun::Core::Algorithms::Math;\n\nvoid ComputeSVDAlgo::run(MatrixHandle input, DenseMatrixHandle& LeftSingMat, DenseMatrixHandle& SingVals, DenseMatrixHandle& RightSingMat) const\n{\n  if (input->nrows() == 0 || input->ncols() == 0){\n\n    THROW_ALGORITHM_INPUT_ERROR(\"Input has a zero dimension.\");\n}\n  if (matrixIs::dense(input))\n  {\n    auto denseInput = castMatrix::toDense(input);\n\n    Eigen::JacobiSVD<DenseMatrix::EigenBase> svd_mat(*denseInput, Eigen::ComputeFullU | Eigen::ComputeFullV);\n\n    LeftSingMat = boost::make_shared<DenseMatrix>(svd_mat.matrixU());\n\n    SingVals = boost::make_shared<DenseMatrix>(svd_mat.singularValues());\n\n    RightSingMat = boost::make_shared<DenseMatrix>(svd_mat.matrixV());\n  }\n  else\n  {\n    THROW_ALGORITHM_INPUT_ERROR(\"ComputeSVD works for dense matrix input only.\");\n  }\n}\n\n\nAlgorithmOutput ComputeSVDAlgo::run(const AlgorithmInput& input) const\n{\n\tauto input_matrix = input.get<Matrix>(Variables::InputMatrix);\n\n\tDenseMatrixHandle LeftSingMat;\n\tDenseMatrixHandle RightSingMat;\n\tDenseMatrixHandle SingVals;\n\n\trun(input_matrix, LeftSingMat, SingVals, RightSingMat);\n\n\tAlgorithmOutput output;\n\n\toutput[LeftSingularMatrix] = LeftSingMat;\n\toutput[SingularValues] = SingVals;\n\toutput[RightSingularMatrix] = RightSingMat;\n\n\treturn output;\n}\n\nAlgorithmOutputName ComputeSVDAlgo::LeftSingularMatrix(\"LeftSingularMatrix\");\nAlgorithmOutputName ComputeSVDAlgo::SingularValues(\"SingularValues\");\nAlgorithmOutputName ComputeSVDAlgo::RightSingularMatrix(\"RightSingularMatrix\");\n", "meta": {"hexsha": "9ee5da344fda33dbebeecc22c3f1b8a973302400", "size": 3199, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/Core/Algorithms/Math/ComputeSVD.cc", "max_stars_repo_name": "Haydelj/SCIRun", "max_stars_repo_head_hexsha": "f7ee04d85349b946224dbff183438663e54b9413", "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/Core/Algorithms/Math/ComputeSVD.cc", "max_issues_repo_name": "Haydelj/SCIRun", "max_issues_repo_head_hexsha": "f7ee04d85349b946224dbff183438663e54b9413", "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/Core/Algorithms/Math/ComputeSVD.cc", "max_forks_repo_name": "Haydelj/SCIRun", "max_forks_repo_head_hexsha": "f7ee04d85349b946224dbff183438663e54b9413", "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.5444444444, "max_line_length": 144, "alphanum_fraction": 0.7758674586, "num_tokens": 762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336303, "lm_q2_score": 0.7956581097540519, "lm_q1q2_score": 0.7279483681542624}}
{"text": "//-----------------------------------------------------------------------------\n// Copyright (c) 2016 Benjamin Buch\n//\n// https://github.com/bebuch/mitrax\n//\n// Distributed under the Boost Software License, Version 1.0. (See accompanying\n// file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)\n//-----------------------------------------------------------------------------\n#ifndef _mitrax__uBLAS__convolution__hpp_INCLUDED_\n#define _mitrax__uBLAS__convolution__hpp_INCLUDED_\n\n#include <boost/numeric/ublas/matrix.hpp>\n\n\nnamespace uBLAS{\n\n\n\tnamespace ublas = boost::numeric::ublas;\n\n\ttemplate < typename M1, typename M2 >\n\tinline auto convolution(M1 const& m, M2 const& k){\n\t\tint kc = k.size1();\n\t\tint kr = k.size2();\n\n\t\tint res_c = m.size1() - kc + 1;\n\t\tint res_r = m.size2() - kr + 1;\n\n\t\tusing value_type = typename M2::value_type;\n\t\tublas::matrix< value_type > res(res_c, res_r);\n\n\t\tfor(int my = 0; my < res_r; ++my){\n\t\t\tfor(int mx = 0; mx < res_c; ++mx){\n\t\t\t\tvalue_type b = 0;\n\n\t\t\t\tfor(int ky = 0; ky < kr; ++ky){\n\t\t\t\t\tfor(int kx = 0; kx < kc; ++kx){\n\t\t\t\t\t\tb += m(mx + kx, my + ky) * k(kx, ky);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tres(mx, my) = b;\n\t\t\t}\n\t\t}\n\n\n\t\treturn res;\n\t}\n\n\ttemplate < typename TM, typename V1, typename V2 >\n\tinline auto convolution(\n\t\tublas::matrix< TM > const& m,\n\t\tV1 const& vc,\n\t\tV2 const& vr\n\t){\n\t\treturn convolution(convolution(m, vr), vc);\n\t}\n\n}\n\n\n#endif\n", "meta": {"hexsha": "ca27e8edb38f080deeb5feba82d5cddf7f7985c4", "size": 1387, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "benchmark/include/uBLAS/convolution.hpp", "max_stars_repo_name": "bebuch/Mitrax", "max_stars_repo_head_hexsha": "bc33a1b93058886daab3e4ef736ef9b519111454", "max_stars_repo_licenses": ["BSL-1.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": "benchmark/include/uBLAS/convolution.hpp", "max_issues_repo_name": "bebuch/Mitrax", "max_issues_repo_head_hexsha": "bc33a1b93058886daab3e4ef736ef9b519111454", "max_issues_repo_licenses": ["BSL-1.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": "benchmark/include/uBLAS/convolution.hpp", "max_forks_repo_name": "bebuch/Mitrax", "max_forks_repo_head_hexsha": "bc33a1b93058886daab3e4ef736ef9b519111454", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.3709677419, "max_line_length": 79, "alphanum_fraction": 0.5616438356, "num_tokens": 406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896715436483, "lm_q2_score": 0.7905303285397349, "lm_q1q2_score": 0.7279121615613949}}
{"text": "#include <Core/Core.h>\r\n#include <Functions4U/Functions4U.h>\r\n#include <Eigen/Eigen.h>\r\n#include \"Utility.h\"\r\n\r\nnamespace Upp {\r\n\r\nusing namespace Eigen;\r\n\r\n\r\ndouble R2(const VectorXd &serie, const VectorXd &serie0, double mean) {\r\n\tif (IsNull(mean))\r\n\t\tmean = serie.mean();\r\n\tdouble sse = 0, sst = 0;\r\n\tfor (Eigen::Index i = 0; i < serie.size(); ++i) {\r\n\t\tdouble y = serie(i);\r\n\t\tdouble err = y - serie0(i);\r\n\t\tsse += err*err;\r\n\t\tdouble d = y - mean;\r\n\t\tsst += d*d;\r\n\t}\r\n\tif (sst < 1E-50 || sse > sst)\r\n\t\treturn 0;\r\n\treturn 1 - sse/sst;\r\n}\r\n\r\n}", "meta": {"hexsha": "c031ee5e139bc7dcb84faf06b0eff6bfcbdb76a4", "size": 545, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "STEM4U/Utility.cpp", "max_stars_repo_name": "Libraries4U/STEM4U", "max_stars_repo_head_hexsha": "41472ce21420ff5bcf69577efefd924cf1e7c2cf", "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": "STEM4U/Utility.cpp", "max_issues_repo_name": "Libraries4U/STEM4U", "max_issues_repo_head_hexsha": "41472ce21420ff5bcf69577efefd924cf1e7c2cf", "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": "STEM4U/Utility.cpp", "max_forks_repo_name": "Libraries4U/STEM4U", "max_forks_repo_head_hexsha": "41472ce21420ff5bcf69577efefd924cf1e7c2cf", "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": 20.1851851852, "max_line_length": 72, "alphanum_fraction": 0.5889908257, "num_tokens": 175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850093037731, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.7277742174122147}}
{"text": "#include <Eigen/LU>\n#include <mathtoolbox/matrix-inversion.hpp>\n\nusing Eigen::MatrixXd;\n\nMatrixXd mathtoolbox::GetInverseUsingUpperLeftBlockInverse(const MatrixXd& matrix,\n                                                           const MatrixXd& upper_left_block_inverse)\n{\n    const int size       = matrix.rows();\n    const int block_size = upper_left_block_inverse.rows();\n    const int rest_size  = size - block_size;\n\n    assert(block_size > 0);\n    assert(size > block_size);\n\n    assert(matrix.cols() == size);\n    assert(upper_left_block_inverse.cols() == block_size);\n\n    const Eigen::MatrixXd& A_inv = upper_left_block_inverse;\n    const Eigen::MatrixXd& B     = matrix.block(0, block_size, block_size, rest_size);\n    const Eigen::MatrixXd& C     = matrix.block(block_size, 0, rest_size, block_size);\n    const Eigen::MatrixXd& D     = matrix.block(block_size, block_size, rest_size, rest_size);\n\n    const Eigen::MatrixXd E     = D - C * A_inv * B;\n    const Eigen::MatrixXd E_inv = E.inverse();\n\n    assert((E * E_inv - MatrixXd::Identity(E.rows(), E.cols())).cwiseAbs().maxCoeff() < 1e-10);\n\n    Eigen::MatrixXd result(size, size);\n\n    result.block(0, 0, block_size, block_size)                 = A_inv + (A_inv * B) * E_inv * (C * A_inv);\n    result.block(0, block_size, block_size, rest_size)         = -A_inv * B * E_inv;\n    result.block(block_size, 0, rest_size, block_size)         = -E_inv * C * A_inv;\n    result.block(block_size, block_size, rest_size, rest_size) = E_inv;\n\n    assert((matrix * result - MatrixXd::Identity(size, size)).cwiseAbs().maxCoeff() < 1e-10);\n\n    return result;\n}\n", "meta": {"hexsha": "6496c9dfac2a4816c03c0a9c2ded9266799db793", "size": 1616, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/matrix-inversion.cpp", "max_stars_repo_name": "yuki-koyama/mathtoolbox", "max_stars_repo_head_hexsha": "eb7449c3c489f465849a74405e72aff016a296f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 195.0, "max_stars_repo_stars_event_min_datetime": "2018-04-28T16:12:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:52:56.000Z", "max_issues_repo_path": "src/matrix-inversion.cpp", "max_issues_repo_name": "amazing89/mathtoolbox", "max_issues_repo_head_hexsha": "8904bb06ced2ac501594f9574ef1ba3454b8e38e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 52.0, "max_issues_repo_issues_event_min_datetime": "2018-04-15T01:24:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-02T09:14:23.000Z", "max_forks_repo_path": "src/matrix-inversion.cpp", "max_forks_repo_name": "amazing89/mathtoolbox", "max_forks_repo_head_hexsha": "8904bb06ced2ac501594f9574ef1ba3454b8e38e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 21.0, "max_forks_repo_forks_event_min_datetime": "2018-06-05T04:11:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T13:28:12.000Z", "avg_line_length": 40.4, "max_line_length": 107, "alphanum_fraction": 0.646039604, "num_tokens": 415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850110816422, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.7277742043034808}}
{"text": "#pragma once\n#include <cmath>\n#include <Eigen/Dense>\n\ninline double r2d(double rad)\n{\n    return rad*180.0/M_PI;\n}\n\ninline double d2r(double degree)\n{\n    return degree*M_PI/180.0;\n}\n\ninline double get_angle(const Eigen::Vector3d& v1, const Eigen::Vector3d& v2)\n{\n    return r2d(atan2(v1.cross(v2).norm(), v1.transpose() * v2));\n}\n\ninline double get_angle2(const Eigen::Vector3d& v1, const Eigen::Vector3d& v2)\n{\n    double x = (v1.transpose()*v2);\n    return  r2d(acos( x / ( v1.norm()*v2.norm() ) ));\n}\n\ninline double get_distance(const Eigen::Vector3d& p1, const Eigen::Vector3d& p2)\n{\n    return sqrt( pow(p1.x()-p2.x(), 2.0) \n               + pow(p1.y()-p2.y(), 2.0)\n               + pow(p1.z()-p2.z(), 2.0));\n}", "meta": {"hexsha": "014e1e161ac00f067b35aba06d2f7485ec8fe499", "size": 716, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "toolkits/trajectory/common.hpp", "max_stars_repo_name": "bin70/Toolkit", "max_stars_repo_head_hexsha": "ef47b0bd97334a2ceca415f01570886bfbb11e4a", "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": "toolkits/trajectory/common.hpp", "max_issues_repo_name": "bin70/Toolkit", "max_issues_repo_head_hexsha": "ef47b0bd97334a2ceca415f01570886bfbb11e4a", "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": "toolkits/trajectory/common.hpp", "max_forks_repo_name": "bin70/Toolkit", "max_forks_repo_head_hexsha": "ef47b0bd97334a2ceca415f01570886bfbb11e4a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-30T08:03:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-30T08:03:44.000Z", "avg_line_length": 23.0967741935, "max_line_length": 80, "alphanum_fraction": 0.6187150838, "num_tokens": 241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850093037731, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.7277742029215434}}
{"text": "#include <iostream>\n#include <cmath>\n#include <xtensor/xarray.hpp>\n#include <xtensor/xmath.hpp>\n#include <xtensor/xview.hpp>\n#include \"../src/distance/distance.cpp\"\n#define BOOST_TEST_MODULE \"Distance test\"\n#include <boost/test/unit_test.hpp>\n\nusing namespace std;\nnamespace utf = boost::unit_test;\n\nBOOST_AUTO_TEST_CASE(TestKLDivergence, * utf::tolerance(0.00001))\n{\n\txt::xarray<double> p = {0.5, 0.5};\n\txt::xarray<double> q = {(double) 9 / 10, (double) 1 / 10};\n\n\tdouble v = kl_divergence(p, q);\n\n\tBOOST_TEST(v == 0.7369656);\n\n\tdouble v2 = kl_divergence(q, p);\n\n\tBOOST_TEST(v2 == 0.5310044);\n\n\txt::xarray<double> p1 = {\n\t\t{0.5, 0.5},\n\t\t{(double) 9 / 10, (double) 1 / 10}\n\t};\n\txt::xarray<double> q1  = {\n\t\t{(double) 9 / 10, (double) 1 / 10},\n\t\t{0.5, 0.5}\n\t};\n\n\txt::xarray<double> res1 = kl_divergence(p1, q1, 1);\n\n\tBOOST_TEST(res1[0] == 0.7369656);\n\tBOOST_TEST(res1[1] == 0.5310044);\n\n\txt::xarray<double> p0 = {\n\t\t{0.5, (double) 9 / 10},\n\t\t{0.5, (double) 1 / 10}\n\t};\n\txt::xarray<double> q0  = {\n\t\t{(double) 9 / 10, 0.5},\n\t\t{(double) 1 / 10, 0.5}\n\t};\n\t\n\txt::xarray<double> res0 = kl_divergence(p0, q0, 0);\n\n\tBOOST_TEST(res0[0] == 0.7369656);\n\tBOOST_TEST(res0[1] == 0.5310044);\n\n\txt::xarray<double> a = {1.0, 0.0};\n\txt::xarray<double> b = {0.5, 0.5};\n\n\tBOOST_TEST(kl_divergence(a, b) == 1.0);\n\n\t// Throw: values in q are not allowed to be zero\n\tBOOST_CHECK_THROW(kl_divergence(b, a), runtime_error);\n\n\t// Negative number: kl_divergence should throw an exception.\n\txt::xarray<double> d = {1.0, -0.00001};\n\txt::xarray<double> e = {0.5, 0.5};\n\n\tBOOST_CHECK_THROW(kl_divergence(d, e), runtime_error);\n\n\txt::xarray<double> y = {\n\t\t{-0.001, (double) 9 / 10},\n\t\t{0.5, (double) 1 / 10}\n\t};\n\txt::xarray<double> z  = {\n\t\t{(double) 9 / 10, 0.5},\n\t\t{(double) 1 / 10, 0.5}\n\t};\n\t\n\tBOOST_CHECK_THROW(kl_divergence(y, z, 0);, runtime_error);\n\n\t// All values are zero: throw\n\txt::xarray<double> pzero = {0.0, 0.0};\n\n\tBOOST_CHECK_THROW(kl_divergence(pzero, q), runtime_error);\n\tBOOST_CHECK_THROW(kl_divergence(q, pzero), runtime_error);\n\n\txt::xarray<double> p1zero = {{0.0, 0.0}, {0.5, 0.5}};\n\n\tBOOST_CHECK_THROW(kl_divergence(p1zero, q1, 1), runtime_error);\n\n\t// Values do not sum to 1: throw\n\txt::xarray<double> p_not_one = {0.33, 0.1};\n\t\n\tBOOST_CHECK_THROW(kl_divergence(p_not_one, q), runtime_error);\n\tBOOST_CHECK_THROW(kl_divergence(q, p_not_one), runtime_error);\n\n\txt::xarray<double> p_not_one_1 = {{0.33, 0.1}, {0.5, 0.5}};\n\t\n\tBOOST_CHECK_THROW(kl_divergence(p_not_one_1, q1, 1), runtime_error);\n\n\t// Shape mismatch exception\n\tBOOST_CHECK_THROW(kl_divergence(p, q0);, runtime_error);\n\tBOOST_CHECK_THROW(kl_divergence(p, q0, 0);, runtime_error);\n\tBOOST_CHECK_THROW(kl_divergence(p, q0, 1);, runtime_error);\n}\n\nBOOST_AUTO_TEST_CASE(TestJensenShannonDistance, * utf::tolerance(0.00001)) {\n\txt::xarray<double> p = {0.5, 0.5};\n\txt::xarray<double> q = {(double) 9 / 10, (double) 1 / 10};\n\n\tdouble v = jensen_shannon_distance(p, q);\n\n\tBOOST_TEST(v == 0.3831359);\n\n\t// distance is symmetric\n\tdouble v_sym = jensen_shannon_distance(q, p);\n\n\tBOOST_TEST(v_sym == 0.3831359);\n\n\txt::xarray<double> p1 = {\n\t\t{0.5, 0.5},\n\t\t{(double) 9 / 10, (double) 1 / 10}\n\t};\n\txt::xarray<double> q1  = {\n\t\t{(double) 9 / 10, (double) 1 / 10},\n\t\t{0.5, 0.5}\n\t};\n\n\txt::xarray<double> res1 = jensen_shannon_distance(p1, q1, 1);\n\n\tBOOST_TEST(res1[0] == 0.3831359);\n\tBOOST_TEST(res1[1] == 0.3831359);\n\n\txt::xarray<double> res1_sym = jensen_shannon_distance(q1, p1, 1);\n\n\tBOOST_TEST(res1_sym[0] == 0.3831359);\n\tBOOST_TEST(res1_sym[1] == 0.3831359);\n\n\txt::xarray<double> a = {1.0, 0.0};\n\txt::xarray<double> b = {0.5, 0.5};\n\n\tBOOST_TEST(jensen_shannon_distance(a, b) == 0.5579230);\n\tBOOST_TEST(jensen_shannon_distance(b, a) == 0.5579230);\n\n\txt::xarray<double> aa = {1.0, 0.0};\n\txt::xarray<double> bb = {0.0, 1.0};\n\n\tBOOST_TEST(jensen_shannon_distance(aa, bb) == 1.0);\n\n\t// All values are zero: throw\n\txt::xarray<double> pzero = {0.0, 0.0};\n\n\tBOOST_CHECK_THROW(jensen_shannon_distance(pzero, q), runtime_error);\n\tBOOST_CHECK_THROW(jensen_shannon_distance(q, pzero), runtime_error);\n\n\txt::xarray<double> p1zero = {{0.0, 0.0}, {0.5, 0.5}};\n\n\tBOOST_CHECK_THROW(jensen_shannon_distance(p1zero, q1, 1), runtime_error);\n\n\t// Values do not sum to 1: throw\n\txt::xarray<double> p_not_one = {0.33, 0.1};\n\t\n\tBOOST_CHECK_THROW(jensen_shannon_distance(p_not_one, q), runtime_error);\n\tBOOST_CHECK_THROW(jensen_shannon_distance(q, p_not_one), runtime_error);\n\n\txt::xarray<double> p_not_one_1 = {{0.33, 0.1}, {0.5, 0.5}};\n\t\n\tBOOST_CHECK_THROW(jensen_shannon_distance(p_not_one_1, q1, 1), runtime_error);\n\n\t// Negative number: jensen_shannon_distance should throw an exception.\n\txt::xarray<double> d = {1.0, -0.00001};\n\txt::xarray<double> e = {0.5, 0.5};\n\n\tBOOST_CHECK_THROW(jensen_shannon_distance(d, e), runtime_error);\n\n\t// Shape mismatch exception\n\tBOOST_CHECK_THROW(jensen_shannon_distance(p, q1);, runtime_error);\n\tBOOST_CHECK_THROW(jensen_shannon_distance(p, q1, 0);, runtime_error);\n\tBOOST_CHECK_THROW(jensen_shannon_distance(p, q1, 1);, runtime_error);\n}\n\nBOOST_AUTO_TEST_CASE(TestDuplicateRow, * utf::tolerance(0.00001)) {\n\txt::xarray<double> a = {0.5, 0.5};\n\n\tauto b = duplicate_rows(a, 10);\n\n\tBOOST_TEST(b.shape()[0] == 10);\n\tBOOST_TEST(xt::row(b, 0)[0] == a[0]);\n\tBOOST_TEST(xt::row(b, 0)[1] == a[1]);\n\tBOOST_TEST(xt::row(b, 5)[0] == a[0]);\n\tBOOST_TEST(xt::row(b, 5)[1] == a[1]);\n}\n", "meta": {"hexsha": "b73c812cca6fa74f1e7c2cf6bcc14f98ab417e2c", "size": 5326, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/distance/test_distance.cpp", "max_stars_repo_name": "srom/nbias", "max_stars_repo_head_hexsha": "be8cf8dd623038dcf08d38ed3d19f635ee2dbeae", "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/distance/test_distance.cpp", "max_issues_repo_name": "srom/nbias", "max_issues_repo_head_hexsha": "be8cf8dd623038dcf08d38ed3d19f635ee2dbeae", "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/distance/test_distance.cpp", "max_forks_repo_name": "srom/nbias", "max_forks_repo_head_hexsha": "be8cf8dd623038dcf08d38ed3d19f635ee2dbeae", "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.8848167539, "max_line_length": 79, "alphanum_fraction": 0.6682313181, "num_tokens": 2000, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834278, "lm_q2_score": 0.803173801068221, "lm_q1q2_score": 0.7276672877664725}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <cmath>\n\n#include \"Generator.hpp\"\n\n\n//A class to generate normal distribution values of type T\n//with expected value 0.0 and variation 1.0\ntemplate<class T>\nclass NormalGenerator {\nprivate: \n    int hasValue = 0;\n    T value;\npublic:\n    T operator()(){\n        if(hasValue){\n            hasValue = 0;\n            return value;\n        } else {\n            T x, y;\n            T s;\n            do{\n                x = 2.0 * (T) rand()/RAND_MAX - 1.0;\n                y = 2.0 * (T) rand()/RAND_MAX - 1.0;\n                s = x*x + y*y;\n            } while(s>1.0);\n            T tmp = sqrt(-2*log(s)/s);\n            value = x*tmp;\n            hasValue = 1;\n            return y*tmp;\n        }\n    }\n};\n\n\n//A class to generate N-dimensional multivariate normal distributions of floating type Float\ntemplate<class Float, int N>\nclass Generator<Gaussian<Float, N> > {\nprivate:\npublic:\n    typedef Eigen::Matrix<Float, N, 1> Vec;\n    typedef Eigen::Matrix<Float, N, N> Mat;\n    NormalGenerator<Float> ng;\n    Vec mean;\n    Mat transform;\npublic:\n    Generator(const Gaussian<Float, N>& gaussian) :\n        Generator(gaussian.invCovariance.inverse(), gaussian.mean){\n    }\n    Generator(const Mat& covar, const Vec& _mean) :\n        mean{_mean} \n    {\n        Eigen::SelfAdjointEigenSolver<Mat> eigenSolver(covar);\n        transform = eigenSolver.eigenvectors() \n                  * eigenSolver.eigenvalues().cwiseSqrt().asDiagonal();\n    }\n    \n    Vec operator()(){\n        Vec normal(mean.size());\n        return mean + transform * normal.unaryExpr([&](auto){ return ng(); });\n    }\n\n};\n\n\ntemplate<class Float, int N>\nclass Generator<IndependentGaussian<Float, N> > {\nprivate:\n    typedef Eigen::Matrix<Float, N, 1> Vec;\n    typedef Eigen::Matrix<Float, N, N> Mat;\n    Generator<Gaussian<Float, N> > gg;\npublic:\n    Generator(const IndependentGaussian<Float, N>& gaussian) :\n        gg(gaussian.deviation.cwiseAbs2().asDiagonal(), gaussian.mean){\n    }\n    Generator(const Vec& deviation, const Vec& mean) :\n        gg(deviation.cwiseAbs2().asDiagonal(), mean){\n    }\n    Vec operator()(){\n        return gg();\n    }\n};\n\n", "meta": {"hexsha": "11b679b6a2c888c74dd40abdd3509d0336143a1c", "size": 2163, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/GaussianGenerator.hpp", "max_stars_repo_name": "waterlaz/Expectation-Maximization", "max_stars_repo_head_hexsha": "ec20426d8746c08fb043fc3a989167f5ebd51f3b", "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": "include/GaussianGenerator.hpp", "max_issues_repo_name": "waterlaz/Expectation-Maximization", "max_issues_repo_head_hexsha": "ec20426d8746c08fb043fc3a989167f5ebd51f3b", "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": "include/GaussianGenerator.hpp", "max_forks_repo_name": "waterlaz/Expectation-Maximization", "max_forks_repo_head_hexsha": "ec20426d8746c08fb043fc3a989167f5ebd51f3b", "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.1511627907, "max_line_length": 92, "alphanum_fraction": 0.5792880259, "num_tokens": 551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818864, "lm_q2_score": 0.800692004473946, "lm_q1q2_score": 0.7275230891587188}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#include \"Helpers/NumericalAlgorithms/Spectral/SwshTestHelpers.hpp\"\n\n#include <boost/math/special_functions/binomial.hpp>\n#include <cmath>\n#include <complex>\n\n#include \"NumericalAlgorithms/Spectral/SwshTags.hpp\"  // IWYU pragma: keep\n\nnamespace Spectral {\nnamespace Swsh {\nnamespace TestHelpers {\n\ndouble factorial(const size_t arg) {\n  if (arg <= 1) {\n    return 1.0;\n  }\n  double factorial_result = 1.0;\n  for (size_t product_term = 1; product_term <= arg; ++product_term) {\n    factorial_result *= static_cast<double>(product_term);\n  }\n  return factorial_result;\n}\n\nstd::complex<double> spin_weighted_spherical_harmonic(const int s, const int l,\n                                                      const int m,\n                                                      const double theta,\n                                                      const double phi) {\n  if (l + s < 0 or l - s < 0) {\n    return 0.0;\n  }\n  std::complex<double> swshval = 0.0;\n  for (int r = 0; r <= l - s; ++r) {\n    if (r + s - m >= 0 and l - r + m >= 0) {\n      swshval +=\n          boost::math::binomial_coefficient<double>(\n              static_cast<unsigned>(l - s), static_cast<unsigned>(r)) *\n          boost::math::binomial_coefficient<double>(\n              static_cast<unsigned>(l + s), static_cast<unsigned>(r + s - m)) *\n          ((l - r - s) % 2 == 0 ? 1.0 : -1.0) *\n          pow(cos(theta / 2.0) / sin(theta / 2.0), 2.0 * r + s - m);\n    }\n  }\n  swshval *= (m % 2 == 0 ? 1.0 : -1.0) *\n             sqrt(factorial(static_cast<size_t>(l) + static_cast<size_t>(m)) *\n                  factorial(static_cast<size_t>(l - m)) * (2.0 * l + 1) /\n                  (4.0 * M_PI *\n                   factorial(static_cast<size_t>(l) + static_cast<size_t>(s)) *\n                   factorial(static_cast<size_t>(l - s)))) *\n             (std::complex<double>(cos(m * phi), sin(m * phi))) *\n             pow(sin(theta / 2.0), 2.0 * l);\n  return swshval;\n}\n\ntemplate <>\nstd::complex<double> derivative_of_spin_weighted_spherical_harmonic<Tags::Eth>(\n    const int s, const int l, const int m, const double theta,\n    const double phi) {\n  return sqrt(static_cast<std::complex<double>>((l - s) * (l + s + 1))) *\n         spin_weighted_spherical_harmonic(s + 1, l, m, theta, phi);\n}\n\ntemplate <>\nstd::complex<double>\nderivative_of_spin_weighted_spherical_harmonic<Tags::Ethbar>(const int s,\n                                                             const int l,\n                                                             const int m,\n                                                             const double theta,\n                                                             const double phi) {\n  return -sqrt(static_cast<std::complex<double>>((l + s) * (l - s + 1))) *\n         spin_weighted_spherical_harmonic(s - 1, l, m, theta, phi);\n}\n\ntemplate <>\nstd::complex<double>\nderivative_of_spin_weighted_spherical_harmonic<Tags::EthEth>(const int s,\n                                                             const int l,\n                                                             const int m,\n                                                             const double theta,\n                                                             const double phi) {\n  return sqrt(static_cast<std::complex<double>>((l - s) * (l + s + 1))) *\n         derivative_of_spin_weighted_spherical_harmonic<Tags::Eth>(s + 1, l, m,\n                                                                   theta, phi);\n}\n\ntemplate <>\nstd::complex<double>\nderivative_of_spin_weighted_spherical_harmonic<Tags::EthbarEth>(\n    const int s, const int l, const int m, const double theta,\n    const double phi) {\n  return sqrt(static_cast<std::complex<double>>((l - s) * (l + s + 1))) *\n         derivative_of_spin_weighted_spherical_harmonic<Tags::Ethbar>(\n             s + 1, l, m, theta, phi);\n}\n\ntemplate <>\nstd::complex<double>\nderivative_of_spin_weighted_spherical_harmonic<Tags::EthEthbar>(\n    const int s, const int l, const int m, const double theta,\n    const double phi) {\n  return -sqrt(static_cast<std::complex<double>>((l + s) * (l - s + 1))) *\n         derivative_of_spin_weighted_spherical_harmonic<Tags::Eth>(s - 1, l, m,\n                                                                   theta, phi);\n}\n\ntemplate <>\nstd::complex<double>\nderivative_of_spin_weighted_spherical_harmonic<Tags::EthbarEthbar>(\n    const int s, const int l, const int m, const double theta,\n    const double phi) {\n  return -sqrt(static_cast<std::complex<double>>((l + s) * (l - s + 1))) *\n         derivative_of_spin_weighted_spherical_harmonic<Tags::Ethbar>(\n             s - 1, l, m, theta, phi);\n}\n\ntemplate <>\nstd::complex<double>\nderivative_of_spin_weighted_spherical_harmonic<Tags::InverseEth>(\n    const int s, const int l, const int m, const double theta,\n    const double phi) {\n  return (l - s + 1) * (l + s) == 0\n             ? 0.0\n             : spin_weighted_spherical_harmonic(s - 1, l, m, theta, phi) /\n                   sqrt(static_cast<std::complex<double>>((l - s + 1) *\n                                                          (l + s)));\n}\n\ntemplate <>\nstd::complex<double>\nderivative_of_spin_weighted_spherical_harmonic<Tags::InverseEthbar>(\n    const int s, const int l, const int m, const double theta,\n    const double phi) {\n  return (l + s + 1) * (l - s) == 0\n             ? 0.0\n             : spin_weighted_spherical_harmonic(s + 1, l, m, theta, phi) /\n                   -sqrt(static_cast<std::complex<double>>((l + s + 1) *\n                                                           (l - s)));\n  ;\n}\n\n}  // namespace TestHelpers\n}  // namespace Swsh\n}  // namespace Spectral\n", "meta": {"hexsha": "27269391a3006a70c5b4f572d9827dd944a2e3d8", "size": 5724, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/Unit/Helpers/NumericalAlgorithms/Spectral/SwshTestHelpers.cpp", "max_stars_repo_name": "nilsvu/spectre", "max_stars_repo_head_hexsha": "1455b9a8d7e92db8ad600c66f54795c29c3052ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 117.0, "max_stars_repo_stars_event_min_datetime": "2017-04-08T22:52:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T07:23:36.000Z", "max_issues_repo_path": "tests/Unit/Helpers/NumericalAlgorithms/Spectral/SwshTestHelpers.cpp", "max_issues_repo_name": "GitHimanshuc/spectre", "max_issues_repo_head_hexsha": "4de4033ba36547113293fe4dbdd77591485a4aee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3177.0, "max_issues_repo_issues_event_min_datetime": "2017-04-07T21:10:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:55:59.000Z", "max_forks_repo_path": "tests/Unit/Helpers/NumericalAlgorithms/Spectral/SwshTestHelpers.cpp", "max_forks_repo_name": "geoffrey4444/spectre", "max_forks_repo_head_hexsha": "9350d61830b360e2d5b273fdd176dcc841dbefb0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 85.0, "max_forks_repo_forks_event_min_datetime": "2017-04-07T19:36:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T10:21:00.000Z", "avg_line_length": 39.2054794521, "max_line_length": 80, "alphanum_fraction": 0.5305730259, "num_tokens": 1437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067211996142, "lm_q2_score": 0.7718434978390746, "lm_q1q2_score": 0.7274676844275477}}
{"text": "<<<<<<< HEAD\n/*    Copyright (c) 2010-2018, Delft University of Technology\n=======\n/*    Copyright (c) 2010-2019, Delft University of Technology\n>>>>>>> origin/master\n *    All rigths reserved\n *\n *    This file is part of the Tudat. Redistribution and use in source and\n *    binary forms, with or without modification, are permitted exclusively\n *    under the terms of the Modified BSD license. You should have received\n *    a copy of the license with this file. If not, please or visit:\n *    http://tudat.tudelft.nl/LICENSE.\n */\n\n#include <boost/math/special_functions/erf.hpp>\n\n#include \"Tudat/Mathematics/BasicMathematics/mathematicalConstants.h\"\n#include \"Tudat/Mathematics/Statistics/continuousProbabilityDistributions.h\"\n\nnamespace tudat\n{\n\nnamespace statistics\n{\n\n//! Function to evaluate pdf of Gaussian distribution.\ndouble evaluateGaussianPdf( const double independentVariable, const double mean, const double standardDeviation )\n{\n    double offsetFromMean = independentVariable - mean;\n    return 1.0 / ( std::sqrt( 2.0 * mathematical_constants::PI ) * standardDeviation ) *\n            std::exp( -( offsetFromMean * offsetFromMean ) / ( 2.0 * standardDeviation * standardDeviation ) );\n}\n\n//! Function to evaluate cdf of Gaussian distribution.\ndouble calculateGaussianCdf( const double independentVariable, const double mean, const double standardDeviation )\n{\n    return 0.5 * ( 1.0 + boost::math::erf( ( independentVariable - mean ) / ( std::sqrt( 2.0 ) * ( standardDeviation ) ) ) );\n}\n\n}\n\n}\n", "meta": {"hexsha": "c15cf64c92e985743a22b813cd3e986ddf74f1d8", "size": 1513, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Mathematics/Statistics/continuousProbabilityDistributions.cpp", "max_stars_repo_name": "ViktorJordanov/tudat", "max_stars_repo_head_hexsha": "069ceeab8f12405c356e19f50d6df037914df85c", "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": "Tudat/Mathematics/Statistics/continuousProbabilityDistributions.cpp", "max_issues_repo_name": "ViktorJordanov/tudat", "max_issues_repo_head_hexsha": "069ceeab8f12405c356e19f50d6df037914df85c", "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": "Tudat/Mathematics/Statistics/continuousProbabilityDistributions.cpp", "max_forks_repo_name": "ViktorJordanov/tudat", "max_forks_repo_head_hexsha": "069ceeab8f12405c356e19f50d6df037914df85c", "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": 35.1860465116, "max_line_length": 125, "alphanum_fraction": 0.7217448777, "num_tokens": 374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067211996141, "lm_q2_score": 0.7718434873426303, "lm_q1q2_score": 0.7274676745345783}}
{"text": "#include \"geometrycentral/surface/trace_geodesic.h\"\n\n#include \"geometrycentral/surface/barycentric_coordinate_helpers.h\"\n#include \"geometrycentral/surface/vertex_position_geometry.h\"\n\n#include <Eigen/Dense>\n\n#include <iomanip>\n\nusing std::cout;\nusing std::endl;\n\nnamespace geometrycentral {\nnamespace surface {\n\n\n// Helper functions which support tracing\nnamespace {\n\n\n// === Geometric subroutines for tracing\n\n// a few parameters\nconst double TRACE_EPS_TIGHT = 1e-12;\nconst double TRACE_EPS_LOOSE = 1e-9;\nconst bool TRACE_PRINT = false;\n\ninline std::array<Vector2, 3> vertexCoordinatesInTriangle(IntrinsicGeometryInterface& geom, Face face) {\n  return {Vector2{0., 0.}, geom.halfedgeVectorsInFace[face.halfedge()],\n          -geom.halfedgeVectorsInFace[face.halfedge().next().next()]};\n}\n\ninline Vector3 faceCoordsToBaryCoords(const std::array<Vector2, 3>& vertCoords, Vector2 faceCoord) {\n\n  // Warning: bakes in assumption that vertCoords[0] == (0,0)\n\n  // Invert the system to solve for coordinates\n  double b2 = faceCoord.y / vertCoords[2].y;\n  b2 = clamp(b2, 0.0, 1.0); // comment these to get useful errors rather than clamping\n  double b1 = (faceCoord.x - b2 * vertCoords[2].x) / vertCoords[1].x;\n  b1 = clamp(b1, 0.0, 1.0 - b2);\n  double b0 = 1.0 - b1 - b2;\n  b0 = clamp(b0, 0.0, 1.0);\n  Vector3 result{b0, b1, b2};\n\n  return result;\n}\n\ninline Vector2 baryCoordsToFaceCoords(const std::array<Vector2, 3>& vertCoords, Vector3 baryCoord) {\n  return vertCoords[0] * baryCoord.x + vertCoords[1] * baryCoord.y + vertCoords[2] * baryCoord.z;\n}\n\ninline Vector2 barycentricDisplacementToCartesian(const std::array<Vector2, 3>& vertCoords, Vector3 baryVec) {\n  // Note: happens to be the same as baryCoordsToFaceCoords()\n  return vertCoords[0] * baryVec.x + vertCoords[1] * baryVec.y + vertCoords[2] * baryVec.z;\n}\n\ninline Vector3 cartesianVectorToBarycentric(const std::array<Vector2, 3>& vertCoords, Vector2 faceVec) {\n\n\n  // Build matrix for linear transform problem\n  // (last constraint comes from chosing the displacement vector with sum = 0)\n  Eigen::Matrix3d A;\n  Eigen::Vector3d rhs;\n  const std::array<Vector2, 3>& c = vertCoords; // short name\n  A << c[0].x, c[1].x, c[2].x, c[0].y, c[1].y, c[2].y, 1., 1., 1.;\n  rhs << faceVec.x, faceVec.y, 0.;\n\n  // Solve\n  Eigen::Vector3d result = A.colPivHouseholderQr().solve(rhs);\n  Vector3 resultBary{result(0), result(1), result(2)};\n\n  resultBary = normalizeBarycentricDisplacement(resultBary);\n\n  if (TRACE_PRINT) {\n    cout << \"       cartesianVectorToBarycentric() \" << endl;\n    cout << \"         input = \" << faceVec << endl;\n    cout << \"         positions = \" << vertCoords[0] << \" \" << vertCoords[1] << \" \" << vertCoords[2] << endl;\n    cout << \"         transform result = \" << resultBary << endl;\n    cout << \"         transform back = \" << barycentricDisplacementToCartesian(vertCoords, resultBary) << endl;\n    cout << \" A = \" << endl << A << endl;\n    cout << \" rhs = \" << endl << rhs << endl;\n    cout << \" Ax = \" << endl << A * result << endl;\n  }\n\n  return resultBary;\n}\n\n// Converts tCross from halfedge to edge coordinates, handling sign conventions\ninline double convertTToEdge(Halfedge he, double tCross) {\n  if (he == he.edge().halfedge()) return tCross;\n  return 1.0 - tCross;\n}\n// Converts vectors in halfedge basis from halfedge to edge coordinates, handling sign conventions\ninline Vector2 convertVecToEdge(Halfedge he, Vector2 halfedgeVec) {\n  if (he == he.edge().halfedge()) return halfedgeVec;\n  return -halfedgeVec;\n}\n\n\n// === Tracing subroutines\n\n\n// Return type from tracing subroutines\n// When trace ends, will set newFace = Face() and newVector = Vector3::zero(). only then is incomingVecToPoint populated\nstruct TraceSubResult {\n  // Did the trace end?\n  bool terminated;\n\n  // One of the two sets of values will be defined:\n\n  // If the trace continues (terminated == false)\n  Halfedge crossHe;              // halfedge we crossed over from (crossHe.twin().face() is new face)\n  double tCross;                 // t along crossHe\n  Vector2 traceVectorInHalfedge; // vector to keep tracing, measured against crossHe\n\n  // If the trace ends (terminated == true)\n  SurfacePoint endPoint;      // ending location\n  Vector2 incomingVecToPoint; // final incoming direction\n};\n\n\n// General form for tracing barycentrically within a face\n// Assumes that approriate projects have already been performed such that startPoint and vectors are valid (inside\n// triangle and pointing in the right direction)\n//\n// This function is tightly coupled with the routines which call it. They prepare the values startPoint, vecBary, and\n// vecCartesian, ensuring that those values satisify basic properties (essentially that the trace points in a vallid\n// direction).\n//\n// Note that this expects to be given the trace vector in both barycentric _and_ cartesian coordinates. These are two\n// different representations of the same data! This is useful the barycentric representation is good for relilably\n// performing tracing, while the cartesian representation is good for transforming the trace vector between triangles.\ninline TraceSubResult traceInFaceBarycentric(IntrinsicGeometryInterface& geom, Face face, Vector3 startPoint,\n                                             Vector3 vecBary, Vector2 vecCartesian,\n                                             const std::array<bool, 3>& edgeIsHittable, bool errorOnProblem) {\n\n  // Gather values\n  std::array<Vector2, 3> vertexCoords = vertexCoordinatesInTriangle(geom, face);\n  Vector3 triangleLengths{geom.edgeLengths[face.halfedge().edge()], geom.edgeLengths[face.halfedge().next().edge()],\n                          geom.edgeLengths[face.halfedge().next().next().edge()]};\n\n  if (sum(startPoint) < 0.5) {\n    if (TRACE_PRINT) {\n      cout << \"  bad bary point: \" << startPoint << endl;\n    }\n    if (errorOnProblem) {\n      throw std::runtime_error(\"bad bary point\");\n    }\n  }\n\n  if (TRACE_PRINT) {\n    cout << \"  general trace in face: \" << endl;\n    cout << \"  face: \" << face << \" startPoint \" << startPoint << \" vecBary = \" << vecBary << \" vecCartesian \"\n         << vecCartesian << endl;\n  }\n\n  if (TRACE_PRINT) {\n    cout << \"  vec bary  = \" << vecBary << endl;\n    cout << \"  reconvert = \" << cartesianVectorToBarycentric(vertexCoords, vecCartesian) << endl;\n  }\n\n  // Test if the vector ends in the triangle\n  Vector3 endPoint = startPoint + vecBary;\n  if (TRACE_PRINT) {\n    cout << \"    endpoint: \" << endPoint << endl;\n  }\n  if (isInsideTriangle(endPoint)) {\n    // The trace ended! Call it a day.\n    TraceSubResult result;\n    result.terminated = true;\n    result.endPoint = SurfacePoint(face, endPoint);\n    result.incomingVecToPoint = vecCartesian;\n    return result;\n  }\n\n\n  // The vector did not end in this triangle. Pick an appropriate point along some edge\n  double tRay = std::numeric_limits<double>::infinity();\n  Halfedge crossHe = Halfedge();\n  int iOppVertEnd = -777;\n  Halfedge currHe = face.halfedge();\n  for (int i = 0; i < 3; i++) {\n    currHe = currHe.next(); // always opposite the i'th vertex\n\n    // Check the crossing\n    double tRayThisRaw = -startPoint[i] / vecBary[i];\n    double tRayThis = clamp(tRayThisRaw, 0., 1. - TRACE_EPS_LOOSE);\n\n    if (TRACE_PRINT) {\n      cout << \"    considering intersection:\" << endl;\n      cout << std::boolalpha;\n      cout << \"      hittable[(i+1)%3]: \" << edgeIsHittable[(i + 1) % 3] << endl;\n      cout << \"      vecBary[i]: \" << vecBary[i] << endl;\n      cout << \"      startPoint[i]: \" << startPoint[i] << endl;\n      cout << \"      tRayThisRaw: \" << tRayThisRaw << endl;\n      cout << \"      tRayThis: \" << tRayThis << endl;\n    }\n\n\n    if (!edgeIsHittable[(i + 1) % 3] || vecBary[i] >= 0) {\n      // note should ALWAYS satisfy precondition that vecBary[i] is negative for at least one hittable edge.\n      // if not, fix projection of inputs in caller\n      continue;\n    }\n\n    if (tRayThis < tRay) {\n      // This is the new closest intersection\n      tRay = tRayThis;\n      crossHe = currHe;\n      iOppVertEnd = i;\n    }\n  }\n\n  if (TRACE_PRINT) {\n    cout << \"    selected intersection:\" << endl;\n    cout << \"      crossHe: \" << crossHe << endl;\n    cout << \"      tRay: \" << tRay << endl;\n    cout << \"      iOppVertEnd: \" << iOppVertEnd << endl;\n  }\n\n  if (crossHe == Halfedge()) {\n    if (errorOnProblem) {\n      throw std::logic_error(\"no halfedge intersection was selected, precondition problem?\");\n    }\n    if (TRACE_PRINT) {\n      cout << \"    PROBLEM PROBLEM NO INTERSECTION:\" << endl;\n    }\n\n    // End immediately\n    TraceSubResult result;\n    result.terminated = true;\n    result.endPoint = SurfacePoint(face, startPoint);\n    result.incomingVecToPoint = vecCartesian;\n    return result;\n  }\n\n  // Compute some useful info about the endpoint\n  Vector3 endPointOnEdge = startPoint + tRay * vecBary;\n  double tCross = endPointOnEdge[(iOppVertEnd + 2) % 3] /\n                  (endPointOnEdge[(iOppVertEnd + 1) % 3] + endPointOnEdge[(iOppVertEnd + 2) % 3]);\n  if (TRACE_PRINT) {\n    cout << \"    end point on edge: \" << endPointOnEdge << endl;\n    cout << \"    tCross raw: \" << tCross << endl;\n  }\n  tCross = clamp(tCross, 0., 1.);\n\n  // Rotate the vector in to the frame of crossHe and shorten it\n  Vector2 vecCartesianRemaining = (1.0 - tRay) * vecCartesian;\n  Vector2 crossingEdgeVec = (vertexCoords[(iOppVertEnd + 2) % 3] - vertexCoords[(iOppVertEnd + 1) % 3]);\n  Vector2 remainingVecInHalfedge = vecCartesianRemaining / crossingEdgeVec.normalize();\n  if (!isfinite(remainingVecInHalfedge)) {\n    if (TRACE_PRINT) {\n      cout << \"    NON FINITE REMAINING TRACE\" << endl;\n      cout << \"    vecCartesianRemaining = \" << vecCartesianRemaining << endl;\n      cout << \"    crossingEdgeVec = \" << crossingEdgeVec << endl;\n      cout << \"    remainingVecInHalfedge = \" << remainingVecInHalfedge << endl;\n    }\n\n    if (errorOnProblem) {\n      throw std::runtime_error(\"bad value transforming to new edge. is there a zero-length edge?\");\n    }\n  }\n\n\n  // Stop tracing if we hit a boundary\n  if (!crossHe.twin().isInterior()) {\n    // Build the result\n    TraceSubResult result;\n    result.terminated = true;\n    result.endPoint = SurfacePoint(crossHe.edge(), convertTToEdge(crossHe, tCross));\n    result.incomingVecToPoint = remainingVecInHalfedge;\n\n    return result;\n  }\n\n  // Build the result\n  TraceSubResult result;\n  result.terminated = false;\n  result.crossHe = crossHe;\n  result.tCross = tCross;\n  result.traceVectorInHalfedge = remainingVecInHalfedge;\n  return result;\n}\n\n// Trace within a face towards a given edge. The trace is assumed to start at the vertex opposite towardsHe.\n//   - towardsHe: the halfedge we are tracing towards (opposite the source vertex)\n//   - vecCartesian: vector to trace, in the cartesian basis of the face\ninline TraceSubResult traceInFaceTowardsEdge(IntrinsicGeometryInterface& geom, Halfedge towardsHe, Vector2 vecCartesian,\n                                             bool errorOnProblem) {\n\n  // Gather some values\n  Face face = towardsHe.face();\n  Halfedge rootHe = towardsHe.next().next();\n  std::array<Vector2, 3> vertexCoords = vertexCoordinatesInTriangle(geom, face);\n\n  if (TRACE_PRINT) {\n    cout << \"  face trace towards edge \" << towardsHe << \" vec = \" << vecCartesian << endl;\n    cout << \"  wedge vec right = \" << geom.halfedgeVectorsInFace[towardsHe.next().next()] << endl;\n    cout << \"  wedge vec left  = \" << -geom.halfedgeVectorsInFace[towardsHe.next()] << endl;\n    cout << \"  wedge vec opp = \" << geom.halfedgeVectorsInFace[towardsHe] << endl;\n  }\n\n  // TODO do some reasonable angular projection on the cartesian vector\n\n  // Convert to barycentric\n  Vector3 vecBaryCanonical = cartesianVectorToBarycentric(vertexCoords, vecCartesian);\n  Vector3 vecBaryFromRoot = permuteBarycentricFromCanonical(vecBaryCanonical, towardsHe.next().next());\n\n  if (TRACE_PRINT) {\n    cout << \"  canonical bary vec\" << vecBaryCanonical << endl;\n    cout << \"  bary vec before projection \" << vecBaryFromRoot << endl;\n  }\n\n  { // Project to ensure the vector is inside the triangle\n    vecBaryFromRoot.x = std::fmin(vecBaryFromRoot.x, TRACE_EPS_TIGHT);\n    vecBaryFromRoot.y = std::fmax(vecBaryFromRoot.y, 0.);\n    vecBaryFromRoot.z = std::fmax(vecBaryFromRoot.z, 0.);\n\n    // Manual displacement projection to sum to 0 while perserving above properties\n    double diff = -sum(vecBaryFromRoot);\n    if (diff > 0) {\n      vecBaryFromRoot.y += diff / 2;\n      vecBaryFromRoot.z += diff / 2;\n    } else {\n      vecBaryFromRoot.x += diff;\n    }\n  }\n\n  if (TRACE_PRINT) {\n    cout << \"  bary vec after projection \" << vecBaryFromRoot << endl;\n  }\n\n  // Assemble data to call the general trace function\n  int iHe = halfedgeIndexInTriangle(towardsHe.next().next());\n  Vector3 startPoint{0., 0., 0.};\n  startPoint[iHe] = 1.0;\n  Vector3 vecBaryCanonicalFixed = permuteBarycentricToCanonical(vecBaryFromRoot, rootHe);\n  std::array<bool, 3> hittable = {{false, false, false}};\n  hittable[(iHe + 1) % 3] = true;\n\n  return traceInFaceBarycentric(geom, face, startPoint, vecBaryCanonicalFixed, vecCartesian, hittable, errorOnProblem);\n}\n\n\n// Trace within a face away from a given edge. The trace must hit one of the two opposite edges\n//   - fromHe: the halfedge we enter from along the face\n//   - tCrossFrom: t value in [0, 1] along fromHe we we enter the face\n//   - traceVecInHalfedge: vector to trace, in the basis of fromHe\ninline TraceSubResult traceInFaceFromEdge(IntrinsicGeometryInterface& geom, Halfedge fromHe, double tCrossFrom,\n                                          Vector2 traceVecInHalfedge, bool errorOnProblem) {\n\n  // Gather some values\n  Halfedge faceHe = fromHe.twin(); // the halfedge in hte face we're heading in to\n  Face face = faceHe.face();\n  std::array<Vector2, 3> vertexCoords = vertexCoordinatesInTriangle(geom, face);\n\n  if (TRACE_PRINT) cout << \"  face trace from edge \" << fromHe << \" vec = \" << traceVecInHalfedge << endl;\n\n\n  // Project the cartesian vector to definitely point in the right direction\n  Vector2 traceVecInFaceHalfedge = -traceVecInHalfedge;\n  if (TRACE_PRINT) cout << \"    vec in face before project \" << traceVecInFaceHalfedge << endl;\n  traceVecInFaceHalfedge.y = std::fmax(traceVecInFaceHalfedge.y, TRACE_EPS_LOOSE);\n  if (TRACE_PRINT) cout << \"    vec in face after project \" << traceVecInFaceHalfedge << endl;\n\n  // Convert to face coordinates\n  Vector2 heDir = geom.halfedgeVectorsInFace[faceHe].normalize();\n  Vector2 traceVecInFace = heDir * traceVecInFaceHalfedge;\n  if (TRACE_PRINT) cout << \"    traceVec in face \" << traceVecInFace << endl;\n\n  // Convert to barycentric\n  Vector3 vecBaryCanonical = cartesianVectorToBarycentric(vertexCoords, traceVecInFace);\n  if (TRACE_PRINT) cout << \"    vecBaryCanonical \" << vecBaryCanonical << endl;\n  Vector3 vecBaryFromEdge = permuteBarycentricFromCanonical(vecBaryCanonical, faceHe);\n\n  if (TRACE_PRINT) cout << \"    vec bary before project \" << vecBaryFromEdge << endl;\n  { // Project to ensure the vector is in the right direction\n    vecBaryFromEdge.z = std::fmax(vecBaryFromEdge.z, TRACE_EPS_TIGHT);\n\n    // Manual displacement projection to sum to 0 which perserves above properties\n    double diff = -sum(vecBaryFromEdge);\n    if (diff > 0) {\n      vecBaryFromEdge.z += diff;\n    } else {\n      vecBaryFromEdge.x += diff / 3.;\n      vecBaryFromEdge.y += diff / 3.;\n      vecBaryFromEdge.z += diff / 3.;\n    }\n  }\n  if (TRACE_PRINT) cout << \"    vec bary after project \" << vecBaryFromEdge << endl;\n\n  // Project ensure tCrossFrom is valid\n  tCrossFrom = clamp(tCrossFrom, 0., 1.);\n\n\n  // Assemble data to call the general trace function\n  int iHe = halfedgeIndexInTriangle(faceHe);\n  Vector3 startPoint{0., 0., 0.};\n  startPoint[iHe] = tCrossFrom; // notice: switched from what you'd expect becasue tCrossFrom is defined on twin\n  startPoint[(iHe + 1) % 3] = 1.0 - tCrossFrom;\n  Vector3 vecBaryCanonicalFixed = permuteBarycentricToCanonical(vecBaryFromEdge, faceHe);\n  if (TRACE_PRINT) {\n    cout << \"    iHe = \" << iHe << endl;\n    cout << \"    startPoint = \" << startPoint << endl;\n    cout << \"    canonical bary \" << vecBaryCanonicalFixed << endl;\n  }\n  std::array<bool, 3> hittable = {{true, true, true}};\n  hittable[iHe] = false;\n\n  return traceInFaceBarycentric(geom, face, startPoint, vecBaryCanonicalFixed, traceVecInFace, hittable,\n                                errorOnProblem);\n}\n\n\n// Trace starting from an edge\ninline TraceSubResult traceGeodesic_fromEdge(IntrinsicGeometryInterface& geom, Edge currEdge, double tEdge,\n                                             Vector2 currVec, bool errorOnProblem) {\n\n  if (TRACE_PRINT) cout << \"  edge trace \" << currEdge << \" tEdge = \" << tEdge << \" edge vec = \" << currVec << endl;\n\n  // Project to ensure tEdge is valid\n  tEdge = clamp(tEdge, 0., 1.);\n\n  // Find coordinates in adjacent face\n\n  // Check which side of the face we're exiting\n  Halfedge traceHe;\n  Vector2 halfedgeTraceVec;\n  if (currVec.y >= 0.) {\n    traceHe = currEdge.halfedge().twin();\n    halfedgeTraceVec = -currVec;\n    tEdge = 1.0 - tEdge;\n  } else {\n    traceHe = currEdge.halfedge();\n\n    // Can't go anyywhere if boundary halfedge\n    if (!traceHe.isInterior()) {\n      TraceSubResult result;\n      result.terminated = true;\n      result.endPoint = SurfacePoint(currEdge, tEdge);\n      result.incomingVecToPoint = currVec;\n\n      return result;\n    }\n\n    halfedgeTraceVec = currVec;\n  }\n\n  return traceInFaceFromEdge(geom, traceHe, tEdge, halfedgeTraceVec, errorOnProblem);\n}\n\n// Trace starting from a face\ninline TraceSubResult traceGeodesic_fromFace(IntrinsicGeometryInterface& geom, Face currFace, Vector3 faceBary,\n                                             Vector2 currVec, bool errorOnProblem) {\n\n  // Convert the vector to barycentric\n  std::array<Vector2, 3> vertexCoords = vertexCoordinatesInTriangle(geom, currFace);\n  Vector3 vecBary = cartesianVectorToBarycentric(vertexCoords, currVec);\n\n  return traceInFaceBarycentric(geom, currFace, faceBary, vecBary, currVec, {true, true, true}, errorOnProblem);\n}\n\n\n// Trace starting from a vertex (with a rescaled cartesian vector)\ninline TraceSubResult traceGeodesic_fromVertex(IntrinsicGeometryInterface& geom, Vertex currVert, Vector2 currVec,\n                                               bool errorOnProblem) {\n  if (TRACE_PRINT) cout << \"  vertex trace \" << currVert << \" edge vec = \" << currVec << endl;\n\n  double traceLen = currVec.norm();\n\n  // Find the halfedge opening the wedge where tracing will start\n  Halfedge wedgeHe;\n  Vector2 traceVecRelativeToStart;\n\n  // Normally, one of the interval tests below will return positive and we'll simply launch the trace in to that\n  // interval. However, due to numerical misfortune, it is possible that none of the intervals will test positive. In\n  // that case, we'll simply launch along whichever halfedge was closest.\n  double minCross = std::numeric_limits<double>::infinity();\n  Halfedge minCrossHalfedge;\n  Vector2 minCrossHalfedgeVec; // the trace vector in this closest halfedge\n\n  Halfedge currHe = currVert.halfedge();\n  do {\n\n    // Once we hit the boundary we're done\n    // (and traversal below doesn't work on boundary loop, so need to exit specially)\n    if (!currHe.isInterior()) {\n      break;\n    }\n\n    Halfedge nextHe = currHe.next().next().twin();\n\n    // The interval spanned by this edge, which we are currently testing\n    Vector2 intervalStart = geom.halfedgeVectorsInVertex[currHe].normalize();\n    Vector2 intervalEnd = geom.halfedgeVectorsInVertex[nextHe].normalize();\n\n    if (TRACE_PRINT) {\n      cout << \"  testing wedge \" << intervalStart << \" -- \" << intervalEnd << endl;\n      cout << \"    testing wedge (un norm) \" << geom.halfedgeVectorsInVertex[currHe] << \" -- \"\n           << geom.halfedgeVectorsInVertex[nextHe] << endl;\n      cout << \"    corner angle \" << geom.cornerAngles[currHe.corner()] << endl;\n      cout << \"    corner \" << currHe.corner() << endl;\n      Vector2 relAngle = intervalEnd / intervalStart;\n      cout << \"    wedge width \" << relAngle << \" radians: \" << relAngle.arg() << endl;\n    }\n\n\n    // Check if our trace vector lies within the interval\n    double crossStart = cross(intervalStart, currVec);\n    double crossEnd = cross(intervalEnd, currVec);\n    if (crossStart > 0. && crossEnd <= 0.) {\n      wedgeHe = currHe;\n      traceVecRelativeToStart = currVec / intervalStart;\n      if (TRACE_PRINT) cout << \"    wedge match! relative angle \" << traceVecRelativeToStart << endl;\n      if (TRACE_PRINT) cout << \"    cross start = \" << crossStart << \" cross end = \" << crossEnd << endl;\n      break;\n    }\n\n    // Keep track of the closest halfedge, as described above\n    if (std::fabs(crossStart) < minCross) {\n      minCross = std::fabs(crossStart);\n      minCrossHalfedge = currHe;\n      minCrossHalfedgeVec = Vector2{1, TRACE_EPS_TIGHT} * traceLen;\n    }\n    if (std::fabs(crossEnd) < minCross) {\n      minCross = std::fabs(crossEnd);\n      minCrossHalfedge = nextHe;\n      minCrossHalfedgeVec = Vector2{1, -TRACE_EPS_TIGHT} * traceLen;\n    }\n\n    currHe = nextHe;\n  } while (currHe != currVert.halfedge());\n\n  // None of the interval tests passed (probably due to unfortunate numerics), so just trace along the closest\n  // halfedge\n  if (wedgeHe == Halfedge()) {\n    if (TRACE_PRINT) cout << \"  no wedge worked. following closest edge with dir \" << minCrossHalfedgeVec << endl;\n    // Convert to edge coordinates\n    currVec = convertVecToEdge(minCrossHalfedge, minCrossHalfedgeVec);\n    return traceGeodesic_fromEdge(geom, minCrossHalfedge.edge(), convertTToEdge(minCrossHalfedge, 0.), currVec,\n                                  errorOnProblem);\n  }\n\n  // Compute the actual starting face point, slightly inside and adjacent face\n  Face startFace = wedgeHe.face();\n  int iHe = halfedgeIndexInTriangle(wedgeHe);\n\n  // Need to convert from \"powered\" representation to flat vector in face\n  double sum = currVert.isBoundary() ? M_PI : 2. * M_PI;\n  traceVecRelativeToStart = traceVecRelativeToStart.pow(geom.vertexAngleSums[currVert] / sum);\n  traceVecRelativeToStart = traceVecRelativeToStart.normalize() * currVec.norm(); // fix length\n\n  // Compute the starting vector\n  Vector2 startDirInFace = geom.halfedgeVectorsInFace[wedgeHe].normalize();\n  Vector2 traceVecInFace = traceVecRelativeToStart * startDirInFace;\n  if (TRACE_PRINT) {\n    cout << \"  starting vector\" << endl;\n    cout << \"    start wedge vec \" << geom.halfedgeVectorsInFace[wedgeHe] << endl;\n    cout << \"    start wedge vec unit \" << geom.halfedgeVectorsInFace[wedgeHe].normalize() << endl;\n    cout << \"    trace vec in face \" << traceVecInFace << endl;\n  }\n\n\n  return traceInFaceTowardsEdge(geom, wedgeHe.next(), traceVecInFace, errorOnProblem);\n}\n\n\n// Run tracing iteratively in faces, after on of the variants below has gotten it started.\n// Will internally add the point path point encoded by prevTraceEnd, don't add beforehand.\nvoid traceGeodesic_iterative(IntrinsicGeometryInterface& geom, TraceGeodesicResult& result, TraceSubResult prevTraceEnd,\n                             bool includePath, bool errorOnProblem) {\n\n  // Now, points are always in faces. Trace until termination.\n  while (!prevTraceEnd.terminated) {\n\n    // Construct a point where the previous trace ended\n    if (includePath) {\n      SurfacePoint currPoint(prevTraceEnd.crossHe.edge(), convertTToEdge(prevTraceEnd.crossHe, prevTraceEnd.tCross));\n      result.pathPoints.push_back(currPoint);\n    }\n\n    if (TRACE_PRINT) {\n      cout << \"> tracing from \" << prevTraceEnd.crossHe << \" t = \" << prevTraceEnd.tCross\n           << \" vec = \" << prevTraceEnd.traceVectorInHalfedge << endl;\n    }\n\n    // Execute the next step of tracing\n    prevTraceEnd = traceInFaceFromEdge(geom, prevTraceEnd.crossHe, prevTraceEnd.tCross,\n                                       prevTraceEnd.traceVectorInHalfedge, errorOnProblem);\n  }\n\n  // Add the final ending point\n  if (includePath) {\n    result.pathPoints.push_back(prevTraceEnd.endPoint);\n  }\n  result.endPoint = prevTraceEnd.endPoint;\n  result.endingDir = prevTraceEnd.incomingVecToPoint.normalize();\n\n  if (prevTraceEnd.endPoint.type == SurfacePointType::Edge) {\n    result.hitBoundary = true;\n  }\n}\n\n\n} // namespace\n\nTraceGeodesicResult traceGeodesic(IntrinsicGeometryInterface& geom, SurfacePoint startP, Vector2 traceVec,\n                                  bool includePath, bool errorOnProblem) {\n  geom.requireVertexAngleSums();\n  geom.requireHalfedgeVectorsInVertex();\n  geom.requireHalfedgeVectorsInFace();\n\n  // The output data\n  TraceGeodesicResult result;\n  result.hasPath = includePath;\n  if (includePath) {\n    result.pathPoints.push_back(startP);\n  }\n\n  if (TRACE_PRINT) cout << \"\\n>>> Trace query from \" << startP << \" vec = \" << traceVec << endl;\n\n  // Quick out with a zero vector\n  if (traceVec.norm2() == 0) {\n    geom.unrequireVertexAngleSums();\n    geom.unrequireHalfedgeVectorsInVertex();\n    geom.unrequireHalfedgeVectorsInFace();\n\n    result.endingDir = Vector2::zero();\n\n    // probably want to ensure we still return a point in a face...\n    if (errorOnProblem) {\n      throw std::runtime_error(\"zero vec passed to trace, do something good here\");\n    }\n\n    return result;\n  }\n\n\n  // Trace the first point, based on what kind of input we got\n  TraceSubResult prevTraceEnd;\n  switch (startP.type) {\n  case SurfacePointType::Vertex: {\n    prevTraceEnd = traceGeodesic_fromVertex(geom, startP.vertex, traceVec, errorOnProblem);\n    break;\n  }\n  case SurfacePointType::Edge: {\n    prevTraceEnd = traceGeodesic_fromEdge(geom, startP.edge, startP.tEdge, traceVec, errorOnProblem);\n    break;\n  }\n  case SurfacePointType::Face: {\n    prevTraceEnd = traceGeodesic_fromFace(geom, startP.face, startP.faceCoords, traceVec, errorOnProblem);\n    break;\n  }\n  }\n\n  // Keep tracing through triangles until finished\n  traceGeodesic_iterative(geom, result, prevTraceEnd, includePath, errorOnProblem);\n\n  geom.unrequireVertexAngleSums();\n  geom.unrequireHalfedgeVectorsInVertex();\n  geom.unrequireHalfedgeVectorsInFace();\n\n  return result;\n}\n\n\nTraceGeodesicResult traceGeodesic(IntrinsicGeometryInterface& geom, Face startFace, Vector3 startBary,\n                                  Vector3 traceBaryVec, bool includePath, bool errorOnProblem) {\n\n\n  geom.requireVertexAngleSums();\n  geom.requireHalfedgeVectorsInVertex();\n  geom.requireHalfedgeVectorsInFace();\n\n  // The output data\n  TraceGeodesicResult result;\n  result.hasPath = includePath;\n  if (includePath) {\n    result.pathPoints.push_back(SurfacePoint(startFace, startBary));\n  }\n\n  if (TRACE_PRINT) {\n    cout << \"\\n>>> Trace query (barycentric) from \" << startFace << \" \" << startBary << \" vec = \" << traceBaryVec\n         << endl;\n  }\n\n  // Early-out if zero\n  if (traceBaryVec.norm2() == 0) {\n    geom.unrequireVertexAngleSums();\n    geom.unrequireHalfedgeVectorsInVertex();\n    geom.unrequireHalfedgeVectorsInFace();\n\n    // probably want to ensure we still return a point in a face...\n    if (errorOnProblem) {\n      throw std::runtime_error(\"zero vec passed to trace, do something good here\");\n    }\n\n    result.endingDir = Vector2::zero();\n    return result;\n  }\n\n  // Make sure the input is sane\n  startBary = projectInsideTriangle(startBary);\n  traceBaryVec -= Vector3::constant(sum(traceBaryVec) / 3);\n\n  // Construct the cartesian equivalent\n  std::array<Vector2, 3> vertexCoords = vertexCoordinatesInTriangle(geom, startFace);\n  Vector2 traceVectorCartesian = barycentricDisplacementToCartesian(vertexCoords, traceBaryVec);\n\n  // Trace the first point starting inside the face\n  TraceSubResult prevTraceEnd = traceInFaceBarycentric(geom, startFace, startBary, traceBaryVec, traceVectorCartesian,\n                                                       {true, true, true}, errorOnProblem);\n\n  // Keep tracing through triangles until finished\n  traceGeodesic_iterative(geom, result, prevTraceEnd, includePath, errorOnProblem);\n\n  geom.unrequireVertexAngleSums();\n  geom.unrequireHalfedgeVectorsInVertex();\n  geom.unrequireHalfedgeVectorsInFace();\n\n  return result;\n}\n\n} // namespace surface\n} // namespace geometrycentral\n", "meta": {"hexsha": "c362a1a5edb90b6fb0dbac1637c097a513423289", "size": 28047, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/surface/trace_geodesic.cpp", "max_stars_repo_name": "yousufmsoliman/geometry-central", "max_stars_repo_head_hexsha": "467d8a57c8d48315cd2b03eb27fb044c611e547c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-07-05T00:50:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-17T08:20:20.000Z", "max_issues_repo_path": "src/surface/trace_geodesic.cpp", "max_issues_repo_name": "yousufmsoliman/geometry-central", "max_issues_repo_head_hexsha": "467d8a57c8d48315cd2b03eb27fb044c611e547c", "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/surface/trace_geodesic.cpp", "max_forks_repo_name": "yousufmsoliman/geometry-central", "max_forks_repo_head_hexsha": "467d8a57c8d48315cd2b03eb27fb044c611e547c", "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.5790921596, "max_line_length": 120, "alphanum_fraction": 0.6807501694, "num_tokens": 7494, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511506439707, "lm_q2_score": 0.849971181358171, "lm_q1q2_score": 0.7274488135796057}}
{"text": "#include <QatGenericFunctions/Variable.h>\n#include <QatGenericFunctions/Parameter.h>\n#include <QatGenericFunctions/Square.h>\n#include <QatGenericFunctions/Sqrt.h>\n#include <QatGenericFunctions/Exp.h>\n#include <QatGenericFunctions/VoigtDistribution.h>\n#include <QatDataAnalysis/Hist1D.h>\n#include <QatDataAnalysis/Table.h>\n#include <QatDataModeling/TableLikelihoodFunctional.h>\n#include <QatDataModeling/MinuitMinimizer.h>\n#include <QatPlotWidgets/PlotView.h>\n#include <QatPlotWidgets/MultipleViewWindow.h>\n#include <QatPlotting/PlotStream.h>\n#include <QatPlotting/PlotHist1D.h>\n#include <QatPlotting/PlotFunction1D.h>\n#include <QatPlotting/PlotProfile.h>\n#include <QatPlotting/PlotKey.h>\n#include <Eigen/Dense>\n#include <QApplication>\n#include <QMainWindow>\n#include <QAction>\n#include <QToolBar>\n#include <QFont>\n#include <cmath>\n#include <iostream>\n#include <string>\n#include <vector>\n#include <fstream>\n#include <algorithm>\n#include <random>\n\nPlotView *createPlotView(const std::string& title, const std::string& xLabel, const std::string yLabel, const PRectF& viewRange);\n\ntypedef std::vector<double> Data;\n\nData readData(const std::string& file);\nData refineData(const Data& rawData, const double lowerBound, const double upperBound);\nHist1D binData(const Data& data);\nTable tableData(const Data& data);\n\nconst std::string dataFileName = \"data04.dat\";\nconst bool verbose = true;\nconst double dataLowerBound = 0;\nconst double dataUpperBound = 200;\nconst double nBin = 1000;\nconst double histogramMin = 0;\nconst double histogramMax = 200;\nconst double M_PI4 = M_PI * M_PI * M_PI * M_PI;\n\nint main(int argc, char **argv)\n{\n    QApplication app(argc, argv);\n    QMainWindow window;\n\n    Genfun::Square qPow2;\n    Genfun::Sqrt qSqrt;\n    Genfun::Exp qExp;\n\n    const Data rawData = readData(dataFileName);\n    const Data data = refineData(rawData, dataLowerBound, dataUpperBound);\n    Hist1D dataHist = binData(data);\n    Table dataTable = tableData(data);\n    TableLikelihoodFunctional objFunc(dataTable);\n    Genfun::Variable X = dataTable.symbol(\"E\");\n\n//  Prepare View\n    const double viewXMin = histogramMin;\n    const double viewXMax = histogramMax;\n    const double viewYMin = 1e-2;\n    const double viewYMax = dataHist.maxContents() * 3;\n    PRectF viewRange(viewXMin, viewXMax, viewYMin, viewYMax);\n    PlotView *view = createPlotView(\"Spectrum\", \"Energy / eV\", \"\", viewRange);\n    view->setLogY(true);\n    window.setCentralWidget(view);\n\n    PlotKey legend(viewXMin, viewYMax);\n    legend.setFont(QFont(\"Times\", 25, QFont::Bold));\n    view->add(&legend);\n\n// Plot Data\n    PlotHist1D dataHistPlot(dataHist);\n    {\n        PlotHist1D::Properties prop;\n        prop.plotStyle = PlotHist1D::Properties::SYMBOLS;\n        prop.symbolSize = 10;\n        prop.pen.setWidth(1.9);\n        dataHistPlot.setProperties(prop);\n    }\n    view->add(&dataHistPlot);\n    legend.add(&dataHistPlot, \"Data\");\n\n// Voigt Fit\n    Genfun::Parameter T(\"T\", dataHist.mean()/3, dataHist.mean()/10, dataHist.mean());\n    Genfun::Parameter Mu1(\"Mu1\", 97, 92, 103);\n    Genfun::Parameter Delta1(\"Delta1\", 0.3, 0.01, 1);\n    Genfun::Parameter Mu2(\"Mu2\", 105, 100, 110);\n    Genfun::Parameter Delta2(\"Delta2\", 0.35, 0.01, 1);\n    Genfun::Parameter Sigma(\"Sigma\", 1, 0, 5);\n    Genfun::Parameter fP(\"fPlank\", 0.8, 0, 1);\n    Genfun::Parameter fL1(\"fLine1\", 0.6, 0, 1);\n\n    Genfun::GENFUNCTION PlankPDF = (15/M_PI4)/(T*T*T*T) * (X*X*X) / (qExp(X/T) - 1);\n\n    Genfun::VoigtDistribution VoigtPDF1;\n    VoigtPDF1.delta().connectFrom(&Delta1);\n    VoigtPDF1.sigma().connectFrom(&Sigma);\n    \n    Genfun::VoigtDistribution VoigtPDF2;\n    VoigtPDF2.delta().connectFrom(&Delta2);\n    VoigtPDF2.sigma().connectFrom(&Sigma);\n\n    Genfun::GENFUNCTION Combo = dataHist.sum() * dataHist.binWidth() * \n            (fP * PlankPDF + (1-fP)*fL1*VoigtPDF1(X-Mu1) + (1-fP)*(1-fL1)*VoigtPDF2(X-Mu2));\n\n    MinuitMinimizer comboMinimizer(verbose);\n    comboMinimizer.addParameter(&T);\n    comboMinimizer.addParameter(&Mu1);\n    comboMinimizer.addParameter(&Delta1);\n    comboMinimizer.addParameter(&Mu2);\n    comboMinimizer.addParameter(&Delta2);\n    comboMinimizer.addParameter(&Sigma);\n    comboMinimizer.addParameter(&fP);\n    comboMinimizer.addParameter(&fL1);\n    comboMinimizer.addStatistic(&objFunc, &Combo);\n    comboMinimizer.minimize();\n\n\n    PlotFunction1D comboPlot(Combo);\n    {\n        PlotFunction1D::Properties prop;\n        prop.pen.setColor(Qt::red);\n        prop.pen.setWidth(2);\n        comboPlot.setProperties(prop);\n    }\n    view->add(&comboPlot);\n    legend.add(&comboPlot, \"Fit\");\n\n\n\n\tQToolBar *toolBar = window.addToolBar(\"Tools\");\n\t\n    QAction *quitAction = toolBar->addAction(\"Quit (q)\");\n    quitAction->setShortcut(QKeySequence(\"q\"));\n\tQObject::connect(quitAction, SIGNAL(triggered()), &app, SLOT(quit()));\n    \n    QAction *saveAction = toolBar->addAction(\"Save as (s)\");\n    saveAction->setShortcut(QKeySequence(\"s\"));\n    QObject::connect(saveAction, SIGNAL(triggered()), view, SLOT(save()));\n\n\twindow.show();\n\tapp.exec();\n\n    return 0;\n}\n\n\n//////////////////////////////////////////////////////////////////////////////\n\nData readData(const std::string& file)\n{\n    std::ifstream dataFile(file);\n    double dataIn;\n    Data data;\n\n    while (dataFile >> dataIn)\n    {\n        if (true)\n        {\n            data.push_back(dataIn);\n        }\n    }\n    \n    std::pair<Data::const_iterator,Data::const_iterator> MIN_MAX = std::minmax_element(data.begin(), data.end());\n\n    std::cout << \"Raw Data Min: \" << *(MIN_MAX.first) << std::endl;\n    std::cout << \"Raw Data Max: \" << *(MIN_MAX.second) << std::endl;\n    std::cout << std::endl;\n\n    return data;\n}\n\nData refineData(const Data& rawData, const double lowerBound, const double upperBound)\n{\n    std::cout << \"Data Selection Range: [\" << lowerBound << \", \" << upperBound << \"]\" << std::endl << std::endl;\n\n    Data data;\n    for (size_t i = 0; i < rawData.size(); i++)\n    {\n        if (lowerBound <= rawData[i] && rawData[i] <= upperBound)\n        {\n            data.push_back(rawData[i]);\n        }\n    }\n    \n    return data;\n}\n\nHist1D binData(const Data& data)\n{\n    std::pair<Data::const_iterator,Data::const_iterator> MIN_MAX_Iter = std::minmax_element(data.begin(), data.end());\n    double dataMin = *(MIN_MAX_Iter.first);\n    double dataMax = *(MIN_MAX_Iter.second);\n\n    std::cout << \"Data Num: \" << data.size() << std::endl;\n    std::cout << \"Data Min: \" << dataMin << std::endl;\n    std::cout << \"Data Max: \" << dataMax << std::endl;\n    \n    //Hist1D dataHist(nBin, binMin, binMax);\n    Hist1D dataHist(nBin, std::floor(dataMin-1), std::ceil(dataMax+1));\n    for (size_t i = 0; i < data.size(); i++)\n    {\n        dataHist.accumulate(data[i]);\n    }\n    \n    std::cout << \"Data Mean: \" << dataHist.mean() << std::endl;\n    std::cout << \"Data Variance: \" << dataHist.variance() << std::endl;\n    std::cout << \"Data Sigma: \" << std::sqrt(dataHist.variance()) << std::endl;\n    std::cout << std::endl;\n\n    return dataHist;\n}\n\nTable tableData(const Data& data)\n{\n    Table dataTable(\"Data Table\");\n\n    for (size_t i = 0; i < data.size(); i++)\n    {\n        dataTable.add(\"E\", data[i]);\n        dataTable.capture();\n    }\n    \n    return dataTable;\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n\nPlotView *createPlotView(const std::string& title, const std::string& xLabel, const std::string yLabel, const PRectF& viewRange)\n{\n    PlotView *view_ptr = new PlotView(viewRange);\n    view_ptr->setFixedWidth(1200);\n    view_ptr->setFixedHeight(800);\n\n    PlotStream titleStream(view_ptr->titleTextEdit());\n    titleStream << PlotStream::Clear()\n                << PlotStream::Center()\n                << PlotStream::Family(\"Sans Serif\")\n                << PlotStream::Size(24)\n                << title\n                << PlotStream::EndP();\n\n    PlotStream xLabelStream(view_ptr->xLabelTextEdit());\n    xLabelStream << PlotStream::Clear()\n                << PlotStream::Center()\n                << PlotStream::Family(\"Sans Serif\")\n                << PlotStream::Size(24)\n                << xLabel\n                << PlotStream::EndP();\n\n    PlotStream yLabelStream(view_ptr->yLabelTextEdit());\n    yLabelStream << PlotStream::Clear()\n                << PlotStream::Center()\n                << PlotStream::Family(\"Sans Serif\")\n                << PlotStream::Size(24)\n                << yLabel\n                << PlotStream::EndP();\n    \n    return view_ptr;\n}", "meta": {"hexsha": "f068021629c8c36db8f975ba38193d9cc28f5494", "size": 8447, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Assignments/Assignments_12/EX3/e/main.cpp", "max_stars_repo_name": "CaoSY/PittCompMethods", "max_stars_repo_head_hexsha": "853c36676df140eecd249bd9905eb9fa704f1585", "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": "Assignments/Assignments_12/EX3/e/main.cpp", "max_issues_repo_name": "CaoSY/PittCompMethods", "max_issues_repo_head_hexsha": "853c36676df140eecd249bd9905eb9fa704f1585", "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": "Assignments/Assignments_12/EX3/e/main.cpp", "max_forks_repo_name": "CaoSY/PittCompMethods", "max_forks_repo_head_hexsha": "853c36676df140eecd249bd9905eb9fa704f1585", "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.2851851852, "max_line_length": 129, "alphanum_fraction": 0.6338344975, "num_tokens": 2272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403959948495, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.727438129080064}}
{"text": "\n#include \"EigenUtil.h\"\n#include <boost/format.hpp>\n\nusing namespace boost;\n\nnamespace cnoid {\n\nMatrix3 rotFromRpy(double r, double p, double y)\n{\n    const double cr = cos(r);\n    const double sr = sin(r);\n    const double cp = cos(p);\n    const double sp = sin(p);\n    const double cy = cos(y);\n    const double sy = sin(y);\n\n    Matrix3 R;\n    R << cp*cy, sr*sp*cy - cr*sy, cr*sp*cy + sr*sy,\n        cp*sy, sr*sp*sy + cr*cy, cr*sp*sy - sr*cy,\n        -sp  , sr*cp           , cr*cp;\n\n    return R;\n}\n\n\nVector3 rpyFromRot(const Matrix3& R)\n{\n    double roll, pitch, yaw;\n    \n    if((fabs(R(0,0)) < fabs(R(2,0))) && (fabs(R(1,0)) < fabs(R(2,0)))) {\n        // cos(p) is nearly = 0\n        double sp = -R(2,0);\n        if (sp < -1.0) {\n            sp = -1.0;\n        } else if (sp > 1.0) {\n            sp = 1.0;\n        }\n        pitch = asin(sp); // -pi/2< p < pi/2\n            \n        roll = atan2(sp * R(0,1) + R(1,2),  // -cp*cp*sr*cy\n                     sp * R(0,2) - R(1,1)); // -cp*cp*cr*cy\n            \n        if (R(0,0) > 0.0) { // cy > 0\n            (roll < 0.0) ? (roll += PI) : (roll -= PI);\n        }\n        const double sr = sin(roll);\n        const double cr = cos(roll);\n        if(sp > 0.0){\n            yaw = atan2(sr * R(1,1) + cr * R(1,2), //sy*sp\n                        sr * R(0,1) + cr * R(0,2));//cy*sp\n        } else {\n            yaw = atan2(-sr * R(1,1) - cr * R(1,2),\n                        -sr * R(0,1) - cr * R(0,2));\n        }\n    } else {\n        yaw = atan2(R(1,0), R(0,0));\n        const double sa = sin(yaw);\n        const double ca = cos(yaw);\n        pitch = atan2(-R(2,0), ca * R(0,0) + sa * R(1,0));\n        roll = atan2(sa * R(0,2) - ca * R(1,2), -sa * R(0,1) + ca * R(1,1));\n    }\n    return Vector3(roll, pitch, yaw);\n}\n\n\nVector3 omegaFromRot(const Matrix3& R)\n{\n    double alpha = (R(0,0) + R(1,1) + R(2,2) - 1.0) / 2.0;\n\n    if(fabs(alpha - 1.0) < 1.0e-6) {   //th=0,2PI;\n        return Vector3::Zero();\n\n    } else {\n        double th = acos(alpha);\n        double s = sin(th);\n\n        if (s < std::numeric_limits<double>::epsilon()) {   //th=PI\n            return Vector3( sqrt((R(0,0)+1)*0.5)*th, sqrt((R(1,1)+1)*0.5)*th, sqrt((R(2,2)+1)*0.5)*th );\n        }\n\n        double k = -0.5 * th / s;\n\n        return Vector3((R(1,2) - R(2,1)) * k,\n                       (R(2,0) - R(0,2)) * k,\n                       (R(0,1) - R(1,0)) * k);\n    }\n}\n\nstd::string str(const Vector3& v)\n{\n    return str(format(\"%1%  %2%  %3%\") % v[0] % v[1] % v[2]);\n}\n    \nbool toVector3(const std::string& s, Vector3& out_v)\n{\n    const char* nptr = s.c_str();\n    char* endptr;\n    for(int i=0; i < 3; ++i){\n        out_v[i] = strtod(nptr, &endptr);\n        if(endptr == nptr){\n            return false;\n        }\n        nptr = endptr;\n        while(isspace(*nptr)){\n            nptr++;\n        }\n        if(*nptr == ','){\n            nptr++;\n        }\n    }\n    return true;\n}\n\n\nvoid normalizeRotation(Matrix3& R)\n{\n    Matrix3::ColXpr x = R.col(0);\n    Matrix3::ColXpr y = R.col(1);\n    Matrix3::ColXpr z = R.col(2);\n    x.normalize();\n    z = x.cross(y).normalized();\n    y = z.cross(x);\n}\n\nvoid normalizeRotation(Position& T)\n{\n    typedef Position::LinearPart::ColXpr ColXpr;\n    Position::LinearPart R = T.linear();\n    ColXpr x = R.col(0);\n    ColXpr y = R.col(1);\n    ColXpr z = R.col(2);\n    x.normalize();\n    z = x.cross(y).normalized();\n    y = z.cross(x);\n}\n    \n}\n\n", "meta": {"hexsha": "28d8accfdd1dee580e6ac7edd111274c9731fbcb", "size": 3411, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Util/EigenUtil.cpp", "max_stars_repo_name": "snozawa/choreonoid", "max_stars_repo_head_hexsha": "12ab42ccbf287d68216637e55ddae8412771c752", "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/Util/EigenUtil.cpp", "max_issues_repo_name": "snozawa/choreonoid", "max_issues_repo_head_hexsha": "12ab42ccbf287d68216637e55ddae8412771c752", "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/Util/EigenUtil.cpp", "max_forks_repo_name": "snozawa/choreonoid", "max_forks_repo_head_hexsha": "12ab42ccbf287d68216637e55ddae8412771c752", "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.3642857143, "max_line_length": 104, "alphanum_fraction": 0.4447376136, "num_tokens": 1220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045907347107, "lm_q2_score": 0.8198933271118221, "lm_q1q2_score": 0.7274131237263644}}
{"text": "//  (C) Copyright Nick Thompson 2019.\n//  (C) Copyright Matt Borland 2021.\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#ifndef BOOST_MATH_STATISTICS_T_TEST_HPP\n#define BOOST_MATH_STATISTICS_T_TEST_HPP\n\n#include <cmath>\n#include <cstddef>\n#include <iterator>\n#include <utility>\n#include <type_traits>\n#include <vector>\n#include <stdexcept>\n#include <boost/math/distributions/students_t.hpp>\n#include <boost/math/statistics/univariate_statistics.hpp>\n\nnamespace boost { namespace math { namespace statistics { namespace detail {\n\ntemplate<typename ReturnType, typename T>\nReturnType one_sample_t_test_impl(T sample_mean, T sample_variance, T num_samples, T assumed_mean) \n{\n    using Real = typename std::tuple_element<0, ReturnType>::type;\n    using std::sqrt;\n    typedef boost::math::policies::policy<\n          boost::math::policies::promote_float<false>,\n          boost::math::policies::promote_double<false> >\n          no_promote_policy;\n\n    Real test_statistic = (sample_mean - assumed_mean)/sqrt(sample_variance/num_samples);\n    auto student = boost::math::students_t_distribution<Real, no_promote_policy>(num_samples - 1);\n    Real pvalue;\n    if (test_statistic > 0) {\n        pvalue = 2*boost::math::cdf<Real>(student, -test_statistic);;\n    }\n    else {\n        pvalue = 2*boost::math::cdf<Real>(student, test_statistic);\n    }\n    return std::make_pair(test_statistic, pvalue);\n}\n\ntemplate<typename ReturnType, typename ForwardIterator>\nReturnType one_sample_t_test_impl(ForwardIterator begin, ForwardIterator end, typename std::iterator_traits<ForwardIterator>::value_type assumed_mean) \n{\n    using Real = typename std::tuple_element<0, ReturnType>::type;\n    std::pair<Real, Real> temp = mean_and_sample_variance(begin, end);\n    Real mu = std::get<0>(temp);\n    Real s_sq = std::get<1>(temp);\n    return one_sample_t_test_impl<ReturnType>(mu, s_sq, Real(std::distance(begin, end)), Real(assumed_mean));\n}\n\n// https://en.wikipedia.org/wiki/Student%27s_t-test#Equal_or_unequal_sample_sizes,_unequal_variances_(sX1_%3E_2sX2_or_sX2_%3E_2sX1)\ntemplate<typename ReturnType, typename T>\nReturnType welchs_t_test_impl(T mean_1, T variance_1, T size_1, T mean_2, T variance_2, T size_2)\n{\n    using Real = typename std::tuple_element<0, ReturnType>::type;\n    using no_promote_policy = boost::math::policies::policy<boost::math::policies::promote_float<false>, boost::math::policies::promote_double<false>>;\n    using std::sqrt;\n\n    Real dof_num = (variance_1/size_1 + variance_2/size_2) * (variance_1/size_1 + variance_2/size_2);\n    Real dof_denom = ((variance_1/size_1) * (variance_1/size_1))/(size_1 - 1) +\n                     ((variance_2/size_2) * (variance_2/size_2))/(size_2 - 1);\n    Real dof = dof_num / dof_denom;\n\n    Real s_estimator = sqrt((variance_1/size_1) + (variance_2/size_2));\n\n    Real test_statistic = (static_cast<Real>(mean_1) - static_cast<Real>(mean_2))/s_estimator;\n    auto student = boost::math::students_t_distribution<Real, no_promote_policy>(dof);\n    Real pvalue;\n    if (test_statistic > 0) \n    {\n        pvalue = 2*boost::math::cdf<Real>(student, -test_statistic);;\n    }\n    else \n    {\n        pvalue = 2*boost::math::cdf<Real>(student, test_statistic);\n    }\n\n    return std::make_pair(test_statistic, pvalue);\n}\n\n// https://en.wikipedia.org/wiki/Student%27s_t-test#Equal_or_unequal_sample_sizes,_similar_variances_(1/2_%3C_sX1/sX2_%3C_2)\ntemplate<typename ReturnType, typename T>\nReturnType two_sample_t_test_impl(T mean_1, T variance_1, T size_1, T mean_2, T variance_2, T size_2)\n{\n    using Real = typename std::tuple_element<0, ReturnType>::type;\n    using no_promote_policy = boost::math::policies::policy<boost::math::policies::promote_float<false>, boost::math::policies::promote_double<false>>;\n    using std::sqrt;\n\n    Real dof = size_1 + size_2 - 2;\n    Real pooled_std_dev = sqrt(((size_1-1)*variance_1 + (size_2-1)*variance_2) / dof);\n    Real test_statistic = (mean_1-mean_2) / (pooled_std_dev*sqrt(1.0/static_cast<Real>(size_1) + 1.0/static_cast<Real>(size_2)));\n\n    auto student = boost::math::students_t_distribution<Real, no_promote_policy>(dof);\n    Real pvalue;\n    if (test_statistic > 0) \n    {\n        pvalue = 2*boost::math::cdf<Real>(student, -test_statistic);;\n    }\n    else \n    {\n        pvalue = 2*boost::math::cdf<Real>(student, test_statistic);\n    }\n\n    return std::make_pair(test_statistic, pvalue);\n}\n\ntemplate<typename ReturnType, typename ForwardIterator>\nReturnType two_sample_t_test_impl(ForwardIterator begin_1, ForwardIterator end_1, ForwardIterator begin_2, ForwardIterator end_2)\n{\n    using Real = typename std::tuple_element<0, ReturnType>::type;\n    using std::sqrt;\n    auto n1 = std::distance(begin_1, end_1);\n    auto n2 = std::distance(begin_2, end_2);\n\n    ReturnType temp_1 = mean_and_sample_variance(begin_1, end_1);\n    Real mean_1 = std::get<0>(temp_1);\n    Real variance_1 = std::get<1>(temp_1);\n    Real std_dev_1 = sqrt(variance_1);\n\n    ReturnType temp_2 = mean_and_sample_variance(begin_2, end_2);\n    Real mean_2 = std::get<0>(temp_2);\n    Real variance_2 = std::get<1>(temp_2);\n    Real std_dev_2 = sqrt(variance_2);\n    \n    if(std_dev_1 > 2 * std_dev_2 || std_dev_2 > 2 * std_dev_1)\n    {\n        return welchs_t_test_impl<ReturnType>(mean_1, variance_1, Real(n1), mean_2, variance_2, Real(n2));\n    }\n    else\n    {\n        return two_sample_t_test_impl<ReturnType>(mean_1, variance_1, Real(n1), mean_2, variance_2, Real(n2));\n    }\n}\n\n// https://en.wikipedia.org/wiki/Student%27s_t-test#Dependent_t-test_for_paired_samples\ntemplate<typename ReturnType, typename ForwardIterator>\nReturnType paired_samples_t_test_impl(ForwardIterator begin_1, ForwardIterator end_1, ForwardIterator begin_2, ForwardIterator end_2)\n{\n    using Real = typename std::tuple_element<0, ReturnType>::type;\n    using no_promote_policy = boost::math::policies::policy<boost::math::policies::promote_float<false>, boost::math::policies::promote_double<false>>;\n    using std::sqrt;\n    \n    std::vector<Real> delta;\n    ForwardIterator it_1 = begin_1;\n    ForwardIterator it_2 = begin_2;\n    std::size_t n = 0;\n    while(it_1 != end_1 && it_2 != end_2)\n    {\n        delta.emplace_back(static_cast<Real>(*it_1++) - static_cast<Real>(*it_2++));\n        ++n;\n    }\n\n    if(it_1 != end_1 || it_2 != end_2)\n    {\n        throw std::domain_error(\"Both sets must have the same number of values.\");\n    }\n\n    std::pair<Real, Real> temp = mean_and_sample_variance(delta.begin(), delta.end());\n    Real delta_mean = std::get<0>(temp);\n    Real delta_std_dev = sqrt(std::get<1>(temp));\n\n    Real test_statistic = delta_mean/(delta_std_dev/sqrt(n));\n\n    auto student = boost::math::students_t_distribution<Real, no_promote_policy>(n - 1);\n    Real pvalue;\n    if (test_statistic > 0) \n    {\n        pvalue = 2*boost::math::cdf<Real>(student, -test_statistic);;\n    }\n    else \n    {\n        pvalue = 2*boost::math::cdf<Real>(student, test_statistic);\n    }\n\n    return std::make_pair(test_statistic, pvalue);\n}\n} // namespace detail\n\ntemplate<typename Real, typename std::enable_if<std::is_integral<Real>::value, bool>::type = true>\ninline auto one_sample_t_test(Real sample_mean, Real sample_variance, Real num_samples, Real assumed_mean) -> std::pair<double, double>\n{\n    return detail::one_sample_t_test_impl<std::pair<double, double>>(sample_mean, sample_variance, num_samples, assumed_mean);\n}\n\ntemplate<typename Real, typename std::enable_if<!std::is_integral<Real>::value, bool>::type = true>\ninline auto one_sample_t_test(Real sample_mean, Real sample_variance, Real num_samples, Real assumed_mean) -> std::pair<Real, Real>\n{\n    return detail::one_sample_t_test_impl<std::pair<Real, Real>>(sample_mean, sample_variance, num_samples, assumed_mean);\n}\n\ntemplate<typename ForwardIterator, typename Real = typename std::iterator_traits<ForwardIterator>::value_type, \n         typename std::enable_if<std::is_integral<Real>::value, bool>::type = true>\ninline auto one_sample_t_test(ForwardIterator begin, ForwardIterator end, Real assumed_mean) -> std::pair<double, double>\n{\n    return detail::one_sample_t_test_impl<std::pair<double, double>>(begin, end, assumed_mean);\n}\n\ntemplate<typename ForwardIterator, typename Real = typename std::iterator_traits<ForwardIterator>::value_type, \n         typename std::enable_if<!std::is_integral<Real>::value, bool>::type = true>\ninline auto one_sample_t_test(ForwardIterator begin, ForwardIterator end, Real assumed_mean) -> std::pair<Real, Real>\n{\n    return detail::one_sample_t_test_impl<std::pair<Real, Real>>(begin, end, assumed_mean);\n}\n\ntemplate<typename Container, typename Real = typename Container::value_type,\n         typename std::enable_if<std::is_integral<Real>::value, bool>::type = true>\ninline auto one_sample_t_test(Container const & v, Real assumed_mean) -> std::pair<double, double>\n{\n    return detail::one_sample_t_test_impl<std::pair<double, double>>(std::begin(v), std::end(v), assumed_mean);\n}\n\ntemplate<typename Container, typename Real = typename Container::value_type,\n         typename std::enable_if<!std::is_integral<Real>::value, bool>::type = true>\ninline auto one_sample_t_test(Container const & v, Real assumed_mean) -> std::pair<Real, Real>\n{\n    return detail::one_sample_t_test_impl<std::pair<Real, Real>>(std::begin(v), std::end(v), assumed_mean);\n}\n\ntemplate<typename ForwardIterator, typename Real = typename std::iterator_traits<ForwardIterator>::value_type, \n         typename std::enable_if<std::is_integral<Real>::value, bool>::type = true>\ninline auto two_sample_t_test(ForwardIterator begin_1, ForwardIterator end_1, ForwardIterator begin_2, ForwardIterator end_2) -> std::pair<double, double>\n{\n    return detail::two_sample_t_test_impl<std::pair<double, double>>(begin_1, end_1, begin_2, end_2);\n}\n\ntemplate<typename ForwardIterator, typename Real = typename std::iterator_traits<ForwardIterator>::value_type, \n         typename std::enable_if<!std::is_integral<Real>::value, bool>::type = true>\ninline auto two_sample_t_test(ForwardIterator begin_1, ForwardIterator end_1, ForwardIterator begin_2, ForwardIterator end_2) -> std::pair<Real, Real>\n{\n    return detail::two_sample_t_test_impl<std::pair<Real, Real>>(begin_1, end_1, begin_2, end_2);\n}\n\ntemplate<typename Container, typename Real = typename Container::value_type, typename std::enable_if<std::is_integral<Real>::value, bool>::type = true>\ninline auto two_sample_t_test(Container const & u, Container const & v) -> std::pair<double, double>\n{\n    return detail::two_sample_t_test_impl<std::pair<double, double>>(std::begin(u), std::end(u), std::begin(v), std::end(v));\n}\n\ntemplate<typename Container, typename Real = typename Container::value_type, typename std::enable_if<!std::is_integral<Real>::value, bool>::type = true>\ninline auto two_sample_t_test(Container const & u, Container const & v) -> std::pair<Real, Real>\n{\n    return detail::two_sample_t_test_impl<std::pair<Real, Real>>(std::begin(u), std::end(u), std::begin(v), std::end(v));\n}\n\ntemplate<typename ForwardIterator, typename Real = typename std::iterator_traits<ForwardIterator>::value_type, \n         typename std::enable_if<std::is_integral<Real>::value, bool>::type = true>\ninline auto paired_samples_t_test(ForwardIterator begin_1, ForwardIterator end_1, ForwardIterator begin_2, ForwardIterator end_2) -> std::pair<double, double>\n{\n    return detail::paired_samples_t_test_impl<std::pair<double, double>>(begin_1, end_1, begin_2, end_2);\n}\n\ntemplate<typename ForwardIterator, typename Real = typename std::iterator_traits<ForwardIterator>::value_type, \n         typename std::enable_if<!std::is_integral<Real>::value, bool>::type = true>\ninline auto paired_samples_t_test(ForwardIterator begin_1, ForwardIterator end_1, ForwardIterator begin_2, ForwardIterator end_2) -> std::pair<Real, Real>\n{\n    return detail::paired_samples_t_test_impl<std::pair<Real, Real>>(begin_1, end_1, begin_2, end_2);\n}\n\ntemplate<typename Container, typename Real = typename Container::value_type, typename std::enable_if<std::is_integral<Real>::value, bool>::type = true>\ninline auto paired_samples_t_test(Container const & u, Container const & v) -> std::pair<double, double>\n{\n    return detail::paired_samples_t_test_impl<std::pair<double, double>>(std::begin(u), std::end(u), std::begin(v), std::end(v));\n}\n\ntemplate<typename Container, typename Real = typename Container::value_type, typename std::enable_if<!std::is_integral<Real>::value, bool>::type = true>\ninline auto paired_samples_t_test(Container const & u, Container const & v) -> std::pair<Real, Real>\n{\n    return detail::paired_samples_t_test_impl<std::pair<Real, Real>>(std::begin(u), std::end(u), std::begin(v), std::end(v));\n}\n\n}}} // namespace boost::math::statistics\n#endif\n", "meta": {"hexsha": "ec06bda8c345fa0a19cbd8666b58ece0cefe143e", "size": 12892, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/math/statistics/t_test.hpp", "max_stars_repo_name": "Harshitha91/Tmdb-react-native-node", "max_stars_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 310.0, "max_stars_repo_stars_event_min_datetime": "2017-02-02T09:14:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T06:50:11.000Z", "max_issues_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/math/statistics/t_test.hpp", "max_issues_repo_name": "Harshitha91/Tmdb-react-native-node", "max_issues_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_issues_repo_licenses": ["Apache-2.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": "ReactNativeFrontend/ios/Pods/boost/boost/math/statistics/t_test.hpp", "max_forks_repo_name": "Harshitha91/Tmdb-react-native-node", "max_forks_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_forks_repo_licenses": ["Apache-2.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": 46.7101449275, "max_line_length": 158, "alphanum_fraction": 0.7282035371, "num_tokens": 3428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045817875224, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.7274131222473151}}
{"text": "/********************************************************************************\n * Quick Sort - Count number of comparisons \n********************************************************************************/\n#include <iostream>\n#include <string>\n#include <fstream>\n#include <vector>\n#include <sstream>\n#include <assert.h>\n#include <algorithm>\n\n// #include <boost/log/core.hpp>\n// #include <boost/log/trivial.hpp>\n// #include <boost/log/expressions.hpp>\n// \n// namespace logging = boost::log;\n\nnamespace {\n    void print_vector(std::vector<int> &arr) {\n        std::stringstream ss;\n        for (auto &v : arr) {\n            ss << v << \" \";\n        }\n        //BOOST_LOG_TRIVIAL(trace) << ss.str(); \n    }\n\n    enum pivot_choice_t { FIRST, MEDIAN_OF_THREE, LAST};\n    pivot_choice_t pc = pivot_choice_t::FIRST;\n    // start and end are always INCLUSIVE\n    size_t choose_pivot(std::vector<int> arr, size_t start, size_t end) {\n        assert (start <= end);\n        switch (pc) {\n            case pivot_choice_t::FIRST:\n                return start;\n            \n            case pivot_choice_t::LAST:\n                return end;\n            \n            case pivot_choice_t::MEDIAN_OF_THREE:\n                // Random using 3 median rule\n                assert (end >= (start+2));\n                auto compute_m3_idx = [&]() -> size_t {\n                    auto a = arr[start];\n                    auto b = arr[(start+end)/2];\n                    auto c = arr[end];\n                    \n                    auto x = a - b; \n                    auto y = b - c;\n                    auto z = a - c;\n  \n                    // Checking if b is middle (x and y both are positive) \n                    if (x * y > 0) \n                        return (start+end)/2;\n                    else if (x * z > 0) // Checking if c is middle then if a>c => a>b \n                        return end; \n                    else\n                        return start;  \n                };\n                return compute_m3_idx(); \n        }\n    }\n\n    void quick_sort_partition(std::vector<int> &arr, size_t l, \n        size_t r, size_t &p) {\n        assert(p>=l && p<=r);\n\n        auto pval = arr[p];\n\n        // Move the pivot to left most if its not at the left already\n        if (l != p)\n            std::swap(arr[l], arr[p]);\n\n        // l position is pivot\n        // l+1 to i-1 is <p\n        // i to j-1 is >p\n        // j to r is TBD\n\n        auto i = l+1; \n        for (auto j=l+1; j<=r; j++) {\n            if (arr[j] < pval) {\n                std::swap(arr[j], arr[i++]);\n            }\n        }\n\n        // l - pivot\n        // l+1 to i-1 are <p\n        // i to r are >p\n\n        std::swap(arr[l], arr[i-1]);\n        p = i-1;\n    }\n\n    int quick_sort_impl(std::vector<int> &arr, size_t start, size_t end) {\n        //BOOST_LOG_TRIVIAL(info) << \"Quick Sort Called with start = \" << \n        //    start << \" end = \" << end; \n\n        if (start == end) {\n            return 0;\n        } else if (end == (start+1)) {\n            if (arr[start] > arr[end]) \n                std::swap(arr[start], arr[end]);\n            return 1;\n        }\n\n        auto p = choose_pivot(arr, start, end);\n        assert(p>=start && p<=end);\n        //BOOST_LOG_TRIVIAL(info) << \"Partition around chosen pivot index = \" << p; \n\n        quick_sort_partition(arr, start, end, p);\n        //BOOST_LOG_TRIVIAL(trace) << \"Post Partitioning\"; \n        print_vector(arr);\n\n        auto left  = (p!=start) ? quick_sort_impl(arr, start, p-1) : 0;\n        auto right = (p!=end) ? quick_sort_impl(arr, p+1, end) : 0;\n\n        return left+right+(end-start);\n\n    }\n\n    void quick_sort(std::vector<int> &arr) {\n        auto arr1 = arr; \n        auto arr2 = arr;\n        pc = pivot_choice_t::FIRST;\n        auto comp_pc_first = quick_sort_impl(arr, 0, arr.size()-1);\n        std::cout << comp_pc_first << std::endl;\n\n        pc = pivot_choice_t::LAST;\n        auto comp_pc_last = quick_sort_impl(arr1, 0, arr1.size()-1);\n        std::cout << comp_pc_last << std::endl;\n        \n        pc = pivot_choice_t::MEDIAN_OF_THREE;\n        auto comp_pc_random = quick_sort_impl(arr2, 0, arr.size()-1);\n        std::cout << comp_pc_random << std::endl;\n    }\n}\n\n\nint main (int argc, char **argv) {\n    // logging::core::get()->set_filter\n    // (\n    //     // logging::trivial::severity >= logging::trivial::fatal\n    //     logging::trivial::severity >= logging::trivial::info\n    // );\n\n    //BOOST_LOG_TRIVIAL(info) << \"Reading Input file\";\n    std::string input_file = argv[1];\n    std::ifstream inFile;\n    inFile.open(input_file);\n    std::string str;\n    int count = 0;\n    std::vector<int> input_vector;\n\n    while(std::getline(inFile, str)) {\n        int n = std::stoi(str);\n        // std::cout << n << std::endl;\n        input_vector.push_back(n);\n        count++;\n    }\n    \n    //BOOST_LOG_TRIVIAL(info) << \"Final count read = \" << count ; \n    //BOOST_LOG_TRIVIAL(trace) << \"Pre Sorting\"; \n    print_vector(input_vector);\n\n    quick_sort(input_vector);\n\n    //BOOST_LOG_TRIVIAL(trace) << \"Post Sorting\"; \n    print_vector(input_vector);\n\n    return 0;\n}\n\n", "meta": {"hexsha": "4bc590efd739618010c4bc29fe15fc91c487bfa0", "size": 5116, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "coursera_algorithms_specialization/0003_QuickSort/quick_sort.cpp", "max_stars_repo_name": "manikandan-ananth/algorithms", "max_stars_repo_head_hexsha": "5c9f6b2adb3cdcdb31572bff89c2ff587297225d", "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": "coursera_algorithms_specialization/0003_QuickSort/quick_sort.cpp", "max_issues_repo_name": "manikandan-ananth/algorithms", "max_issues_repo_head_hexsha": "5c9f6b2adb3cdcdb31572bff89c2ff587297225d", "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": "coursera_algorithms_specialization/0003_QuickSort/quick_sort.cpp", "max_forks_repo_name": "manikandan-ananth/algorithms", "max_forks_repo_head_hexsha": "5c9f6b2adb3cdcdb31572bff89c2ff587297225d", "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.7441860465, "max_line_length": 86, "alphanum_fraction": 0.4863174355, "num_tokens": 1294, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677430095496, "lm_q2_score": 0.8577680995361899, "lm_q1q2_score": 0.7273596793892937}}
{"text": "static bool eigen_did_assert = false;\n#define eigen_assert(X) if(!eigen_did_assert && !(X)){ std::cout << \"### Assertion raised in \" << __FILE__ << \":\" << __LINE__ << \":\\n\" #X << \"\\n### The following would happen without assertions:\\n\"; eigen_did_assert = true;}\n\n#include <iostream>\n#include <Eigen/Eigen>\n\n#ifndef M_PI\n#define M_PI 3.1415926535897932384626433832795\n#endif\n\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  MatrixXf m = MatrixXf::Random(3,2);\ncout << \"Here is the matrix m:\" << endl << m << endl;\nJacobiSVD<MatrixXf> svd(m, ComputeThinU | ComputeThinV);\ncout << \"Its singular values are:\" << endl << svd.singularValues() << endl;\ncout << \"Its left singular vectors are the columns of the thin U matrix:\" << endl << svd.matrixU() << endl;\ncout << \"Its right singular vectors are the columns of the thin V matrix:\" << endl << svd.matrixV() << endl;\nVector3f rhs(1, 0, 0);\ncout << \"Now consider this rhs vector:\" << endl << rhs << endl;\ncout << \"A least-squares solution of m*x = rhs is:\" << endl << svd.solve(rhs) << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "39c6bbf7bcac20ca09842384382a854c334d6afd", "size": 1098, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/snippets/compile_JacobiSVD_basic.cpp", "max_stars_repo_name": "mousepawmedia/libdeps", "max_stars_repo_head_hexsha": "b004d58d5b395ceaf9fdc993cfb00e91334a5d36", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2021-02-27T11:00:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T10:31:46.000Z", "max_issues_repo_path": "doc/snippets/compile_JacobiSVD_basic.cpp", "max_issues_repo_name": "mousepawmedia/libdeps", "max_issues_repo_head_hexsha": "b004d58d5b395ceaf9fdc993cfb00e91334a5d36", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-11-14T23:14:58.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-14T23:14:58.000Z", "max_forks_repo_path": "doc/snippets/compile_JacobiSVD_basic.cpp", "max_forks_repo_name": "mousepawmedia/libdeps", "max_forks_repo_head_hexsha": "b004d58d5b395ceaf9fdc993cfb00e91334a5d36", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-03-13T13:28:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-05T02:26:02.000Z", "avg_line_length": 36.6, "max_line_length": 224, "alphanum_fraction": 0.6684881603, "num_tokens": 316, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.8128673178375735, "lm_q1q2_score": 0.7273451110594841}}
{"text": "//\n// Created by Hamza El-Kebir on 6/17/21.\n//\n\n#include \"catchOnce.hpp\"\n#include <Eigen/Dense>\n#include <unsupported/Eigen/FFT>\n\n#include <complex>\n#include <cmath>\n#include <iostream>\n#include <fstream>\n\nunsigned const N = 5000;  //\ndouble const Fs = 128;    // [Hz]\ndouble const Ts = 1. / Fs; // [s]\nconst double f0 = 5;     // [Hz]\nconst double f1 = 12;\n\ndouble f(double const &t)\n{\n    return sin(2 * M_PI * f0 * t) + sin(2 * M_PI * f1 * t);\n}\n\nTEST_CASE(\"FastFourierTransform\", \"[data]\")\n{\n    Eigen::VectorXd time(N);\n    Eigen::VectorXd f_values(N);\n    Eigen::VectorXd freq(N);\n    for (int u = 0; u < N; ++u) {\n        time(u) = u * Ts;\n        f_values(u) = f(time(u));\n        freq(u) = Fs * u / double(N);\n    }\n\n    Eigen::FFT<double> fft;\n    Eigen::VectorXcd f_freq(N);\n    fft.fwd(f_freq, f_values);\n\n    Eigen::VectorXd t_values(N);\n    fft.inv(t_values, f_freq);\n\n//    std::ofstream xrec(\"xrec.txt\");\n//    std::ofstream yrec(\"yrec.txt\");\n//    for (int u = 0; u < N; ++u) {\n//        xrec << freq(u) << \" \" << std::abs(f_freq(u)) << \"\\n\";\n//        yrec << time(u) << \" \" << t_values(u) << \"\\n\";\n//    }\n}", "meta": {"hexsha": "62f89da197855fcea21c914559c2a243095d35f2", "size": 1126, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/data/FastFourierTransform_test.cpp", "max_stars_repo_name": "helkebir/Lodestar", "max_stars_repo_head_hexsha": "6b325d3e7a388676ed31d44eac1146630ee4bb2c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-06-05T14:08:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-26T22:15:31.000Z", "max_issues_repo_path": "tests/data/FastFourierTransform_test.cpp", "max_issues_repo_name": "helkebir/Lodestar", "max_issues_repo_head_hexsha": "6b325d3e7a388676ed31d44eac1146630ee4bb2c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-06-25T15:14:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-01T17:43:20.000Z", "max_forks_repo_path": "tests/data/FastFourierTransform_test.cpp", "max_forks_repo_name": "helkebir/Lodestar", "max_forks_repo_head_hexsha": "6b325d3e7a388676ed31d44eac1146630ee4bb2c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-16T03:15:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-16T03:15:23.000Z", "avg_line_length": 22.9795918367, "max_line_length": 64, "alphanum_fraction": 0.5444049734, "num_tokens": 366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533163686646, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.7273069713547048}}
{"text": "#include <Eigen/Dense>\n#include <boost/math/distributions.hpp>\n#include <math.h>\n#include <iostream>\n\n#ifdef BAZEL\n#include \"Stats/Stats.hpp\"\n#else\n#include \"Stats.hpp\"\n#endif\n\nusing namespace std;\nusing namespace Eigen;\n\n\nfloat Stats::ChiSquaredTest(MatrixXf observed, MatrixXf expected) {\n    MatrixXf diff = observed - expected;\n    MatrixXf x = diff.cwiseProduct(diff).cwiseQuotient(expected);\n    return x.sum();\n}\n\n\nfloat Stats::ChiToPValue(float chisqr_value, int dof) {\n    boost::math::chi_squared dist(dof);\n    return 1 - boost::math::cdf(dist, chisqr_value);\n}\n\n\nfloat Stats::WaldTest(float mle, float var, float candidate) {\n    return pow(mle - candidate, 2) / var;\n}\n\nfloat Stats::FisherExactTest(MatrixXf X) {\n   int N = X.sum();\n   float NFac = boost::math::factorial<float>(N);\n   MatrixXf rowSums = X.rowwise().sum();\n   MatrixXf colSums = X.colwise().sum();\n   MatrixXf comFacs = X.unaryExpr(std::ptr_fun(boost::math::factorial<float>));\n   MatrixXf rFacs = rowSums.unaryExpr(std::ptr_fun(boost::math::factorial<float>));\n   MatrixXf cFacs = colSums.unaryExpr(std::ptr_fun(boost::math::factorial<float>));\n   float rowsFacs = rFacs.prod();\n   float colsFacs = cFacs.prod();\n   float componentFacs = comFacs.prod();\n   return rowsFacs*colsFacs/(NFac*componentFacs);\n}\n\nfloat Stats::BonCorrection(float pVal, int number) {\n  return pVal/number;\n}\n\nfloat Stats::get_ts(float beta, float var, float sigma){\n  return beta/(sqrt(var * sigma));\n}\n\nfloat Stats::get_qs(float ts, int N, int q){\n  return 2*Stats::ChiToPValue(abs(ts), N-q);  \n}\n\nvoid StatsBasic::setAttributeMatrix(const string &string1, MatrixXf *xd) {\n\n}\n\n\nStatsBasic::StatsBasic() {\n    shouldCorrect = false;\n}\n\nStatsBasic::StatsBasic(const unordered_map<string, string> & options) {\n    string tmp;\n    try {\n        tmp = options.at(\"correctNum\");\n        if (tmp == \"Bonferroni correction\"){\n            shouldCorrect = true;\n        }\n        else{\n            shouldCorrect = false;\n        }\n    } catch (std::out_of_range& oor) {\n        shouldCorrect = true;\n    }\n}\n\nvoid StatsBasic::checkGenoType() {\n    long r = X.rows();\n    long c = X.cols();\n    int s = 0;\n    bool go = true;\n    for (long i=0;i<r&&go;i++){\n        for (long j=0;j<c&&go;j++){\n            if (X(i,j) == 2){\n                s = 1;\n                go = false;\n            }\n        }\n    }\n    if (s == 0){\n        genoType = 1;\n    }\n    else{\n        genoType = 2;\n    }\n}\n\n\nvoid StatsBasic::assertReadyToRun() {\n    beta = MatrixXf::Zero(X.cols(), y.cols());\n    checkGenoType();\n}\n\n\nvoid StatsBasic::BonferroniCorrection() {\n    if (shouldCorrect){\n        beta = beta*X.rows();\n        MatrixXf m = MatrixXf::Ones(beta.rows(), beta.cols());\n        beta = beta.cwiseMin(m);\n    }\n}\n\nfloat StatsBasic::getProgress() {\n    return progress;\n}\n\nbool StatsBasic::getIsRunning() {\n    return isRunning;\n}\n\n\nvoid StatsBasic::stop() {\n    shouldStop = true;\n}\n\nvoid StatsBasic::setUpRun() {\n    isRunning = true;\n    progress = 0.0;\n    shouldStop = false;\n}\n\nvoid StatsBasic::finishRun() {\n    isRunning = false;\n    progress = 1.0;\n}\n\nMatrixXf StatsBasic::getBeta() {\n    MatrixXf tmp = MatrixXf::Zero(beta.rows(), beta.cols());\n    for (long i = 0; i<beta.rows(); i++){\n        for (long j=0; j<beta.cols(); j++){\n            if (beta(i,j)>0){\n                tmp(i,j) = -log10(beta(i,j));\n            }\n            else{\n                tmp(i,j) = 0;\n            }\n        }\n    }\n    return tmp;\n}\n", "meta": {"hexsha": "6899a34e9bb82e360f3fbf4529b700f746adc568", "size": 3462, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Stats/Stats.cpp", "max_stars_repo_name": "blengerich/jenkins_test", "max_stars_repo_head_hexsha": "512aec681577063e3d68f699d19f53374e59585a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2016-10-20T00:36:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-06T16:40:52.000Z", "max_issues_repo_path": "src/Stats/Stats.cpp", "max_issues_repo_name": "blengerich/jenkins_test", "max_issues_repo_head_hexsha": "512aec681577063e3d68f699d19f53374e59585a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 44.0, "max_issues_repo_issues_event_min_datetime": "2016-11-11T22:41:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-04T21:55:57.000Z", "max_forks_repo_path": "src/Stats/Stats.cpp", "max_forks_repo_name": "blengerich/jenkins_test", "max_forks_repo_head_hexsha": "512aec681577063e3d68f699d19f53374e59585a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-02-01T09:19:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-28T14:40:43.000Z", "avg_line_length": 22.050955414, "max_line_length": 83, "alphanum_fraction": 0.5973425765, "num_tokens": 980, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813538993888, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.7271678356038785}}
{"text": "/*\r\n * qball.cpp\r\n *\r\n * Created on: 10.07.2012\r\n * @author Ralph Schurade\r\n */\r\n#include \"qball.h\"\r\n#include \"sharpqballthread.h\"\r\n\r\n#include \"fmath.h\"\r\n\r\n#include \"../data/datasets/datasetdwi.h\"\r\n\r\n#include \"../gui/gl/glfunctions.h\"\r\n\r\n#include <QDebug>\r\n#include <qmath.h>\r\n\r\n#include <boost/math/special_functions/spherical_harmonic.hpp>\r\n\r\nQBall::QBall()\r\n{\r\n}\r\n\r\nQBall::~QBall()\r\n{\r\n}\r\n\r\nMatrix QBall::calcQBallBase( Matrix gradients, double lambda, int maxOrder )\r\n{\r\n    //qDebug() << \"start calculating qBall base\";\r\n    double sh_size( ( maxOrder + 1 ) * ( maxOrder + 2 ) / 2 );\r\n\r\n    // check validity of input:\r\n    if ( gradients.Nrows() == 0 )\r\n        throw std::invalid_argument( \"No gradient directions specified.\" );\r\n\r\n    if ( gradients.Ncols() != 3 )\r\n        throw std::invalid_argument( \"Gradients have to be 3D.\" );\r\n\r\n    // calculate spherical harmonics base:\r\n    Matrix SH = FMath::sh_base( gradients, maxOrder );\r\n\r\n    // calculate the Laplace-Beltrami and the Funk-Radon transformation:\r\n    ColumnVector LBT( sh_size );\r\n    ColumnVector FRT( sh_size );\r\n    LBT = 0;\r\n    FRT = 0;\r\n\r\n    for ( int order = 0; order <= maxOrder; order += 2 )\r\n    {\r\n        double frt_val = 2.0 * M_PI * boost::math::legendre_p<double>( order, 0 );\r\n        double lbt_val = lambda * order * order * ( order + 1 ) * ( order + 1 );\r\n\r\n        for ( int degree( -order ); degree <= order; ++degree )\r\n        {\r\n            int i = order * ( order + 1 ) / 2 + degree;\r\n            LBT( i + 1 ) = lbt_val;\r\n            FRT( i + 1 ) = frt_val;\r\n        }\r\n    }\r\n\r\n    // prepare the calculation of the pseudoinverse:\r\n    Matrix B = SH.t() * SH;\r\n\r\n    // update with Laplace-Beltrami operator:\r\n    for ( int i = 0; i < sh_size; ++i )\r\n    {\r\n        B( i + 1, i + 1 ) += LBT( i + 1 );\r\n    }\r\n\r\n    Matrix out = B.i() * SH.t();\r\n\r\n    // the Funk-Radon transformation:\r\n    for ( int i = 0; i < B.Nrows(); ++i )\r\n    {\r\n        for ( int j = 0; j < out.Ncols(); ++j )\r\n        {\r\n            out( i + 1, j + 1 ) *= FRT( i + 1 );\r\n        }\r\n    }\r\n\r\n    //qDebug() << \"finished calculating qBall base\";\r\n\r\n    return out;\r\n}\r\n\r\n/*\r\n * CMRImage calc_sharp_q_ball(\r\n\r\n const CMRImage& data,\r\n const CMRImage& b_zero,\r\n const matrixT gradients,\r\n const baseT order,\r\n const rangeS r )\r\n {\r\n *\r\n */\r\n\r\nvoid QBall::sharpQBall( DatasetDWI* ds, int order, QVector<ColumnVector>& out )\r\n{\r\n    int numThreads = GLFunctions::idealThreadCount;\r\n\r\n    QVector<SharpQBallThread*> threads;\r\n    // create threads\r\n    for ( int i = 0; i < numThreads; ++i )\r\n    {\r\n        threads.push_back( new SharpQBallThread( ds, order, i ) );\r\n    }\r\n\r\n    // run threads\r\n    for ( int i = 0; i < numThreads; ++i )\r\n    {\r\n        threads[i]->start();\r\n    }\r\n\r\n    // wait for all threads to finish\r\n    for ( int i = 0; i < numThreads; ++i )\r\n    {\r\n        threads[i]->wait();\r\n    }\r\n\r\n    out.clear();\r\n    // combine fibs from all threads\r\n    for ( int i = 0; i < numThreads; ++i )\r\n    {\r\n        out += threads[i]->getQBallVector();\r\n    }\r\n\r\n    for ( int i = 0; i < numThreads; ++i )\r\n    {\r\n        delete threads[i];\r\n    }\r\n}\r\n", "meta": {"hexsha": "c8f7e05e7404a5a14a381a17497b41ce23f81260", "size": 3134, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/algos/qball.cpp", "max_stars_repo_name": "rdmenezes/fibernavigator2", "max_stars_repo_head_hexsha": "bbb8bc8ff16790580d5b03fce7e1fad45fae1b91", "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/algos/qball.cpp", "max_issues_repo_name": "rdmenezes/fibernavigator2", "max_issues_repo_head_hexsha": "bbb8bc8ff16790580d5b03fce7e1fad45fae1b91", "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/algos/qball.cpp", "max_forks_repo_name": "rdmenezes/fibernavigator2", "max_forks_repo_head_hexsha": "bbb8bc8ff16790580d5b03fce7e1fad45fae1b91", "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.2148148148, "max_line_length": 83, "alphanum_fraction": 0.5325462668, "num_tokens": 896, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305318133553, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.7271571589631471}}
{"text": "// BSD 2-Clause License\r\n//\r\n// Copyright (c) 2021, Eijiro SHIBUSAWA\r\n// All rights reserved.\r\n//\r\n// Redistribution and use in source and binary forms, with or without\r\n// modification, are permitted provided that the following conditions are met:\r\n//\r\n// 1. Redistributions of source code must retain the above copyright notice, this\r\n//    list of conditions and the following disclaimer.\r\n//\r\n// 2. Redistributions in binary form must reproduce the above copyright notice,\r\n//    this list of conditions and the following disclaimer in the documentation\r\n//    and/or other materials provided with the distribution.\r\n//\r\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\r\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\r\n// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\r\n// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\r\n// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\r\n// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\r\n// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\r\n// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\r\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n\r\n#include \"mex.h\"\r\n\r\n#include <Eigen/Dense>\r\n\r\n#include <iostream>\r\n\r\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])\r\n{\r\n\tif ((nlhs != 1) || (nrhs != 2))\r\n\t{\r\n\t\treturn;\r\n\t}\r\n\r\n\tconst mxArray *A = prhs[0];\r\n\tconst mxArray *B = prhs[1];\r\n\tmwSize cA = mxGetNumberOfDimensions(A);\r\n\tmwSize cB = mxGetNumberOfDimensions(B);\r\n\tif ((cA != 2) || (cB != 2))\r\n\t{\r\n\t\treturn;\r\n\t}\r\n\r\n\tconst mwSize *dA = mxGetDimensions(A);\r\n\tconst mwSize *dB = mxGetDimensions(B);\r\n\tconst mwSize nA = dA[0], mA = dA[1]; // [nA, mA] = size(A)\r\n\tconst mwSize nB = dB[0], mB = dB[1]; // [nB, mB] = size(B)\r\n\tif (mA != nB)\r\n\t{\r\n\t\tstd::cerr << \"nonconformant arguments (op1 is \" << nA << \"x\" << mA << \", op2 is \" << nB << \"x\" << mB << \")\" << std::endl;\r\n\t\treturn;\r\n\t}\r\n\r\n\tint nDims = 2;\r\n\tmwSize dims[] = {nA, mB};\r\n\tplhs[0] = mxCreateNumericArray(nDims, dims, mxDOUBLE_CLASS, mxREAL);\r\n\r\n\tdouble *pA = reinterpret_cast<double *>(mxGetData(A)); // column major\r\n\tdouble *pB = reinterpret_cast<double *>(mxGetData(B)); // column major\r\n\tdouble *pC = reinterpret_cast<double *>(mxGetData(plhs[0]));\r\n\tEigen::Map<const Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > matA(pA, nA, mA);\r\n\tEigen::Map<const Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > matB(pB, nB, mB);\r\n\tEigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > matC(pC, dims[0], dims[1]);\r\n\tmatC = matA * matB;\r\n}", "meta": {"hexsha": "4a968f34099fd772c1064b4d7cfccc38044c0830", "size": 2822, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mex-octave/mexSimpleMM.cpp", "max_stars_repo_name": "eshibusawa/Simple-Examples", "max_stars_repo_head_hexsha": "42814690352696f23ea03e5dff684d5bc2c40541", "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": "mex-octave/mexSimpleMM.cpp", "max_issues_repo_name": "eshibusawa/Simple-Examples", "max_issues_repo_head_hexsha": "42814690352696f23ea03e5dff684d5bc2c40541", "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": "mex-octave/mexSimpleMM.cpp", "max_forks_repo_name": "eshibusawa/Simple-Examples", "max_forks_repo_head_hexsha": "42814690352696f23ea03e5dff684d5bc2c40541", "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": 40.3142857143, "max_line_length": 124, "alphanum_fraction": 0.680368533, "num_tokens": 753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412808, "lm_q2_score": 0.843895106480586, "lm_q1q2_score": 0.7270478849851983}}
{"text": "#include \"../include/util.h\"\n#include <Eigen/Dense>\n#include <vector>\n#include <iostream>\n#include <tbb/tbb.h>\n\nusing namespace std;\nusing namespace Eigen;\n\n\nMatrix3f eigenso3hat(Vector3f w) \n{\n  Matrix3f what;\n  what << 0.0, -w(2), w(1),\n          w(2), 0.0, -w(0),\n          -w(1), w(0), 0.0;\n  return what;\n}\n\nMatrix3f eigenso3exp(Vector3f w) \n{\n  float theta = w.norm();\n  Matrix3f R = Matrix3f::Identity();\n  if (theta < 1e-6) {\n    return R;\n  }\n  else {\n    Matrix3f what = eigenso3hat(w);\n    R += (sin(theta) / theta) * what + ((1 - cos(theta)) / (theta * theta)) * (what * what);\n    return R;\n  }\n}\n\nVector3f so3log(Matrix3f R) \n{\n  float d = 0.5 * (R.trace() - 1);\n\n  Matrix3f lnR = (acos(d) / (2 * sqrt(1 - d*d))) * (R - R.transpose());\n\n  Vector3f w;\n  w(0) = lnR(2,1);\n  w(1) = lnR(0,2);\n  w(2) = lnR(1,0);\n\n  return w;\n}\n\nMatrixXf reprojectionJacFn(VectorXf cam, Vector3f lmk, std::vector<float> K_vec) \n{\n  Matrix3f K = Map<Matrix<float,3,3>>(K_vec.data()).transpose();\n  Vector3f w;\n  Vector3f t;\n  t << cam(0), cam(1), cam(2);\n  w << cam(3), cam(4), cam(5);\n  Matrix3f Rcw = eigenso3exp(w);\n\n  Vector3f lmk_cf = Rcw * lmk + t;\n  Vector3f p = K * lmk_cf;\n\n  MatrixXf j_proj(2,3);\n  j_proj << 1 / p(2), 0, -p(0) / pow(p(2),2),\n           0, 1 / p(2), -p(1) / pow(p(2),2);\n\n  Matrix3f dR_wx_dw = - eigenso3hat(Rcw * lmk);\n\n  MatrixXf jac(2, 9); \n  jac.block(0, 0, 2, 3) = j_proj * K;\n  jac.block(0, 3, 2, 3) = j_proj * K * dR_wx_dw;\n  jac.block(0, 6, 2, 3) = (j_proj * K) * Rcw;\n\n  return jac;\n}\n\nvoid eval_reprojection_error(float* reproj, unsigned n_edges, \n                      vector<unsigned int> active_flag,\n                      float* cam_beliefs_eta_, float* cam_beliefs_lambda_, \n                      float* lmk_beliefs_eta_, float* lmk_beliefs_lambda_,\n                      unsigned* measurements_camIDs, unsigned* measurements_lIDs, \n                      float* measurements_, float* K_,\n                      const vector<unsigned int>& bad_associations) \n{\n  Matrix3f K = Map<Matrix3f>(K_).transpose();\n  reproj[0] = 0.0;\n  reproj[1] = 0.0;\n  unsigned n_active_edges = 0;\n\n  // Make two vectors for storing every reprojection result computed in\n  // parallel so that no locking is required in the parallel loop:\n  vector<float> reprojNorm(n_edges, 0.f);\n  vector<float> reprojSqNorm(n_edges, 0.f);\n\n  // Use as many threads as there are cores on the CPU:\n  tbb::task_scheduler_init init(tbb::task_scheduler_init::automatic);\n\n  for (unsigned e = 0; e < n_edges; ++e) {\n    n_active_edges += active_flag[e];\n  }\n\n  tbb::parallel_for(0U, n_active_edges, [&](unsigned e) {\n    if ((find(bad_associations.begin(), bad_associations.end(), e) == bad_associations.end())) {\n\n      Matrix<float,6,1> cam_eta = Map<Matrix<float,6,1>>(&cam_beliefs_eta_[measurements_camIDs[e] * 6]);\n      Matrix<float,6,6> cam_lam = Map<Matrix<float,6,6>>(&cam_beliefs_lambda_[measurements_camIDs[e] * 36]);\n      VectorXf cam_mu = cam_lam.transpose().inverse() * cam_eta;\n\n      Vector3f lmk_eta = Map<Vector3f>(&lmk_beliefs_eta_[measurements_lIDs[e] * 3]);\n      Matrix3f lmk_lam = Map<Matrix3f>(&lmk_beliefs_lambda_[measurements_lIDs[e] * 9]);\n      Vector3f lmk_mu = lmk_lam.transpose().inverse() * lmk_eta;\n\n      Vector3f w;\n      w << cam_mu(3), cam_mu(4), cam_mu(5);\n      Matrix3f R = eigenso3exp(w);\n\n      Vector3f pcf = R * lmk_mu;\n\n      pcf(0) += cam_mu(0);\n      pcf(1) += cam_mu(1);\n      pcf(2) += cam_mu(2);\n\n      Vector3f predicted = (K * pcf) / pcf(2);\n      Vector2f residuals = Map<Vector2f>(&measurements_[2*e]);\n\n      residuals(0) -= predicted(0);\n      residuals(1) -= predicted(1);\n\n      reprojNorm[e] = residuals.norm();\n      reprojSqNorm[e] = 0.5 * residuals.squaredNorm();\n    }\n  });\n\n  n_active_edges -= bad_associations.size();\n\n  // Now sum up the results outside of the prallel loop.\n  // No need to exclude inactive edges while summing as their entries\n  // will have been initialised to 0 and then not updated in the loop above:\n  for (unsigned e = 0; e < n_edges; ++e) {\n    // n_active_edges += active_flag[e];\n    reproj[0] += reprojNorm[e];\n    reproj[1] += reprojSqNorm[e];\n  }\n\n  // cout << \"Number of active edges: \" << n_active_edges << \"\\n\";\n  reproj[0] /= n_active_edges;\n}\n\nvoid update_eta(unsigned n_keyframes, unsigned n_points,\n                std::vector<float> cam_priors_lambda_,\n                std::vector<float> cam_priors_mean_,\n                std::vector<float>& cam_priors_eta_,\n                std::vector<float> lmk_priors_lambda_,\n                std::vector<float> lmk_priors_mean_,\n                std::vector<float>& lmk_priors_eta_)\n{\n  for (unsigned cID = 0; cID < n_keyframes; ++cID) {\n    Matrix<float,6,6> lambda;\n    Matrix<float,6,1> mu;\n    lambda = Map<Matrix<float,6,6>>(&cam_priors_lambda_[cID * 36]);\n    mu = Map<Matrix<float,6,1>>(&cam_priors_mean_[cID*6]);\n\n    Matrix<float,6,1> eta = lambda * mu;\n\n    cam_priors_eta_[cID*6] = eta(0,0);\n    cam_priors_eta_[cID*6 + 1] = eta(1,0);\n    cam_priors_eta_[cID*6 + 2] = eta(2,0);\n    cam_priors_eta_[cID*6 + 3] = eta(3,0);\n    cam_priors_eta_[cID*6 + 4] = eta(4,0);\n    cam_priors_eta_[cID*6 + 5] = eta(5,0);\n\n  }\n  for (unsigned lID = 0; lID < n_points; ++lID) {\n    Matrix3f lambda;\n    Vector3f mu;\n    lambda = Map<Matrix3f>(&lmk_priors_lambda_[lID*9]);\n    mu = Map<Vector3f>(&lmk_priors_mean_[lID*3]);\n    Vector3f eta = lambda * mu;\n\n    lmk_priors_eta_[lID*3] = eta(0);\n    lmk_priors_eta_[lID*3 + 1] = eta(1);\n    lmk_priors_eta_[lID*3 + 2] = eta(2);\n  }\n}\n\nvoid initialise_new_kf(std::vector<float>& cam_priors_eta_, std::vector<float>& lmk_priors_eta_,\n                       float* cam_beliefs_eta_, float* cam_beliefs_lambda_,\n                       std::vector<float> cam_priors_lambda_, std::vector<float> lmk_priors_lambda_,\n                       std::vector<unsigned int> lmk_weaken_flag_, \n                       unsigned data_counter, unsigned n_points)\n{\n  Matrix<float,6,1> previous_kf_eta = Map<Matrix<float,6,1>>(&cam_beliefs_eta_[data_counter * 6]);\n  Matrix<float,6,6> previous_kf_lam = Map<Matrix<float,6,6>>(&cam_beliefs_lambda_[data_counter * 36]);\n  VectorXf previous_kf_mu = previous_kf_lam.transpose().inverse() * previous_kf_eta;\n  Matrix<float,6,6> new_kf_lam = Map<Matrix<float,6,6>>(&cam_priors_lambda_[(data_counter + 1) * 36]);\n  VectorXf new_kf_eta = new_kf_lam.transpose() * previous_kf_mu;\n  for (unsigned i = 0; i < 6; ++i) {\n    cam_priors_eta_[(data_counter + 1) * 6 + i] = new_kf_eta(i);\n  }\n\n  // Use prior on keyframe for prior on newly observed landmarks\n  Vector3f previous_kf_w;\n  previous_kf_w << previous_kf_mu(3), previous_kf_mu(4), previous_kf_mu(5);\n  Matrix3f previous_kf_R_w2c = eigenso3exp(previous_kf_w);\n  Vector4f loc_cam_frame;\n  loc_cam_frame << 0.0, 0.0, 1.0, 1.0;\n  Matrix4f Tw2c;\n  Tw2c << previous_kf_R_w2c(0,0), previous_kf_R_w2c(0,1), previous_kf_R_w2c(0,2), previous_kf_mu(0),\n          previous_kf_R_w2c(1,0), previous_kf_R_w2c(1,1), previous_kf_R_w2c(1,2), previous_kf_mu(1),\n          previous_kf_R_w2c(2,0), previous_kf_R_w2c(2,1), previous_kf_R_w2c(2,2), previous_kf_mu(2),\n          0.0, 0.0, 0.0, 1.0;\n  Vector4f new_lmk_mu_wf_homog = Tw2c.inverse() * loc_cam_frame;\n  Vector3f new_lmk_mu_wf;\n  new_lmk_mu_wf << new_lmk_mu_wf_homog(0), new_lmk_mu_wf_homog(1), new_lmk_mu_wf_homog(2);\n  Matrix3f lmk_prior_lambda;\n  Vector3f new_lmk_eta;\n  for (unsigned i = 0; i < n_points; ++i) {\n    if (lmk_weaken_flag_[data_counter*n_points + i] == 5) {  // newly observed landmark\n      lmk_prior_lambda = Map<Matrix3f>(&lmk_priors_lambda_[i*9]);\n      new_lmk_eta = lmk_prior_lambda.transpose() * new_lmk_mu_wf;\n      for (unsigned j = 0; j < 3; ++j) {\n        lmk_priors_eta_[i * 3 + j] = new_lmk_eta(j);\n      }\n    }\n  }\n}\n\nfloat KL_divergence(VectorXf eta1, VectorXf eta2, MatrixXf lambda1, MatrixXf lambda2) {\n\n  VectorXf mu1 = lambda1.inverse() * eta1;\n  VectorXf mu2 = lambda2.inverse() * eta2;\n\n  float KL =  0.5 * ( (lambda2 * lambda1.inverse()).trace() + (mu2 - mu1).dot(lambda1 * (mu2 - mu1)) - eta1.size() \n              + log( lambda1.determinant() / lambda2.determinant() ) );\n\n  if (isnan(KL)) {\n    cout << \"was null\" << \"\\n\";\n    cout << eta1 << \"\\n\";\n    cout << lambda1 << \"\\n\";\n    cout << eta2 << \"\\n\";\n    cout << lambda2 << \"\\n\";\n  }\n\n\n  return KL;\n\n}\n\nfloat symmetricKL(VectorXf eta1, VectorXf eta2, MatrixXf lambda1, MatrixXf lambda2) {\n\n  return (KL_divergence(eta1, eta2, lambda1, lambda2) + KL_divergence(eta2, eta1, lambda2, lambda1)) / 2;\n\n}\n\n", "meta": {"hexsha": "5773664513ce3d08f57daafb3e4e1931b18cf0ab", "size": 8478, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ba/util.cpp", "max_stars_repo_name": "changh95/gbp-poplar", "max_stars_repo_head_hexsha": "68cf4019c3ee50ce55f2e5db67e8a7344da812b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2020-04-07T08:53:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:02:38.000Z", "max_issues_repo_path": "ba/util.cpp", "max_issues_repo_name": "changh95/gbp-poplar", "max_issues_repo_head_hexsha": "68cf4019c3ee50ce55f2e5db67e8a7344da812b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-02-01T17:58:21.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-01T17:58:21.000Z", "max_forks_repo_path": "ba/util.cpp", "max_forks_repo_name": "changh95/gbp-poplar", "max_forks_repo_head_hexsha": "68cf4019c3ee50ce55f2e5db67e8a7344da812b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-04-24T16:29:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-04T09:04:09.000Z", "avg_line_length": 33.6428571429, "max_line_length": 115, "alphanum_fraction": 0.6293937249, "num_tokens": 2901, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.913676530465412, "lm_q2_score": 0.7956581097540519, "lm_q1q2_score": 0.7269741411567502}}
{"text": "/*\n * @file\n * @author University of Warwick\n * @version 1.0\n *\n * @section LICENSE\n *\n * @section DESCRIPTION\n *\n * Unit Tests for the methods of the Triangle class\n */\n\n#define BOOST_TEST_MODULE Triangle\n#include <boost/test/unit_test.hpp>\n#include <boost/test/output_test_stream.hpp>\n#include <stdexcept>\n\n#include \"Triangle.h\"\n#include \"Triangle2D.h\"\n#include \"Triangle3D.h\"\n#include \"EuclideanPoint.h\"\n\nusing namespace cupcfd::geometry::shapes;\nnamespace euc = cupcfd::geometry::euclidean;\nnamespace utf = boost::unit_test;\n\n// === heronsFormula ===\n// Test 1: Test the area is computed correctly - 2D\nBOOST_AUTO_TEST_CASE(heronsFormula_test1, * utf::tolerance(0.00001))\n{\n\t// Setup\n\teuc::EuclideanPoint<double,2> p1(3.0, 4.0);\n\teuc::EuclideanPoint<double,2> p2(3.15, 12.0);\n\teuc::EuclideanPoint<double,2> p3(3.3, 4.0);\n\n\t// Test and Check\n\tdouble area = Triangle<Triangle2D<double>, double,2>::heronsFormula(p1, p2, p3);\n\tBOOST_TEST(area == 1.2);\n}\n\n// Test 2: Test the area is computed correctly - 2D\nBOOST_AUTO_TEST_CASE(heronsFormula_test2, * utf::tolerance(0.00001))\n{\n\t// Setup\n\teuc::EuclideanPoint<double,2> p1(3.0, 4.0);\n\teuc::EuclideanPoint<double,2> p2(6.0, 4.0);\n\teuc::EuclideanPoint<double,2> p3(3.0, 12.0);\n\n\t// Test and Check\n\tdouble area = Triangle<Triangle2D<double>, double,2>::heronsFormula(p1, p2, p3);\n\tBOOST_TEST(area == 12.0);\n}\n\n// Test 3: Test the area is computed correctly - 3D\nBOOST_AUTO_TEST_CASE(areaHeronsFormula_test3,  * utf::tolerance(0.00001))\n{\n\t// Setup\n\teuc::EuclideanPoint<double,3> p1(3.0, 4.0, 8.0);\n\teuc::EuclideanPoint<double,3> p2(3.15, 12.0, 14.0);\n\teuc::EuclideanPoint<double,3> p3(3.3, 4.0, 9.0);\n\n\t// Test and Check\n\tdouble area = Triangle<Triangle3D<double>, double,3>::heronsFormula(p1, p2, p3);\n\tBOOST_TEST(area == 4.25683);\n}\n\n// Test 4: Test the area is computed correctly - 3D\nBOOST_AUTO_TEST_CASE(areaHeronsFormula_test4,  * utf::tolerance(0.00001))\n{\n\t// Setup\n\teuc::EuclideanPoint<double,3> p1(3.0, 4.0, 8.9);\n\teuc::EuclideanPoint<double,3> p2(6.0, 4.0, 7.6);\n\teuc::EuclideanPoint<double,3> p3(3.0, 12.0, 15.4);\n\n\t// Test and Check\n\tdouble area = Triangle<Triangle3D<double>, double,3>::heronsFormula(p1, p2, p3);\n\tBOOST_TEST(area == 16.3126);\n}\n", "meta": {"hexsha": "85b7a04bae18982a1cbf1007932c005503c51ae0", "size": 2207, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/geometry/shapes/implementation/component/TriangleTests.cpp", "max_stars_repo_name": "thorbenlouw/CUP-CFD", "max_stars_repo_head_hexsha": "d06f7673a1ed12bef24de4f1b828ef864fa45958", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-06-24T10:20:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-18T14:43:19.000Z", "max_issues_repo_path": "tests/geometry/shapes/implementation/component/TriangleTests.cpp", "max_issues_repo_name": "thorbenlouw/CUP-CFD", "max_issues_repo_head_hexsha": "d06f7673a1ed12bef24de4f1b828ef864fa45958", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-07-22T15:31:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-28T14:27:28.000Z", "max_forks_repo_path": "tests/geometry/shapes/implementation/component/TriangleTests.cpp", "max_forks_repo_name": "thorbenlouw/CUP-CFD", "max_forks_repo_head_hexsha": "d06f7673a1ed12bef24de4f1b828ef864fa45958", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-22T15:24:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-22T15:24:24.000Z", "avg_line_length": 27.9367088608, "max_line_length": 81, "alphanum_fraction": 0.7018577254, "num_tokens": 778, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137296, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.7269741222645031}}
{"text": "/**\n * @file burgersequation.cc\n * @brief NPDE homework BurgersEquation code\n * @author Oliver Rietmann\n * @date 15.04.2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"burgersequation.h\"\n\n#include <Eigen/Core>\n#include <cmath>\n\nnamespace BurgersEquation {\n/* SAM_LISTING_BEGIN_1 */\nconstexpr double PI = 3.14159265358979323846;\n\ndouble Square(double x) { return x * x; }\n\ndouble f(double x) { return 2.0 / 3.0 * std::sqrt(x * x * x); }\n\nEigen::VectorXd solveBurgersGodunov(double T, unsigned int N) {\n  double h = 5.0 / N;           // meshwidth\n  double tau = h;               // timestep = meshwidth by CFL condition\n  int m = std::round(T / tau);  // no. of timesteps\n\n  // initialize vector with initial nodal values\n  Eigen::VectorXd x = Eigen::VectorXd::LinSpaced(N + 1, -1.0, 4.0);\n  Eigen::VectorXd mu =\n      x.unaryExpr([](double x) {\n         return 0.0 <= x && x <= 1.0 ? Square(std::sin(PI * x)) : 0.0;\n       }).eval();\n\n  for (int i=0; i<m; m++){\n    for (int int j= N; j>0; j--){\n      mu(j) = mu(j) -tau/h*(f(mu(j))-f(mu(j-1))); \n    }\n    mu(0)=0.0; \n  }\n  //====================\n  // Your code goes here\n\n  // implement the function that solves 11.1.2 based on the smi discretization developed in sub-problem 11-1g\n  // using N equispaced nodes xj in ipace interval -1, 4. \n  // fpr temporal discretization use explicit Euler timestepping with timestep tau=h, \n  //where h is the mesh width in space. \n  // the function is supposed to return nodal values (averages over dual cells) of the\n  // the solution at time T. \n  // for computingthe flux you may assume that the solution is zero outside the domian, uss the initial condition \n  // and find the mu(0) by simply sampling w0 at the nodes of mesh, outside -1,4 the solution is set to zero\n\n  //====================\n  return mu;\n}\n/* SAM_LISTING_END_1 */\n\n/**\n * @brief Converts a large vector on  a grid to a smaller vector correponding to\n * a sub-grid.\n *\n * @param mu vector of function values on a spacial grid of size N_large\n * @param N divides the size N_large of mu\n * @return a vector mu_sub of size N, that represents mu on a sub-grid of size N\n */\n/* SAM_LISTING_BEGIN_2 */\nEigen::VectorXd reduce(const Eigen::VectorXd &mu, unsigned int N) {\n  Eigen::VectorXd mu_sub(N + 1);\n  int fraction = mu.size() / N;\n  for (int j = 0; j < N + 1; ++j) {\n    mu_sub(j) = mu(j * fraction);\n  }\n  return mu_sub;\n}\n\nEigen::Matrix<double, 3, 4> numexpBurgersGodunov() {\n  const unsigned int N_large = 3200;\n  Eigen::Vector2d T{0.3, 3.0};\n  Eigen::Vector4i N{5 * 10, 5 * 20, 5 * 40, 5 * 80};\n  Eigen::Vector4d h;\n  for (int i = 0; i < 4; ++i) h(i) = 5.0 / N(i);\n\n  Eigen::Matrix<double, 3, 4> result;\n  result.row(0) = h.transpose();\n\n  //====================\n  // Your code goes here\n  //tabulate the discrete error norm as a\n  for (int k=0; k<1; k++){\n    Eigen::VectorXd mu_ref = solveBurgerGodunov(T(k), 3200); \n    Eigen::Vector4d error; \n    for (int i=0; i<4; i++){\n      Eigen::VectorXd mu_ref_sub = reduce(mu_ref, N(i)); \n      Eigen::VectorXd mu = solveBurgerGodunov(T(k), h(i)); \n      error(i) = (mu-mu_ref_sub).lpNorm<1>(); \n\u00df\n    }\n    result.row(k+1) = error.transpose();\n  }\n\n\n  //====================\n\n  return result;\n}\n/* SAM_LISTING_END_2 */\n\n}  // namespace BurgersEquation\n", "meta": {"hexsha": "836ef5ed55a25111bbad58015ed83430a39c69c4", "size": 3271, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/BurgersEquation/mysolution/burgersequation.cc", "max_stars_repo_name": "yiluchen1066/NPDECODES", "max_stars_repo_head_hexsha": "f7b1d96555bace59aba2b65f3ef1e95fa7a9017c", "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": "homeworks/BurgersEquation/mysolution/burgersequation.cc", "max_issues_repo_name": "yiluchen1066/NPDECODES", "max_issues_repo_head_hexsha": "f7b1d96555bace59aba2b65f3ef1e95fa7a9017c", "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": "homeworks/BurgersEquation/mysolution/burgersequation.cc", "max_forks_repo_name": "yiluchen1066/NPDECODES", "max_forks_repo_head_hexsha": "f7b1d96555bace59aba2b65f3ef1e95fa7a9017c", "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.287037037, "max_line_length": 114, "alphanum_fraction": 0.6178538673, "num_tokens": 1038, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473846343394, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7269485276609311}}
{"text": "// This section of program is the Levenberg-Marquardt solution to estimate 2 parameters of a and b.\r\n//and was modified from this source: https://github.com/SarvagyaVaish/Eigen-Levenberg-Marquardt-Optimization\r\n\r\n#include <iostream>\r\n#include <iomanip>\r\n#include <fstream>\r\n#include <sstream>\r\n#include <math.h>\r\n#include <Eigen/Eigen>\r\n\r\n#include <unsupported/Eigen/NonLinearOptimization>\r\nusing namespace std;\r\n\r\nstruct LMFunctor\r\n{\r\n\t// 'm' pairs of (x, f(x))\r\n\tEigen::MatrixXf measuredValues;\r\n\r\n\t// Compute 'm' errors, one for each data point, for the given parameter values in 'x'\r\n\tint operator()(const Eigen::VectorXf &x, Eigen::VectorXf &fvec) const\r\n\t{\r\n\t\t// 'x' has dimensions n x 1\r\n\t\t// It contains the current estimates for the parameters.\r\n\r\n\t\t// 'fvec' has dimensions m x 1\r\n\t\t// It will contain the error for each data point.\r\n\r\n\t\tfloat aParam = x(0);\r\n\t\tfloat bParam = x(1);\r\n\r\n\t\tfor (int i = 0; i < values(); i++) {\r\n\t\t\tfloat xValue = measuredValues(i, 0);\r\n\t\t\tfloat yValue = measuredValues(i, 1);\r\n\r\n\t\t\tfvec(i) = yValue - (1.0 / (1.0+ aParam * pow(xValue, 2*bParam)) );\r\n\t\t}\r\n\t\treturn 0;\r\n\t}\r\n\r\n\t// Compute the jacobian of the errors\r\n\tint df(const Eigen::VectorXf &x, Eigen::MatrixXf &fjac) const\r\n\t{\r\n\t\t// 'x' has dimensions n x 1\r\n\t\t// It contains the current estimates for the parameters.\r\n\r\n\t\t// 'fjac' has dimensions m x n\r\n\t\t// It will contain the jacobian of the errors, calculated numerically in this case.\r\n\r\n\t\tfloat epsilon;\r\n\t\tepsilon = 1e-5f;\r\n\r\n\t\tfor (int i = 0; i < x.size(); i++) {\r\n\t\t\tEigen::VectorXf xPlus(x);\r\n\t\t\txPlus(i) += epsilon;\r\n\t\t\tEigen::VectorXf xMinus(x);\r\n\t\t\txMinus(i) -= epsilon;\r\n\r\n\t\t\tEigen::VectorXf fvecPlus(values());\r\n\t\t\toperator()(xPlus, fvecPlus);\r\n\r\n\t\t\tEigen::VectorXf fvecMinus(values());\r\n\t\t\toperator()(xMinus, fvecMinus);\r\n\r\n\t\t\tEigen::VectorXf fvecDiff(values());\r\n\t\t\tfvecDiff = (fvecPlus - fvecMinus) / (2.0f * epsilon);\r\n\r\n\t\t\tfjac.block(0, i, values(), 1) = fvecDiff;\r\n\t\t}\r\n\r\n\t\treturn 0;\r\n\t}\r\n\r\n\t// Number of data points, i.e. values.\r\n\tint m;\r\n\r\n\t// Returns 'm', the number of values.\r\n\tint values() const { return m; }\r\n\r\n\t// The number of parameters, i.e. inputs.\r\n\tint n;\r\n\r\n\t// Returns 'n', the number of inputs.\r\n\tint inputs() const { return n; }\r\n\r\n};\r\n\r\n\r\n\r\n//\r\n// Goal\r\n//\r\n// Given a non-linear equation: f(x) = 1.0/(1.0+a*pow(x,2*b))\r\n// and 'm' data points (x1, f(x1)), (x2, f(x2)), ..., (xm, f(xm))\r\n// our goal is to estimate 'n' parameters (2 in this case: a, b)\r\n// using LM optimization.\r\n//\r\nvoid estimateParameters(float &a, float &b, float mindist, float spread, ofstream& logFile)\r\n{\r\n\r\n\tstd::vector<float> x_values;\r\n\tstd::vector<float> y_values;\r\n\r\n\t/**\r\n\t * The interval used for data fitting \r\n\t * The values were adopted from https://github.com/lmcinnes/umap/blob/master/umap/umap_.py#L1138\r\n\t */\r\n\tconst float minInterval=0;\r\n\tconst float maxInterval=3*spread;\r\n\tconst int intervalCounts=300;\r\n\r\n\r\n\tfor (int i = 0; i<intervalCounts; ++i){\r\n\r\n\t\tfloat tmp=minInterval+float(i)/float(intervalCounts)*(maxInterval-minInterval);    \r\n\t\tx_values.push_back(tmp);\r\n\r\n\t\tif (tmp <= mindist) y_values.push_back(1.0);\r\n\t\telse if (tmp > mindist) y_values.push_back(exp((mindist-tmp)/spread));\r\n\t\telse {\r\n\t\t\tlogFile<< \"Error: Negative x_values during Parameter Estimation\"<<endl;\r\n\t\t\tcout<< \"Error: Negative x_values during Parameter Estimation\"<<endl;\r\n\t\t}\r\n\t}\r\n\r\n\t// 'm' is the number of data points.\r\n\tint m = x_values.size();\r\n\r\n\t// Move the data into an Eigen Matrix.\r\n\t// The first column has the input values, x. The second column is the f(x) values.\r\n\tEigen::MatrixXf measuredValues(m, 2);\r\n\tfor (int i = 0; i < m; i++) {\r\n\t\tmeasuredValues(i, 0) = x_values[i];\r\n\t\tmeasuredValues(i, 1) = y_values[i];\r\n\t}\r\n\r\n\t// 'n' is the number of parameters (a and b) in the function.\r\n\tint n = 2;\r\n\r\n\t// 'x' is vector of length 'n' containing the initial values for the parameters.\r\n\t// The parameters 'x' are also referred to as the 'inputs' in the context of LM optimization.\r\n\t// The LM optimization inputs should not be confused with the x input values.\r\n\tEigen::VectorXf x(n);\r\n\tx(0) = 1.8;             // initial value for 'a'\r\n\tx(1) = 0.7;             // initial value for 'b'\r\n\r\n\t//\r\n\t// Run the LM optimization\r\n\t// Create a LevenbergMarquardt object and pass it the functor.\r\n\t//\r\n\r\n\tLMFunctor functor;\r\n\tfunctor.measuredValues = measuredValues;\r\n\tfunctor.m = m;\r\n\tfunctor.n = n;\r\n\r\n\tEigen::LevenbergMarquardt<LMFunctor, float> lm(functor);\r\n\tint status = lm.minimize(x);\r\n\tlogFile << \"LM optimization status: \" << status << std::endl;\r\n\tcout << \"LM optimization status: \" << status << std::endl;\r\n\t//\r\n\t// Results\r\n\t// The 'x' vector also contains the results of the optimization.\r\n\t//\r\n\tlogFile << \"Optimization results\" << std::endl;\r\n\tlogFile << \"\\ta: \" << x(0) << std::endl;\r\n\tlogFile << \"\\tb: \" << x(1) << std::endl;\r\n\tcout << \"Optimization results\" << std::endl;\r\n\tcout << \"\\ta: \" << x(0) << std::endl;\r\n\tcout << \"\\tb: \" << x(1) << std::endl;\r\n\r\n\ta=x(0);\r\n\tb=x(1);\r\n\r\n}\r\n", "meta": {"hexsha": "36e689716e09f891cf634b735ad202728a69d686", "size": 4958, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dimension_reduction/UMAP/Shared-Memory-OpenMP/LMOptimization.cpp", "max_stars_repo_name": "mmvih/polus-plugins", "max_stars_repo_head_hexsha": "c424938e3f35900758f7d74f3dfec2adfb3228fc", "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": "dimension_reduction/UMAP/Shared-Memory-OpenMP/LMOptimization.cpp", "max_issues_repo_name": "mmvih/polus-plugins", "max_issues_repo_head_hexsha": "c424938e3f35900758f7d74f3dfec2adfb3228fc", "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": "dimension_reduction/UMAP/Shared-Memory-OpenMP/LMOptimization.cpp", "max_forks_repo_name": "mmvih/polus-plugins", "max_forks_repo_head_hexsha": "c424938e3f35900758f7d74f3dfec2adfb3228fc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-26T19:23:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T19:23:57.000Z", "avg_line_length": 28.3314285714, "max_line_length": 109, "alphanum_fraction": 0.6327148044, "num_tokens": 1466, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.7266163310244513}}
{"text": "#include <iostream>\n#include <vector>\n\n#include <dlib/statistics.h>\n#include <sampml/data.hpp>\n\n#include \"common.hpp\"\n#include \"transform.hpp\"\n\ntemplate<class PositiveCont, class NegativeCont>\nvoid print_statistics(const PositiveCont& data_positive, const NegativeCont& data_negative) {\n    static_assert(PositiveCont::value_type::NR == NegativeCont::value_type::NR);\n\n    std::cout << \"Aggregate parameter(s) statistics:\\n\";\n    for(int i = 0; i < PositiveCont::value_type::NR; i++) {\n        dlib::running_stats<double> values;\n        for(const auto& v : data_positive)\n            values.add(v(i));\n        std::cout << \"positive field \" << i << \":\\n\";\n        std::cout << \"average: \" << values.mean() << \", stddev: \" << values.stddev() << '\\n'\n                  << \"min: \" << values.min() << \", max: \" << values.max()  << '\\n'\n                  << \"skewness: \" << values.skewness() << \", excess kurtosis: \" << values.ex_kurtosis() << \"\\n\\n\";\n        values.clear();\n\n        for(const auto& v : data_negative)\n            values.add(v(i));\n        std::cout << \"negative field \" << i << \":\\n\";\n        std::cout << \"average: \" << values.mean() << \", stddev: \" << values.stddev() << '\\n'\n                  << \"min: \" << values.min() << \", max: \" << values.max()  << '\\n'\n                  << \"skewness: \" << values.skewness() << \", excess kurtosis: \" << values.ex_kurtosis() << '\\n';\n        \n        std::cout << \"\\n\\n\";\n    }\n}\n\nint main () {\n    using sample_type = output_vector;\n    sampml::data::reader<sample_type> data_positive_train(positive_train_data);\n    sampml::data::reader<sample_type> data_positive_test(positive_test_data);\n\n    std::vector<sample_type> data_positive;\n    data_positive.insert(data_positive.end(), data_positive_train.begin(), data_positive_train.end());\n    data_positive.insert(data_positive.end(), data_positive_test.begin(), data_positive_test.end());\n\n    sampml::data::reader<sample_type> data_negative_train(negative_train_data);\n    sampml::data::reader<sample_type> data_negative_test(negative_test_data);   \n\n    std::vector<sample_type> data_negative;\n    data_negative.insert(data_negative.end(), data_negative_train.begin(), data_negative_train.end());\n    data_negative.insert(data_negative.end(), data_negative_test.begin(), data_negative_test.end());\n\n    print_statistics(data_positive, data_negative);\n    return 0;\n}", "meta": {"hexsha": "710f28bee89474d7a27be3269ccdbd15ca3e19a0", "size": 2375, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/anti-aimbot/training/analyzer.cpp", "max_stars_repo_name": "YashasSamaga/sampml", "max_stars_repo_head_hexsha": "dc84110b53b120caeeb4c0234fcfd6ab16793c59", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2018-12-01T18:30:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-08T21:53:36.000Z", "max_issues_repo_path": "examples/anti-aimbot/training/analyzer.cpp", "max_issues_repo_name": "YashasSamaga/sampml", "max_issues_repo_head_hexsha": "dc84110b53b120caeeb4c0234fcfd6ab16793c59", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-08-21T17:52:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-17T03:28:11.000Z", "max_forks_repo_path": "examples/anti-aimbot/training/analyzer.cpp", "max_forks_repo_name": "YashasSamaga/sampml", "max_forks_repo_head_hexsha": "dc84110b53b120caeeb4c0234fcfd6ab16793c59", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-09-04T14:53:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T17:53:33.000Z", "avg_line_length": 43.9814814815, "max_line_length": 114, "alphanum_fraction": 0.6307368421, "num_tokens": 573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.8031737940012417, "lm_q1q2_score": 0.7265915983928186}}
{"text": "#include \"convergence.hpp\"\n#include \"dofs.hpp\"\n#include \"fem_solve.hpp\"\n#include \"writer.hpp\"\n#include <Eigen/Core>\n#include <igl/readMESH.h>\n#include <igl/readSTL.h>\n#include <igl/slice.h>\n#include <igl/slice_into.h>\n#include <sstream>\n\ntypedef Eigen::VectorXd Vector;\n\ndouble f_square(double x, double y) {\n\treturn 2 * M_PI * M_PI * sin(M_PI * x) * sin(M_PI * y);\n}\n\ndouble uex_square(double x, double y) {\n\treturn sin(M_PI * x) * sin(M_PI * y);\n}\n\nEigen::Vector2d uex_grad_square(double x, double y) {\n\tEigen::Vector2d grad;\n\tgrad << M_PI * cos(M_PI * x) * sin(M_PI * y),\n\t    M_PI * sin(M_PI * x) * cos(M_PI * y);\n\treturn grad;\n}\n\nint main(int, char **) {\n\ttry {\n\t\tVector u;\n\n\t\tEigen::MatrixXd vertices;\n\t\tEigen::MatrixXi triangles;\n\t\tEigen::MatrixXi tetrahedra;\n\n\t\tigl::readMESH(NPDE_DATA_PATH \"square_5.mesh\", vertices, tetrahedra, triangles);\n\n\t\tQDofs quadraticDofs(vertices, triangles);\n\t\tsolveFiniteElement(u, quadraticDofs, f_square);\n\n\t\twriteToFile(\"square_values.txt\", u.segment(0, vertices.rows()));\n\t\twriteMatrixToFile(\"square_vertices.txt\", vertices);\n\t\twriteMatrixToFile(\"square_triangles.txt\", triangles);\n\n\t\tconvergenceAnalysis(\"square\", 7, f_square, uex_square, uex_grad_square);\n\n\t} catch (std::runtime_error &e) {\n\t\tstd::cerr << \"An error occurred. Error message: \" << std::endl;\n\t\tstd::cerr << \"    \\\"\" << e.what() << \"\\\"\" << std::endl;\n\t\treturn EXIT_FAILURE;\n\t} catch (...) {\n\t\tstd::cerr << \"An unknown error occurred.\" << std::endl;\n\t\tthrow;\n\t}\n\n\treturn EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "4ef32faf19b285f20a788a122e5cce8ff38c3c67", "size": 1494, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "series3/2d-poissonqFEM/fem2d.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": "series3/2d-poissonqFEM/fem2d.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": "series3/2d-poissonqFEM/fem2d.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": 25.3220338983, "max_line_length": 81, "alphanum_fraction": 0.6773761714, "num_tokens": 437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299612154571, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.726591027836946}}
{"text": "#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <vector>\n//#include <boost/multiprecision/mpfr.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/math/special_functions/bessel.hpp>\n#define PREC 300    //change this to set precision\n\nusing namespace boost::multiprecision;\n\ntypedef number<cpp_dec_float<PREC> > big_float;\n\nbig_float dpii_iter( big_float current, big_float previous, big_float alpha, big_float beta, big_float gamma, int n )\n{\n  return (current * (alpha * n + beta)) / (1 - current * current) - previous; \n}\n\nbig_float initval( big_float lambda )\n{\n  using namespace boost::math;\n  return cyl_bessel_i(1, lambda) / cyl_bessel_i(0, lambda);\n}\n\nbig_float jac_offdiag( big_float a, big_float b, big_float c )\n{\n  return (1 - a)*(1 - b * b)*(1 + c);\n}\n\nbig_float jac_diag( big_float a, big_float b, big_float c )\n{\n  return (1 - b)*a - (1 + b)*c;\n}\n\nint compute_verb ( std::vector<big_float > &verblunsky, big_float lambda, bool use_bessel, double init )\n{\n  std::cout << \"Computing verblunsky coefficients: initializing...\" << std::endl;\n  big_float coeff = -1*(2 / lambda);\n  if (use_bessel)\n    verblunsky[0] = initval( lambda );\n  else\n    verblunsky[0] = init;\n  verblunsky[1] = dpii_iter( verblunsky[0], (big_float) -1, coeff, coeff, (big_float) 0, 0 );\n  int kmax = verblunsky.size() - 1;\n  std::cout << \"Computing verblunsky coefficients: iterating...\" << std::endl;\n  for (int k = 2; k <= kmax; k++)\n  {\n    verblunsky[k] = dpii_iter( verblunsky[k-1], verblunsky[k-2], coeff, coeff, (big_float) 0, (k-1) );\n  }\n  std::cout << \"Done computing verblunsky coefficients.\" << std::endl;\n  return 0;\n}\n\nint compute_jac ( std::vector<big_float > &diag, std::vector<big_float > &offdiag, const std::vector<big_float > & verblunsky )\n{\n  std::cout << \"Computing jacobi coefficients: initializing...\" << std::endl;\n  int kmax = offdiag.size() - 1;\n  diag[0] = jac_diag( verblunsky[1], verblunsky[0], (big_float) -1 );\n  offdiag[0] = 2 * verblunsky[0];\n  std::cout << \"Computing jacobi coefficients: iterating...\" << std::endl;\n  for (int k = 1; k <= kmax; k++)\n  {\n    diag[k] = jac_diag( verblunsky[2*k], verblunsky[2*k - 1], verblunsky[2*k - 2] );\n    offdiag[k] = jac_offdiag( verblunsky[2*k + 1], verblunsky[2*k], verblunsky[2*k - 1] );\n  }\n  std::cout << \"Done computing jacobi coefficients.\" << std::endl;\n  return 0;\n}\n\nint writeout_csv( std::string fname, int out_digits, std::vector<big_float> verblunsky, std::vector<big_float> diag, std::vector<big_float> offdiag )\n{\n  std::cout << \"Writing to file...\" << std::endl;\n  int terms = (int) verblunsky.size() / 2 - 1;\n  std::ofstream outfile{fname};\n  outfile << \"Index alpha b square(a) diagnostic(1-sq(a))\" << std::endl;\n  outfile << std::setprecision(out_digits);\n//  outfile << std::setprecision(std::numeric_limits<big_float>::maxdigits10);\n  for (int k = 0; k < terms; k++)\n  {\n    big_float diagnostic;\n    diagnostic = log(abs(1. - offdiag[k]));\n    outfile << k << \" \" << verblunsky[k] << \" \" << diag[k] << \" \" << offdiag[k] << \" \" << diagnostic << std::endl;\n  }\n  outfile.close();\n  return 0;\n}\n\nint get_input( int &digits, int &terms, double &lambda, std::string &fname, double &init_val, bool &use_bessel )\n{\n  std::string s;\n  while (true) \n  {\n    std::cout << \"Enter number of digits to output: \" << std::endl;\n    std::getline(std::cin, s);\n    std::stringstream instr(s);\n    if (instr >> digits)\n      break;\n    std::cout << \"Input should be an integer: \" << std::endl;\n  }\n  while (true) \n  {\n    std::cout << \"Enter number of terms to compute: \" << std::endl;\n    std::getline(std::cin, s);\n    std::stringstream instr(s);\n    if (instr >> terms)\n      break;\n    std::cout << \"Input should be an integer: \" << std::endl;\n  }\n  while (true) \n  {\n    std::cout << \"Enter value of lambda to use: \" << std::endl;\n    std::getline(std::cin, s);\n    std::stringstream instr(s);\n    if (instr >> lambda)\n      break;\n    std::cout << \"Input should be a float: \" << std::endl;\n  }\n  while (true) \n  {\n    std::cout << \"Use mod bessel initial condition? (y/n) \" << std::endl;\n    std::getline(std::cin, s);\n    if (s == \"y\")\n    {\n      use_bessel = true;\n      break;\n    }\n    if (s == \"n\")\n    {\n      use_bessel = false;\n      break;\n    }\n    std::cout << \"Input should be (y/n) \" << std::endl;\n  }\n  if (!use_bessel)\n  {\n    while (true) \n    {\n      std::cout << \"Enter alternative initial value: \" << std::endl;\n      std::getline(std::cin, s);\n      std::stringstream instr(s);\n      if (instr >> init_val)\n        break;\n      std::cout << \"Input should be a float: \" << std::endl;\n    }\n  }\n  std::cout << \"Enter output filename: \" << std::endl;\n  std::getline(std::cin, fname);\n}\n\nint main(int argc, char *argv[])\n{\n\n  int digits;\n  int terms;\n  double lambda_in;\n  std::string fname;\n  bool use_bessel;\n  double init_val;\n\n  get_input( digits, terms, lambda_in, fname, init_val, use_bessel );\n//  big_float::default_precision(digits);\n  big_float lambda(lambda_in);\n\n  int jterms = (terms / 2) - 1;\n  std::vector<big_float > verblunsky(terms);\n  std::vector<big_float > diag(jterms);\n  std::vector<big_float > offdiag(jterms); \n\n  compute_verb (verblunsky, lambda, use_bessel, init_val );\n  compute_jac (diag, offdiag, verblunsky);\n  writeout_csv( fname, digits, verblunsky, diag, offdiag );\n  return 0;\n}\n\n\n\n\n", "meta": {"hexsha": "28c814f89a66caa7b188cd96829e4bd6332a5072", "size": 5344, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/examples/mbessel.cc", "max_stars_repo_name": "dtaquinas/Measures", "max_stars_repo_head_hexsha": "0630e343e81051381dcb223a3290fe242180d617", "max_stars_repo_licenses": ["BSL-1.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": "src/examples/mbessel.cc", "max_issues_repo_name": "dtaquinas/Measures", "max_issues_repo_head_hexsha": "0630e343e81051381dcb223a3290fe242180d617", "max_issues_repo_licenses": ["BSL-1.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": "src/examples/mbessel.cc", "max_forks_repo_name": "dtaquinas/Measures", "max_forks_repo_head_hexsha": "0630e343e81051381dcb223a3290fe242180d617", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0224719101, "max_line_length": 149, "alphanum_fraction": 0.6274326347, "num_tokens": 1674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086367, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.7265719783617126}}
{"text": "#define BOOST_TEST_MODULE Logic test\n#include <boost/test/unit_test.hpp>\n\n#include \"Variable.h\"\n\nusing namespace omnn::math;\nusing namespace boost::unit_test;\n\nBOOST_AUTO_TEST_CASE(logic_or_tests)\n{\n    auto x = \"x\"_va;\n    auto eq = x.Equals(1).logic_or(x.Equals(2)).logic_or(x.Equals(3));\n    auto ok = eq(x);\n    auto set = Valuable({1_v, 2_v, 3_v});\r\n    BOOST_TEST(ok == set);\r\n}\n\nBOOST_AUTO_TEST_CASE(ifz_tests)\n{\n    // two different bits\n    // if a=0 then b=1 else b=0\n    // if a=1 then b=0 else b=1\n    Variable a,b;\n    auto e = a.Equals(1).Ifz(b.Equals(0), b.Equals(1));\n    {\n        auto ee = e;\n        ee.Eval(a, 0);\n        ee.Eval(b, 1);\n        ee.optimize();\n        BOOST_TEST(ee==0);\n    }\n    {\n        auto ee = e;\n        ee.Eval(a, 1);\n        ee.Eval(b, 0);\n        ee.optimize();\n        BOOST_TEST(ee==0);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(not_tests\n    ,*disabled() //TODO:\n)\n{\n    auto x = \"x\"_va;\n    auto x_eq_1 = x-1;\n    auto x_ne_1 = !x_eq_1; //!x; // must mean all except this equation\n    std::cout << x_ne_1 << std::endl;\n    auto eval_x_eq_1 = x_eq_1;\n    eval_x_eq_1.Eval(x, 1);\n    auto ok = eval_x_eq_1 == 0_v;\n    BOOST_TEST(ok);\n\n    auto eval_x_ne_1 = x_ne_1;\n    eval_x_ne_1.Eval(x, 7);\n    ok = eval_x_ne_1 != 0_v;\n    BOOST_TEST(ok);\n}\n\nBOOST_AUTO_TEST_CASE(test_logic_intersection)\n{\n    Variable x;\n    auto _1 = x.Abet({1,2,3,3});\n    auto _2 = x.Abet({2,3,3});\n    auto _ = _1.Intersect(_2, x);\n\n    auto solutions = _.IntSolutions(x);\n    if(solutions.size() != 2)\n\t\tfor (auto& s : solutions){\n\t\t\tstd::cout << s << std::endl;\n\t\t}\n    decltype(solutions) check = { 2, 3 };\n    BOOST_TEST(solutions == check);\n}\n\nBOOST_AUTO_TEST_CASE(test_logic_intersection_with_exception\n    ,*disabled() //TODO:\n)\n{\n    Variable x;\n    auto _1 = x.Abet({1,2,3,3});\n    auto _2 = x.Abet({2,3,3});\n    auto _ = _1.Intersect(_2, x).logic_and(x.NotEquals(3));\n    \n    auto solutions = _.IntSolutions(x);\n    if(solutions.size() != 1)\n\t\tfor (auto& s : solutions){\n\t\t\tstd::cout << s << std::endl;\n\t\t}\n    BOOST_TEST(solutions.size() == 1);\n    if(solutions.size()){\n        _ = *solutions.begin();\n        BOOST_TEST(_ == 2);\n    }\n}\n\n#include \"Sum.h\"\n\nBOOST_AUTO_TEST_CASE(test_logic_intersection_simplifying\n                      ,*disabled()\n                     )\n{\n    Variable x;\n    auto _1 = x.Abet({1,2});\n    auto _2 = x.Abet({2,3});\n    auto i = _1.Intersect(_2, x);\n    auto solutions = i.IntSolutions(x);\n    BOOST_TEST(solutions.size() == 1);\n    auto _ = *solutions.begin();\n    BOOST_TEST(_ == 2);\n    BOOST_TEST(i.IsSum());\n    auto& sum = i.as<Sum>();\n    std::vector<Valuable> coefficients;\n    auto grade = sum.FillPolyCoeff(coefficients, x);\n    BOOST_TEST(grade == 1);\n}\n", "meta": {"hexsha": "5da24a2f2d91632bfc2d9f7fa59798f45f4fe28c", "size": 2723, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "omnn/math/test/logic.cpp", "max_stars_repo_name": "iHateInventNames/openmind", "max_stars_repo_head_hexsha": "2587b811e594daf9d9c235cb63eeae2950e93ff0", "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": "omnn/math/test/logic.cpp", "max_issues_repo_name": "iHateInventNames/openmind", "max_issues_repo_head_hexsha": "2587b811e594daf9d9c235cb63eeae2950e93ff0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2016-05-21T08:48:41.000Z", "max_issues_repo_issues_event_max_datetime": "2017-02-22T19:37:03.000Z", "max_forks_repo_path": "omnn/math/test/logic.cpp", "max_forks_repo_name": "iHateInventNames/openmind", "max_forks_repo_head_hexsha": "2587b811e594daf9d9c235cb63eeae2950e93ff0", "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.2735042735, "max_line_length": 70, "alphanum_fraction": 0.5769372016, "num_tokens": 862, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314624993576759, "lm_q2_score": 0.7799929104825006, "lm_q1q2_score": 0.726534145879298}}
{"text": "#pragma once\n\n//! All the number theory goes in here\n\n#include <boost/multiprecision/gmp.hpp>\n\nnamespace rubbishrsa {\n  // Saves me a lot of typing\n  namespace bmp = boost::multiprecision;\n  using bigint = bmp::mpz_int;\n\n  // Extended Euclid's algorithm is the name of this algorithm (I think)\n  struct egcd_result { bigint gcd; std::pair<bigint, bigint> coefficients; };\n  egcd_result egcd(const bigint& a, const bigint& b);\n\n  // This is actually implemented in the numeric library I have used, but that would be cheating\n  /// Performs the Miller-Rabin primality check `certainty_log_2` times\n  bool is_prime(const bigint& candidate, uint_fast8_t certainty_log_4 = 64);\n\n  /// Generates a prime that is at least 2^(bits - 1) long.\n  //\n  // Apparently \"strong primes\" are better, but computing these is much harder, and RSA say they are unnecceary\n  //\n  // Because RSA (company) can be trusted. Yes.\n  bigint generate_prime(uint_fast16_t bits);\n\n  /// Calculate the lowest common multiple of two numbers\n  bigint lcm(const bigint& a, const bigint& b);\n\n  // Calculating Carmichael's function for an arbitrary number is complex and pointless\n  //\n  // Instead, we can just calculate it for our special case\n  inline bigint carmichael_semiprime(const bigint& p, const bigint& q) {\n    return lcm(p - 1, q - 1);\n  }\n\n  // Again, exists in our library, but I don't want to cheat\n  /// Computes a^(-1) mod n\n  bigint modinv(const bigint& a, const bigint& n);\n\n  /// An implementation of Pollard's rho algorithm\n  ///\n  /// @param a: the x^0 term of the polynomial\n  bigint pollard_rho(const bigint& n);\n\n  /// Selects the fastest implemented factorisation algorithm for the given semiprime, and returns the factors\n  std::pair<bigint, bigint> factorise_semiprime(const bigint& semiprime);\n\n  // Some functions that convert between ascii and bigint\n  bigint ascii2bigint(std::string_view str);\n  bigint ascii2bigint(std::istream& str);\n  std::string bigint2ascii(bigint str);\n  bigint hex2bigint(std::string_view hex);\n\n  inline size_t floor_log2(bigint i) {\n    size_t bits = 0;\n    while (i) {\n      i >>= 1;\n      ++bits;\n    }\n    return bits;\n  }\n}\n", "meta": {"hexsha": "375c2ae9da9f395be9aca1711dd7875756f119db", "size": 2152, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/rubbishrsa/maths.hpp", "max_stars_repo_name": "Cyclic3/rubbishrsa", "max_stars_repo_head_hexsha": "d1755b6ed464c84fa7a44e8665631f28766ee7fb", "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/rubbishrsa/maths.hpp", "max_issues_repo_name": "Cyclic3/rubbishrsa", "max_issues_repo_head_hexsha": "d1755b6ed464c84fa7a44e8665631f28766ee7fb", "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": "include/rubbishrsa/maths.hpp", "max_forks_repo_name": "Cyclic3/rubbishrsa", "max_forks_repo_head_hexsha": "d1755b6ed464c84fa7a44e8665631f28766ee7fb", "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.625, "max_line_length": 111, "alphanum_fraction": 0.7105018587, "num_tokens": 558, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625126757597, "lm_q2_score": 0.7799928900257126, "lm_q1q2_score": 0.7265341372125778}}
{"text": "/**\n * @file engquistoshernumericalflux.cc\n * @brief NPDE homework \"EngquistOsherNumericalFlux\" code\n * @author Oliver Rietmann\n * @date 23.04.2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"engquistoshernumericalflux.h\"\n\n#include <Eigen/Core>\n#include <algorithm>\n#include <cmath>\n\nnamespace EngquistOsherNumericalFlux {\n\n/* SAM_LISTING_BEGIN_1 */\ndouble EngquistOsherNumFlux(double v, double w) {\n  double result;\n  //====================\n  // Your code goes here\n  if(v>=0 && w>=0){\n    result=std::cosh(v); \n  } else if (w>0 && v<=0){\n    result=std::cosh(v)+std::cosh(0); \n  } else if (w<0 && v>=0){\n    result=std::cosh(v)+std::cosh(w)-std::cosh(0); \n  } else if (w<0 && v<0){\n    result=std::cosh(w); \n  }\n  //====================\n  return result;\n}\n/* SAM_LISTING_END_1 */\n\n/* SAM_LISTING_BEGIN_2 */\nEigen::VectorXd solveCP(double a, double b, Eigen::VectorXd u0, double T) {\n  // Find the maximal speed of propagation\n  double A = u0.minCoeff();\n  double B = u0.maxCoeff();\n  double K = std::max(std::abs(std::sinh(A)), std::abs(std::sinh(B)));\n  // Set uniform timestep according to CFL condition\n  int N = u0.size();\n  double h = (b - a) / N;\n  double tau_max = h / K;\n  double timesteps = std::ceil(T / tau_max);\n  double tau = T / timesteps;\n\n  // Main timestepping loop\n  //====================\n  // Your code goes here\n  for (int i = 0; i < timesteps; i++)\n  {\n    u0(0)=u0(0)-tau/h*(EngquistOsherNumericalFlux(u0(0),u0(1))-EngquistOsherNumericalFlux(u0(0),u0(0))); \n    for (int j=1; i<N-1; j++){\n      u0(j)=u0(j) - tau/h*(EngquistOsherNumFlux(u0(j),u0(j+1))-EngquistOsherNumFlux(u0(j-1),u0(j))); \n    }\n    u0(N-1)=u0(N-1)-tau/h*(EngquistOsherNumericalFlux(u0(N-1),u0(N-1))-EngquistOsherNumericalFlux(u0(N-2),u0(N-1)));    /* code */\n  }\n\n  //===================//\n  return u0;\n}\n/* SAM_LISTING_END_2 */\n\n}  // namespace EngquistOsherNumericalFlux\n", "meta": {"hexsha": "2fac6941b9cd6c6ebcf6b07f324ded647496121b", "size": 1876, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/EngquistOsherNumericalFlux/mysolution/engquistoshernumericalflux.cc", "max_stars_repo_name": "yiluchen1066/NPDECODES", "max_stars_repo_head_hexsha": "f7b1d96555bace59aba2b65f3ef1e95fa7a9017c", "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": "homeworks/EngquistOsherNumericalFlux/mysolution/engquistoshernumericalflux.cc", "max_issues_repo_name": "yiluchen1066/NPDECODES", "max_issues_repo_head_hexsha": "f7b1d96555bace59aba2b65f3ef1e95fa7a9017c", "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": "homeworks/EngquistOsherNumericalFlux/mysolution/engquistoshernumericalflux.cc", "max_forks_repo_name": "yiluchen1066/NPDECODES", "max_forks_repo_head_hexsha": "f7b1d96555bace59aba2b65f3ef1e95fa7a9017c", "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.0, "max_line_length": 130, "alphanum_fraction": 0.6082089552, "num_tokens": 649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772253241803, "lm_q2_score": 0.831143045767024, "lm_q1q2_score": 0.7264832072915286}}
{"text": "#include \"bayesclassifier.h\"\n\n#include <algorithm> // for std::max_element\n#include <cassert>\n\n#include <Eigen/LU>\n\n#include \"algorithm.h\"\n\nusing Eigen::VectorXd;\nusing Eigen::MatrixXd;\nusing std::vector;\n\ndouble multivariate_normal_pd(const VectorXd& x,\n                              const VectorXd& mu,\n                              const MatrixXd& sigma) {\n    // XXX would be more efficient to pre-compute sigma.inverse() and\n    // sigma.determinant()\n    double d = x.size();\n    VectorXd v = x - mu;\n    double a = pow(2.0 * M_PI, d/2.0);\n    double b = sqrt(sigma.determinant());\n    double c = v.transpose() * sigma.inverse() * v;\n    return (1.0 / (a*b)) * exp( - c / 2.0);\n}\n\nBayesClassifier::BayesClassifier(const vector<VectorXd>& x,\n                                 const vector<int>& y) :\nk(0), p(), mu(), sigma() {\n    // n is the number of points\n    unsigned n = x.size();\n    assert(n > 0);\n    assert(y.size() == n);\n\n    // d is the dimensionality\n    int d = x[0].size();\n    for (const VectorXd& v : x)\n        assert(v.size() == d);\n\n    // number of classes\n    k = *(std::max_element(y.cbegin(), y.cend())) + 1;\n\n    for (int i = 0; i < k; ++i) {\n        // find all points in class i\n        vector<VectorXd> xi;\n        for (unsigned j = 0; j < n; ++j)\n            if (y[j] == i)\n                xi.push_back(x[j]);\n\n        // ni is the number of points in class i\n        unsigned ni = xi.size();\n        assert(ni > 0);\n\n        // prior probability\n        p.push_back((double)ni / (double)n);\n\n        // class mean\n        VectorXd m = VectorXd::Zero(d);\n        for (const VectorXd& v : xi)\n            m += v;\n        m /= ni;\n        mu.push_back(m);\n\n        // centered data matrix\n        MatrixXd z(d, ni);\n        for (unsigned j = 0; j < ni; ++j)\n            z.col(j) = xi[j] - m;\n\n        // covariance matrix\n        sigma.push_back((1.0/(double)ni) * z * z.transpose());\n    }\n}\n\nint BayesClassifier::predict(const VectorXd& x) const {\n    return arg_max(0, k, [&x,this](int i) {\n        return multivariate_normal_pd(x, mu[i], sigma[i]) * p[i];\n    });\n}\n\nint BayesClassifier::nClasses() const {\n    return k;\n}\ndouble BayesClassifier::priorProbability(int i) const {\n    return p[i];\n}\nVectorXd BayesClassifier::mean(int i) const {\n    return mu[i];\n}\nMatrixXd BayesClassifier::covarianceMatrix(int i) const {\n    return sigma[i];\n}\n", "meta": {"hexsha": "aca10de76bd23a6928edcecd9b2dbee27c2b3de6", "size": 2381, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/bayesclassifier.cpp", "max_stars_repo_name": "lfritz/data-mining-and-analysis", "max_stars_repo_head_hexsha": "f92aba784f2a8a0e8c02f6b8d3adf5bdf884fed7", "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/bayesclassifier.cpp", "max_issues_repo_name": "lfritz/data-mining-and-analysis", "max_issues_repo_head_hexsha": "f92aba784f2a8a0e8c02f6b8d3adf5bdf884fed7", "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/bayesclassifier.cpp", "max_forks_repo_name": "lfritz/data-mining-and-analysis", "max_forks_repo_head_hexsha": "f92aba784f2a8a0e8c02f6b8d3adf5bdf884fed7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-06T19:20:37.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-06T19:20:37.000Z", "avg_line_length": 25.8804347826, "max_line_length": 69, "alphanum_fraction": 0.5443091138, "num_tokens": 649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.7264776368897848}}
{"text": "#include \"Gaussian.h\"\n#include <iostream>\n#include <stdexcept>\n#include <cmath>\n#include \"../Utils.h\"\n//#include <boost/math/special_functions/erf.hpp>\n\nnamespace DNest4\n{\n\nGaussian::Gaussian(double center, double width)\n:center(center)\n,width(width)\n{\n    if(width <= 0.0)\n        throw std::domain_error(\"Gaussian distribution must have positive width.\");\n}\n\ndouble Gaussian::cdf(double x) const\n{\n    return normal_cdf((x-center)/width);\n}\n\ndouble Gaussian::cdf_inverse(double x) const\n{\n    if(x < 0.0 || x > 1.0)\n        throw std::domain_error(\"Input to cdf_inverse must be in [0, 1].\");\n    return center + width*normal_inverse_cdf(x);\n    //return center + width * sqrt(2) * boost::math::erf_inv(2*x - 1);\n}\n\ndouble Gaussian::log_pdf(double x) const\n{\n\tdouble r = (x - center)/width;\n    return -0.5*r*r - _norm_pdf_logC;\n}\n\n\n} // namespace DNest4", "meta": {"hexsha": "05ad68f818c13e71722db835229f697093e90184", "size": 855, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/Distributions/Gaussian.cpp", "max_stars_repo_name": "modsim/DNest4", "max_stars_repo_head_hexsha": "4de91f440cd0455893e59da1ac5031399e5c0969", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 54.0, "max_stars_repo_stars_event_min_datetime": "2016-01-20T10:00:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T14:38:11.000Z", "max_issues_repo_path": "code/Distributions/Gaussian.cpp", "max_issues_repo_name": "modsim/DNest4", "max_issues_repo_head_hexsha": "4de91f440cd0455893e59da1ac5031399e5c0969", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 30.0, "max_issues_repo_issues_event_min_datetime": "2016-03-07T21:36:37.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-14T19:33:46.000Z", "max_forks_repo_path": "code/Distributions/Gaussian.cpp", "max_forks_repo_name": "modsim/DNest4", "max_forks_repo_head_hexsha": "4de91f440cd0455893e59da1ac5031399e5c0969", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2016-01-21T13:37:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-14T17:23:45.000Z", "avg_line_length": 21.9230769231, "max_line_length": 83, "alphanum_fraction": 0.6725146199, "num_tokens": 238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242132, "lm_q2_score": 0.7981867801399695, "lm_q1q2_score": 0.7262757472763818}}
{"text": "// Copyright Yamaha 2021\n// MIT License\n// https://github.com/yamaha-bps/cbr_math/blob/master/LICENSE\n\n#ifndef CBR_MATH__INTERP__PIECEWISE_LINEAR_HPP_\n#define CBR_MATH__INTERP__PIECEWISE_LINEAR_HPP_\n\n#include <Eigen/Dense>\n\n#include <utility>\n#include <vector>\n#include <array>\n\n#include \"piecewise_poly.hpp\"\n\nnamespace cbr\n{\n\nclass PiecewiseLinear\n{\nprotected:\n  using row_t = Eigen::Matrix<double, 1, Eigen::Dynamic>;\n  using matrix_t = Eigen::MatrixXd;\n\npublic:\n  /**\n   * @brief Create a scalar-valued piecewise linear polynomial\n   *\n   * @tparam T1 PiecewisePoly::row_t\n   * @tparam T2 PiecewisePoly::row_t\n   * @param x sorted breakpoints\n   * @param y values\n   *\n   * The resulting function f is s.t.\n   *  f(t) = y[i] + alpha * (y[i+1] - y[i]) if x[i] <= t < x[i+1]\n   *     where alpha = (t - x[i]) / (x[i+1] - x[i])\n   *  f(t) = y[0] if t < x[0]\n   *  f(t) = y[x.size() - 1] if t >= x[x.size() - 1]\n   */\n  template<typename T1, typename T2>\n  static PiecewisePoly fit(\n    T1 && x,\n    const Eigen::DenseBase<T2> & y)\n  {\n    static_assert(is_eigen_dense_v<T1>, \"x must be an Eigen::DenseBase object.\");\n\n    auto coeffs = generateCoeffs(x, y);\n    return PiecewisePoly(std::forward<T1>(x), std::move(coeffs));\n  }\n\n  /**\n   * @brief Create a vector-valued piecewise linear polynomial\n   *\n   * @tparam T1 PiecewisePoly::row_t\n   * @tparam T2 PiecewisePoly::matrix_t or container_t<PiecewisePoly::row_t>\n   * @param x sorted breakpoints\n   * @param y values\n   *\n   * The resulting function f is s.t.\n   *  f(t) = y[i] + alpha * (y[i+1] - y[i]) if x[i] <= t < x[i+1]\n   *     where alpha = (t - x[i]) / (x[i+1] - x[i])\n   *  f(t) = y[0] if t < x[0]\n   *  f(t) = y[x.size() - 1] if t >= x[x.size() - 1]\n   */\n  template<typename T1, typename T2>\n  static PiecewisePolyND fitND(\n    T1 && x,\n    const T2 & ys)\n  {\n    static_assert(is_eigen_dense_v<T1>, \"x must be an Eigen::DenseBase object.\");\n\n    if (x.size() < 2) {\n      throw std::invalid_argument(\"x must be of size > 1.\");\n    }\n\n    std::vector<matrix_t> coefLists;\n\n    if constexpr (is_eigen_dense_v<T2>) {\n      if (ys.rows() < 1) {\n        throw std::invalid_argument(\"Dimension of the data must be > 0.\");\n      }\n\n      if (ys.cols() != x.size()) {\n        throw std::invalid_argument(\"The number of columns of ys must be equal to the size of x.\");\n      }\n      coefLists.reserve(static_cast<std::size_t>(ys.rows()));\n\n      for (Eigen::Index i = 0; i < ys.rows(); i++) {\n        coefLists.push_back(generateCoeffs(x, ys.row(i)));\n      }\n    } else {\n      static_assert(\n        is_eigen_dense_v<typename T2::value_type>&& T2::value_type::IsVectorAtCompileTime,\n        \"ys must be a container of Eigen::DenseBase vector objects\");\n\n      if (ys.size() < 1) {\n        throw std::invalid_argument(\"Dimension of the data must be > 0.\");\n      }\n\n      coefLists.reserve(ys.size());\n\n      for (const auto & y : ys) {\n        coefLists.push_back(generateCoeffs(x, y));\n      }\n    }\n\n    return PiecewisePolyND(std::forward<T1>(x), std::move(coefLists));\n  }\n\nprotected:\n  template<typename T1, typename T2>\n  static matrix_t generateCoeffs(\n    const Eigen::DenseBase<T1> & x,\n    const Eigen::DenseBase<T2> & y)\n  {\n    static_assert(\n      T1::IsVectorAtCompileTime && T2::IsVectorAtCompileTime,\n      \"x and y must be vectors.\");\n\n    if (x.size() != y.size()) {\n      throw std::invalid_argument(\"Each element of ys must have the same size as x.\");\n    }\n\n    Eigen::Index nj = x.size() - 1;\n    matrix_t coeffs(2, nj);\n\n    for (Eigen::Index i = 0; i < nj; i++) {\n      coeffs(1, i) = y[i];\n      coeffs(0, i) = (y[i + 1] - y[i]) / (x[i + 1] - x[i]);\n    }\n\n    return coeffs;\n  }\n};\n\n}  // namespace cbr\n\n#endif  // CBR_MATH__INTERP__PIECEWISE_LINEAR_HPP_\n", "meta": {"hexsha": "202ab28f1741a79efec888e0cb0fac4469399aa1", "size": 3741, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/cbr_math/interp/piecewise_linear.hpp", "max_stars_repo_name": "yamaha-bps/cbr_math", "max_stars_repo_head_hexsha": "cf1ad7d4661f4b0063d07e00a4e0052454518931", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-24T17:41:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-24T17:41:16.000Z", "max_issues_repo_path": "include/cbr_math/interp/piecewise_linear.hpp", "max_issues_repo_name": "yamaha-bps/cbr_math", "max_issues_repo_head_hexsha": "cf1ad7d4661f4b0063d07e00a4e0052454518931", "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": "include/cbr_math/interp/piecewise_linear.hpp", "max_forks_repo_name": "yamaha-bps/cbr_math", "max_forks_repo_head_hexsha": "cf1ad7d4661f4b0063d07e00a4e0052454518931", "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.9136690647, "max_line_length": 99, "alphanum_fraction": 0.6014434643, "num_tokens": 1166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070035949656, "lm_q2_score": 0.798186775339273, "lm_q1q2_score": 0.7262757370580858}}
{"text": "\n#pragma once\n///@file simpleClusterization_common.hpp\n///@brief common definitions that users of the library might need independently from the rest of the files \n\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\n///Shorthand type for a RowMajor Matrix of floats\ntypedef Matrix<float, Dynamic, Dynamic, RowMajor>   MatrixXfR;\n///Shorthand type for a ColMajor Matrix of bools\ntypedef Matrix<bool, Dynamic, Dynamic>              MatrixXb;\n///Shorthand type for a RowMajor Matrix of bools\ntypedef Matrix<bool, Dynamic, Dynamic, RowMajor>    MatrixXbR;\n\n///The type signature for the norm parameters of the functions in this library\ntypedef float squaredNorm_t(const VectorXf &v1, const VectorXf &v2);\n\n///A basic example of norm that satisfies the type signature\nfloat euclideanNorm(const VectorXf &v1, const VectorXf &v2);\n", "meta": {"hexsha": "0ace57d235ffb7623d468a3d8884c25126a2ef72", "size": 820, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/simpleClusterization_common.hpp", "max_stars_repo_name": "tesseract241/simpleClusterization", "max_stars_repo_head_hexsha": "d5125e5b99b67ac92847cccb28b8bf058ac35efd", "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/simpleClusterization_common.hpp", "max_issues_repo_name": "tesseract241/simpleClusterization", "max_issues_repo_head_hexsha": "d5125e5b99b67ac92847cccb28b8bf058ac35efd", "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": "include/simpleClusterization_common.hpp", "max_forks_repo_name": "tesseract241/simpleClusterization", "max_forks_repo_head_hexsha": "d5125e5b99b67ac92847cccb28b8bf058ac35efd", "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.2727272727, "max_line_length": 107, "alphanum_fraction": 0.7695121951, "num_tokens": 196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970842359876, "lm_q2_score": 0.8244619350028204, "lm_q1q2_score": 0.7261836684140445}}
{"text": "#include <iostream>\n\n#include <stack>\n\n// #include <boost/lexical_cast.hpp>\n\n#include \".\\\\headers\\\\min_path.h\"\n\nusing namespace std;\n\n\n\n/**\n\n * @brief MinPath::initGraph\n\n * @note the start vertex must start with '0'\n\n * @todo fix the vertex info(automatically to certain question)\n\n */\n\nvoid MinPath::initGraph() {\n\n    M_vertexNum = 6;\n\n    M_edgeNum = 10;\n\n    int i;\n\n    int j;\n\n    for ( i=0; i<M_vertexNum; i++ ) {\n\n        this->M_vertexs[i] = i;\n\n    }\n\n\n\n    for ( i=0; i<M_vertexNum; i++ )\n\n        for ( j=0; j<M_vertexNum; j++ )\n\n            this->M_edges[i][j] = MAXWEIGHT;\n\n\n\n    M_edges[0][1] = 3;\n\n    M_edges[0][2] = 2;\n\n    M_edges[0][3] = 5;\n\n    M_edges[2][3] = 1;\n\n    M_edges[3][1] = 2;\n\n    M_edges[1][5] = 7;\n\n    M_edges[4][2] = 5;\n\n    M_edges[3][5] = 5;\n\n    M_edges[4][3] = 3;\n\n    M_edges[4][5] = 1;\n\n    return;\n\n}\n\n\n\n/**\n\n * @brief MinPath::computeShortestPath\n\n * @param v0, the start vertex\n\n * @param pre, array to store the current vertex's pirror vertex\n\n * @param dist, array to store the current vertex's weight to the start vertex\n\n */\n\nvoid MinPath::computeShortestPath(int v0, int *pre, int *dist) {\n\n    bool final[MAXVERTEXNUM];\n\n\n\n    int i;\n\n    int w;\n\n    int v;\n\n    int current_tmp_min;\n\n    // \u521d\u59cb\u5316\n\n    for ( v=0; v<=M_vertexNum-1; v++ ) {\n\n        final[v] = false;\n\n        dist[v] = M_edges[v0][v];       // \u5982\u679c\u4e0d\u76f4\u63a5\u8fde\u901a\uff0cdist[v]\u5c31\u662fMAXWEIGHT,\u5426\u5219\u662f\u76f8\u5e94\u7684\u6743\u503c, \u6211\u79f0\u6b64\u65f6dist[v] \u4e3a \"\u4f30\u8ba1\u503c\"\n\n        pre[v] = -1;      // \u6240\u6709\u7684\u9876\u70b9\u90fd\u65e0\u524d\u9a71\uff0c\u7f6epre\u6570\u7ec4\u4e3a -1\n\n\n\n        if ( dist[v] < MAXWEIGHT )  // v \u5230 v0 (\u76f4\u63a5)\u8fde\u901a\n\n            pre[v] = v0;\n\n    }\n\n\n\n    // \u5f00\u59cb\u65f6V0\u5c5e\u4e8e\uff33\u96c6\u5408\uff0c\u9ed8\u8ba4\u5df2\u7ecf\u627e\u5230\u6700\u77ed\u8def\u5f84\n\n    dist[v0] = 0;\n\n    final[v0] = true;       // (final[i] = true \u76f8\u5f53\u4e8e\u628ai \u52a0\u5165S\u96c6\u5408)\n\n\n\n    // main loop\n\n    // \u5bfb\u627e\u5176\u4f596\u4e2a\u8282\u70b9\n\n    for ( i=1; i<M_vertexNum+1; i++ ) {\n\n        v = -1;     // ---> if (v==-1)\n\n        current_tmp_min = MAXWEIGHT;    // \u5f53\u524d\u8dddV0\u8def\u5f84\u6700\u77ed\u7684\u6743\u503c ,\u521d\u59cb\u5316\u4e3a\u4e0d\u8fde\u901a\u72b6\u6001\n\n\n\n        // \u5bfb\u627e\u5f53\u524d\u79bbV0\u6700\u8fd1\u7684\u9876\u70b9 V\n\n        // \u7b2c\u4e00\u6b21main loop \u4e0b, current_tmp_min \u53d8\u5316\u60c5\u51b5: dist[1] -> dist[2]\n\n        for ( w=0; w<M_vertexNum; w++ ) {\n\n            if ( final[w] == false && dist[w] < current_tmp_min ) {  // w\u8fd8\u6ca1\u627e\u5230\u6700\u77ed\u8def\u5f84\uff0c\u5e76\u4e14d[w]\u6bd4\u5f53\u524dmin \u8fd8\u8981\u5c0f\n\n                v = w;                          // \u66f4\u65b0\n\n                current_tmp_min = dist[v];\n\n            }\n\n        }\n\n\n\n        if ( v == -1 )                      // \u6240\u6709\u4e0eV0\u76f8\u901a\u7684\u70b9\u90fd\u627e\u5230\u4e86\u6700\u77ed\u8def\u5f84(\u4e0d\u6ee1\u8db3line 108 \u7684if )\uff0c\u5219\u9000\u51famain loop\n\n            break;\n\n\n\n        final[v] = true;\t\t// \u628aV \u52a0\u5165S\u96c6\u5408\n\n\n\n        // \u66f4\u65b0\u5f53\u524d\u6700\u77ed\u8def\u5f84\u53ca\u8ddd\u79bb(V \u4f5c\u4e3a\u4e2d\u95f4\u70b9)\n\n        for ( w=0; w<M_vertexNum; w++ ) {\n\n            if ( final[w] == false && (current_tmp_min+(M_edges[v][w]) < dist[w]) )  // v0 -> v -> w \u6bd4 v0 -> w \u77ed\n\n            {\n\n                // \u7b2c\u4e00\u6b21main loop, dist[1] \u66f4\u65b0\u6210 4, 2 \u4f5c\u4e3a1 \u7684\u524d\u9a71\n\n                dist[w] = current_tmp_min + (M_edges[v][w]);     // \u66f4\u65b0\u6700\u77ed\u8def\u5f84\u957f\u5ea6, \u6b64\u65f6dist[w]\u4e3a \"\u786e\u5b9a\u503c\"\n\n                pre[w] = v;     // v\u4f5c\u4e3aw\u7684\u524d\u9a71\u9876\u70b9\n\n            }\n\n        }\n\n    }   //end main loop\n\n    return;\n\n}\n\n\n\n/**\n\n * @brief MinPath::showShortestPath\n\n * @param v0\n\n * @param pre\n\n * @param dist\n\n */\n\nvoid MinPath::showShortestPath(int v0, int *pre, int *dist) {\n\n    int v;\n\n    int i;\n\n    stack<int> s;\n\n    cout << \"\u4ece\u9876\u70b9 \" << v0 << \"\u3000\u5230\u5176\u4ed6\u9876\u70b9: \" << endl;\n\n\n\n    for ( v=0; v<M_vertexNum; v++ ) {\n\n        if ( pre[v] == -1 )   //v0 \u5230 v \u4e0d\u901a\n\n        {\n\n            cout << \"\\t\" << v << \" \u6ca1\u6709\u901a\u8def\" << endl << endl;\n\n            continue;\n\n        }\n\n        cout <<  \"\\t\u9876\u70b9\" << v << endl;\n\n        cout << \"\\t\u6700\u77ed\u8def\u5f84\u957f\u5ea6: \" << dist[v] << endl;\n\n        i = v;\n\n        while ( pre[i] != -1 ) {\n\n            //cout << \"\u524d\u9a71: \" << pre[i] << endl;\n\n            s.push(pre[i]);             // \u5165\u6808\uff0c\u4ea4\u6362\u987a\u5e8f\n\n\n\n            i = pre[i];\n\n        }\n\n        cout << \"\\t\u6700\u77ed\u8def\u5f84: \";\n\n        for ( unsigned long size = s.size(); size > 0; size -- ) {\n\n            cout << s.top() << \" -> \";\n\n            s.pop();\n\n        }\n\n        cout << v << endl << endl;\n\n    }\n\n    return;\n\n}\n\n\n\n/**\n\n * @brief main\n\n * @return\n\n */\n\nint main() {\n\n    MinPath G;\n\n    int pre[MAXVERTEXNUM];\n\n    int dist[MAXVERTEXNUM];\n\n    G.initGraph();\n\n    G.showOriginalGraph();\n\n    G.computeShortestPath(0, pre, dist);\n\n    G.showShortestPath(0, pre, dist);\n\n\n\n    return 0;\n\n}", "meta": {"hexsha": "d6476725b4f29b565eec9e16d611765d2c747d53", "size": 4078, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "min_path.cpp", "max_stars_repo_name": "mokeeqian/data_structure", "max_stars_repo_head_hexsha": "6078c711d8029b161f46908e577b5c7e377dd8d3", "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": "min_path.cpp", "max_issues_repo_name": "mokeeqian/data_structure", "max_issues_repo_head_hexsha": "6078c711d8029b161f46908e577b5c7e377dd8d3", "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": "min_path.cpp", "max_forks_repo_name": "mokeeqian/data_structure", "max_forks_repo_head_hexsha": "6078c711d8029b161f46908e577b5c7e377dd8d3", "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": 13.7306397306, "max_line_length": 112, "alphanum_fraction": 0.4654242276, "num_tokens": 1466, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.8244619220634457, "lm_q1q2_score": 0.7261836570170811}}
{"text": "/**\n * @section DESCRIPTION\n *\n * Perfect Numbers.\n *\n * An integer is said to be a perfect number if the sum of its divisors,\n * including 1 (but not the number itself), is equal to the number. For\n * example, 6 is a perfect number, because 6=1+2+3. Write a function isPerfect\n * that determines whether parameter number is a perfect number. Use this\n * function in a program that determines and prints all the perfect numbers\n * between 1 and 1000. Print the divisors of each perfect number to confirm\n * that the number is indeed perfect. Challenge the power of your computer by\n * testing numbers much larger than 1000.\n */\n\n#include <boost/multiprecision/cpp_int.hpp>\n#include <iomanip>\n#include <iostream>\n#include <set>\n#include <memory>\n\nusing boost::multiprecision::pow;\nusing boost::multiprecision::sqrt;\nusing boost::multiprecision::uint128_t;\nusing std::cout;\nusing std::endl;\nusing std::set;\nusing std::setw;\nusing std::unique_ptr;\n\nusing int_set_ptr = unique_ptr<set<uint128_t>>;\n\ntemplate <class T>\nstruct Accumulator final\n{\n    Accumulator() : sum {0}\n    {\n    }\n\n    void operator()(const T &input)\n    {\n        sum += input;\n    }\npublic:\n    T sum;\n};\n\nstatic int_set_ptr FindDivisors(const uint128_t &number)\n{\n    int_set_ptr divisor_set_ptr {new set<uint128_t>};\n    const uint128_t kDivisorLimit {sqrt(number)};\n\n    // Base Case:\n    // 1 does not have any valid candidate divisor to be considered as a\n    // potential perfect number.\n    if (number <= 1) {\n        return divisor_set_ptr;\n    }\n\n    divisor_set_ptr->insert(1);\n\n    for (uint128_t i {2}; i <= kDivisorLimit; ++i) {\n        if (number % i == 0) {\n            divisor_set_ptr->insert(i);\n            divisor_set_ptr->insert(number / i);\n        }\n    }\n    return divisor_set_ptr;\n}\n\nstatic bool IsPerfectNumber(const uint128_t &number,\n                            int_set_ptr &divisor_set_ptr)\n{\n    // Compiler would use copy elision, so a 'move' in unnecessary.\n    divisor_set_ptr = FindDivisors(number);\n\n    if (divisor_set_ptr->size() == 0) {\n        return false;\n    }\n\n    Accumulator<uint128_t> accumulator;\n\n    for (auto &i : *divisor_set_ptr) {\n        accumulator(i);\n    }\n\n    return accumulator.sum == number;\n}\n\nint main(void)\n{\n    static constexpr int kWidthLeft {15}, kWidthRight {40};\n    int_set_ptr divisor_set_ptr;\n\n    cout \\\n        << setw(kWidthLeft) << \"Perfect Number\"\n        << setw(kWidthRight) << \"Divisors\" << endl;\n\n    for (uint128_t i = 1; i <= uint128_t(1) << 16; ++i) {\n        if (IsPerfectNumber(i, divisor_set_ptr)) {\n            cout << setw(kWidthLeft) << i << setw(kWidthRight);\n            for (auto divisor_iterator = divisor_set_ptr->cbegin();\n                 divisor_iterator != divisor_set_ptr->cend();\n                 ++divisor_iterator) {\n                cout << *divisor_iterator;\n                if (++divisor_iterator == divisor_set_ptr->cend()) {\n                    --divisor_iterator;\n                    cout << endl;\n                } else {\n                    --divisor_iterator;\n                    cout << \", \";\n                }\n            }\n        }\n    }\n    return 0;\n}\n", "meta": {"hexsha": "d6ef85fe1793171cc60461eec253bcb603f5461d", "size": 3139, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/6/exercises/6-28.cpp", "max_stars_repo_name": "jhxie/CPlusPlusHowToProgram", "max_stars_repo_head_hexsha": "a622902a9e5e9766d9ddb83a38070d57dba786c3", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-01-10T03:32:46.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-10T03:32:46.000Z", "max_issues_repo_path": "src/6/exercises/6-28.cpp", "max_issues_repo_name": "jhxie/CPlusPlusHowToProgram", "max_issues_repo_head_hexsha": "a622902a9e5e9766d9ddb83a38070d57dba786c3", "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/6/exercises/6-28.cpp", "max_forks_repo_name": "jhxie/CPlusPlusHowToProgram", "max_forks_repo_head_hexsha": "a622902a9e5e9766d9ddb83a38070d57dba786c3", "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": 26.6016949153, "max_line_length": 78, "alphanum_fraction": 0.6138897738, "num_tokens": 768, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094117351309, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.7261420214665106}}
{"text": "#include <iostream>\n#include <tuple>\n#include <Eigen/Dense>\n#include \"linear_algebra_addon.hpp\"\nusing namespace Eigen;\nusing namespace std;\n\nMatrixXcd bl_bicr_rq(const MatrixXcd& A, const MatrixXcd& B, const double& tol, const int& itermax)\n{\n    // Tadano et al 2014, Improvement of the accuracy of the approximate solution of the block BiCR method\n  double Bnorm= B.norm();\n  MatrixXcd X= MatrixXcd::Zero(B.rows(),B.cols()); // Initial guess of X (zeros)\n  MatrixXcd R= B-A*X;\n  MatrixXcd Q;\n  MatrixXcd xi;\n  tie(Q,xi)= qr_reduced(R);\n\n  MatrixXcd R_til= R; // or R_til= R.conjugate();\n  MatrixXcd Q_til;\n  MatrixXcd xi_til;\n  tie(Q_til,xi_til)= qr_reduced(R_til);\n\n  MatrixXcd S= Q;\n  MatrixXcd S_til= Q_til;\n  MatrixXcd U= A*Q;\n  MatrixXcd U_til= A.adjoint()*Q_til;\n  MatrixXcd V_til= U_til;\n\n  for(int k= 0; k < itermax; ++k){\n\n      MatrixXcd alpha= (U_til.adjoint()*U).fullPivLu().solve(V_til.adjoint()*Q);\n      MatrixXcd alpha_til= (U.adjoint()*U_til).fullPivLu().solve(Q.adjoint()*V_til);\n\n      X= X+S*alpha*xi;\n\n      MatrixXcd Qnew;\n      MatrixXcd tau;\n      tie(Qnew,tau)= qr_reduced(Q-U*alpha);\n      MatrixXcd Qnew_til;\n      MatrixXcd tau_til;\n      tie(Qnew_til,tau_til)= qr_reduced(Q_til-U_til*alpha_til);\n\n      xi= tau*xi;\n      MatrixXcd Vnew_til= A.adjoint()*Qnew_til;\n\n      double err= xi.norm()/Bnorm;\n      cout << \"bl_bicr_rq: \" << \"iter= \" << k << \" relative err= \" << err << endl;\n      if(err < tol) break;\n\n      MatrixXcd beta= (V_til.adjoint()*Q).fullPivLu().solve(tau_til.adjoint()*Vnew_til.adjoint()*Qnew);\n      MatrixXcd beta_til= (Q.adjoint()*V_til).fullPivLu().solve(tau.adjoint()*Qnew.adjoint()*Vnew_til);\n\n      Q= Qnew;\n      Q_til= Qnew_til;\n      V_til= Vnew_til;\n      S= Q+S*beta;\n      S_til= Q_til+S_til*beta_til;\n      U_til= V_til+U_til*beta_til;\n      U= A*S;\n  }\n\n  if((A*X-B).norm()/Bnorm > 10*tol){\n      cerr << \"bl_bicr_rq did not converge to solution within error tolerance !\" << endl;\n     // exit(EXIT_FAILURE);\n  }\n\n  return X;\n}\n", "meta": {"hexsha": "bff459522b16b1ca37a0ab051eadbc8a31606397", "size": 1993, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bl_bicr_rq.cpp", "max_stars_repo_name": "nmoteki/block-Krylov-linear-solvers", "max_stars_repo_head_hexsha": "0c123f474296219c1b944ad83f8e3c7abbf0c2b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-27T08:44:06.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-27T08:44:06.000Z", "max_issues_repo_path": "bl_bicr_rq.cpp", "max_issues_repo_name": "nmoteki/block-Krylov-linear-solvers", "max_issues_repo_head_hexsha": "0c123f474296219c1b944ad83f8e3c7abbf0c2b0", "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": "bl_bicr_rq.cpp", "max_forks_repo_name": "nmoteki/block-Krylov-linear-solvers", "max_forks_repo_head_hexsha": "0c123f474296219c1b944ad83f8e3c7abbf0c2b0", "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.884057971, "max_line_length": 106, "alphanum_fraction": 0.6452584044, "num_tokens": 699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361533336451, "lm_q2_score": 0.7956581073313276, "lm_q1q2_score": 0.7259872228221251}}
{"text": "#include <Eigen/Dense>\n#include \"simple_loss.h\"\n\nnamespace MyDL{\n\n    double cross_entropy_error(MatrixXd& y, MatrixXd& t){\n        int batch_size = y.rows();\n        double ret = (t.array() * y.array().log()).sum() / batch_size;\n        return -ret;\n    }\n\n}", "meta": {"hexsha": "4ccc0fbcfe43449e4c7496790225445b066d2314", "size": 259, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/simple_loss.cpp", "max_stars_repo_name": "potedo/MNIST_loader_sample", "max_stars_repo_head_hexsha": "6c6723c8c20e05ecc093a04fa045d20a73dd04f8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-22T15:26:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-22T15:26:20.000Z", "max_issues_repo_path": "simple_lib/src/simple_loss.cpp", "max_issues_repo_name": "potedo/zeroDL_cpp", "max_issues_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "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": "simple_lib/src/simple_loss.cpp", "max_forks_repo_name": "potedo/zeroDL_cpp", "max_forks_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "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.5833333333, "max_line_length": 70, "alphanum_fraction": 0.6023166023, "num_tokens": 67, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9372107966642556, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.7259479203098498}}
{"text": "#include \"../incidencematrices.h\"\n\n#include <gtest/gtest.h>\n#include <lf/mesh/mesh.h>\n\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n#include <memory>\n\nnamespace IncidenceMatrices::test {\n\n// Create demo mesh from exercise sheet and test if edge vertex incidence\n// matrix is the same as the one calculated by hand\nTEST(Homework_2_6, EdgeVertexIncidenceMatrix) {\n  std::shared_ptr<lf::mesh::Mesh> demoMesh =\n      IncidenceMatrices::createDemoMesh();\n  Eigen::SparseMatrix<int> G_sp =\n      IncidenceMatrices::computeEdgeVertexIncidenceMatrix(*demoMesh);\n  Eigen::MatrixXi G(G_sp);\n\n  Eigen::MatrixXi G_expected(6, 5);\n  // clang-format off\n  G_expected << 1, -1,  0,  0,  0, \n               -1,  0,  0,  1,  0, \n                0,  1, -1,  0,  0, \n                0, -1,  0,  0,  1,\n                0,  0,  1,  0, -1, \n                0,  0,  0, -1,  1;\n  // clang-format on\n  EXPECT_EQ(G.rows(), G_expected.rows());\n  EXPECT_EQ(G.cols(), G_expected.cols());\n  if (G.rows() == G_expected.rows() && G.cols() == G_expected.cols())\n    EXPECT_EQ(G, G_expected);\n}\n\n// Create demo mesh from exercise sheet and test if cell edge incidence\n// matrix is the same as the one calculated by hand\nTEST(Homework_2_6, CellEdgeIncidenceMatrix) {\n  std::shared_ptr<lf::mesh::Mesh> demoMesh =\n      IncidenceMatrices::createDemoMesh();\n  Eigen::SparseMatrix<int> D_sp =\n      IncidenceMatrices::computeCellEdgeIncidenceMatrix(*demoMesh);\n  Eigen::MatrixXi D(D_sp);\n\n  Eigen::MatrixXi D_expected(2, 6);\n  // clang-format off\n  D_expected << 0, 0, 1,  1, 1, 0,\n                1, 1, 0, -1, 0, 1;\n  // clang-format on\n  EXPECT_EQ(D.rows(), D_expected.rows());\n  EXPECT_EQ(D.cols(), D_expected.cols());\n  if (D.rows() == D_expected.rows() && D.cols() == D_expected.cols())\n    EXPECT_EQ(D, D_expected);\n}\n\n// Test co-chain complex property (D*G = 0) at the example of the mesh\n// in the exercise sheet\nTEST(Homework_2_6, CoChainComplexProperty) {\n  std::shared_ptr<lf::mesh::Mesh> demoMesh =\n      IncidenceMatrices::createDemoMesh();\n  EXPECT_TRUE(IncidenceMatrices::testZeroIncidenceMatrixProduct(*demoMesh));\n}\n\n}  // namespace IncidenceMatrices::test\n", "meta": {"hexsha": "4b2b057b0f34d1953e5753d22ae8ec153d609474", "size": 2140, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/IncidenceMatrices/templates/test/incidencematrices_test.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/IncidenceMatrices/templates/test/incidencematrices_test.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/IncidenceMatrices/templates/test/incidencematrices_test.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": 32.9230769231, "max_line_length": 76, "alphanum_fraction": 0.653271028, "num_tokens": 662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7258904738170532}}
{"text": "#include \"DenseMatrix.hpp\"\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/operation.hpp>\n#include <gtest/gtest.h>\n#include <math.h>\n\n#define REAL double\n#define TOL 1.0E-06\n\nconst int SIZE = 100;\n\nTEST(CASE_01, one_dimension_configuration){\n  int side = sqrt(SIZE);\n  REAL *A = (REAL*)calloc(SIZE, sizeof(REAL));\n  REAL *B = (REAL*)calloc(SIZE, sizeof(REAL)); \n  REAL *C = (REAL*)calloc(SIZE, sizeof(REAL));\n\n  boost::numeric::ublas::matrix<double> A_bst(side, side), B_bst(side, side), \n    C_bst(side, side);\n\n  randMatrix(A, side, side); randMatrix(B, side, side);\n  for (int i=0; i<SIZE; ++i) C[i] = 0.0;\n  \n  for (int i=0; i<side; ++i){\n    for (int j=0; j<side; ++j){\n      int idx = i*side + j;\n      A_bst(i,j) = A[idx];\n      B_bst(i,j) = B[idx];\n    }\n  }\n  // Manual Version\n  dgemm(A, side, side, B, side, side, C);\n  // Boost Version\n  boost::numeric::ublas::axpy_prod(A_bst, B_bst, C_bst, true);\n\n  for (int i=0; i<side; ++i){\n\t  for (int j=0; j<side; ++j){\n\t    int idx = i*side + j;\n\t    EXPECT_NEAR(C_bst(i,j), C[idx], TOL);\n  \t}\n  }\n  free(A); free(B); free(C);\n}\n\nint main(int argc, char *argv[]){\n  testing::InitGoogleTest(&argc,argv);\n  return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "ccfb7f157a166b6c306ff2b1728e22993882341d", "size": 1209, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "DENSE_MATRIX/GTEST/Boost/main.cpp", "max_stars_repo_name": "lnugraha/mtx-toolbox", "max_stars_repo_head_hexsha": "188078b4749db8b42f15ac5607501cc4b660317f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-29T20:51:22.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-29T20:51:22.000Z", "max_issues_repo_path": "DENSE_MATRIX/GTEST/Boost/main.cpp", "max_issues_repo_name": "lnugraha/mtx-toolbox", "max_issues_repo_head_hexsha": "188078b4749db8b42f15ac5607501cc4b660317f", "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": "DENSE_MATRIX/GTEST/Boost/main.cpp", "max_forks_repo_name": "lnugraha/mtx-toolbox", "max_forks_repo_head_hexsha": "188078b4749db8b42f15ac5607501cc4b660317f", "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.6734693878, "max_line_length": 78, "alphanum_fraction": 0.6079404467, "num_tokens": 424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273633016692238, "lm_q2_score": 0.7826624840223699, "lm_q1q2_score": 0.725812465275621}}
{"text": "\n#include <Eigen/Geometry>\n#include <Eigen/SVD>\n#include <Eigen/Jacobi>\n#include <Eigen/LU>\n#include <Eigen/Eigenvalues>\n\n#include <cmath>\n\n#include <sphericalsfm/plane_estimator.h>\n#include <sphericalsfm/so3.h>\n\nnamespace sphericalsfm {\n    int PlaneEstimator::sampleSize()\n    {\n        return 3;\n    }\n\n    double PlaneEstimator::score( RayPairList::iterator it )\n    {\n        const Eigen::Vector3d &x = it->first.head(3);\n        const double proj = normal.dot( x ) + d;\n        return proj*proj;\n    }\n\n    bool PlaneEstimator::canRefine()\n    {\n        return true;\n    }\n\n    int PlaneEstimator::compute( RayPairList::iterator begin, RayPairList::iterator end )\n    {\n        int N = std::distance(begin,end);\n        \n        Eigen::MatrixXd A(N,4);\n        \n        int i = 0;\n        for ( RayPairList::iterator it = begin; it != end; it++,i++ )\n        {\n            const Eigen::Vector3d x = it->first.head(3);\n            \n            A(i,0) = x(0);\n            A(i,1) = x(1);\n            A(i,2) = x(2);\n            A(i,3) = 1;\n        }\n        \n        Eigen::Matrix4d B = A.jacobiSvd(Eigen::ComputeFullV).matrixV();\n        Eigen::Vector4d soln = B.col(3);\n        soln = soln/soln.head(3).norm();\n        normal = soln.head(3);\n        d = soln(3);\n        \n        return 1;\n    }\n}\n\n", "meta": {"hexsha": "b05e56168fdabc65c2dd315a83c21c421c1ebcda", "size": 1303, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/plane_estimator.cpp", "max_stars_repo_name": "jonathanventura/spherical-sfm", "max_stars_repo_head_hexsha": "0f0dafdd66641cebcb57cdb8a87b9ce466ab36eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2020-03-26T15:07:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-04T06:27:32.000Z", "max_issues_repo_path": "src/plane_estimator.cpp", "max_issues_repo_name": "jonathanventura/spherical-sfm", "max_issues_repo_head_hexsha": "0f0dafdd66641cebcb57cdb8a87b9ce466ab36eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-07-09T06:32:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-09T07:26:47.000Z", "max_forks_repo_path": "src/plane_estimator.cpp", "max_forks_repo_name": "jonathanventura/spherical-sfm", "max_forks_repo_head_hexsha": "0f0dafdd66641cebcb57cdb8a87b9ce466ab36eb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-08T20:30:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T20:30:46.000Z", "avg_line_length": 22.4655172414, "max_line_length": 89, "alphanum_fraction": 0.5287797391, "num_tokens": 372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632896242074, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.7258124464460277}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include <Eigen/Jacobi>\n\n\nusing namespace Eigen;\n\nvoid My_Polar(const Eigen::Matrix3f& F, Eigen::Matrix3f& R, Eigen::Matrix3f& S) {\n\n\t \n\tEigen::JacobiRotation<float> G;\n\tfloat tol = 1e-6, max_it = 1e4, S_diff[] = { 100,100,100 }, S_diff_max;\n\tint it = 0, i_rot = 0, i, j, i_max;\n\n\n\t\n\n\tR = MatrixXf::Identity(3, 3);\n\tS = F;\n\n\tfor (i_max = 0; i_max < 3; i_max++) {\n\t\tif (i_max == 0)\n\t\t\tS_diff_max = S_diff[0];\n\t\telse if (S_diff[i_max] > S_diff[i_max - 1])\n\t\t\tS_diff_max = S_diff[i_max];\n\t}\n\n\n\n\twhile (it<max_it && S_diff_max > tol) {\n\n\n\t\tfor (i_rot = 0; i_rot < 3; i_rot++) {\n\t\t\tif (i_rot == 0) {\n\t\t\t\ti = 1;\n\t\t\t\tj = 2;\n\t\t\t}\n\t\t\telse if (i_rot == 1) {\n\t\t\t\ti = 0;\n\t\t\t\tj = 2;\n\t\t\t}\n\t\t\telse if (i_rot == 2) {\n\t\t\t\ti = 0;\n\t\t\t\tj = 1;\n\t\t\t}\n\t\t\tG.makeGivens(S(i, i) + S(j, j), S(i, j) - S(j, i));\n\t\t\tR.applyOnTheRight(i, j, G.adjoint());\n\t\t\tS.applyOnTheLeft(i, j, G);\n\n\n\n\t\t}\n\n\t\tit++;\n\t\tS_diff[0] = std::abs(S(1, 2) - S(2, 1));\n\t\tS_diff[1] = std::abs(S(0, 2) - S(2, 0));\n\t\tS_diff[2] = std::abs(S(0, 1) - S(1, 0));\n\t\tfor (i_max = 0; i_max < 3; i_max++) {\n\t\t\tif (i_max == 0)\n\t\t\t\tS_diff_max = S_diff[0];\n\t\t\telse if (S_diff[i_max] > S_diff[i_max - 1])\n\t\t\t\tS_diff_max = S_diff[i_max];\n\t\t}\n\n\n\n\t}\n\n}\n\nint main()\n{\n\tEigen::Matrix3f F, R, S;\n\n\tF << 1, 2, 6,\n\t\t4, 3, 2,\n\t\t8, 4, 6;\n\n\tMy_Polar(F, R, S);\n\t\n\n\n\tstd::cout << R << '\\n' << '\\n';\n\tstd::cout << R*R.transpose() << '\\n' << '\\n';\n\tstd::cout << S << '\\n' << '\\n';\n\tstd::cout << R*S << '\\n' << '\\n';\n\tstd::cout << F << '\\n';\n\n\t\n\t\n\n\tsystem(\"pause\");\n    \n\t\n\treturn 0;\n\n\t\n}\n", "meta": {"hexsha": "16c189860ac00153bfed78ffbf50102cfb7e0ddb", "size": 1544, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "HW1/HW1_2.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_2.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_2.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": 15.595959596, "max_line_length": 81, "alphanum_fraction": 0.4961139896, "num_tokens": 651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038784, "lm_q2_score": 0.8031737963569016, "lm_q1q2_score": 0.7255022372255497}}
{"text": "#ifndef POLYNOMIAL_HPP\n#define POLYNOMIAL_HPP\n\n#include <Eigen/Core>\n\n#include <cmath>\n\nnamespace polynomial {\n\n    // Evaluate polynomial using Horner's scheme\n    template <typename T> double eval(const Eigen::DenseBase<T>& c, double x) {\n        double y = 0;\n        for (int i = c.size()-1; i >= 0; i--)\n            y = c(i) + y * x;\n        return y;\n    }\n\n    // Evaluate polynomial derivative using Horner's scheme\n    template <typename T> double deriv(const Eigen::DenseBase<T>& c, double x) {\n        double yd = 0;\n        for (int i = c.size()-1; i > 0; i--)\n            yd = (i+1) * c(i) + yd * x;\n        return yd;\n    }\n\n    // Find root of polynomial using Newton's method\n    template <typename T> double solve(const Eigen::DenseBase<T>& c,\n            double x, double tol) {\n        double dx;\n        int it = 0;\n        do {\n            dx = eval(c, x) / deriv(c, x);\n            x -= dx;\n            it++;\n        } while (fabs(dx) > tol && it < 10);\n        return x;\n    }\n\n}\n\n#endif\n", "meta": {"hexsha": "00e768f7ff700b8700edd36eb35b93479a905c72", "size": 1011, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "polynomial.hpp", "max_stars_repo_name": "SIOSlab/ACCIS", "max_stars_repo_head_hexsha": "f5a2f1119053084ad2dbc64c298dbf7af28ea45e", "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": "polynomial.hpp", "max_issues_repo_name": "SIOSlab/ACCIS", "max_issues_repo_head_hexsha": "f5a2f1119053084ad2dbc64c298dbf7af28ea45e", "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": "polynomial.hpp", "max_forks_repo_name": "SIOSlab/ACCIS", "max_forks_repo_head_hexsha": "f5a2f1119053084ad2dbc64c298dbf7af28ea45e", "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.0714285714, "max_line_length": 80, "alphanum_fraction": 0.5212660732, "num_tokens": 282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.8056321983146848, "lm_q1q2_score": 0.725495791238011}}
{"text": "#include <iostream>\n\n#include <Eigen/Core>\n#include <catch2/catch.hpp>\n\n#include <finitediff.hpp>\n\nTEST_CASE(\"Test finite difference jacobian of linear\", \"[jacobian]\")\n{\n    int n = GENERATE(1, 2, 4, 10, 100);\n\n    // f(x) = Ax\n    Eigen::MatrixXd A = Eigen::MatrixXd::Random(n, n);\n\n    const auto f = [&](const Eigen::VectorXd x) -> Eigen::VectorXd {\n        return A * x;\n    };\n\n    Eigen::VectorXd x = Eigen::VectorXd::Random(n);\n\n    Eigen::MatrixXd jac = A;\n\n    fd::AccuracyOrder accuracy = fd::AccuracyOrder(GENERATE(range(0, 4)));\n\n    Eigen::MatrixXd fjac;\n    fd::finite_jacobian(x, f, fjac, accuracy);\n\n    CHECK(fd::compare_jacobian(jac, fjac));\n}\n\nTEST_CASE(\"Test finite difference jacobian of trig\", \"[jacobian]\")\n{\n    int n = GENERATE(1, 2, 4, 10, 100);\n\n    const auto f = [&](const Eigen::VectorXd x) -> Eigen::VectorXd {\n        return x.array().sin();\n    };\n\n    Eigen::VectorXd x = Eigen::VectorXd::Random(n);\n\n    Eigen::MatrixXd jac = x.array().cos().matrix().asDiagonal();\n\n    fd::AccuracyOrder accuracy = fd::AccuracyOrder(GENERATE(range(0, 4)));\n\n    Eigen::MatrixXd fjac;\n    fd::finite_jacobian(x, f, fjac, accuracy);\n\n    CHECK(fd::compare_jacobian(jac, fjac));\n}\n", "meta": {"hexsha": "cee91c5f713ecb6844cb8ef8396e617704f7d94a", "size": 1197, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_jacobian.cpp", "max_stars_repo_name": "ImprovingZero/finite-diff", "max_stars_repo_head_hexsha": "69e0eb897d0c0f4b6c8d3fa92dde1c434d4aee2e", "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_jacobian.cpp", "max_issues_repo_name": "ImprovingZero/finite-diff", "max_issues_repo_head_hexsha": "69e0eb897d0c0f4b6c8d3fa92dde1c434d4aee2e", "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_jacobian.cpp", "max_forks_repo_name": "ImprovingZero/finite-diff", "max_forks_repo_head_hexsha": "69e0eb897d0c0f4b6c8d3fa92dde1c434d4aee2e", "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.94, "max_line_length": 74, "alphanum_fraction": 0.626566416, "num_tokens": 337, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.900529778109184, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.7254957805834217}}
{"text": "/**\n * @file\n * @brief function realizing an embedded Runge-Kutta-Fehlberg explicit\n * single-step method\n * @author Ralf Hiptmair\n * @date   April 2021\n * @copyright Developed at ETH Zurich\n */\n\n#include <Eigen/Dense>\n#include <cassert>\n#include <cmath>\n#include <iostream>\n#include <vector>\n\nnamespace EmbeddedRKSSM {\n\n/**\n * @brief Adaptive embedded Runge-Kutta-Fehlberg timestepping\n *\n * @tparam RHSFunction functor type for right-hand-side vector field\n * @param f_rhs functor providing the right-hand-side function of the autonomous\n * ODE through its evaluation operator\n * @param A Butcher matrix of size s x s (only strictly lower triangular part\n * used)\n * @param b weight vector for RKSSM of order p+1\n * @param bh weight vector for RKSSM of order p\n * @param p order of lower-order method\n * @param y0 intial value\n * @param T final time\n * @param h0 initial stepsize\n * @param reltol relative tolerance for timestep control\n * @param abstol absolute tolerance for timestep control\n * @param hmin minimal admissible stepsize\n */\ntemplate <typename RHSFunction>\nstd::vector<std::pair<double, Eigen::VectorXd>> embeddedRKSSM(\n    RHSFunction &&f_rhs, const Eigen::MatrixXd &A, const Eigen::VectorXd &b,\n    const Eigen::VectorXd &bh, unsigned int p, const Eigen::VectorXd &y0,\n    double T, double h0, double reltol, double abstol, double hmin) {\n  // Check parameters defining embedded RK-SSM\n  unsigned int s = A.cols();  // Number of stages\n  assert((s == A.rows()) && \"Butcher matrix must be square\");\n  assert((s == b.size()) && \"Length of weight vector b != no of stages\");\n  assert((s == bh.size()) && \"Length of weight vector bh != no of stages\");\n  unsigned int N = y0.size();  // Dimension of state space\n  Eigen::MatrixXd K(N, s);     // Columns hold increment vectors\n\n  double t = 0.0;  // Initial time zero for autonomous initial-value problem\n  double h = h0;   // Current timestep size\n  std::vector<std::pair<double, Eigen::VectorXd>> states{\n      {t, y0}};            // State sequence\n  Eigen::VectorXd y = y0;  // Current state\n  states.emplace_back(t, y);\n  // Main timestepping loop\n  while ((states.back().first < T) && (h >= hmin)) {\n    // Compute increments\n    K.col(0) = f_rhs(y);\n    for (int l = 1; l < s; ++l) {\n      Eigen::VectorXd v{Eigen::VectorXd::Zero(N)};\n      for (int i = 0; i < l; ++i) {\n        v += A(l, i) * K.col(i);\n      }\n      K.col(l) = f_rhs(y + h * v);\n    }\n    // Compute next two approximate states\n    auto yh = y + h * K * b;   // high-order method\n    auto yH = y + h * K * bh;  // low-order method\n    double est = (yh - yH).norm();\n    double tol = std::max(reltol * y.norm(), abstol);\n    if (est <= tol) {\n      y = yh;  // Advance to next approximate state\n      t += h;  // Next time\n      states.emplace_back(t, y);\n      // std::cout << \"t = \" << t << \", y = \" << y.transpose() << std::endl;\n    }\n    // else {\n    //   std::cout << \"tol/est = \" << tol / est << \", h = \" << h << std::endl;\n    // }\n    h *= std::max(0.5, std::min(2., 0.9 * std::pow(tol / est, 1. / (p + 1))));\n    if (h < hmin) {\n      std::cerr\n          << \"Warning: Failure at t=\" << states.back().first\n          << \". Unable to meet integration tolerances without reducing the step\"\n          << \" size below the smallest value allowed (\" << hmin\n          << \") at time t.\" << std::endl;\n    } else {\n      h = std::min(T - t + hmin, h);\n    }\n  }\n  return states;\n}\n\n// Helper function for testing\nvoid testrun(const Eigen::MatrixXd &A, const Eigen::VectorXd &b,\n             const Eigen::VectorXd &bh, unsigned int p) {\n  std::cout << \"Test run of embedded RK-SSM\" << std::endl;\n  std::cout << \"Butcher matrix = \\n \" << A << std::endl;\n  std::cout << \"Weight vector (order p+1) = \" << b.transpose() << std::endl;\n  std::cout << \"Weight vector (order p) = \" << bh.transpose() << std::endl;\n  // Simple linear test case: rotation ODE\n  auto f = [](Eigen::Vector2d y) -> Eigen::Vector2d {\n    return Eigen::Vector2d(-y[1], y[0]);\n  };\n  Eigen::VectorXd y0(2);\n  y0 << 1.0, 0.0;\n  // Final time\n  const double T = 2.0 * 3.14159265358979323846;\n  const double hmin = T / 1E6;\n  const double h0 = T / 100;\n  // Test different tolerances\n  const int m = 6;\n  std::array<double, m> rtol{0.1, 0.01, 0.001, 0.0001, 0.00001, 0.000001};\n  std::array<double, m> atol{0.01, 0.001, 0.0001, 0.00001, 0.000001, 0.0000001};\n  for (int j = 0; j < m; ++j) {\n    auto res = embeddedRKSSM(f, A, b, bh, p, y0, T, h0, rtol[j], atol[j], hmin);\n    double err = 0.0;\n    for (const auto &i : res) {\n      const double t = i.first;\n      const Eigen::Vector2d exact(std::cos(t), std::sin(t));\n      const Eigen::Vector2d approx = i.second;\n      err = std::max(err, (exact - approx).norm());\n    }\n    std::cout << \"rtol = \" << rtol[j] << \", atol = \" << atol[j] << \" : \"\n              << (res.size() - 1) << \" steps, err = \" << err << std::endl;\n  }\n}\n\n}  // namespace EmbeddedRKSSM\n\nint main(int /*argc*/, char ** /*argv*/) {\n  std::cout << \"Adaptive embedded Runge-Kutta-Fehlberg single-step method\"\n            << std::endl;\n  {\n    // Simplest embedded method: Euler - Heun\n    Eigen::MatrixXd A(2, 2);\n    A << 0, 0, 1, 0;\n    Eigen::VectorXd b(2);\n    b << 0.5, 0.5;\n    Eigen::VectorXd bh(2);\n    bh << 1.0, 0.0;\n    EmbeddedRKSSM::testrun(A, b, bh, 1);\n  }\n\n  {\n    // More complicated: Bogacki-Shampine\n    // https://en.wikipedia.org/wiki/List_of_Runge%E2%80%93Kutta_methods#Embedded_methods\n    Eigen::MatrixXd A(4, 4);\n    A << 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 0.75, 0, 0, 2. / 9., 1. / 3., 4. / 9., 0;\n    Eigen::VectorXd b(4);\n    b << 2.0 / 9., 1. / 3., 4. / 9., 0;\n    Eigen::VectorXd bh(4);\n    bh << 7. / 24., 1. / 4., 1. / 3., 1. / 8.;\n    EmbeddedRKSSM::testrun(A, b, bh, 2);\n  }\n  return 0;\n}\n", "meta": {"hexsha": "0903bcd2a19f77264f41ddec34ce63a70854cd85", "size": 5740, "ext": "cc", "lang": "C++", "max_stars_repo_path": "lecturecodes/Ode45/embeddedrkssm.cc", "max_stars_repo_name": "0xBachmann/NPDECODES", "max_stars_repo_head_hexsha": "70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-22T10:59:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T10:59:19.000Z", "max_issues_repo_path": "lecturecodes/Ode45/embeddedrkssm.cc", "max_issues_repo_name": "0xBachmann/NPDECODES", "max_issues_repo_head_hexsha": "70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea", "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": "lecturecodes/Ode45/embeddedrkssm.cc", "max_forks_repo_name": "0xBachmann/NPDECODES", "max_forks_repo_head_hexsha": "70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea", "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.3291139241, "max_line_length": 89, "alphanum_fraction": 0.5860627178, "num_tokens": 1875, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.7253981312379635}}
{"text": "/***************************************************************************************\n    File: data_generator.cpp\n\n    Description:\n      produces a linearly separable dataset from a weight vector with randomly\n      generated weights. All features will be uniformally drawn from [-1, 1]\n      as bounded rationals.\n      I.e if the bound for the dataset is 100 the denominator is set to 100 and\n      the numerator is randomly chosen from [-100, 100] (integral values).\n\n    Usage:\n    data_generator\n      -o <OUTPUT_FILE>\n      -t <TRAINING_COUNT>\n      -f <FEATURE_COUNT>\n      -b <BOUND>\n      -w (STDOUT | FEATURE | BOTH) // prints weights to stdout or at end of features_file\n ***************************************************************************************/\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <random>\n#include <algorithm>\n#include <string>\n#include <sstream>\n\n#include <boost/rational.hpp>\n#include <boost/multiprecision/gmp.hpp>\n#include <boost/multiprecision/random.hpp>\n\ntypedef boost::multiprecision::mpz_int Z;\ntypedef boost::rational<Z> Q;\ntypedef std::vector<Q> Qvec;\n\nstd::ostream& operator << (std::ostream& outs, const Q& q){\n  return outs << q.numerator() << \" % \" << q.denominator();\n}\n\nclass Random{\n  public:\n    Random (Z b) : bound(b), engine(std::random_device{}()) {}\n\n    Q operator()() {\n      return Q(randZ(), bound);\n    }\n\n  private:\n    Z bound;\n    std::mt19937 engine;\n\n    Z randZ(){\n      return boost::random::uniform_int_distribution<Z>(-bound, bound)(engine);\n    }\n};\n\n\nint main(int argc, char ** argv){\n  if (!(argc % 2) || argc > 11){\n    std::cerr << \"\\033[1;31mError: Invalid number of Arguments.\\n\\033[0m\";\n    return -1;\n  }\n\n  std::string file_string = \"test_features.dat\";\n  size_t training_count = 100;\n  size_t feature_count = 10;\n  char show_weight = 0; // 0 = don't print, 1 = std_out, 2 = features_file\n  Z bound = 100;\n\n  for (size_t i = 1; i < argc; i += 2){\n    std::stringstream argss(std::string(argv[i]) + \" \" + std::string(argv[i+1]));\n    std::string option;\n    argss >> option;\n\n    if (option == \"-o\"){\n      argss >> file_string;\n\n    } else if (option == \"-t\"){\n      if (!(argss >> training_count) || training_count < 2) {\n        std::cerr << \"\\033[1;31mError: Invalid training count.\\n\\033[0m\";\n        return -1;\n      }\n\n    } else if (option == \"-f\"){\n      if (!(argss >> feature_count) || feature_count < 1) {\n        std::cerr << \"\\033[1;31mError: Invalid feature count.\\n\\033[0m\";\n        return -1;\n      }\n\n    } else if (option == \"-b\"){\n      if (!(argss >> bound) || bound < 1) {\n        std::cerr << \"\\033[1;31mError: Invalid feature count.\\n\\033[0m\";\n        return -1;\n      }\n\n    } else if (option == \"-w\"){\n      std::string w;\n      argss >> w;\n      if (w == \"STDOUT\"){\n        show_weight = 1;\n      } else if (w == \"BOTH\"){\n        show_weight = 2;\n      } else if (w == \"FEATURE\"){\n        show_weight = 3;\n      } else {\n        std::cerr << \"\\033[1;31mError: Invalid selection: \" << w << \".\\n\\033[0m\";\n        return -1;\n      }\n\n    } else {\n      std::cerr << \"\\033[1;31mError: Invalid option: \" << option << \".\\n\\033[0m\";\n      return -1;\n    }\n  }\n\n  std::ofstream features_ofs(file_string);\n  if (!features_ofs.is_open()) {\n    std::cerr << \"\\033[1;31mError: Invalid Output file: \" << file_string << \".\\n\\033[0m\";\n    return -1;\n  }\n\n  Qvec weights(feature_count + 1); // Adds bias term\n  Qvec features(feature_count);\n\n  std::generate(weights.begin(), weights.end(), Random(bound));\n\n  features_ofs << training_count << std::endl;\n  features_ofs << feature_count << std::endl;\n\n  while (training_count--){\n    Q dot;\n    do {\n      dot = weights[0];\n      std::generate(features.begin(), features.end(), Random(bound));\n      for (size_t i = 0; i < features.size(); ++i){\n        dot += weights[i+1] * features[i];\n      }\n    } while (!dot); // make sure point does not lie on boundary\n\n    features_ofs << (dot > 0) << std::endl;\n    for (size_t i = 0; i < features.size(); ++i){\n      features_ofs << features[i] << std::endl;\n    }\n  }\n\n  if (show_weight == 1 || show_weight == 2){\n    for (size_t i = 0; i < weights.size(); ++i){\n      std::cout << weights[i] << std::endl;\n    }\n  } else if (show_weight == 2 || show_weight == 3){\n    for (size_t i = 0; i < weights.size(); ++i){\n      features_ofs << weights[i] << std::endl;\n    }\n  }\n\n  features_ofs.close();\n  return 0;\n}\n", "meta": {"hexsha": "24559435b3a794a72eb437733489b3ce99a9f765", "size": 4426, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Benchmarks/cpp/data_generator.cpp", "max_stars_repo_name": "billy-price/CoqPerceptron", "max_stars_repo_head_hexsha": "e21936d4f405de495594183d5ee51efed5214dcf", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2016-03-07T20:47:44.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-04T18:18:07.000Z", "max_issues_repo_path": "Benchmarks/cpp/data_generator.cpp", "max_issues_repo_name": "billy-price/CoqPerceptron", "max_issues_repo_head_hexsha": "e21936d4f405de495594183d5ee51efed5214dcf", "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": "Benchmarks/cpp/data_generator.cpp", "max_forks_repo_name": "billy-price/CoqPerceptron", "max_forks_repo_head_hexsha": "e21936d4f405de495594183d5ee51efed5214dcf", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-15T13:32:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-15T13:32:33.000Z", "avg_line_length": 28.0126582278, "max_line_length": 89, "alphanum_fraction": 0.5542250339, "num_tokens": 1235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952893703476, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.7253981290262841}}
{"text": "/* adcpp_eigen_backward.test.cpp\n *\n *  Created on: 21 Aug 2019\n *      Author: Fabian Meyer\n */\n\n#include <catch2/catch.hpp>\n#include <adcpp/adcpp_eigen.hpp>\n#include <Eigen/Geometry>\n#include <Eigen/Eigenvalues>\n#include \"assert/eigen_require.hpp\"\n\nusing namespace adcpp;\n\nTEST_CASE(\"Eigen backward algorithmic differentiation\")\n{\n    double eps = 1e-6;\n\n    SECTION(\"exp\")\n    {\n        bwd::Vector2d x;\n        x << 3, 2;\n\n        Eigen::Vector2d valExp;\n        valExp <<\n            std::exp(x(0).value()),std::exp(x(1).value());\n        Eigen::Matrix2d jacExp;\n        jacExp << std::exp(x(0).value()), 0,\n            0, std::exp(x(1).value());\n\n        bwd::Vector2d f = x.array().exp();\n\n        Eigen::Matrix2d jacAct;\n        bwd::jacobian(x, f, jacAct);\n\n        REQUIRE_MATRIX_APPROX(valExp, f.template cast<double>(), eps);\n        REQUIRE_MATRIX_APPROX(jacExp, jacAct, eps);\n    }\n\n    // SECTION(\"singular value decomposition\")\n    // {\n    //     bwd::Matrix4d A;\n    //     A << 2, 3, 11, 5,\n    //         1, 1, 5, 2,\n    //         2, 1, -3, 2,\n    //         1, 1, -3, 4;\n    //     bwd::Vector4d b;\n    //     b << 2, 1, -3, -3;\n    //\n    //     Eigen::Vector4d valExp;\n    //     Eigen::Vector4d gradExp;\n    //     valExp << -0.5, -0.1875, 0.4375, -0.25;\n    //     gradExp << -0.205283, 0.687338, -0.0722404, -0.117474;\n    //\n    //     Eigen::JacobiSVD<bwd::Matrix4d, Eigen::FullPivHouseholderQRPreconditioner>\n    //         solver(A, Eigen::ComputeFullU | Eigen::ComputeFullV);\n    //     bwd::Vector4d f = solver.solve(b);\n    //\n    //     Eigen::MatrixXd jacAct(4, 4);\n    //     std::cout << \"jacobian\" << std::endl;\n    //     jacobian(b, f, jacAct);\n    //\n    //     std::cout << jacAct << std::endl;\n    //     REQUIRE_MATRIX_APPROX(valExp, f.template cast<double>(), eps);\n    // }\n\n    // SECTION(\"eigen value decomposition\")\n    // {\n    //     bwd::Matrix4d A;\n    //     A << 2, 3, 11, 5,\n    //         1, 1, 5, 2,\n    //         2, 1, -3, 2,\n    //         1, 1, -3, 4;\n    //     bwd::Vector4d b;\n    //     b << 2, 1, -3, -3;\n    //\n    //     Eigen::Vector4d eigvalsExp;\n    //     eigvalsExp << 7.27048, -5.64984, -0.291657, 2.67103;\n    //     Eigen::Vector4d eiggradExp;\n    //     eiggradExp <<  0.536189,  0.463811, 0, 0;\n    //\n    //     Eigen::EigenSolver<bwd::Matrix4d> solver(A);\n    //     bwd::Vector4d eigvals = solver.eigenvalues().real();\n    //     bwd::Matrix4d eigvecs = solver.eigenvectors().real();\n    //\n    //     Eigen::MatrixXd jacAct(4, 4);\n    //     std::cout << \"jacobian\" << std::endl;\n    //     jacobian(b, eigvals, jacAct);\n    //\n    //     REQUIRE_MATRIX_APPROX(eigvalsExp, eigvals.template cast<double>(), eps);\n    // }\n\n    SECTION(\"multiple outputs\")\n    {\n        bwd::Vector2d x;\n        x << bwd::Double(3), bwd::Double(2);\n\n        bwd::Matrix2d c;\n        c << bwd::Double(2.1), bwd::Double(3.4),\n            bwd::Double(1.6), bwd::Double(2.3);\n\n        Eigen::Vector2d valExp;\n        valExp <<\n            x(0).value() * c(0, 0).value() +  x(1).value() * c(0, 1).value(),\n            x(0).value() * c(1, 0).value() +  x(1).value() * c(1, 1).value();\n        Eigen::Matrix2d jacExp;\n        jacExp << c(0, 0).value(), c(0, 1).value(),\n            c(1, 0).value(), c(1, 1).value();\n\n        bwd::Vector2d f = c * x;\n        Eigen::Matrix2d jacAct;\n        jacobian(x, f, jacAct);\n\n        REQUIRE_MATRIX_APPROX(valExp, f.template cast<double>(), eps);\n        REQUIRE_MATRIX_APPROX(jacExp, jacAct, eps);\n    }\n}\n", "meta": {"hexsha": "8d570b57c0a358788d155b35ef9df86d96693075", "size": 3504, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/src/adcpp_eigen_backward.test.cpp", "max_stars_repo_name": "Rookfighter/algorithmic-differentiation", "max_stars_repo_head_hexsha": "6392ff3c94f8d0e97986f1023a7478786ab76a9a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-10-08T10:31:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-16T21:54:12.000Z", "max_issues_repo_path": "tests/src/adcpp_eigen_backward.test.cpp", "max_issues_repo_name": "Rookfighter/algorithmic-differentiation-cpp", "max_issues_repo_head_hexsha": "6392ff3c94f8d0e97986f1023a7478786ab76a9a", "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/src/adcpp_eigen_backward.test.cpp", "max_forks_repo_name": "Rookfighter/algorithmic-differentiation-cpp", "max_forks_repo_head_hexsha": "6392ff3c94f8d0e97986f1023a7478786ab76a9a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-10-02T04:34:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-16T22:17:54.000Z", "avg_line_length": 29.6949152542, "max_line_length": 85, "alphanum_fraction": 0.5065639269, "num_tokens": 1200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.908617906830944, "lm_q2_score": 0.7981867825403177, "lm_q1q2_score": 0.7252468036119094}}
{"text": "/**\n * @date 2021.3.4 \n * @author hqy - sentinel\n * @note \u6570\u5b57\u56fe\u50cf\u5904\u7406\u7b2c\u4e00\u6b21\u4f5c\u4e1a\n */\n\n#include <utility>\n#include <opencv2/core.hpp>\n#include <opencv2/imgproc.hpp>\n#include <opencv2/highgui.hpp>\n#include <Eigen/Core>\n#include \"include/utils.hpp\"\n\n/// \u6c42\u5f97\u56fe\u50cf\u5747\u503c\u4ee5\u53ca\u65b9\u5dee\nstd::pair<double, double> getMeanVar(const cv::Mat& src, bool use_buildin = false) {\n    if (use_buildin == false){      // \u624b\u5199\u5b9e\u73b0\n        int img_sz = src.cols * src.rows;\n        uchar* data = src.data;\n        double mean = 0.0, var = 0.0;\n        uint64_t start_t = getCurrentTime();\n        for (size_t i = 0; i < img_sz; i++){\n            mean += double(data[i]);\n        }\n        mean /= double(img_sz);\n        for (size_t i = 0; i < img_sz; i++){\n            var += std::pow(double(data[i]) - mean, 2);\n        }\n        var /= double(img_sz);\n        return std::make_pair(mean, var);\n    }\n    else{           // opencv \u8c03\u5e93\u4e24\u884c\n        cv::Scalar mean, var2;\n        cv::meanStdDev(src, mean, var2);\n        return std::make_pair(mean[0], std::pow(var2[0], 2));\n    }\n}\n\nvoid imgCrop(const uchar* const data, int px, int py, int step, uchar* buf) {\n    int cnt = 0;\n    for (int i = 0; i < 4; i++){\n        int offset = (py + i) * step + px;\n        for (int j = 0; j < 4; j++, cnt++){\n            buf[cnt] = data[offset + j];\n        }\n    }\n}\n\n\nvoid linearInterpZoom(const cv::Mat& src, cv::Mat& dst, int k = 4) {\n    cv::Mat padding;\n    int nrows = src.rows * k, ncols = src.cols * k;\n    dst = cv::Mat::zeros(cv::Size(ncols, nrows), CV_8UC1);\n    cv::copyMakeBorder(src, padding, 1, 1, 1, 1, CV_HAL_BORDER_REPLICATE);      // opencv padding\u64cd\u4f5c\n    uint64_t start_t = getCurrentTime();\n    #pragma omp parallel for num_threads(8)\n    for (size_t i = 0; i < nrows; i++) {\n        int base = i * ncols;\n        for (size_t j = 0; j < ncols; j++) {\n            ;\n        }\n    }\n}\n\ntemplate<typename T>\nvoid getWeightVector(T* res, double z, double a = -0.5){\n    for (int i = -1, cnt = 0; cnt < 4; i++, cnt++){\n        double x = std::abs(i - z);\n        if (x <= 1)\n            res[cnt] = (a + 2) * std::pow(x, 3) - (a + 3) * std::pow(x, 2) + 1;\n        else if (x < 2)\n            res[cnt] = a * std::pow(x, 3) - 5 * a * std::pow(x, 2) + 8 * a * x - 4 * a;\n    }\n}\n\ntemplate<typename T = double>\nuchar calcWeightSum(const T* const wx, const T* const wy, const uchar* const buf) {\n    int cnt = 0;\n    T res = 0.0;\n    for (int i = 0; i < 4; i++) {\n        for (int j = 0; j < 4; j++, cnt++) {\n            res += wx[j] * wy[i] * T(buf[cnt]);\n        }\n    }\n    return uchar(res);\n}\n\nvoid biCubicInterpZoom(const cv::Mat& src, cv::Mat& dst, int k = 4) {\n    cv::Mat padding;\n    int nrows = src.rows * k, ncols = src.cols * k;\n    dst = cv::Mat::zeros(cv::Size(ncols, nrows), CV_8UC1);\n    cv::copyMakeBorder(src, padding, 1, 2, 1, 2, CV_HAL_BORDER_REPLICATE);      // opencv padding\u64cd\u4f5c\n    uint64_t start_t = getCurrentTime();\n    #pragma omp parallel for num_threads(8)\n    for (size_t i = 0; i < nrows; i++) {\n        int base = i * ncols;\n        for (size_t j = 0; j < ncols; j++) {\n            int px = j / k, py = i / k;\n            double u = double(j) / double(k) - double(px);\n            double v = double(i) / double(k) - double(py);\n            double wx[4] = {0, 0, 0, 0};\n            double wy[4] = {0, 0, 0, 0};\n            getWeightVector<double>(wx, u);\n            getWeightVector<double>(wy, v);\n            uchar crop[16];\n            imgCrop(padding.data, px, py, padding.cols, crop);\n            dst.data[base + j] = calcWeightSum<double>(wx, wy, crop);\n        }\n    }\n    uint64_t end_t = getCurrentTime();\n    printf(\"Time elapse: %lf ms\\n\", double(end_t - start_t) / 1e6);\n}\n\nvoid rotate(const cv::Mat& src, cv::Mat& dst, double angle) {\n    dst.create(src.rows, src.cols, CV_8UC1);\n}\n\nvoid shear(const cv::Mat& src, cv::Mat& dst, double ratio) {\n    dst.create(src.rows, src.cols, CV_8UC1);\n}\n\nint main() {\n    cv::Mat img = cv::imread(\"../data/lena.bmp\", 0);\n    cv::Mat dst;\n    biCubicInterpZoom(img, dst);\n    cv::imshow(\"disp\", dst);\n    cv::waitKey(0);\n    cv::imwrite(\"../data/czoomed.bmp\", dst);\n    std::pair<double, double> res = getMeanVar(img, false);\n    printf(\"Mean: %lf, Var: %lf\\n\", res.first, res.second);\n    res = getMeanVar(img, true);\n    printf(\"Mean: %lf, Var: %lf\\n\", res.first, res.second);\n    \n    return 0;\n}", "meta": {"hexsha": "8ebec55a1544ff0ae28eaa608c065df889df120a", "size": 4324, "ext": "cc", "lang": "C++", "max_stars_repo_path": "first/homework1.cc", "max_stars_repo_name": "Enigmatisms/DIP", "max_stars_repo_head_hexsha": "f8dcbfc60bcb7be3d79d52e23c689e214f79630b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-28T09:03:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-28T09:03:39.000Z", "max_issues_repo_path": "first/homework1.cc", "max_issues_repo_name": "Enigmatisms/DIP", "max_issues_repo_head_hexsha": "f8dcbfc60bcb7be3d79d52e23c689e214f79630b", "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": "first/homework1.cc", "max_forks_repo_name": "Enigmatisms/DIP", "max_forks_repo_head_hexsha": "f8dcbfc60bcb7be3d79d52e23c689e214f79630b", "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.2686567164, "max_line_length": 99, "alphanum_fraction": 0.5314523589, "num_tokens": 1423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.8104789063814616, "lm_q1q2_score": 0.7252079811067316}}
{"text": "#include <iostream>\r\n#include <string> \r\n#include <Eigen/Dense>\r\nusing Eigen::MatrixXd;\r\nusing std::string;\r\nextern \"C\" {\r\n\tMatrixXd newMatrixXd(int aCols,int aRows,double* aRaw)\r\n\t{\r\n\t\t MatrixXd m(aCols,aRows);\r\n\t\t for(int i=0;i<aCols;i++)\r\n\t\t {\r\n\t\t\t for(int j=0;j<aRows;j++)\r\n\t\t\t {\r\n\t\t\t\t m(i,j) =aRaw[i*aRows+j];   \r\n\t\t\t }\r\n\t\t}\r\n\t\treturn m;\r\n\t}\r\n\tconst char* printMatrixXd(int aCols,int aRows,double* aRaw)\r\n\t{\r\n\t\t std::cout <<\"aCols=\"<< aCols <<\",aRows=\"<< aRows<< std::endl;\r\n\t\t MatrixXd m(aCols,aRows);\r\n\t\t for(int i=0;i<aCols;i++)\r\n\t\t {\r\n\t\t\t for(int j=0;j<aRows;j++)\r\n\t\t\t {\r\n\t\t\t\t int index=i*aRows+j;\r\n\t\t\t\t m(i,j) =aRaw[index];  \r\n\t\t\t\tstd::cout <<index<<\",\"<<\"m(\"<<i<<\",\"<<j<<\")=\"<<m(i,j)<< std::endl;\r\n\t\t\t }\r\n\t\t }\r\n\t\tstd::stringstream str;\r\n\t\tstr << m;\r\n\t\t// std::cout << m << std::endl; \r\n\t\treturn str.str().c_str() ;\r\n\t}\r\n\t\r\n\tconst char* addMatrixXd(int aCols,int aRows,double* aRaw,int bCols,int bRows,double* bRaw)\r\n\t{\r\n\t\tMatrixXd  A=newMatrixXd(aCols,aRows,aRaw);\r\n\t\tMatrixXd  B=newMatrixXd(bCols,bRows,bRaw);\r\n\t\tMatrixXd C=A+B;\r\n\t\tstd::stringstream str;\r\n\t\tstr << C;\r\n\t\tstd::cout << A<< std::endl<<\"+\"<< std::endl<<B<< std::endl<<\"=\"<< std::endl<<C << std::endl; \r\n\t\treturn str.str().c_str() ;\r\n\t}\r\n\tconst char* subMatrixXd(int aCols,int aRows,double* aRaw,int bCols,int bRows,double* bRaw)\r\n\t{\r\n\t\tMatrixXd  A=newMatrixXd(aCols,aRows,aRaw);\r\n\t\tMatrixXd  B=newMatrixXd(bCols,bRows,bRaw);\r\n\t\tMatrixXd C=A-B;\r\n\t\tstd::stringstream str;\r\n\t\tstr << C; \r\n\t\tstd::cout << A<< std::endl<<\"-\"<< std::endl<<B<< std::endl<<\"=\"<< std::endl<<C<< std::endl; \r\n\t\treturn str.str().c_str() ;\r\n\t}\r\n\tconst char* trMatrixXd(int aCols,int aRows,double* aRaw)\r\n\t{\r\n\t\tMatrixXd  A=newMatrixXd(aCols,aRows,aRaw); \r\n\t\tMatrixXd C=A.transpose();\r\n\t\tstd::stringstream str;\r\n\t\tstr << C; \r\n\t\tstd::cout << A<< std::endl<<\"transpose\"<< std::endl<<C<< std::endl; \r\n\t\treturn str.str().c_str() ;\r\n\t}\r\n\tconst char* muiltMatrixXd(int aCols,int aRows,double* aRaw,int bCols,int bRows,double* bRaw)\r\n\t{\r\n\t\tMatrixXd  A=newMatrixXd(aCols,aRows,aRaw);\r\n\t\tMatrixXd  B=newMatrixXd(bCols,bRows,bRaw);\r\n\t\tMatrixXd C=A*B;\r\n\t\tstd::stringstream str;\r\n\t\tstr << C; \r\n\t\tstd::cout << A<< std::endl<<\"*\"<< std::endl<<B<< std::endl<<\"=\"<< std::endl<<C<< std::endl; \r\n\t\treturn str.str().c_str() ;\r\n\t}\r\n\tconst char* inverseMatrixXd(int aCols,int aRows,double* aRaw)\r\n\t{\r\n\t\tMatrixXd  A=newMatrixXd(aCols,aRows,aRaw); \r\n\t\tMatrixXd C=A.inverse();\r\n\t\tstd::stringstream str;\r\n\t\tstr << C; \r\n\t\tstd::cout << A<< std::endl<<\"inverse\"<< std::endl<<C<< std::endl; \r\n\t\treturn str.str().c_str() ;\r\n\t}\r\n\tconst char* adjointMatrixXd(int aCols,int aRows,double* aRaw)\r\n\t{\r\n\t\tMatrixXd  A=newMatrixXd(aCols,aRows,aRaw); \r\n\t\tMatrixXd C=A.adjoint();\r\n\t\tstd::stringstream str;\r\n\t\tstr << C; \r\n\t\tstd::cout << A<< std::endl<<\"adjoint\"<< std::endl<<C<< std::endl; \r\n\t\treturn str.str().c_str() ;\r\n\t}\r\n\tconst char* traceMatrixXd(int aCols,int aRows,double* aRaw )\r\n\t{\r\n\t\tMatrixXd  A=newMatrixXd(aCols,aRows,aRaw); \r\n\t\tdouble C=A.trace();\r\n\t\tstd::stringstream str;\r\n\t\tstr << C; \r\n\t\tstd::cout << A<< std::endl<<\"trace\"<< std::endl<<C<< std::endl; \r\n\t\treturn str.str().c_str() ;\r\n\t}\r\n\tconst char* detMatrixXd(int aCols,int aRows,double* aRaw)\r\n\t{\r\n\t\tMatrixXd  A=newMatrixXd(aCols,aRows,aRaw); \r\n\t\tdouble C=A.determinant();\r\n\t\tstd::stringstream str;\r\n\t\tstr << C; \r\n\t\tstd::cout << A<< std::endl<<\"det\"<< std::endl<<C<< std::endl; \r\n\t\treturn str.str().c_str() ;\r\n\t}\r\n\tconst char* rankMatrixXd(int aCols,int aRows,double* aRaw)\r\n\t{\r\n\t\tMatrixXd  A=newMatrixXd(aCols,aRows,aRaw); \r\n\t\tEigen::FullPivLU<MatrixXd> lu_decomp(A); \r\n\t\tdouble C=lu_decomp.rank();\r\n\t\tstd::stringstream str;\r\n\t\tstr << C; \r\n\t\tstd::cout << A<< std::endl<<\"LU rank\"<< std::endl<<C<< std::endl; \r\n\t\treturn str.str().c_str() ;\r\n\t}\r\n}", "meta": {"hexsha": "d1e2e6f7841b7e2902534b876e18bf413323e77d", "size": 3718, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "zhhaogen/TestEigenjs", "max_stars_repo_head_hexsha": "b1f51e9fc4d890d94493976869a7dc7af7f96cf0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-12T19:01:31.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-12T19:01:31.000Z", "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "zhhaogen/TestEigenjs", "max_issues_repo_head_hexsha": "b1f51e9fc4d890d94493976869a7dc7af7f96cf0", "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": "zhhaogen/TestEigenjs", "max_forks_repo_head_hexsha": "b1f51e9fc4d890d94493976869a7dc7af7f96cf0", "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.2276422764, "max_line_length": 96, "alphanum_fraction": 0.5973641743, "num_tokens": 1179, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111796979521252, "lm_q2_score": 0.7956581073313275, "lm_q1q2_score": 0.7249875139113185}}
{"text": "#include \"../../Headers/Edmonton.hpp\"\r\n#include <boost/multiprecision/cpp_int.hpp>\r\n#include <iostream>\r\n\r\nusing namespace std;\r\nusing boost::multiprecision::cpp_int;\r\n\r\n/* \r\nReally straightforward problem to brute-force. \r\nWe don't really need to worry about the actual decimals, the numerator and denominator follow an obvious pattern where:\r\n1. numerator += 2 * denominator\r\n2. denominator = numerator - denominator\r\nfor each of the expansion/iteration we are testing.\r\n*/\r\n\r\nint main(int argc, char *argv[]) {\r\n\tint num_count = 0;\r\n\tcpp_int numerator = 3, denominator = 2;\r\n\tfor(int i = 1; i < 1'000; i++) {\r\n\t\tnumerator += 2 * denominator;\r\n\t\tdenominator = numerator - denominator;\r\n\t\tif(Edmonton::digitCount<int, cpp_int>(numerator) > Edmonton::digitCount<int, cpp_int>(denominator)) {\r\n\t\t\tnum_count++;\r\n\t\t}\r\n\t}\r\n\tcout << num_count << endl;\r\n\treturn 0;\r\n}", "meta": {"hexsha": "bd8bc1fe1818e2a0f3a0b4dd25c5ac00409f0299", "size": 861, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Solutions/51-100/57/Solution.cpp", "max_stars_repo_name": "kitegi/Edmonton", "max_stars_repo_head_hexsha": "774c9b2f72e7b2c6a3bc1b3329ef227ef39adf9d", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-07-16T13:30:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-16T18:17:40.000Z", "max_issues_repo_path": "Solutions/51-100/57/Solution.cpp", "max_issues_repo_name": "kitegi/Edmonton", "max_issues_repo_head_hexsha": "774c9b2f72e7b2c6a3bc1b3329ef227ef39adf9d", "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": "Solutions/51-100/57/Solution.cpp", "max_forks_repo_name": "kitegi/Edmonton", "max_forks_repo_head_hexsha": "774c9b2f72e7b2c6a3bc1b3329ef227ef39adf9d", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-16T22:56:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-16T22:56:07.000Z", "avg_line_length": 30.75, "max_line_length": 120, "alphanum_fraction": 0.6957026713, "num_tokens": 212, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404077216356, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.7249569239854994}}
{"text": "// -*- coding: utf-8 -*-\n\n#include <iostream>\n#include <fstream>\n#include <Eigen/Dense>\n#include <Eigen/LU>\n#include <chrono>\n\nint main()\n{\n  std::cout << \"\" << std::endl;\n  std::cout << \" # C++ Eigen benchmark\" << std::endl;\n\n  int n;\n  std::ifstream fr(\"input\");\n  fr >> n;\n  std::cout << \"n \" << n << std::endl;\n\n  std::srand((unsigned int)time(NULL));\n\n  Eigen::MatrixXd A = Eigen::MatrixXd::Random(n, n);\n  Eigen::MatrixXd B = Eigen::MatrixXd::Random(n, n);\n  std::chrono::system_clock::time_point start, end;\n  double time;\n\n  // multiplication\n  start = std::chrono::system_clock::now();\n  Eigen::MatrixXd C = A*B;\n  end = std::chrono::system_clock::now();\n  time = static_cast<double>(std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count()/1000.0);\n  std::cout << \"multiplication time \" << time << std::endl;\n\n  // inverse\n  start = std::chrono::system_clock::now();\n  Eigen::MatrixXd D = A.inverse();\n  end = std::chrono::system_clock::now();\n  time = static_cast<double>(std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count()/1000.0);\n  std::cout << \"inverse time \" << time << std::endl;\n\n  // LU inverse\n  start = std::chrono::system_clock::now();\n  Eigen::MatrixXd E = A.partialPivLu().inverse();\n  end = std::chrono::system_clock::now();\n  time = static_cast<double>(std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count()/1000.0);\n  std::cout << \"LU inverse time \" << time << std::endl;\n\n  // LU decomposition\n  start = std::chrono::system_clock::now();\n  Eigen::MatrixXd F = A.partialPivLu().matrixLU();\n  end = std::chrono::system_clock::now();\n  time = static_cast<double>(std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count()/1000.0);\n  std::cout << \"LU decomposition time \" << time << std::endl;\n\n  // rank-revealing QR\n  start = std::chrono::system_clock::now();\n  Eigen::MatrixXd G = A.colPivHouseholderQr().matrixQR();\n  end = std::chrono::system_clock::now();\n  time = static_cast<double>(std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count()/1000.0);\n  std::cout << \"rank-revealing QR time \" << time << std::endl;\n}\n", "meta": {"hexsha": "205135bc504a0157d733a663617789c85dbb4735", "size": 2141, "ext": "cc", "lang": "C++", "max_stars_repo_path": "main.cc", "max_stars_repo_name": "ya-mat/eigen_benchmark", "max_stars_repo_head_hexsha": "387e7a5cecb28553804b14e7e691aa3e6f049ea3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-19T09:15:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-19T09:15:17.000Z", "max_issues_repo_path": "main.cc", "max_issues_repo_name": "ya-mat/eigen_benchmark", "max_issues_repo_head_hexsha": "387e7a5cecb28553804b14e7e691aa3e6f049ea3", "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.cc", "max_forks_repo_name": "ya-mat/eigen_benchmark", "max_forks_repo_head_hexsha": "387e7a5cecb28553804b14e7e691aa3e6f049ea3", "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.0983606557, "max_line_length": 112, "alphanum_fraction": 0.6487622606, "num_tokens": 605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067195846918, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.724863291338949}}
{"text": "/**\n * @file expfittedupwind.cc\n * @brief NPDE homework ExpFittedUpwind\n * @author Am\u00e9lie Loher, Philippe Peter\n * @date 07.01.2021\n * @copyright Developed at ETH Zurich\n */\n\n#include \"expfittedupwind.h\"\n\n#include <lf/base/base.h>\n#include <lf/mesh/mesh.h>\n#include <lf/mesh/utils/utils.h>\n\n#include <Eigen/Core>\n#include <cmath>\n#include <memory>\n#include <vector>\n\nnamespace ExpFittedUpwind {\n\n/**\n * @brief Computes the Bernoulli function B(tau)\n **/\ndouble Bernoulli(double tau) {\n  if (std::abs(tau) < 1e-10) {\n    return 1.0;\n  } else if (std::abs(tau) < 1e-3) {\n    return 1.0 / (1.0 + (0.5 + 1.0 / 6.0 * tau) * tau);\n  } else {\n    return tau / (std::exp(tau) - 1.0);\n  }\n}\n\n/**\n * @brief computes the quantities \\beta(e) for all the edges e of a mesh\n * @param mesh_p underlying mesh\n * @param mu vector of nodal values of a potential Psi\n * @return  Mesh Data set containing the quantities \\beta(e)\n */\nstd::shared_ptr<lf::mesh::utils::CodimMeshDataSet<double>> CompBeta(\n    std::shared_ptr<const lf::mesh::Mesh> mesh_p, const Eigen::VectorXd& mu) {\n  // data set over all edges of the mesh.\n  auto beta_p = lf::mesh::utils::make_CodimMeshDataSet(mesh_p, 1, 1.0);\n\n  // compute beta(e) for all edges of the mesh\n  for (const lf::mesh::Entity* edge : mesh_p->Entities(1)) {\n    // compute the indices of the endpoints of the edge\n    // These are needed to  access the correct nodal values of mu\n    auto endpoints = edge->SubEntities(1);\n    unsigned int i = mesh_p->Index(*(endpoints[0]));\n    unsigned int j = mesh_p->Index(*(endpoints[1]));\n\n    (*beta_p)(*edge) = std::exp(mu(j)) * Bernoulli(mu(j) - mu(i));\n  }\n\n  return beta_p;\n}\n\n/**\n * @brief actual computation of the element matrix\n * @param cell reference to the triangle for which the matrix is evaluated\n * @return 3x3 dense matrix containg the element matrix\n */\nEigen::Matrix3d ExpFittedEMP::Eval(const lf::mesh::Entity& cell) {\n  LF_VERIFY_MSG(cell.RefEl() == lf::base::RefEl::kTria(),\n                \"Only 2D triangles are supported.\");\n\n  // Evaluate the element matrix A_K\n  Eigen::Matrix3d AK = laplace_provider_.Eval(cell).block<3, 3>(0, 0);\n\n  Eigen::Matrix3d result;\n\n  // get the values of beta on the edges of the triangle.\n  // by the Lehrfem++ numbering convention\n  // b = [beta(e_0), beta(e_1), beta(e_2)]' = [\\beta_{1,2}, \\beta_{2,3},\n  // \\beta_{1,3}]'\n  Eigen::Vector3d b = beta_loc(cell);\n\n  // evaluate the element matrix using the formula in subproblem h)\n  result << AK(0, 1) * b(0) + AK(0, 2) * b(2), -AK(0, 1) * b(0),\n      -AK(0, 2) * b(2), -AK(0, 1) * b(0), AK(0, 1) * b(0) + AK(1, 2) * b(1),\n      -AK(1, 2) * b(1), -AK(0, 2) * b(2), -AK(1, 2) * b(1),\n      AK(0, 2) * b(2) + AK(1, 2) * b(1);\n\n  Eigen::Vector3d mu_exp = (-mu_loc(cell)).array().exp();\n  result *= mu_exp.asDiagonal();\n\n  return std::move(result);\n}\n\n/**\n * @brief returns the quanties beta(e) for  the\n * three edges e_0, e_1 and e_2 of a triangle.\n * @param cell reference to the triangle for which the quantities are needed\n * @return vector  [beta(e_0),beta(e_1),beta(e_2)]'\n **/\nEigen::Vector3d ExpFittedEMP::beta_loc(const lf::mesh::Entity& cell) {\n  Eigen::Vector3d b;\n  auto edges = cell.SubEntities(1);\n  for (int i = 0; i < 3; ++i) {\n    b(i) = (*beta_)(*(edges[i]));\n  }\n  return b;\n}\n\n/** @brief returns the nodal values of the potential Psi for the\n * three vertices a_1, a_2 and a_3 of a triangle\n * @param cell reference to the triangle for which the quantities are needed\n * @return vector [Psi(a_1), Psi(a_2), Psi(a_3)]'\n **/\nEigen::Vector3d ExpFittedEMP::mu_loc(const lf::mesh::Entity& cell) {\n  Eigen::Vector3d m;\n  auto mesh_p = fe_space_->Mesh();\n  auto vertices = cell.SubEntities(2);\n  for (int i = 0; i < 3; ++i) {\n    int index = mesh_p->Index(*(vertices[i]));\n    m(i) = mu_(index);\n  }\n  return m;\n}\n\n} /* namespace ExpFittedUpwind */\n", "meta": {"hexsha": "d2c4085a1ebbf626ea89b19095215d951517ef18", "size": 3831, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/ExpFittedUpwind/mastersolution/expfittedupwind.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": "homeworks/ExpFittedUpwind/mastersolution/expfittedupwind.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": "homeworks/ExpFittedUpwind/mastersolution/expfittedupwind.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": 30.8951612903, "max_line_length": 78, "alphanum_fraction": 0.6376925085, "num_tokens": 1261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.7246422881766386}}
{"text": "#include \"math/rotation.h\"\n\n#include <ceres/rotation.h>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <glog/logging.h>\n#include <limits>\n\nnamespace GraphSfM {\n// Eigen::Vector3d MultiplyRotations(const Eigen::Vector3d& rotation1,\n//                                   const Eigen::Vector3d& rotation2) {\n//   const double theta1_sq = rotation1.squaredNorm();\n//   const double theta2_sq = rotation2.squaredNorm();\n\n//   // Compute the sin and cosine terms below. Take care to ensure that there will\n//   // not be any divide-by-zeros when the rotations are small.\n//   double cos_a;\n//   double cos_b;\n//   Eigen::Vector3d sin_a_times_v1;\n//   Eigen::Vector3d sin_b_times_v2;\n\n//   // We need to explicity handle the cases when the rotations are near zero.\n//   // Near zero, the first order Taylor approximation of the rotation matrix R\n//   // corresponding to a vector w and angle w is\n//   //\n//   //   R = I + hat(w) * sin(theta)\n//   //\n//   // But sintheta ~ theta and theta * w = angle_axis, which gives us\n//   //\n//   //  R = I + hat(angle_axis)\n//   //\n//   // We will use this in the special cases below to ensure stable computation\n//   // when composing the rotations and avoid dividing by zero when theta is\n//   // small.\n//   if (theta1_sq < std::numeric_limits<double>::epsilon()) {\n//     // Use the fact that theta ~ sin(theta) when theta is small. Since\n//     // a = 0.5 * theta1, we end up with:\n//     //   sin(a) * v1 = sin(theta / 2) * v1 = theta / 2 * v1 = rotation1 / 2.\n//     sin_a_times_v1 = 0.5 * rotation1;\n//     // When a is small, cos(a) ~ 1.0 by the first order taylor approximation.\n//     cos_a = 1.0;\n//   } else {\n//     const double theta1 = std::sqrt(theta1_sq);\n//     const double sin_a = std::sin(0.5 * theta1);\n//     cos_a = std::cos(0.5 * theta1);\n//     sin_a_times_v1 = sin_a * rotation1 / theta1;\n//   }\n\n//   // Same as above, but for theta2.\n//   if (theta2_sq < std::numeric_limits<double>::epsilon()) {\n//     sin_b_times_v2 = 0.5 * rotation2;\n//     cos_b = 1.0;\n//   } else {\n//     const double theta2 = std::sqrt(theta2_sq);\n//     const double sin_b = std::sin(0.5 * theta2);\n//     cos_b = std::cos(0.5 * theta2);\n//     sin_b_times_v2 = sin_b * rotation2 / theta2;\n//   }\n\n//   // Compute sin(c) * v3 using the formula above.\n//   const Eigen::Vector3d sin_c_times_v3 = cos_b * sin_a_times_v1 +\n//                                          cos_a * sin_b_times_v2 +\n//                                          sin_a_times_v1.cross(sin_b_times_v2);\n\n//   // If sin(c) is near zero then we again need to take care to avoid dividing by\n//   // zero. We can use the first order Taylor approximation again, noting that\n//   // sin(c) ~ c, which gives us:\n//   //   rotation3 = theta * v3 = 2 * c * v3 ~ 2 * sin(c) * v3\n//   const double sin_c_sq = sin_c_times_v3.squaredNorm();\n//   if (sinc_c < std::numeric_limits<double>::epsilon()) {\n//     const double diff = (2.0 * sin_c_times_v3 - rotation_aa).norm();\n//     return 2.0 * sin_c_times_v3;\n//   } else {\n//     // Otherwise, we use the formula above. The angle axis rotation is the axis\n//     // (v3) times the angle theta3.\n//     const double sin_c = std::sqrt(sin_c_sq);\n//     const double theta3 = 2.0 * std::asin(sin_c);\n//     const Eigen::Vector3d v3 = sin_c_times_v3 / sin_c;\n\n//     return theta3 * v3;\n//   }\n// }\n\n// Use Ceres to perform a stable composition of rotations. This is not as\n// efficient as directly composing angle axis vectors (see the old\n// implementation commented above) but is more stable.\nEigen::Vector3d MultiplyRotations(const Eigen::Vector3d& rotation1,\n                                  const Eigen::Vector3d& rotation2) {\n  Eigen::Matrix3d rotation1_mat, rotation2_mat;\n  ceres::AngleAxisToRotationMatrix(rotation1.data(), rotation1_mat.data());\n  ceres::AngleAxisToRotationMatrix(rotation2.data(), rotation2_mat.data());\n\n  const Eigen::Matrix3d rotation = rotation1_mat * rotation2_mat;\n  Eigen::Vector3d rotation_aa;\n  ceres::RotationMatrixToAngleAxis(rotation.data(), rotation_aa.data());\n  return rotation_aa;\n}\n\n}  // namespace GraphSfM\n", "meta": {"hexsha": "9acdd9016cb0929f855182bfcd58db6f00ca9243", "size": 4105, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/math/rotation.cpp", "max_stars_repo_name": "longchao343/GraphSfM", "max_stars_repo_head_hexsha": "c4cac7885f1ee383d9d0031a390bd1dbf3ee0104", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-17T04:16:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-17T04:16:29.000Z", "max_issues_repo_path": "src/math/rotation.cpp", "max_issues_repo_name": "longchao343/GraphSfM", "max_issues_repo_head_hexsha": "c4cac7885f1ee383d9d0031a390bd1dbf3ee0104", "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/math/rotation.cpp", "max_forks_repo_name": "longchao343/GraphSfM", "max_forks_repo_head_hexsha": "c4cac7885f1ee383d9d0031a390bd1dbf3ee0104", "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": 40.6435643564, "max_line_length": 83, "alphanum_fraction": 0.6321559074, "num_tokens": 1157, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425377849806, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.7246150489406563}}
{"text": "#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include \"vio/eigen_utils.h\"\n\nnamespace vio{\n\nusing namespace Eigen;\nusing namespace std;\nEigen::Vector3d rotro2eu(Eigen::Matrix3d R)\n{\n    Eigen::Vector3d euler;\n    euler[0] = atan2(R(2,1), R(2,2));\n    euler[1] = -(atan2(R(2,0),  sqrt(1 - R(2,0) * R(2,0))));\n    euler[2] = atan2(R(1,0), R(0,0));\n    return euler;\n}\n\n\nEigen::Matrix3d roteu2ro(Eigen::Vector3d eul)\n{\n    double cr = cos(eul[0]); double sr = sin(eul[0]);\t//roll\n    double cp = cos(eul[1]); double sp = sin(eul[1]);\t//pitch\n    double ch = cos(eul[2]); double sh = sin(eul[2]);\t//heading\n    Eigen::Matrix3d dcm;\n    dcm(0,0) = cp * ch;\n    dcm(0,1) = (sp * sr * ch) - (cr * sh);\n    dcm(0,2) = (cr * sp * ch) + (sh * sr);\n\n    dcm(1,0) = cp * sh;\n    dcm(1,1) = (sr * sp * sh) + (cr * ch);\n    dcm(1,2) = (cr * sp * sh) - (sr * ch);\n\n    dcm(2,0) = -sp;\n    dcm(2,1) = sr * cp;\n    dcm(2,2) = cr * cp;\n    return dcm;\n}\n//input: lat, long in radians, height is immaterial\n//output: Ce2n\nEigen::Matrix3d llh2dcm(const Eigen::Vector3d llh)\n{\n    double sL = sin(llh[0]);\n    double cL = cos(llh[0]);\n    double sl = sin(llh[1]);\n    double cl = cos(llh[1]);\n\n    Eigen::Matrix3d Ce2n;\n    Ce2n<< -sL * cl, -sL * sl, cL ,  -sl, cl, 0 , -cL * cl, -cL * sl, -sL;\n    return Ce2n;\n}\n\nEigen::MatrixXd nullspace(const Eigen::MatrixXd& A)\n{\n    Eigen::HouseholderQR<Eigen::MatrixXd> qr(A);\n   //ColPivHouseholderQR<MatrixXd> qr(A); //don't use column pivoting because in that case Q*R-A!=0\n    Eigen::MatrixXd nullQ = qr.householderQ();\n\n    int rows= A.rows(), cols= A.cols();\n    assert( rows> cols); // \"Rows should be greater than columns in computing nullspace\"\n    nullQ= nullQ.block(0,cols,rows,rows-cols).eval();\n    return nullQ;\n}\n\nvoid leftNullspaceAndColumnSpace(const Eigen::MatrixXd &A,\n                                        Eigen::MatrixXd *Q2,\n                                        Eigen::MatrixXd *Q1)\n{\n    int rows= A.rows(), cols= A.cols();\n    assert( rows> cols); // \"Rows should be greater than columns in computing left nullspace\"\n    Eigen::HouseholderQR<Eigen::MatrixXd> qr(A);\n    //don't use column pivoting because in that case Q*R-A!=0\n    Eigen::MatrixXd Q = qr.householderQ();\n\n    Q2->resize(rows, rows-cols);\n    *Q2 = Q.block(0,cols,rows,rows-cols);\n\n    Q1->resize(rows, cols);\n    *Q1 = Q.block(0,0,rows,cols);\n}\n\nEigen::Matrix<double, Eigen::Dynamic, 1> superdiagonal(\n        const Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> & M)\n{\n    const int numElements = std::min(M.rows(), M.cols()) - 1;\n    Eigen::Matrix<double, Eigen::Dynamic, 1> r(numElements, 1);\n    for(int jack = 0; jack< numElements; ++jack)\n        r[jack] = M(jack, jack+1);\n    return r;\n}\n\nEigen::Matrix<double, Eigen::Dynamic, 1> subdiagonal(\n        const Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> & M)\n{\n    const int numElements = std::min(M.rows(), M.cols()) - 1;\n    Eigen::Matrix<double, Eigen::Dynamic, 1> r(numElements, 1);\n    for(int jack = 0; jack< numElements; ++jack)\n        r[jack] = M(jack+1, jack);\n    return r;\n}\n\nvoid reparameterize_AIDP(const Eigen::Matrix3d &Ri, const Eigen::Matrix3d &Rj, const Eigen::Vector3d &abrhoi,\n                         const Eigen::Vector3d &pi, const Eigen::Vector3d &pj, Eigen::Vector3d& abrhoj,\n                         Eigen::Matrix<double, 3, 9>* jacobian)\n{\n   Eigen::Matrix<double, 4,4> Tci2cj =Eigen::Matrix<double, 4,4>::Identity();\n   Tci2cj.topLeftCorner<3,3>()= Rj.transpose()*Ri;\n   Tci2cj.block<3,1>(0,3).noalias() = Rj.transpose()*(pi-pj);\n   Eigen::Matrix<double, 4, 1> homogi;\n   homogi<< abrhoi.head<2>(), 1, abrhoi[2];\n   double rhoj_drhoi = 1/ (Tci2cj.row(2)* homogi); //\\rho_j divided by \\rho_i\n   abrhoj.head<2>() = rhoj_drhoi* Tci2cj.topLeftCorner<2,4>()*homogi;\n   abrhoj[2] = abrhoi[2]*rhoj_drhoi;\n   if(jacobian)\n   {\n       Eigen::Matrix3d lhs;\n       lhs.setIdentity();\n       lhs.col(2)= - abrhoj;\n       //{\\alpha, \\beta, \\rho}_i\n       Eigen::Matrix<double, 3, 3> subrhs;\n       subrhs<< Tci2cj.topLeftCorner<3,2>(), Tci2cj.block<3,1>(0,3);\n       jacobian->topLeftCorner<3,3>() = rhoj_drhoi*lhs*subrhs;\n       (*jacobian)(2,2) = rhoj_drhoi*rhoj_drhoi*Tci2cj.block<1,3>(2,0)*homogi.head<3>();\n       //{pi, pj}\n       Eigen::Matrix<double, 3, 6> rhs;\n       rhs.topLeftCorner<3,3>()= abrhoi[2]*Rj.transpose(),\n       rhs.block<3,3>(0,3)= - rhs.topLeftCorner<3,3>();\n       jacobian->block<3,6>(0,3) = rhoj_drhoi*lhs*rhs;\n\n   }\n}\n\nvoid reparameterizeNumericalJacobian(const Eigen::Matrix3d &Ri, const Eigen::Matrix3d &Rj, const Eigen::Vector3d &abrhoi,\n                                     const Eigen::Vector3d &pi, const Eigen::Vector3d &pj, Eigen::Vector3d& abrhoj,\n                                     Eigen::Matrix<double, 3, 9>& jacobian){\n   // numerical differentation\n   Eigen::Vector3d abrhojp;\n   reparameterize_AIDP(Ri, Rj, abrhoi, pi, pj, abrhoj);\n   double h= 1e-8;\n   for(int jack =0; jack<3; ++jack){\n       Eigen::Vector3d abrhoip= abrhoi;\n       abrhoip[jack]= abrhoi[jack] + h;\n       reparameterize_AIDP(Ri, Rj, abrhoip, pi, pj, abrhojp);\n       Eigen::Vector3d subJacobian = (abrhojp - abrhoj)/h;\n       jacobian.col(jack) = subJacobian;\n   }\n\n   for(int jack =0; jack<3; ++jack){\n       Eigen::Vector3d pip= pi; pip[jack]= pi[jack] + h;\n       reparameterize_AIDP(Ri, Rj, abrhoi, pip, pj, abrhojp);\n       Eigen::Vector3d subJacobian = (abrhojp - abrhoj)/h;\n       jacobian.col(jack+3) = subJacobian;\n   }\n\n   for(int jack =0; jack<3; ++jack){\n       Eigen::Vector3d pjp =pj; pjp[jack]= pj[jack] + h;\n       reparameterize_AIDP(Ri, Rj, abrhoi, pi, pjp, abrhojp);\n       Eigen::Vector3d subJacobian = (abrhojp - abrhoj)/h;\n       jacobian.col(jack+6) = subJacobian;\n   }\n}\n\nvoid testReparameterize()\n{\n    double distances[] ={3, 3e2, 3e4, 3e8}; //close to inifity\n    for(size_t jack = 0; jack< sizeof(distances)/sizeof(distances[0]); ++jack){\n        double dist = distances[jack];\n\n        Eigen::Matrix3d Ri = Eigen::Matrix3d::Identity();\n        Eigen::Vector3d ptini;\n        ptini<< dist*cos(15*M_PI/180)*cos(45*M_PI/180), -dist*sin(15*M_PI/180),  dist*cos(15*M_PI/180)*sin(45*M_PI/180);\n        Eigen::Matrix3d Rj = Eigen::AngleAxisd(30*M_PI/180, Eigen::Vector3d::UnitY()).toRotationMatrix();\n\n        Eigen::Vector3d pi =Eigen::Vector3d::Zero();\n        Eigen::Vector3d pj =Eigen::Vector3d::Random();\n\n        Eigen::Vector3d ptinj = Rj.transpose()*(ptini - pj);\n\n        Eigen::Vector3d abrhoi =Eigen::Vector3d(ptini[0],ptini[1],1)/ptini[2];\n        Eigen::Vector3d abrhoj;\n        Eigen::Matrix<double, 3, 9> jacobian;\n\n        reparameterize_AIDP(Ri, Rj, abrhoi, pi, pj, abrhoj, &jacobian);\n        Eigen::Matrix<double, 3, 9> jacobian3;\n        reparameterizeNumericalJacobian(Ri, Rj, abrhoi, pi, pj, abrhoj, jacobian3);\n        std::cout<<\"analytic jacobian \" << std::endl<< jacobian<<std::endl;\n        std::cout <<\"analytic jacobian - numerical jacobian \"<< std::endl << (jacobian - jacobian3) <<std::endl;\n        std::cout <<\"abrhoi and j\"<< abrhoi.transpose()<< \" \"<< abrhoj.transpose()<< std::endl;\n    }\n    //infinity\n    Eigen::Matrix3d Ri = Eigen::Matrix3d::Identity();\n    Eigen::Vector3d ptiniRay;\n    ptiniRay<< cos(15*M_PI/180)*cos(45*M_PI/180), -sin(15*M_PI/180),  cos(15*M_PI/180)*sin(45*M_PI/180);\n    Eigen::Matrix3d Rj = Eigen::AngleAxisd(30*M_PI/180, Eigen::Vector3d::UnitY()).toRotationMatrix();\n\n    Eigen::Vector3d pi =Eigen::Vector3d::Zero();\n    Eigen::Vector3d pj =Eigen::Vector3d::Random();\n\n    Eigen::Vector3d ptinjRay = Rj.transpose()*ptiniRay;\n    ptinjRay/=ptinjRay[2];\n    ptinjRay[2] =0;\n\n    Eigen::Vector3d abrhoi =Eigen::Vector3d(1, -tan(15*M_PI/180)/sin(45*M_PI/180),0);\n    Eigen::Vector3d abrhoj;\n    Eigen::Matrix<double, 3, 9> jacobian;\n\n    reparameterize_AIDP(Ri, Rj, abrhoi, pi, pj, abrhoj, &jacobian);\n    Eigen::Matrix<double, 3, 9> jacobian3;\n    reparameterizeNumericalJacobian(Ri, Rj, abrhoi, pi, pj, abrhoj, jacobian3);\n    std::cout <<\"infinity point case \"<< std::endl;\n    std::cout<<\"analytic jacobian \" << std::endl<< jacobian<<std::endl;\n    std::cout <<\"analytic jacobian - numerical jacobian \"<< std::endl << (jacobian - jacobian3) <<std::endl;\n    std::cout <<\"abrhoi and j\"<< abrhoi.transpose()<< \" \"<< abrhoj.transpose()<< std::endl;\n    std::cout <<\"expected abrhoj \"<< ptinjRay.transpose()<<std::endl;\n}\n\nvoid testExtractBlocks()\n{\n    Eigen::MatrixXd m(5,5);\n    m<< 1,2,3,4,5,\n        6,7,8,9,10,\n        11,12,13,14,15,\n        16,17,18,19,20,\n        21,22,23,24,25;\n\n    std::vector<std::pair<size_t, size_t> > vRowStartInterval;\n    for(size_t jack=0; jack<5; ++jack)\n        vRowStartInterval.push_back(std::make_pair(jack, 1));\n    // test deleting none entry\n    Eigen::MatrixXd res = extractBlocks(m, vRowStartInterval, vRowStartInterval);\n    assert((res- m).lpNorm<Eigen::Infinity>()<1e-8);\n\n    // test deleting odd indexed rows/cols\n    vRowStartInterval.clear();\n    for(size_t jack=0; jack<5; jack+=2)\n        vRowStartInterval.push_back(std::make_pair(jack, 1));\n    res = extractBlocks(m, vRowStartInterval, vRowStartInterval);\n    Eigen::MatrixXd expected(3,3);\n    expected<< 1,3,5,\n            11,13,15,\n            21,23,25;\n    assert((res- expected).lpNorm<Eigen::Infinity>()<1e-8);\n\n// test deleting even indexed rows/cols\n    vRowStartInterval.clear();\n    for(size_t jack=1; jack<5; jack+=2)\n        vRowStartInterval.push_back(std::make_pair(jack, 1));\n    res = extractBlocks(m, vRowStartInterval, vRowStartInterval);\n    Eigen::MatrixXd expected2(2,2);\n    expected2<< 7,9,17,19;\n    assert((res- expected2).lpNorm<Eigen::Infinity>()<1e-8);\n\n// test with keeping more than 1 rows/cols each time\n    vRowStartInterval.clear();\n    vRowStartInterval.push_back(std::make_pair(0, 2));\n    vRowStartInterval.push_back(std::make_pair(3, 2));\n    res = extractBlocks(m, vRowStartInterval, vRowStartInterval);\n    Eigen::MatrixXd expected3(4,4);\n    expected3<<1,2,4,5,\n            6,7,9,10,\n            16,17,19,20,\n            21,22,24,25;;\n    assert((res- expected3).lpNorm<Eigen::Infinity>()<1e-8);\n\n// test with different rows and cols to keep\n    vRowStartInterval.clear();\n    vRowStartInterval.push_back(std::make_pair(0, 2));\n    vRowStartInterval.push_back(std::make_pair(3, 2));\n    std::vector<std::pair<size_t, size_t> > vColStartInterval;\n    vColStartInterval.push_back(std::make_pair(0,2));\n    vColStartInterval.push_back(std::make_pair(3,1));\n    res = extractBlocks(m, vRowStartInterval, vColStartInterval);\n    Eigen::MatrixXd expected4(4,3);\n    expected4<< 1,2,4,\n            6,7,9,\n            16,17,19,\n            21,22,24;\n    assert((res- expected4).lpNorm<Eigen::Infinity>()<1e-8);\n}\n\nEigen::Vector3d unskew3d(const Eigen::Matrix3d & Omega) {\n   return 0.5 * Eigen::Vector3d(Omega(2,1) - Omega(1,2), Omega(0,2) - Omega(2,0), Omega(1,0) - Omega(0,1));\n}\n\n}\n", "meta": {"hexsha": "6d4b1591abd2db797a6c8f8e14c4d4aa4d66dac1", "size": 10831, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/eigen_utils.cpp", "max_stars_repo_name": "xiaod17/vio_common", "max_stars_repo_head_hexsha": "8e483b62f7794cdad2ba9081cf019ed15a9377d2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-08-06T03:22:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-06T20:15:41.000Z", "max_issues_repo_path": "src/eigen_utils.cpp", "max_issues_repo_name": "xiaod17/vio_common", "max_issues_repo_head_hexsha": "8e483b62f7794cdad2ba9081cf019ed15a9377d2", "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/eigen_utils.cpp", "max_forks_repo_name": "xiaod17/vio_common", "max_forks_repo_head_hexsha": "8e483b62f7794cdad2ba9081cf019ed15a9377d2", "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": 38.0035087719, "max_line_length": 121, "alphanum_fraction": 0.6172098606, "num_tokens": 3698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213664574069, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.7243611167168696}}
{"text": "/**\n * @file dynamical_systems.hpp\n * @author Manuel Wuthrich\n * @license License BSD-3-Clause\n * @copyright Copyright (c) 2019, New York University and Max Planck Gesellschaft.\n * @date 2019-08-05\n */\n\n#pragma once\n\n#include <cmath>\n#include <math.h>\n#include <Eigen/Eigen>\n#include <iostream>\n\n#include \"mpi_cpp_tools/basic_tools.hpp\"\n#include \"mpi_cpp_tools/math.hpp\"\n\n\nnamespace mct\n{\n\n\n\n\n\n\nclass LinearDynamics\n{\npublic:\n    typedef Eigen::Matrix<double, Eigen::Dynamic, 1, 0, 10> Vector;\n\n    LinearDynamics(Eigen::Vector4d parameters): LinearDynamics(parameters[0],\n                                                parameters[1],\n                                                parameters[2],\n                                                parameters[3]) { }\n\n\n    LinearDynamics(double jerk,\n                   double initial_acceleration,\n                   double initial_velocity,\n                   double initial_position)\n    {\n        jerk_ = jerk;\n        initial_acceleration_ = initial_acceleration;\n        initial_velocity_ = initial_velocity;\n        initial_position_= initial_position;\n    }\n    double get_acceleration(mct::NonnegDouble t) const\n    {\n        return  jerk_ * t +\n                initial_acceleration_;\n    }\n    double get_velocity(mct::NonnegDouble t) const\n    {\n        return jerk_ * 0.5 * t * t +\n                initial_acceleration_ * t +\n                initial_velocity_;\n    }\n    double get_position(mct::NonnegDouble t) const\n    {\n        return jerk_ * 0.5 * 1./3. * t * t * t +\n                initial_acceleration_ * 0.5 * t * t +\n                initial_velocity_ * t +\n                initial_position_;\n    }\n\n    Vector find_t_given_velocity(double velocity) const\n    {\n        double a = jerk_ * 0.5;\n        double b = initial_acceleration_;\n        double c = initial_velocity_ - velocity;\n\n        double determinant = b * b - 4 * a * c;\n\n        Vector solutions(Vector::Index(0));\n        if(a == 0)\n        {\n            if(b != 0)\n            {\n                solutions.resize(1);\n                solutions[0] = - c / b;\n            }\n\n        }\n        else if(determinant == 0)\n        {\n            solutions.resize(1);\n            solutions[0] = -b / 2 / a;\n        }\n        else if(determinant > 0)\n        {\n            double determinant_sqrt = std::sqrt(determinant);\n            solutions.resize(2);\n            solutions[0] = (-b + determinant_sqrt) / 2 / a;\n            solutions[1] = (-b - determinant_sqrt) / 2 / a;\n        }\n\n        Vector positive_solutions(Vector::Index(0));\n        for(int i = 0; i < solutions.size(); i++)\n        {\n            if(solutions[i] >= 0)\n            {\n                mct::append_to_vector(positive_solutions, solutions[i]);\n            }\n        }\n\n        return positive_solutions;\n    }\n\nprotected:\n    double jerk_;\n    double initial_acceleration_;\n    double initial_velocity_;\n    double initial_position_;\n};\n\n\n\n\n\n\nclass LinearDynamicsWithAccelerationConstraint: public LinearDynamics\n{\npublic:\n\n    void print_parameters() const\n    {\n        std::cout << \"-------------------------------------------\" << std::endl;\n        std::cout << \"jerk: \" << jerk_ << std::endl\n                  << \"initial_acceleration: \" << initial_acceleration_ << std::endl\n                  << \"initial_velocity: \" << initial_velocity_ << std::endl\n                  << \"initial_position: \" << initial_position_ << std::endl\n                  << \"acceleration_limit: \" << acceleration_limit_ << std::endl\n                  << \"jerk_duration: \" << jerk_duration_ << std::endl;\n        std::cout << \"-------------------------------------------\" << std::endl;\n    }\n\n    typedef LinearDynamics::Vector Vector;\n\n    typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, 0, 10, 10>\n    Matrix;\n\n\n    LinearDynamicsWithAccelerationConstraint(Eigen::Matrix<double, 5, 1> parameters):\n        LinearDynamicsWithAccelerationConstraint(parameters[0],\n        parameters[1],\n        parameters[2],\n        parameters[3],\n        parameters[4]) { }\n\n    LinearDynamicsWithAccelerationConstraint(double jerk,\n                                             double initial_acceleration,\n                                             double initial_velocity,\n                                             double initial_position,\n                                             mct::NonnegDouble abs_acceleration_limit):\n        LinearDynamics(jerk,\n                       initial_acceleration,\n                       initial_velocity,\n                       initial_position)\n    {\n        if(jerk_ > 0)\n            acceleration_limit_ = abs_acceleration_limit;\n        else\n            acceleration_limit_ = -abs_acceleration_limit;\n\n        set_initial_acceleration(initial_acceleration);\n    }\n\n\n    void set_initial_acceleration(double initial_acceleration)\n    {\n        if(std::fabs(initial_acceleration) > std::fabs(acceleration_limit_))\n            throw std::invalid_argument(\"expected \"\n                                        \"std::fabs(initial_acceleration) > \"\n                                        \"abs_acceleration_limit\");\n        initial_acceleration_ = initial_acceleration;\n        jerk_duration_ =\n                (acceleration_limit_ - initial_acceleration_) / jerk_;\n    }\n\n    double get_acceleration(mct::NonnegDouble t) const\n    {\n        if(t < jerk_duration_)\n        {\n            return  LinearDynamics::get_acceleration(t);\n        }\n        else\n        {\n            return acceleration_limit_;\n        }\n    }\n    double get_velocity(mct::NonnegDouble t) const\n    {\n        if(t < jerk_duration_)\n        {\n            return LinearDynamics::get_velocity(t);\n        }\n        else\n        {\n            return LinearDynamics::get_velocity(jerk_duration_) +\n                    acceleration_limit_ * (t - jerk_duration_);\n        }\n    }\n    double get_position(mct::NonnegDouble t) const\n    {\n        if(t < jerk_duration_)\n        {\n            return LinearDynamics::get_position(t);\n        }\n        else\n        {\n            return LinearDynamics::get_position(jerk_duration_) +\n                    LinearDynamics::get_velocity(jerk_duration_) * (t - jerk_duration_) +\n                    acceleration_limit_ * 0.5 * (t - jerk_duration_) * (t - jerk_duration_);\n        }\n    }\n\n    template<typename Array>\n    Array get_positions(const Array& times) const\n    {\n        Array positions(times.size());\n        for(size_t i = 0; i < size_t(times.size()); i++)\n        {\n            positions[i] = get_position(times[i]);\n        }\n        return positions;\n    }\n\n    Vector find_t_given_velocity(double velocity) const\n    {\n        Vector potential_solutions =\n                LinearDynamics::find_t_given_velocity(velocity);\n\n        Vector solutions(Vector::Index(0));\n        for(int i = 0; i < potential_solutions.size(); i++)\n        {\n            if(potential_solutions[i] <= jerk_duration_)\n            {\n                mct::append_to_vector(solutions, potential_solutions[i]);\n            }\n        }\n\n        double potential_solution = jerk_duration_\n                + (velocity - LinearDynamics::get_velocity(jerk_duration_))\n                / acceleration_limit_;\n        if(potential_solution > jerk_duration_ &&\n                !(mct::contains(solutions, jerk_duration_) &&\n                  mct::approx_equal(potential_solution, jerk_duration_)))\n        {\n            mct::append_to_vector(solutions, potential_solution);\n        }\n\n\n\n        if(solutions.size() > 2)\n        {\n            std::cout << \"too many solutions, something went wrong!!!\"\n                      << std::endl;\n            print_parameters();\n\n            std::cout << \"potential_solutions[0]: \" << potential_solutions[0] << std::endl;\n\n            std::cout << \"potential_solutions size: \" << potential_solutions.size() << \" content: \" << potential_solutions.transpose() << std::endl;\n\n\n            std::cout << \"solutions size: \" << solutions.size() << \" content: \" << solutions.transpose() << std::endl;\n            exit(-1);\n        }\n        return solutions;\n    }\n\n    bool will_exceed_jointly(const double& max_velocity,\n                             const double& max_position) const\n    {\n        double certificate_time;\n        return will_exceed_jointly(max_velocity, max_position, certificate_time);\n    }\n\n\n    bool will_exceed_jointly(const double& max_velocity,\n                             const double& max_position,\n                             double& certificate_time) const\n    {\n        if(max_velocity == std::numeric_limits<double>::infinity() ||\n                max_position == std::numeric_limits<double>::infinity())\n        {\n            return false;\n        }\n        if(jerk_ > 0)\n        {\n            certificate_time = std::numeric_limits<double>::infinity();\n            return true;\n        }\n        if(jerk_ == 0)\n        {\n            throw std::domain_error(\"not implemented for jerk == 0\");\n        }\n\n        // find maximum achieved position --------------------------------------\n        ///\\todo we could do this in a cleaner way with candidate points\n        //        Matrix candidate_points(0, 0);\n        //        Vector candidate_times(0);\n\n        //        mct::append_rows_to_matrix(candidate_points,\n        //                              Eigen::Vector2d(initial_velocity_,\n        //                                              initial_position_).transpose());\n        //        mct::append_to_vector(candidate_times, 0);\n\n\n        if(initial_velocity_ > max_velocity &&\n                initial_position_ > max_position)\n        {\n            certificate_time = 0;\n            return true;\n        }\n\n        Vector t_given_zero_velocity = find_t_given_velocity(0);\n        if(t_given_zero_velocity.size() > 0)\n        {\n            Vector position_given_zero_velocity =\n                    get_positions(t_given_zero_velocity);\n\n            Vector::Index max_index;\n            double max_achieved_position =\n                    position_given_zero_velocity.maxCoeff(&max_index);\n            if(max_achieved_position < max_position)\n            {\n                return false;\n            }\n            if(max_velocity < 0)\n            {\n                certificate_time = t_given_zero_velocity[max_index];\n                return true;\n            }\n        }\n\n        Vector t_given_max_velocity =\n                find_t_given_velocity(max_velocity);\n        Vector position_given_max_velocity =\n                get_positions(t_given_max_velocity);\n\n        for(int i = 0; i < position_given_max_velocity.size(); i++)\n        {\n            if(position_given_max_velocity[i] > max_position)\n            {\n                certificate_time = t_given_max_velocity[i];\n                return true;\n            }\n        }\n\n        return false;\n    }\n\n\n    bool will_deceed_jointly(const double& min_velocity,\n                             const double& min_position) const\n    {\n        double certificate_time;\n        return will_deceed_jointly(min_velocity, min_position, certificate_time);\n    }\n\n    bool will_deceed_jointly(const double& min_velocity,\n                             const double& min_position,\n                             double& certificate_time) const\n    {\n        LinearDynamicsWithAccelerationConstraint\n                flipped_dynamics(-jerk_,\n                                 -initial_acceleration_,\n                                 -initial_velocity_,\n                                 -initial_position_,\n                                 std::fabs(acceleration_limit_));\n\n        return flipped_dynamics.will_exceed_jointly(-min_velocity,\n                                                    -min_position,\n                                                    certificate_time);\n    }\n\n\nprivate:\n    double acceleration_limit_;\n    mct::NonnegDouble jerk_duration_;\n};\n\n\n\ndouble find_max_admissible_acceleration(\n        const double& initial_velocity,\n        const double& initial_position,\n        const double& max_velocity,\n        const double& max_position,\n        const mct::NonnegDouble& abs_jerk_limit,\n        const mct::NonnegDouble& abs_acceleration_limit)\n{\n    double lower = -abs_acceleration_limit;\n    double upper = abs_acceleration_limit;\n\n\n    LinearDynamicsWithAccelerationConstraint dynamics(-abs_jerk_limit,\n                                                      lower,\n                                                      initial_velocity,\n                                                      initial_position,\n                                                      abs_acceleration_limit);\n\n\n    if(dynamics.will_exceed_jointly(max_velocity, max_position))\n    {\n        /// \\todo: not quite sure what is the right thing to do here\n        return lower;\n    }\n\n    dynamics.set_initial_acceleration(upper);\n    if(!dynamics.will_exceed_jointly(max_velocity, max_position))\n    {\n        return upper;\n    }\n\n    for(size_t i = 0; i < 20; i++)\n    {\n        double middle = (lower + upper) / 2.0;\n\n        dynamics.set_initial_acceleration(middle);\n        if(dynamics.will_exceed_jointly(max_velocity, max_position))\n        {\n            upper = middle;\n        }\n        else\n        {\n            lower = middle;\n        }\n    }\n    return lower;\n}\n\n\n\ndouble find_min_admissible_acceleration(\n        const double& initial_velocity,\n        const double& initial_position,\n        const double& min_velocity,\n        const double& min_position,\n        const mct::NonnegDouble& abs_jerk_limit,\n        const mct::NonnegDouble& abs_acceleration_limit)\n{\n    return -find_max_admissible_acceleration(-initial_velocity,\n                                             -initial_position,\n                                             -min_velocity,\n                                             -min_position,\n                                             abs_jerk_limit,\n                                             abs_acceleration_limit);\n}\n\n\n\nclass SafetyConstraint\n{\npublic:\n    SafetyConstraint()\n    {\n        min_velocity_ = -std::numeric_limits<double>::infinity();\n        min_position_ = -std::numeric_limits<double>::infinity();\n        max_velocity_ = std::numeric_limits<double>::infinity();\n        max_position_ = std::numeric_limits<double>::infinity();\n        max_torque_ = 1.0;\n        max_jerk_ = 1.0;\n        inertia_ = 1.0;\n    }\n\n    SafetyConstraint(double min_velocity,\n                     double min_position,\n                     double max_velocity,\n                     double max_position,\n                     mct::NonnegDouble max_torque,\n                     mct::NonnegDouble max_jerk,\n                     mct::NonnegDouble inertia)\n    {\n        min_velocity_ = min_velocity;\n        min_position_ = min_position;\n        max_velocity_ = max_velocity;\n        max_position_ = max_position;\n        max_torque_ = max_torque;\n        max_jerk_ = max_jerk;\n        inertia_ = inertia;\n    }\n\n\n    double get_safe_torque(const double& torque,\n                           const double& velocity,\n                           const double& position)\n    {\n        double safe_torque = mct::clamp(torque, -max_torque_, max_torque_);\n\n//        std::cout << \"safe_torque: \" << safe_torque << std::endl;\n\n\n        mct::NonnegDouble max_achievable_acc = max_torque_ / inertia_;\n\n\n\n\n        double max_admissible_acc =\n                find_max_admissible_acceleration(velocity,\n                                                 position,\n                                                 max_velocity_,\n                                                 max_position_,\n                                                 max_jerk_,\n                                                 max_achievable_acc);\n        double max_admissible_torque = max_admissible_acc * inertia_;\n\n\n\n//        LinearDynamicsWithAccelerationConstraint\n//                test_dynamics(- max_jerk_,\n//                              max_achievable_acc,\n//                              velocity,\n//                              position,\n//                              max_achievable_acc);\n\n//        test_dynamics.print_parameters();\n//        std::cout << \"will exceed: \" << test_dynamics.will_exceed_jointly(max_velocity_, max_position_) << std::endl;\n//        std::cout << \"max_admissible_acc: \" << max_admissible_acc << std::endl;\n\n\n//        std::cout << \"max_achievable_acc: \" << max_achievable_acc << std::endl;\n//        std::cout << \"max_admissible_acc: \" << max_admissible_acc << std::endl;\n//        std::cout << \"max_admissible_torque: \" << max_admissible_torque << std::endl;\n\n\n\n        double min_admissible_acc =\n                find_min_admissible_acceleration(velocity,\n                                                 position,\n                                                 min_velocity_,\n                                                 min_position_,\n                                                 max_jerk_,\n                                                 max_achievable_acc);\n        double min_admissible_torque = min_admissible_acc * inertia_;\n\n//        std::cout << \"min_admissible_acc: \" << min_admissible_acc << std::endl;\n//        std::cout << \"min_admissible_torque: \" << min_admissible_torque << std::endl;\n\n\n\n        if(min_admissible_torque > max_admissible_torque)\n        {\n            std::cout << \"min_admissible_torque > max_admissible_torque!!!!\"\n                      << std::endl;\n            return 0;\n        }\n\n        safe_torque = mct::clamp(safe_torque,\n                            min_admissible_torque, max_admissible_torque);\n\n\n        if(safe_torque > max_torque_ || safe_torque < -max_torque_)\n        {\n            std::cout << \"something went horribly horribly wrong \" << std::endl;\n            return 0;\n        }\n\n        return safe_torque;\n    }\n\n    double min_velocity_;\n    double min_position_;\n    double max_velocity_;\n    double max_position_;\n    mct::NonnegDouble max_torque_;\n    mct::NonnegDouble max_jerk_;\n    mct::NonnegDouble inertia_;\n};\n\n\n\n}\n", "meta": {"hexsha": "8272e05e683ce2f37ac6d7bc336448371b3fad8c", "size": 18051, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mpi_cpp_tools/dynamical_systems.hpp", "max_stars_repo_name": "open-dynamic-robot-initiative/mpi_cpp_tools", "max_stars_repo_head_hexsha": "d6c09b96f3370b8d4f31ac96ac04bca37a9846d1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-07-06T01:18:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T03:14:42.000Z", "max_issues_repo_path": "include/mpi_cpp_tools/dynamical_systems.hpp", "max_issues_repo_name": "open-dynamic-robot-initiative/mpi_cpp_tools", "max_issues_repo_head_hexsha": "d6c09b96f3370b8d4f31ac96ac04bca37a9846d1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-11-18T14:21:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-20T14:20:37.000Z", "max_forks_repo_path": "include/mpi_cpp_tools/dynamical_systems.hpp", "max_forks_repo_name": "open-dynamic-robot-initiative/mpi_cpp_tools", "max_forks_repo_head_hexsha": "d6c09b96f3370b8d4f31ac96ac04bca37a9846d1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-27T17:46:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-27T17:46:46.000Z", "avg_line_length": 31.3385416667, "max_line_length": 148, "alphanum_fraction": 0.5304969254, "num_tokens": 3582, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086368, "lm_q2_score": 0.7905303087996143, "lm_q1q2_score": 0.7242124121038915}}
{"text": "/**\n * @copyright\n * Copyright (c) 2012-2016, OpenGeoSys Community (http://www.opengeosys.org)\n *            Distributed under a Modified BSD License.\n *              See accompanying file LICENSE.txt or\n *              http://www.opengeosys.org/LICENSE.txt\n */\n\n#include <gtest/gtest.h>\n\n#include <Eigen/Eigen>\n\n#include \"MathLib/LinAlg/MatrixTools.h\"\n\n#include \"Tests/TestTools.h\"\n\nTEST(MathLib, LocalMatrixDeterminantInverse_Eigen)\n{\n    Eigen::Matrix3d fMat, fInv;\n    fMat << 1, 2, 3,\n            0, 1, 4,\n            5, 6, 0;\n    double fMat_det = MathLib::determinant(fMat);\n    MathLib::inverse(fMat, fMat_det, fInv);\n\n    Eigen::MatrixXd dMat(3,3), dInv(3,3);\n    dMat = fMat;\n    double dMat_det = MathLib::determinant(dMat);\n    MathLib::inverse(dMat, dMat_det, dInv);\n\n    ASSERT_NEAR(fMat_det, dMat_det, std::numeric_limits<double>::epsilon());\n    ASSERT_ARRAY_NEAR(fInv.data(), dInv.data(), fInv.size(), std::numeric_limits<double>::epsilon());\n}\n", "meta": {"hexsha": "e577578e5ad2e978ce2785fb88d23e6920adb4ec", "size": 962, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tests/MathLib/TestLocalMatrixFunctions.cpp", "max_stars_repo_name": "norihiro-w/ogs", "max_stars_repo_head_hexsha": "ac990b1aa06a583dba3e32efa3009ef0c6f46ae4", "max_stars_repo_licenses": ["BSD-4-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": "Tests/MathLib/TestLocalMatrixFunctions.cpp", "max_issues_repo_name": "norihiro-w/ogs", "max_issues_repo_head_hexsha": "ac990b1aa06a583dba3e32efa3009ef0c6f46ae4", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": 25.0, "max_issues_repo_issues_event_min_datetime": "2015-02-04T20:34:21.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-10T20:19:57.000Z", "max_forks_repo_path": "Tests/MathLib/TestLocalMatrixFunctions.cpp", "max_forks_repo_name": "norihiro-w/ogs", "max_forks_repo_head_hexsha": "ac990b1aa06a583dba3e32efa3009ef0c6f46ae4", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2941176471, "max_line_length": 101, "alphanum_fraction": 0.6486486486, "num_tokens": 281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.7981867777396212, "lm_q1q2_score": 0.7242046183716143}}
{"text": "#include <Eigen/Dense>\n#include <cassert>\n#include <iostream>\n\n// To disable assert*() calls, uncomment this line:\n// #define NDEBUG\n\n// This represents a triplet of indices as a column vector of nonnegative\n// integers:\n// [ i ]\n// [ j ]\n// [ k ]\ntypedef Eigen::Matrix<std::size_t, 3, 1> GridIndices;\n\n// Returns the indices of the grid cell containing the point |p| for a grid with\n// lower corner |lc| and grid cell width (spacing) |dx|.\n//\n// If |dx| <= 0 or |p|'s location relative to |lc| would result in negative\n// indices being returned and assertions are on, then assertion failures will\n// crash this program.\ninline GridIndices floor(const Eigen::Vector3d& p, const Eigen::Vector3d& lc,\n                         double dx) {\n  // Ensure grid spacings are positive.\n  assert(dx > 0.0);\n\n  // Compute |p|'s location relative to |lc|.\n  // Dividing by |dx| yields a 3D vector indicating the number of grid\n  // cells (including fractions of grid cells, as the vector elements are\n  // floating-point values) away from |lc| that |p| is located.\n  Eigen::Vector3d p_lc_over_dx = (p - lc) / dx;\n\n  // Ensure we won't end up with negative indices.\n  assert(p_lc_over_dx[0] >= 0.0);\n  assert(p_lc_over_dx[1] >= 0.0);\n  assert(p_lc_over_dx[2] >= 0.0);\n\n  // Indices are valid. Construct and return them.\n  // This casts the elements of the vector above as nonnegative integers.\n  return p_lc_over_dx.cast<std::size_t>();\n}\n\n// Prints the provided |indices|.\nvoid Print(const GridIndices& indices) {\n  std::cout << \"Indices: \" << std::endl;\n  std::cout << indices << std::endl;\n}\n\nint main(int argc, char** argv) {\n  // Make a grid with spacing of 2 with lower corner (1, 2, 3).\n  double dx = 2.0;\n  Eigen::Vector3d lc(1, 2, 3);\n\n  // (i, j, k) should be (floor((6-1)/2), floor((4-2)/2), floor((3-3)/2)),\n  // which is (floor(2.5), floor(1), floor(0)) = (2, 1, 0).\n  Eigen::Vector3d p1(6, 4, 3);\n  GridIndices p1_indices = floor(p1, lc, dx);\n  Print(p1_indices);\n\n  // (i, j, k) should be (3, 8, 9).\n  Eigen::Vector3d p2(7, 18, 22);\n  GridIndices p2_indices = floor(p2, lc, dx);\n  Print(p2_indices);\n\n  // Should lead to an assertion failure for index 0 (x-coordinate) being\n  // less than the x-coordinate of |lc|. The program should crash before\n  // it even gets to the Print command below.\n  Eigen::Vector3d p3(-1, 2, 3);\n  GridIndices p3_indices = floor(p3, lc, dx);\n  Print(p3_indices);\n\n  return 0;\n}\n", "meta": {"hexsha": "e31266104320dd56cdf75e4b3f28b0f375a7111c", "size": 2410, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "incremental0/GridIndexing.cpp", "max_stars_repo_name": "unusualinsights/flip_pic_examples", "max_stars_repo_head_hexsha": "3314dd4c67a681d2600feb342c88527e7618bc10", "max_stars_repo_licenses": ["BSD-4-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": "incremental0/GridIndexing.cpp", "max_issues_repo_name": "unusualinsights/flip_pic_examples", "max_issues_repo_head_hexsha": "3314dd4c67a681d2600feb342c88527e7618bc10", "max_issues_repo_licenses": ["BSD-4-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": "incremental0/GridIndexing.cpp", "max_forks_repo_name": "unusualinsights/flip_pic_examples", "max_forks_repo_head_hexsha": "3314dd4c67a681d2600feb342c88527e7618bc10", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0136986301, "max_line_length": 80, "alphanum_fraction": 0.6580912863, "num_tokens": 737, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.8175744761936438, "lm_q1q2_score": 0.7240696833716019}}
{"text": "/*\n * Bayes++ the Bayesian Filtering Library\n * Copyright (c) 2002 Michael Stevens\n * See accompanying Bayes++.htm for terms and conditions of use.\n *\n * $Id$\n */\n\n/*\n * Example of using Bayesian Filter Class to solve a simple problem.\n *  The example implements a Position and Velocity Filter with a Position observation.\n *  The motion model is the so called IOU Integrated Ornstein-Uhlenbeck Process Ref[1]\n *    Velocity is Brownian with a trend towards zero proportional to the velocity\n *    Position is just Velocity integrated.\n *  This model has a well defined velocity and the mean squared speed is parameterised. Also\n *  the velocity correlation is parameterised.\n *  \n * Two implementations are demonstrated\n *  1) A direct filter\n *  2) An indirect filter where the filter is performed on error and state is estimated indirectly\n * Reference\n * [1] \"Bayesian Multiple Target Tracking\" Lawrence D Stone, Carl A Barlow, Thomas L Corwin\n */\n\n#include \"BayesFilter/UDFlt.hpp\"\n#include \"BayesFilter/filters/indirect.hpp\"\n#include \"Test/random.hpp\"\n#include <cmath>\n#include <iostream>\n#include <boost/numeric/ublas/io.hpp>\n\nnamespace\n{\n\tusing namespace Bayesian_filter;\n\tusing namespace Bayesian_filter_matrix;\n\n\t// Choose Filtering Scheme to use\n\ttypedef UD_scheme FilterScheme;\n\n\t// Square \n\ttemplate <class scalar>\n\tinline scalar sqr(scalar x)\n\t{\n\t\treturn x*x;\n\t}\n\n\t// Random numbers from Boost\n\tBayesian_filter_test::Boost_random localRng;\n\n\t// Constant Dimensions\n\tconst unsigned NX = 2;\t\t\t// Filter State dimension \t(Position, Velocity)\n\n\t// Filter Parameters\n\t// Prediction parameters for Integrated Ornstein-Uhlembeck Process\n\tconst Float dt = 0.01;\n\tconst Float V_NOISE = 0.1;\t// Velocity noise, giving mean squared error bound\n\tconst Float V_GAMMA = 1.;\t// Velocity correlation, giving velocity change time constant\n\t// Filter's Initial state uncertainty: System state is unknown\n\tconst Float i_P_NOISE = 1000.;\n\tconst Float i_V_NOISE = 10.;\n\t// Noise on observing system state\n\tconst Float OBS_INTERVAL = 0.10;\n\tconst Float OBS_NOISE = 0.001;\n\n}//namespace\n\n/*\n * Prediction model\n * Linear state predict model\n */\nclass PVpredict : public Linear_predict_model\n{\npublic:\n\tPVpredict();\n};\n\nPVpredict::PVpredict() : Linear_predict_model(NX, 1)\n{\n\t// Position Velocity dependence\n\tconst Float Fvv = exp(-dt*V_GAMMA);\n\tFx(0,0) = 1.;\n\tFx(0,1) = dt;\n\tFx(1,0) = 0.;\n\tFx(1,1) = Fvv;\n\t// Setup constant noise model: G is identity\n\tq[0] = dt*sqr((1-Fvv)*V_NOISE);\n\tG(0,0) = 0.;\n\tG(1,0) = 1.;\n}\n\n\n/*\n * Position Observation model\n * Linear observation is additive uncorrelated model\n */\nclass PVobserve : public Linrz_uncorrelated_observe_model\n{\n\tmutable Vec z_pred;\npublic:\n\tPVobserve ();\n\tconst Vec& h(const Vec& x) const\n\t{\n\t\tz_pred[0] = x[0];\n\t\treturn z_pred;\n\t};\n};\n\nPVobserve::PVobserve () :\n\tLinrz_uncorrelated_observe_model(NX,1), z_pred(1)\n{\n\t// Linear model\n\tHx(0,0) = 1;\n\tHx(0,1) = 0.;\n\t// Observation Noise variance\n\tZv[0] = sqr(OBS_NOISE);\n}\n\n\nvoid initialise (Kalman_state_filter& kf, const Vec& initState)\n/*\n * Initialise Kalman filter with an initial guess for the system state and fixed covariance\n */\n{\n\t// Initialise state guess and covarince\n\tkf.X.clear();\n\tkf.X(0,0) = sqr(i_P_NOISE);\n\tkf.X(1,1) = sqr(i_V_NOISE);\n\n\tkf.init_kalman (initState, kf.X);\n}\n\n\nint main()\n{\n\t// global setup\n\tstd::cout.flags(std::ios::scientific); std::cout.precision(6);\n\n\t// Setup the test filters\n\tVec x_true (NX);\n\n\t// True State to be observed\n\tx_true[0] = 1000.;\t// Position\n\tx_true[1] = 1.0;\t// Velocity\n \n\tstd::cout << \"Position Velocity\" << std::endl;\n\tstd::cout << \"True Initial  \" << x_true << std::endl;\n\n\t// Construct Prediction and Observation model and filter\n\t// Give the filter an initial guess of the system state\n\tPVpredict linearPredict;\n\tPVobserve linearObserve;\n\tVec x_guess(NX);\n\tx_guess[0] = 900.;\n\tx_guess[1] = 1.5;\n\tstd::cout << \"Guess Initial \" << x_guess << std::endl;\n\n\t// f1 Direct filter construct and initialize with initial state guess\n\tFilterScheme f1(NX,NX);\n\tinitialise (f1, x_guess);\n\n\t// f2 Indirect filter construct and Initialize with initial state guess\n\tFilterScheme error_filter(NX,NX);\n\tIndirect_kalman_filter<FilterScheme> f2(error_filter);\n\tinitialise (f2, x_guess);\n\n\n\t// Iterate the filter with test observations\n\tVec u(1), z_true(1), z(1);\n\tFloat time = 0.; Float obs_time = 0.;\n\tfor (unsigned i = 0; i < 100; ++i)\n\t{\n\t\t// Predict true state using Normally distributed acceleration\n\t\t// This is a Guassian\n\t\tx_true = linearPredict.f(x_true);\n\t\tlocalRng.normal (u);\t\t// normally distributed mean 0., stdDev for stationary IOU\n\t\tx_true[1] += u[0]* sqr(V_NOISE) / (2*V_GAMMA);\n\n\t\t// Predict filter with known perturbation\n\t\tf1.predict (linearPredict);\n\t\tf2.predict (linearPredict);\n\t\ttime += dt;\n\n\t\t// Observation time\n\t\tif (obs_time <= time)\n\t\t{\n\t\t\t// True Observation\n\t\t\tz_true[0] = x_true[0];\n\n\t\t\t// Observation with additive noise\n\t\t\tlocalRng.normal (z, z_true[0], OBS_NOISE);\t// normally distributed mean z_true[0], stdDev OBS_NOISE.\n\n\t\t\t// Filter observation\n\t\t\tf1.observe (linearObserve, z);\n\t\t\tf2.observe (linearObserve, z);\n\n\t\t\tobs_time += OBS_INTERVAL;\n\t\t}\n\t}\n\n\t// Update the filter to state and covariance are available\n\tf1.update ();\n\tf2.update ();\n\n\t// Print everything: filter state and covariance\n\tstd::cout <<\"True     \" << x_true << std::endl;\n\tstd::cout <<\"Direct   \" << f1.x << ',' << f1.X <<std::endl;\n\tstd::cout <<\"Indirect \" << f2.x << ',' << f2.X << std::endl;;\n\treturn 0;\n}\n", "meta": {"hexsha": "739e0dd00165d1cc90d3679ef18585f2746811a0", "size": 5452, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PV/PV.cpp", "max_stars_repo_name": "Exadios/Bayes-", "max_stars_repo_head_hexsha": "a1cd9efe2e840506d887bec9b246fd936f2b71e5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-04-02T21:45:49.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-19T01:59:02.000Z", "max_issues_repo_path": "PV/PV.cpp", "max_issues_repo_name": "Exadios/Bayes-", "max_issues_repo_head_hexsha": "a1cd9efe2e840506d887bec9b246fd936f2b71e5", "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": "PV/PV.cpp", "max_forks_repo_name": "Exadios/Bayes-", "max_forks_repo_head_hexsha": "a1cd9efe2e840506d887bec9b246fd936f2b71e5", "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.9619047619, "max_line_length": 103, "alphanum_fraction": 0.6999266324, "num_tokens": 1538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267660487573, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7240147096174261}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\nusing namespace std;\nusing namespace Eigen;\nint main()\n{\n   Matrix3f A;\n   A << 1, 2, 5,\n        2, 1, 4,\n        3, 0, 3;\n   cout << \"Here is the matrix A:\\n\" << A << endl;\n   FullPivLU<Matrix3f> lu_decomp(A);\n   // lu_decomp.setThreshold(1e-5);\n   cout << \"The rank of A is \" << lu_decomp.rank() << endl;\n   cout << \"Here is a matrix whose columns form a basis of the null-space of A:\\n\"\n        << lu_decomp.kernel() << endl;\n   cout << \"Here is a matrix whose columns form a basis of the column-space of A:\\n\"\n        << lu_decomp.image(A) << endl; // yes, have to pass the original A\n}\n", "meta": {"hexsha": "cd05e95c16459904ab1249dae704eee825bde792", "size": 634, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "snippets/eigen-rank-kernel-image.cpp", "max_stars_repo_name": "district10/snippet-manager", "max_stars_repo_head_hexsha": "bebe45a601368947168e3ee6e6ab8c1fc2ee2055", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2018-08-04T09:28:19.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-19T17:46:34.000Z", "max_issues_repo_path": "snippets/eigen-rank-kernel-image.cpp", "max_issues_repo_name": "district10/snippet-manager", "max_issues_repo_head_hexsha": "bebe45a601368947168e3ee6e6ab8c1fc2ee2055", "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": "snippets/eigen-rank-kernel-image.cpp", "max_forks_repo_name": "district10/snippet-manager", "max_forks_repo_head_hexsha": "bebe45a601368947168e3ee6e6ab8c1fc2ee2055", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-07-31T04:14:55.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-02T01:22:39.000Z", "avg_line_length": 31.7, "max_line_length": 84, "alphanum_fraction": 0.6041009464, "num_tokens": 200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094174159127, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.7240084437768314}}
{"text": "//####### Test module for special functions ####################################\n\n//Define Module name\n #define BOOST_TEST_MODULE \"math/special_functions\"\n\n//Include Boost unit tests library & library for floating point comparison\n#include <boost/test/unit_test.hpp>\n#include <boost/test/tools/floating_point_comparison.hpp>\n\n#include <picsar_qed/math/special_functions.hpp>\n\n#include <array>\n\nusing namespace picsar::multi_physics::math;\n\n//Tolerance for double precision calculations\nconst double double_tolerance = 1.0e-12;\n\n//Tolerance for single precision calculations\nconst float float_tolerance = 1.0e-4;\n\n//Templated tolerance\ntemplate <typename T>\nT constexpr tolerance()\n{\n    if(std::is_same<T,float>::value)\n        return float_tolerance;\n    else\n        return double_tolerance;\n}\n\n// ------------- Tests --------------\n\n// ***Test Bessel functions\n\ntemplate<typename T, typename WHATEVER>\nconstexpr void bessel_functions_test(WHATEVER t_v, WHATEVER t_x, WHATEVER t_exp)\n{\n    const T v = static_cast<T>(t_v);\n    const T x = static_cast<T>(t_x);\n    const T exp = static_cast<T>(t_exp);\n\n    T res = k_v(v,x);\n    BOOST_CHECK_SMALL((res-exp)/exp, tolerance<T>());\n}\n\ntemplate<typename T>\nconstexpr void test_case()\n{\n    bessel_functions_test<T>(1.0/3.0, 0.5, 0.989031074246724);\n    bessel_functions_test<T>(1.0/3.0, 1.0, 0.438430633441534);\n    bessel_functions_test<T>(1.0/3.0, 2.0, 0.116544961296165);\n    bessel_functions_test<T>(2.0/3.0, 0.5, 1.205930464720336);\n    bessel_functions_test<T>(2.0/3.0, 1.0, 0.494475062104208);\n    bessel_functions_test<T>(2.0/3.0, 2.0, 0.124838927488128);\n}\n\nBOOST_AUTO_TEST_CASE( picsar_bessel_functions )\n{\n    test_case<double>();\n    test_case<float>();\n}\n\n// *******************************\n", "meta": {"hexsha": "287806203f070d112acd1f49c42663de8306afb6", "size": 1751, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "multi_physics/QED/QED_tests/test_picsar_spec_functions.cpp", "max_stars_repo_name": "ax3l/picsar", "max_stars_repo_head_hexsha": "7ce1b321d9e047a238e56ee95507d36520a95b5b", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2020-06-22T17:38:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T17:20:30.000Z", "max_issues_repo_path": "multi_physics/QED/QED_tests/test_picsar_spec_functions.cpp", "max_issues_repo_name": "ax3l/picsar", "max_issues_repo_head_hexsha": "7ce1b321d9e047a238e56ee95507d36520a95b5b", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2020-11-03T10:55:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-07T17:00:36.000Z", "max_forks_repo_path": "multi_physics/QED/QED_tests/test_picsar_spec_functions.cpp", "max_forks_repo_name": "ax3l/picsar", "max_forks_repo_head_hexsha": "7ce1b321d9e047a238e56ee95507d36520a95b5b", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2020-06-23T13:54:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T21:51:38.000Z", "avg_line_length": 26.9384615385, "max_line_length": 80, "alphanum_fraction": 0.6830382638, "num_tokens": 485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093975331751, "lm_q2_score": 0.81047890180374, "lm_q1q2_score": 0.7240084194836484}}
{"text": "#define BOOST_TEST_MODULE test_utils\n\n#include <boost/test/unit_test.hpp>\n#include <Utils/utils.h>\n\nnamespace utf = boost::unit_test;\n\nBOOST_AUTO_TEST_SUITE(utils_boost)\n\n    BOOST_AUTO_TEST_CASE(annual_cap1) {\n        BOOST_TEST_MESSAGE(\"Testing annual_cap1\");\n        BOOST_TEST_MESSAGE(\"using tolerances within checks.\");\n\n        double amount = 100;\n        double annual_rate = 10.0 / 100;\n        int number_of_years = 2;\n        double theoretical_value = 121; // (100*(1.1)^2)\n\n        auto calculated_value = annual_capitalization(amount, annual_rate, number_of_years);\n\n        BOOST_TEST_MESSAGE(\" - calculated_value: \" << calculated_value);\n        BOOST_TEST_MESSAGE(\" - known_capitalization: \" << theoretical_value);\n        BOOST_TEST_MESSAGE(\" - diff \" << calculated_value - theoretical_value);\n        BOOST_TEST(theoretical_value == calculated_value, boost::test_tools::tolerance(1e-15));\n    }\n\n    BOOST_AUTO_TEST_CASE(annual_discount1) {\n        BOOST_TEST_MESSAGE(\"Testing annual_discount1\");\n        BOOST_TEST_MESSAGE(\"using tolerances within checks.\");\n\n        double amount = 121;\n        double annual_rate = 10.0 / 100;\n        int number_of_years = 2;\n        double theoretical_value = 100; // (121/(1.1)^2)\n\n        auto calculated_value = discount_annually(amount, annual_rate, number_of_years);\n\n        BOOST_TEST_MESSAGE(\" - calculated_value: \" << calculated_value);\n        BOOST_TEST_MESSAGE(\" - known discounted_value: \" << theoretical_value);\n        BOOST_TEST_MESSAGE(\" - diff \" << calculated_value - theoretical_value);\n        BOOST_TEST(theoretical_value == calculated_value, boost::test_tools::tolerance(1e-15));\n    }\n\n    BOOST_AUTO_TEST_CASE(period_cap1) {\n        BOOST_TEST_MESSAGE(\"Testing period_cap1\");\n        BOOST_TEST_MESSAGE(\"using tolerances within checks.\");\n\n        double amount = 100;\n        double annual_rate = 10.0 / 100;\n        int periods_per_year = 2;\n        int number_of_years = 1;\n        double theoretical_value = 110.25; // (100*(1.05)^2)\n\n        auto calculated_value = period_capitalization(amount, annual_rate, periods_per_year, number_of_years);\n\n        BOOST_TEST_MESSAGE(\" - calculated_value: \" << calculated_value);\n        BOOST_TEST_MESSAGE(\" - known_capitalization: \" << theoretical_value);\n        BOOST_TEST_MESSAGE(\" - diff \" << calculated_value - theoretical_value);\n        BOOST_TEST(theoretical_value == calculated_value, boost::test_tools::tolerance(1e-15));\n    }\n\n    BOOST_AUTO_TEST_CASE(period_discount1) {\n        BOOST_TEST_MESSAGE(\"Testing period_discount1\");\n        BOOST_TEST_MESSAGE(\"using tolerances within checks.\");\n\n        double amount = 110.25;\n        double annual_rate = 10.0 / 100;\n        int periods_per_year = 2;\n        int number_of_years = 1;\n        double theoretical_value = 100; // (110.25/(1.05)^2)\n\n        auto calculated_value = discount_by_periods(amount, annual_rate, periods_per_year, number_of_years);\n\n        BOOST_TEST_MESSAGE(\" - calculated_value: \" << calculated_value);\n        BOOST_TEST_MESSAGE(\" - known discounted_value: \" << theoretical_value);\n        BOOST_TEST_MESSAGE(\" - diff \" << calculated_value - theoretical_value);\n        BOOST_TEST(theoretical_value == calculated_value, boost::test_tools::tolerance(1e-15));\n    }\n\n    BOOST_AUTO_TEST_CASE(continuous_cap1) {\n        BOOST_TEST_MESSAGE(\"Testing continuous_cap1\");\n        BOOST_TEST_MESSAGE(\"using tolerances within checks.\");\n\n        double amount = 100;\n        double annual_rate = 10.0 / 100;\n        int number_of_years = 2;\n        double theoretical_value = 122.140275816; // 100 * e^(0.10*2) rounded to second\n\n        auto calculated_value = continuous_capitalization(amount, annual_rate, number_of_years);\n\n        BOOST_TEST_MESSAGE(\" - calculated_value: \" << calculated_value);\n        BOOST_TEST_MESSAGE(\" - known_capitalization: \" << theoretical_value);\n        BOOST_TEST_MESSAGE(\" - diff \" << calculated_value - theoretical_value);\n        BOOST_TEST(theoretical_value == calculated_value, boost::test_tools::tolerance(1e-8));\n    }\n\n    BOOST_AUTO_TEST_CASE(continuous_discount1) {\n        BOOST_TEST_MESSAGE(\"Testing continuous_discount1\");\n        BOOST_TEST_MESSAGE(\"using tolerances within checks.\");\n\n        double amount = 122.140275816;\n        double annual_rate = 10.0 / 100;\n        int number_of_years = 2;\n        double theoretical_value = 100; // 122.140275816 / e^(0.10*2) rounded to second\n\n        auto calculated_value = discount_continuously(amount, annual_rate, number_of_years);\n\n        BOOST_TEST_MESSAGE(\" - calculated_value: \" << calculated_value);\n        BOOST_TEST_MESSAGE(\" - known discounted_value: \" << theoretical_value);\n        BOOST_TEST_MESSAGE(\" - diff \" << calculated_value - theoretical_value);\n        BOOST_TEST(theoretical_value == calculated_value, boost::test_tools::tolerance(1e-8));\n    }\n\n    BOOST_AUTO_TEST_CASE(fwd_rate1) {\n        BOOST_TEST_MESSAGE(\"Testing fwd_rate1\");\n        BOOST_TEST_MESSAGE(\"using tolerances within checks.\");\n\n        double zero_coupon_total = 0.04;\n        int years_total = 2;\n\n        double zero_coupon_partial = 0.03;\n        int years_partial = 1;\n\n        double theoretical_value = 0.05; // (100*(1.1)^2) rounded to second\n\n        auto calculated_value = forward_rate(zero_coupon_total, years_total, zero_coupon_partial, years_partial);\n\n        BOOST_TEST_MESSAGE(\" - calculated_value: \" << calculated_value);\n        BOOST_TEST_MESSAGE(\" - known_fwd_rate: \" << theoretical_value);\n        BOOST_TEST_MESSAGE(\" - diff \" << calculated_value - theoretical_value);\n        BOOST_TEST(theoretical_value == calculated_value, boost::test_tools::tolerance(1e-15));\n    }\n\n    BOOST_AUTO_TEST_CASE(annual_to_cont1) {\n        BOOST_TEST_MESSAGE(\"Testing annual_to_cont1\");\n        BOOST_TEST_MESSAGE(\"using tolerances within checks.\");\n\n        double annual_rate = 0.12;\n\n        double theoretical_value = 0.1133286853; // ln(1.12)\n\n        auto calculated_value = annual_to_continuous_rate(1, annual_rate);\n\n        BOOST_TEST_MESSAGE(\" - calculated_value: \" << calculated_value);\n        BOOST_TEST_MESSAGE(\" - known_fwd_rate: \" << theoretical_value);\n        BOOST_TEST_MESSAGE(\" - diff \" << calculated_value - theoretical_value);\n        BOOST_TEST(theoretical_value == calculated_value, boost::test_tools::tolerance(1e-10));\n    }\n\n    BOOST_AUTO_TEST_CASE(cont_to_annual) {\n        BOOST_TEST_MESSAGE(\"Testing cont_to_annual\");\n        BOOST_TEST_MESSAGE(\"using tolerances within checks.\");\n\n        double continuous_rate = 0.11332868531; //(e^0.1)-1\n\n        double theoretical_value = 0.12; // (e^0.1)-1\n\n        auto calculated_value = continuous_to_annual_rate(1, continuous_rate);\n\n        BOOST_TEST_MESSAGE(\" - calculated_value: \" << calculated_value);\n        BOOST_TEST_MESSAGE(\" - known_fwd_rate: \" << theoretical_value);\n        BOOST_TEST_MESSAGE(\" - diff \" << calculated_value - theoretical_value);\n        BOOST_TEST(theoretical_value == calculated_value, boost::test_tools::tolerance(1e-9));\n    }\n\n    BOOST_AUTO_TEST_CASE(total_day_count, *utf::tolerance(0.0001)) {\n        BOOST_TEST_MESSAGE(\"Testing cont_to_annual\");\n        BOOST_TEST_MESSAGE(\"using tolerances within checks.\");\n\n        double myDoubles[] = {185.0 / 360, 182.0 / 360, 182.0 / 360, 182.0 / 360};\n        std::vector<double> dayCountFractionVector(myDoubles, myDoubles + sizeof(myDoubles) / sizeof(double));\n\n        std::vector<double> calculated_values = getTotalDayCountFractionVector(dayCountFractionVector);\n\n        double myResults[] = {0.513888888889, 1.019444444444, 1.525000000000, 2.030555555556};\n        std::vector<double> expected_values(myResults, myResults + sizeof(myResults) / sizeof(double));\n\n        BOOST_TEST(calculated_values == expected_values, boost::test_tools::per_element());\n\n    }\n\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "4c1bf0aa935fa97850927b4b726633d2469ee9e8", "size": 7852, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "assignment1/src/Utils/tests/test.cpp", "max_stars_repo_name": "paulochang/finance_valuator", "max_stars_repo_head_hexsha": "6bf6e6bc5c803d3a9530d528bd37cd73cce062f2", "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": "assignment1/src/Utils/tests/test.cpp", "max_issues_repo_name": "paulochang/finance_valuator", "max_issues_repo_head_hexsha": "6bf6e6bc5c803d3a9530d528bd37cd73cce062f2", "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": "assignment1/src/Utils/tests/test.cpp", "max_forks_repo_name": "paulochang/finance_valuator", "max_forks_repo_head_hexsha": "6bf6e6bc5c803d3a9530d528bd37cd73cce062f2", "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.6739130435, "max_line_length": 113, "alphanum_fraction": 0.6905247071, "num_tokens": 1803, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.8459424353665381, "lm_q1q2_score": 0.7240008035767284}}
{"text": "/**\n * \\file boost/numeric/ublasx/operation/rank.hpp\n *\n * \\brief Rank of a matrix.\n *\n * The rank of a matrix is the number of linearly independent rows or columns.\n *\n * The \\c rank function provides an estimate of the number of linearly\n * independent rows or columns of a matrix.\n * There are a number of ways to compute the rank of a matrix.\n * The currently adopted method is  based on the singular value decomposition\n * (SVD) which is the most time consuming, but also the most reliable.\n *\n * <hr/>\n *\n * Copyright (c) 2010, Marco Guazzone\n *\n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\n\n#ifndef BOOST_NUMERIC_UBLASX_OPERATION_RANK_HPP\n#define BOOST_NUMERIC_UBLASX_OPERATION_RANK_HPP\n\n\n#include <algorithm>\n#include <boost/numeric/ublas/expression_types.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublasx/operation/eps.hpp>\n#include <boost/numeric/ublasx/operation/max.hpp>\n#include <boost/numeric/ublasx/operation/num_columns.hpp>\n#include <boost/numeric/ublasx/operation/num_rows.hpp>\n#include <boost/numeric/ublasx/operation/size.hpp>\n#include <boost/numeric/ublasx/operation/svd.hpp>\n#include <boost/numeric/ublasx/operation/which.hpp>\n\n\nnamespace boost { namespace numeric { namespace ublasx {\n\nusing namespace ::boost::numeric::ublas;\n\n\n/**\n * \\brief Estimate the rank as the number of singular values of \\a A that are\n *  greater than a given tolerance.\n * \\tparam MatrixExprT The type of the input matrix expression.\n * \\tparam RealT The floating-point type of the tolerance.\n * \\param A The input matrix expression.\n * \\param tol The tolerance.\n * \\return The number of singular values of \\a A that are greater than \\a tol.\n */\ntemplate <typename MatrixExprT, typename RealT>\nBOOST_UBLAS_INLINE\ntypename matrix_traits<MatrixExprT>::size_type rank(matrix_expression<MatrixExprT> const& A, RealT tol)\n{\n\ttypedef typename matrix_traits<MatrixExprT>::value_type value_type;\n\ttypedef typename type_traits<value_type>::real_type real_type;\n\n\tvector<real_type> s = svd_values(A);\n\treturn size(which(s, ::std::bind2nd(::std::greater<real_type>(), tol)));\n}\n\n\n/**\n * \\brief Estimate the rank as the number of singular values of \\a A that are\n *  greater than the default tolerance.\n * \\tparam MatrixExprT The type of the input matrix expression.\n * \\param A The input matrix expression.\n * \\return The number of singular values of \\a A that are greater than \\a tol.\n *\n * The default tolerance is\n * \\f[\n * \t \\max(n,m) \\|A\\|_2 {\\epsilon}_m\n * \\f]\n * where \\f$n\\f$ is the number of rows of \\f$A\\f$, \\f$m\\f$ is the number of\n * columns of \\f$A\\f$, and \\f${\\epsilon}_m\\f$ is the floating-point machine\n * precision.\n */\ntemplate <typename MatrixExprT>\nBOOST_UBLAS_INLINE\ntypename matrix_traits<MatrixExprT>::size_type rank(matrix_expression<MatrixExprT> const& A)\n{\n\ttypedef typename matrix_traits<MatrixExprT>::value_type value_type;\n\ttypedef typename type_traits<value_type>::real_type real_type;\n\n\tvector<real_type> s = svd_values(A);\n\treal_type tol = ::std::max(num_rows(A), num_columns(A))*eps(max(s)); // note: max(s) == norm_2(A)\n\treturn size(which(s, ::std::bind2nd(::std::greater<real_type>(), tol)));\n}\n\n}}} // Namespace boost::numeric::ublasx\n\n\n#endif // BOOST_NUMERIC_UBLASX_OPERATION_RANK_HPP\n", "meta": {"hexsha": "73fce6191c832e1313b10a7a095d23dfcd2b834c", "size": 3410, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/ublasx/operation/rank.hpp", "max_stars_repo_name": "comcon1/boost-ublasx", "max_stars_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_stars_repo_licenses": ["BSL-1.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": "boost/numeric/ublasx/operation/rank.hpp", "max_issues_repo_name": "comcon1/boost-ublasx", "max_issues_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_issues_repo_licenses": ["BSL-1.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": "boost/numeric/ublasx/operation/rank.hpp", "max_forks_repo_name": "comcon1/boost-ublasx", "max_forks_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7959183673, "max_line_length": 103, "alphanum_fraction": 0.7451612903, "num_tokens": 888, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070035949657, "lm_q2_score": 0.795658104908603, "lm_q1q2_score": 0.7239748821234359}}
{"text": "/*\nThis program is free software; you can redistribute it and/or modify it under\nthe terms of the European Union Public Licence - EUPL v.1.1 as published by\nthe European Commission.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT\nANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\nFOR A PARTICULAR PURPOSE. See the European Union Public Licence - EUPL v.1.1\nfor more details.\n\nYou should have received a copy of the European Union Public Licence - EUPL v.1.1\nalong with this program.\n\nFurther information about the European Union Public Licence - EUPL v.1.1 can\nalso be found on the world wide web at http://ec.europa.eu/idabc/eupl\n\n*/\n\n/*\n------ Copyright (C) 2010 STA Steering Board (space.trajectory.analysis AT gmail.com) ----\n*/\n\n\n/*\nSTA uses interpolators based on the State Vector structures defined in \"Astro-Core/statevector.h\"\nfile. Vector and matrices operations are performed using the Eigen library.\n\nGiven a set of data points (x1 , y1 ) . . . (xn , yn ), the STA interpolators compute a\ncontinuous interpolating function y(x) such that y(xi ) = yi\n\nThe interpolation is piecewise smooth, and its behavior at the end-points is determined by the\ntype of interpolation used.\n\n*/\n\n/*\n ------------------ Author: Guillermo Ortega ESA  -------------------------------------------\n */\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include <Astro-Core/statevector.h>\n\n#include \"Interpolators.h\"\n\nusing namespace sta;\nusing namespace Eigen;\n\n/*\n Linear interpolation between two state vectors x0 and x1.\ninterval is the length of time (in seconds) between the two state vectors.\nt is a value between 0 and 1 that specifies the time within the interval.\n\nIf the two known points are given by the coordinates (x_0,y_0)\nand (x_1,y_1), the linear interpolant is the straight line\nbetween these points. For a value x in the interval (x_0, x_1),\nthe value y along the straight line is given from the equation\n\n    \\frac{y - y_0}{x - x_0} = \\frac{y_1 - y_0}{x_1 - x_0}\n\nSolving this equation for y, which is the unknown value at x, gives\n\n    y = y_0 + (x-x_0)\\frac{y_1 - y_0}{x_1-x_0}\n\nwhich is the formula for linear interpolation in the interval\n(x_0,x_1). Outside this interval, the formula is identical\nto linear extrapolation.\n\n*/\nsta::StateVector linearInterpolate(const sta::StateVector& x0,    // First state vector\n                                         const sta::StateVector& x1,     // Second state vector\n                                         double t,                       // Time within x0 an x1\n                                         double interval)                // Time distance between x1 and x1\n{\n    sta::StateVector result;\n    result.position = x0.position + t * ((x1.position - x0.position) * (1.0 / interval));\n    result.velocity = x0.velocity + t * ((x1.velocity - x0.velocity) * (1.0 / interval));\n    return result;\n}\n\n\n\n// Routine programmed C. Laurel\n// Cubic interpolation between two state vectors v0 and v1.\n// Interval is the length of time (in seconds) between the two state vectors.\n// t is a value between 0 and 1 that specifies the time within the interval.\nsta::StateVector cubicInterpolate(const sta::StateVector& v0,\n                                         const sta::StateVector& v1,\n                                         double t,\n                                         double interval)\n{\n    double t2 = t * t;\n    double t3 = t2 * t;\n    Vector3d a = 2.0 * (v0.position - v1.position) + interval * (v1.velocity + v0.velocity);\n    Vector3d b = 3.0 * (v1.position - v0.position) - interval * (2.0 * v0.velocity + v1.velocity);\n    Vector3d c = v0.velocity * interval;\n    Vector3d d = v0.position;\n\n    sta::StateVector result;\n    result.position = a * t3 + b * t2 + c * t + d;\n    result.velocity = (a * (3.0 * t2) + b * (2.0 * t) + c) * (1.0 / interval);\n\n    return result;\n}\n\n\n\n", "meta": {"hexsha": "ff9db4f9be456ccfa7d0a5d602bf9c880e6caf71", "size": 3905, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sta-src/Astro-Core/Interpolators.cpp", "max_stars_repo_name": "hoehnp/SpaceDesignTool", "max_stars_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_stars_repo_licenses": ["IJG"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-09-05T12:41:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-01T05:34:23.000Z", "max_issues_repo_path": "sta-src/Astro-Core/Interpolators.cpp", "max_issues_repo_name": "hoehnp/SpaceDesignTool", "max_issues_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_issues_repo_licenses": ["IJG"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-02-07T19:09:21.000Z", "max_issues_repo_issues_event_max_datetime": "2015-08-14T03:15:42.000Z", "max_forks_repo_path": "sta-src/Astro-Core/Interpolators.cpp", "max_forks_repo_name": "hoehnp/SpaceDesignTool", "max_forks_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_forks_repo_licenses": ["IJG"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-03-25T15:50:31.000Z", "max_forks_repo_forks_event_max_datetime": "2017-12-06T12:16:47.000Z", "avg_line_length": 35.8256880734, "max_line_length": 107, "alphanum_fraction": 0.652496799, "num_tokens": 970, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.7956580927949807, "lm_q1q2_score": 0.7239748769327411}}
{"text": "#include <iostream>\n#include <boost/math/constants/constants.hpp> // pi\n#include <static_math/complex.h> // constexpr complex class\n#include \"static_poly_io.hpp\"\n\nusing std::cout;\n\n/*** Greatest common divisor ***/\nconstexpr int gcd(int m, int n) {\n   while (n != 0) {\n      m %= n;\n      if (m == 0) return n;\n      n %= m;\n    }\n    return m;\n}\n\n/*** The Nth cyclotomic polynomial, computed with complex numbers ***/\ntemplate <int N>\nconstexpr static_poly<smath::complex<double>, N+1> cyclotomic() {\n    static_assert(N > 0, \"No nonpositive numbers please!\");\n    using namespace boost::math::double_constants;\n\n    static_poly<smath::complex<double>, N+1> cyc{1};\n\n    for (int k = 1; k <= N; ++k) {\n        if (gcd(k, N) == 1) {\n            static_poly<smath::complex<double>, 2> x{-smath::polar(1., 2.*k*pi / N), 1};\n            cyc = detail::mul(cyc, x);\n        // alas, std::polar(1., 2.*k*pi / N) is not constexpr\n        // furthermore, std::cos/std::sin are not constexpr (why!?)\n        }\n    }\n    return cyc;\n}\n\n/*** Euler's totient function... ***/\ntemplate <int N>\nconstexpr int euler_totient() {\n    return cyclotomic<N>().degree();\n}\n\ntemplate <int N>\nstruct foo {\n    constexpr int val() const {\n        return N;\n    }\n};\n\nint main() {\n    constexpr auto phi1 = cyclotomic<1>();\n    constexpr auto phi2 = cyclotomic<2>();\n    constexpr auto phi3 = cyclotomic<3>();\n    constexpr auto phi4 = cyclotomic<4>();\n    constexpr auto phi5 = cyclotomic<5>();\n    constexpr auto phi6 = cyclotomic<6>();\n    constexpr auto phi7 = cyclotomic<7>();\n    constexpr auto phi8 = cyclotomic<8>();\n    constexpr auto phi9 = cyclotomic<9>();\n    constexpr auto phi35 = cyclotomic<35>();\n\n    cout << phi1 << '\\n'\n         << phi2 << '\\n'\n         << phi3 << '\\n'\n         << phi4 << '\\n'\n         << phi5 << '\\n'\n         << phi6 << '\\n'\n         << phi7 << '\\n'\n         << phi8 << '\\n'\n         << phi9 << \"\\n\\n\"\n         << phi1*phi2 << '\\n'\n         << phi1*phi3 << '\\n'\n         << phi1*phi2*phi4 << '\\n'\n         << phi1*phi5 << '\\n'\n         << phi1*phi2*phi3*phi6 << '\\n'\n         << phi1*phi7 << '\\n'\n         << phi1*phi2*phi4*phi8 << '\\n'\n         << phi1*phi3*phi9 << \"\\n\\n\"\n         << phi35 << '\\n';\n\n    /* Use euler's totient function as a template parameter! */\n    foo<euler_totient<76>()> myfoo;\n    cout << myfoo.val() << '\\n';\n\n    return 0;\n}\n\n\n", "meta": {"hexsha": "d834a6b0000d7c0d435dffa5455b206673065f61", "size": 2368, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "complex-example.cpp", "max_stars_repo_name": "kundor/static-poly", "max_stars_repo_head_hexsha": "e1fd8ec7a55d67c665a1ec8057c6ccb744c45f5c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-14T19:26:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-14T19:26:32.000Z", "max_issues_repo_path": "complex-example.cpp", "max_issues_repo_name": "kundor/static-poly", "max_issues_repo_head_hexsha": "e1fd8ec7a55d67c665a1ec8057c6ccb744c45f5c", "max_issues_repo_licenses": ["BSL-1.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": "complex-example.cpp", "max_forks_repo_name": "kundor/static-poly", "max_forks_repo_head_hexsha": "e1fd8ec7a55d67c665a1ec8057c6ccb744c45f5c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.606741573, "max_line_length": 88, "alphanum_fraction": 0.5329391892, "num_tokens": 707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951552333004, "lm_q2_score": 0.7745833737577158, "lm_q1q2_score": 0.7237669517634744}}
{"text": "//\n// Created by Lu WJ on 5/7/2017 AD.\n//\n#include \"SMP/Matrix.hpp\"\n#include \"SMP/literal.hpp\"\n\n#include <NTL/ZZ.h>\n#include <iostream>\n#include <sstream>\n#include <cassert>\n#include <fstream>\n\nvoid zeros(Matrix *mat, long N) {\n    if (!mat) return;\n    mat->SetDims(N, N);\n    for (long i = 0; i < N; i++) {\n        for (long j = 0; j < N; j++)\n            (*mat)[i][j] = 0L;\n    }\n}\n\nvoid add(PlainVec *a, const PlainVec &b) {\n    if (!a or a->length() != b.length())\n        return;\n    for (long i = 0; i < b.length(); i++)\n        a->put(i, a->get(i) + b[i]);\n}\n\nvoid add(Matrix *a, const Matrix &b) {\n    if (!a) return;\n    assert(a->NumRows() == b.NumRows());\n    assert(a->NumCols() == b.NumCols());\n    for (long r = 0; r < b.NumRows(); r++) {\n        for (long c = 0; c < b.NumCols(); c++) {\n            (*a)[r][c] += b[r][c];\n        }\n    }\n}\n\nvoid transpose(Matrix *T, const Matrix &mat) {\n    if (!T) return;\n    T->kill();\n    T->SetDims(mat.NumCols(), mat.NumRows());\n    for (long r = 0; r < mat.NumRows(); r++) {\n        for (long c = 0; c < mat.NumCols(); c++)\n            (*T)[c][r] = mat[r][c];\n    }\n}\n\nvoid randomize(Matrix *mat) {\n    if (!mat)\n        return;\n    for (long r = 0; r < mat->NumRows(); r++) {\n        for (long c = 0; c < mat->NumCols(); c++) {\n            (*mat)[r][c] = NTL::RandomBnd(20) - 10;\n        }\n    }\n}\n\nbool is_same(const Matrix &a, const Matrix &b) {\n    if (a.NumRows() != b.NumRows() || a.NumCols() != b.NumCols())\n        return false;\n    for (long r = 0; r < a.NumRows(); r++) {\n        for (long c = 0; c < a.NumCols(); c++) {\n            if (a[r][c] != b[r][c]) {\n                std::cerr << a[r][c] << \"!=\" << b[r][c] << \"(\" << r << \",\" << c << \")\" << std::endl;\n                return false;\n            }\n        }\n    }\n    return true;\n}\n\nbool is_same(const Matrix &a, const Matrix &b, long modulus) {\n    if (a.NumRows() != b.NumRows() || a.NumCols() != b.NumCols())\n        return false;\n    for (long r = 0; r < a.NumRows(); r++) {\n        for (long c = 0; c < a.NumCols(); c++) {\n            long diff = (a[r][c] - b[r][c]) % modulus;\n            if (diff != 0) {\n                std::cerr << a[r][c] << \"!=\" << b[r][c] << \"(\" << r << \",\" << c << \")\" << std::endl;\n                return false;\n            }\n        }\n    }\n    return true;\n}\n\nPlainVec mul(const Matrix &m, const PlainVec &v) {\n    assert(m.NumCols() == v.length());\n    PlainVec result;\n    result.SetLength(m.NumRows());\n    for (long r = 0; r < m.NumRows(); r++) {\n        val_t sum{0};\n        for (long c = 0; c < m.NumCols(); c++) {\n            sum += m[r][c] * v[c];\n        }\n        result.put(r, sum);\n    }\n    return result;\n}\n\nMatrix mul(const Matrix &a, const Matrix &b) {\n    assert(a.NumCols() == b.NumRows());\n    Matrix result;\n    result.SetDims(a.NumRows(), b.NumCols());\n    for (long r = 0; r < a.NumRows(); r++) {\n        for (long c = 0; c < b.NumCols(); c++) {\n            val_t sum{0};\n            for (long k = 0; k < b.NumRows(); k++)\n                sum += a[r][k] * b[k][c];\n            result[r][c] = sum;\n        }\n    }\n    return result;\n}\n\nbool load_matrix(std::istream &in, Matrix *mat) {\n    if (in.bad() || in.eof() || !mat)\n        return false;\n\n    std::string line;\n    int line_num = 0;\n    for (long r = 0; !in.eof() && r < mat->NumRows(); r++) {\n        std::getline(in, line);\n        auto fields = splitBySpace(line);\n        if (fields.size() != mat->NumCols()) {\n            std::cerr << \"Warn: need \" << mat->NumCols() << \" columns, but got \" << fields.size() << \n                \" values in the \" << line_num + 1<< \" line.\" << std::endl;\n            return false;\n        }\n        size_t pos;\n        for (size_t c = 0; c < fields.size(); c++) {\n            long val = std::stol(fields[c], &pos, 10);\n            if (pos != fields[c].size()) {\n                std::cerr << \"Warn: invalid value \" << fields[c] << \" in line \" << line_num + 1 << std::endl;\n                val = 0;\n            }\n            (*mat)[line_num][c] = val;\n        }\n        line_num += 1;\n    }\n\n    if (line_num != mat->NumRows()) {\n        std::cerr << \"Warn: need \" << mat->NumRows() << \" rows but got \" << line_num << \" rows.\" << std::endl;\n        return false;\n    }\n    return true;\n}\n\nbool load_matrix(Matrix *mat, const std::string &file) {\n    if (!mat) {\n        std::cerr << \"Error: can not load matrix in an empty pointer.\" << std::endl;\n        return false;\n    }\n\n    std::ifstream in(file);\n    if (!in.is_open()) {\n        std::cerr << \"Error: can not open file \" << file << std::endl;\n        return false;\n    }\n\n    std::string header_line;\n    std::getline(in, header_line);\n    std::stringstream header(header_line);\n    char sharp;\n    long rows, cols;\n    header >> sharp >> rows >> cols;\n    if (sharp != '#' || rows <= 0 || cols <= 0) {\n        std::cerr << \"Error: invalid header \" << file << std::endl;\n        return false;\n    }\n    mat->SetDims(rows, cols);\n    bool ok = load_matrix(in, mat);\n    in.close();\n    return ok;\n}\n\nbool save_matrix(std::ostream &out, const Matrix &mat) {\n    if (out.bad() || out.eof())\n        return false;\n    if (mat.NumRows() <= 0 || mat.NumCols() <= 0)\n        return false;\n    for (long r = 0; r < mat.NumRows(); r++) {\n        for (long c = 0; c + 1 < mat.NumCols(); c++) {\n            out << mat[r][c] << \" \";\n        }\n        out << mat[r][mat.NumCols() - 1] << std::endl;\n    }\n    return out.good();\n}\n\nbool save_matrix(const Matrix &mat, const std::string &file) {\n    std::ofstream out(file);\n    if (!out.is_open()) {\n        std::cerr << \"Error: can not open file \" << file << std::endl;\n        return false;\n    }\n    out << \"#\" << mat.NumRows() << \" \" << mat.NumCols() << std::endl; \n    bool ok = save_matrix(out, mat);\n    out.close();\n    return ok;\n}\n\nbool load_vector(std::istream &in, PlainVec *vec) {\n    if (in.bad() || in.eof() || !vec)\n        return false;\n    std::string line;\n    std::getline(in, line);\n    const std::vector<std::string> fields = splitBySpace(line);\n    if (fields.size() != vec->length()) {\n        std::cerr << \"Error: need \" << vec->length()\n                  << \" elements but get \" << fields.size() << \".\" << std::endl;\n        return false;\n    }\n    size_t pos;\n    for (size_t c = 0; c < fields.size(); c++) {\n        long val = std::stol(fields.at(c), &pos, 10);\n        if (pos != fields[c].size()) {\n            std::cerr << \"Warn: invalid value: \" << fields[c] << std::endl;\n            val = 0L;\n        }\n        vec->put(c, val);\n    }\n    return true;\n}\n\nbool load_vector(PlainVec *vec, const std::string &file) {\n    std::ifstream in(file);\n    if (!in.is_open()) {\n        std::cerr << \"Error: can not open file \" << file << std::endl;\n        return false;\n    }\n    std::string header;\n    std::getline(in, header);\n    std::stringstream sstream(header);\n    char sharp = '\\0';\n    long length = 0;\n    sstream >> sharp >> length;\n    if (sharp != '#' || length <= 0) {\n        std::cerr << \"Error: invalid header of \" << file << std::endl;\n        return false;\n    }\n\n    vec->SetLength(length);\n    bool ok = load_vector(in, vec);\n    in.close();\n    return ok;\n}\n\nbool save_vector(const PlainVec &vec, const std::string &file) {\n    std::ofstream out(file);\n    if (!out.is_open()) {\n        std::cerr << \"Error: can not open file \" << file << std::endl;\n        return false;\n    }\n\n    out << \"#\" << vec.length() << std::endl;\n    bool ok = save_vector(out, vec);\n    out.close();\n    return ok;\n}\n\nbool save_vector(std::ostream &out, const PlainVec &vec) {\n    if (out.bad())\n        return false;\n    if (vec.length() == 0)\n        return true;\n    for (long c = 0; c + 1< vec.length(); c++)\n        out << vec[c] << \" \";\n    out << vec[vec.length() - 1] << std::endl;\n    return out.good();\n}\n", "meta": {"hexsha": "89349b0b33cfd028e160917f3b53c644731fc2d3", "size": 7805, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Matrix.cpp", "max_stars_repo_name": "Vampsj/SMP", "max_stars_repo_head_hexsha": "ec332ed29bc33685d050478090e0a679ddef0e4d", "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/Matrix.cpp", "max_issues_repo_name": "Vampsj/SMP", "max_issues_repo_head_hexsha": "ec332ed29bc33685d050478090e0a679ddef0e4d", "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/Matrix.cpp", "max_forks_repo_name": "Vampsj/SMP", "max_forks_repo_head_hexsha": "ec332ed29bc33685d050478090e0a679ddef0e4d", "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.4854014599, "max_line_length": 110, "alphanum_fraction": 0.4782831518, "num_tokens": 2316, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972549785201, "lm_q2_score": 0.8311430415844385, "lm_q1q2_score": 0.7235908504979102}}
{"text": "#include \"RSA.h\"\n#include \"math/Euclidean.h\"\n#include \"Encryptor.h\"\n#include \"Decryptor.h\"\n#include <exception>\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing namespace boost::multiprecision;\nusing namespace Crypto;\n\nRSA::RSA(int256_t p, int256_t q, int256_t r) : p(0), q(0), m(0), phi_of_m(0), r(0), public_key(nullptr), private_key(nullptr)\n{\n  try\n  {\n    setParameters(p, q, r);\n    calcKeys();\n  }\n  catch (std::exception &e)\n  {\n    //std::cout << e.what();\n    throw; // Rethrow exception.\n  }\n}\n\nvoid RSA::setParameters(int256_t p, int256_t q, int256_t r)\n{\n  this->p = p;\n  this->q = q;\n  this->r = r;\n  this->m = p * q;\n  this->phi_of_m = calcPhi(p, q);\n\n  if (!isPrime(p) || !isPrime(q)) // p and q must be prime numbers\n  {\n    throw std::exception(\"[ERROR] p or q is not a prime number!\");\n  }\n  else if ((r < m) && (r > 1) && (Euclidean::euclidean(r, phi_of_m) != 1)) // r and phi of m must be coprime\n  {\n    throw std::exception(\"[ERROR] r is not equal or less than p * q (=> m), or r and phi of m are not coprime!\");\n  }\n}\n\nvoid RSA::calcKeys()\n{\n  if (private_key != nullptr || public_key != nullptr)\n  {\n    throw std::exception(\"[ERROR] Keys already calculated!\");\n  }\n\n  calcPublicKey();\n  calcPrivateKey();\n}\n\nvoid RSA::calcPrivateKey()\n{\n\n  int256_t a = this->phi_of_m;\n  int256_t b = this->r;\n\n  int256_t s = 0;\n  int256_t x = 0;\n\n  //calculates the secret key\n  Euclidean::extendedEuclidean(a, b, &x, &s);\n\n  s = s < 0 ? makePositive(s, this->phi_of_m) : s;\n\n  this->private_key = new PrivateKey{ s, this->p, this->q };\n}\n\nvoid RSA::calcPublicKey()\n{\n  this->public_key = new PublicKey{ this->r, this->m };\n}\n\nconst PublicKey* RSA::getPublicKey() const\n{\n  return public_key;\n}\n\nconst PrivateKey* RSA::getPrivateKey() const\n{\n  return private_key;\n}\n\nbool RSA::isPrime(int256_t numb)\n{\n  int it;\n  for (it = 2; it < numb; it++)\n  {\n    if ((numb % it) == 0)\n      return false;\n  }\n\n  return true;\n}\n\nint256_t RSA::calcPhi(int256_t a, int256_t b)\n{\n  if (!isPrime(a) || !isPrime(b))\n  {\n    return 0;\n  }\n\n  return (a - 1) * (b - 1);\n}\n\nint256_t RSA::makePositive(int256_t numb, int256_t mod) const\n{\n  int256_t tmp = numb;\n  while (tmp < 0)\n  {\n    tmp += mod;\n  }\n\n  return tmp;\n}\n\nCryptoString RSA::encrypt(string str)\n{\n  Encryptor enc(public_key);\n  CryptoString out = enc.encryptString(str);\n  return out;\n}\n\nstring RSA::decrypt(CryptoString str)\n{\n  Crypto::Decryptor dec(private_key);\n  string res = dec.decryptString(str);\n  return res;\n}\n\nCryptoChar RSA::encrypt(char ch)\n{\n  Encryptor enc(public_key);\n  CryptoChar out = enc.encryptChar(ch);\n  return out;\n}\n\nchar RSA::decrypt(CryptoChar ch)\n{\n  Crypto::Decryptor dec(private_key);\n  char res = dec.decryptChar(ch);\n  return res;\n}", "meta": {"hexsha": "48d4e16321f50103990e432dd52da272ff99a6c0", "size": 2721, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/RSA.cpp", "max_stars_repo_name": "weniseb/RSA_CPP", "max_stars_repo_head_hexsha": "ea819e30e133205e780df94c17dc5f9236ec9739", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-01-04T07:19:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:03:49.000Z", "max_issues_repo_path": "src/RSA.cpp", "max_issues_repo_name": "weniseb/RSA_CPP", "max_issues_repo_head_hexsha": "ea819e30e133205e780df94c17dc5f9236ec9739", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-01-10T13:03:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-22T19:12:02.000Z", "max_forks_repo_path": "src/RSA.cpp", "max_forks_repo_name": "weniseb/RSA_CPP", "max_forks_repo_head_hexsha": "ea819e30e133205e780df94c17dc5f9236ec9739", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-06-25T20:57:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-27T08:42:35.000Z", "avg_line_length": 18.7655172414, "max_line_length": 125, "alphanum_fraction": 0.6328555678, "num_tokens": 849, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768635777511, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.7235167335477584}}
{"text": "/**\n * @file\n * @brief NPDE homework ElementMatrixComputation code\n * @author Janik Sch\u00fcttler, edited by Oliver Rietmann\n * @date 03.03.2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"mylinearfeelementmatrix.h\"\n\n#include <lf/base/base.h>\n#include <lf/geometry/geometry.h>\n#include <lf/mesh/mesh.h>\n#include <lf/uscalfe/uscalfe.h>\n\n#include <Eigen/Core>\n\nnamespace ElementMatrixComputation {\n\n/* SAM_LISTING_BEGIN_1 */\nEigen::Matrix<double, 4, 4> MyLinearFEElementMatrix::Eval(\n    const lf::mesh::Entity &cell) {\n  // Topological type of the cell\n  const lf::base::RefEl ref_el{cell.RefEl()};\n\n  // Obtain the vertex coordinates of the cell, which completely\n  // describe its shape.\n  const lf::geometry::Geometry *geo_ptr = cell.Geometry();\n  // Matrix storing corner coordinates in its columns\n  auto vertices = geo_ptr->Global(ref_el.NodeCoords());\n  // Matrix for returning element matrix\n  Eigen::Matrix<double, 4, 4> elem_mat;\n\n  //====================\n  // Your code goes here\n\n  // STEP 1: Case distinction depending on type of the mesh element\n  if (ref_el.ToString() == \"TRIA\"){\n      // bottom row and rightmost col are not used\n      elem_mat << 2., 1., 1., 0.,\n                  1., 2., 1., 0.,\n                  1., 1., 2., 0.,\n                  0., 0., 0., 0.;\n      // multiply with size |K|\n      elem_mat /= 12.;\n    }\n    else{\n     //\"QUAD\":\n      elem_mat << 4., 2., 1., 2.,\n                  2., 4., 2., 1.,\n                  1., 2., 4., 2.,\n                  2., 1., 2., 4.;\n      // multiply with size |K|\n      elem_mat /= 36.;\n  }\n\n  // multiply with the size of the mesh element\n  double K = lf::geometry::Volume(*geo_ptr);\n  elem_mat *= K;\n\n\n  // STEP 2: linearly add the computed -Delta u term\n  lf::uscalfe::LinearFELaplaceElementMatrix emp;\n\n  elem_mat += emp.Eval(cell);\n\n\n  //====================\n\n  return elem_mat;\n}\n/* SAM_LISTING_END_1 */\n}  // namespace ElementMatrixComputation\n", "meta": {"hexsha": "6387665c7b0ac54127896abf0db64e61a25cdf39", "size": 1928, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/ElementMatrixComputation/mysolution/mylinearfeelementmatrix.cc", "max_stars_repo_name": "youwuyou/NPDECODES", "max_stars_repo_head_hexsha": "c6db4e50476eab37464744797d3b932ab4cdfb44", "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": "homeworks/ElementMatrixComputation/mysolution/mylinearfeelementmatrix.cc", "max_issues_repo_name": "youwuyou/NPDECODES", "max_issues_repo_head_hexsha": "c6db4e50476eab37464744797d3b932ab4cdfb44", "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": "homeworks/ElementMatrixComputation/mysolution/mylinearfeelementmatrix.cc", "max_forks_repo_name": "youwuyou/NPDECODES", "max_forks_repo_head_hexsha": "c6db4e50476eab37464744797d3b932ab4cdfb44", "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.0540540541, "max_line_length": 67, "alphanum_fraction": 0.5980290456, "num_tokens": 554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476800298183, "lm_q2_score": 0.8244619285331332, "lm_q1q2_score": 0.7234462150169229}}
{"text": "//\n// Copyright (c) 2018-2019 CNRS INRIA\n//\n\n#include \"pinocchio/autodiff/cppad.hpp\"\n#include <cppad/speed/det_by_minor.hpp>\n\n#include <boost/variant.hpp> // to avoid C99 warnings\n\n#include <iostream>\n\n#include <boost/test/unit_test.hpp>\n#include <boost/utility/binary.hpp>\n\nBOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE)\n\n  BOOST_AUTO_TEST_CASE(test_example1_cppad)\n  {\n    using CppAD::AD;\n    using CppAD::NearEqual;\n    using Eigen::Matrix;\n    using Eigen::Dynamic;\n    //\n    typedef Matrix< AD<double> , Dynamic, 1 > eigen_vector;\n    //\n    // some temporary indices\n    size_t i, j;\n    \n    // domain and range space vectors\n    size_t n  = 10, m = n;\n    eigen_vector a_x(n), a_y(m);\n    \n    // set and declare independent variables and start tape recording\n    for(j = 0; j < n; j++)\n    {\n      a_x[(Eigen::DenseIndex)j] = double(1 + j);\n    }\n    CppAD::Independent(a_x);\n    \n    // evaluate a component wise function\n    a_y = a_x.array() + a_x.array().sin();\n    \n    // create f: x -> y and stop tape recording\n    CppAD::ADFun<double> f(a_x, a_y);\n    \n    // compute the derivative of y w.r.t x using CppAD\n    CPPAD_TESTVECTOR(double) x(n);\n    for(j = 0; j < n; j++)\n    {\n      x[j] = double(j) + 1.0 / double(j+1);\n    }\n    CPPAD_TESTVECTOR(double) jac = f.Jacobian(x);\n      \n      // check Jacobian\n    double eps = 100. * CppAD::numeric_limits<double>::epsilon();\n    for(i = 0; i < m; i++)\n    {\n      for(j = 0; j < n; j++)\n      {\n        double check = 1.0 + cos(x[i]);\n        if( i != j ) check = 0.0;\n          BOOST_CHECK(NearEqual(jac[i * n + j], check, eps, eps));\n      }\n    }\n  }\n\n\n  BOOST_AUTO_TEST_CASE(test_example2_cppad)\n  {\n    using CppAD::AD;\n    using CppAD::NearEqual;\n    using Eigen::Matrix;\n    using Eigen::Dynamic;\n    //\n    typedef Matrix< double     , Dynamic, Dynamic > eigen_matrix;\n    typedef Matrix< AD<double> , Dynamic, Dynamic > eigen_ad_matrix;\n    //\n    typedef Matrix< double ,     Dynamic , 1>       eigen_vector;\n    typedef Matrix< AD<double> , Dynamic , 1>       eigen_ad_vector;\n    // some temporary indices\n    size_t i, j;\n    \n    // domain and range space vectors\n    size_t size = 3, n  = size * size, m = 1;\n    eigen_ad_vector a_x(n), a_y(m);\n    eigen_vector x(n);\n    \n    // set and declare independent variables and start tape recording\n    for(i = 0; i < size; i++)\n    {\n      for(j = 0; j < size; j++)\n      {     // lower triangular matrix\n        a_x[(Eigen::DenseIndex)(i * size + j)] = x[(Eigen::DenseIndex)(i * size + j)] = 0.0;\n        if( j <= i )\n          a_x[(Eigen::DenseIndex)(i * size + j)] = x[(Eigen::DenseIndex)(i * size + j)] = double(1 + i + j);\n      }\n    }\n    CppAD::Independent(a_x);\n    \n    // copy independent variable vector to a matrix\n    eigen_ad_matrix a_X(size, size);\n    eigen_matrix X(size, size);\n    for(i = 0; i < size; i++)\n    {\n      for(j = 0; j < size; j++)\n      {\n        X((Eigen::DenseIndex)i, (Eigen::DenseIndex)j)   = x[(Eigen::DenseIndex)(i * size + j)];\n        // If we used a_X(i, j) = X(i, j), a_X would not depend on a_x.\n        a_X((Eigen::DenseIndex)i, (Eigen::DenseIndex)j) = a_x[(Eigen::DenseIndex)(i * size + j)];\n      }\n    }\n    \n    // Compute the log of determinant of X\n    a_y[0] = log( a_X.determinant() );\n    \n    // create f: x -> y and stop tape recording\n    CppAD::ADFun<double> f(a_x, a_y);\n    \n    // check function value\n    double eps = 100. * CppAD::numeric_limits<double>::epsilon();\n    CppAD::det_by_minor<double> det(size);\n    BOOST_CHECK(NearEqual(Value(a_y[0]) , log(det(x)), eps, eps));\n    \n    // compute the derivative of y w.r.t x using CppAD\n    eigen_vector jac = f.Jacobian(x);\n    \n    // check the derivative using the formula\n    // d/dX log(det(X)) = transpose( inv(X) )\n    eigen_matrix inv_X = X.inverse();\n    for(i = 0; i < size; i++)\n    {\n      for(j = 0; j < size; j++)\n        BOOST_CHECK(NearEqual(jac[(Eigen::DenseIndex)(i * size + j)],\n                              inv_X((Eigen::DenseIndex)j, (Eigen::DenseIndex)i),\n                              eps,\n                              eps));\n    }\n  }\n\n  BOOST_AUTO_TEST_CASE(test_sincos)\n  {\n    using CppAD::AD;\n    using CppAD::NearEqual;\n    double eps99 = 99.0 * std::numeric_limits<double>::epsilon();\n    \n    typedef AD<double> AD_double;\n    \n    double x0 = 1.;\n    CPPAD_TESTVECTOR(AD_double) x(1), y(1), z(1);\n    x[0] = x0;\n    CppAD::Independent(x);\n    \n    y[0] = CppAD::cos(x[0]);\n    BOOST_CHECK(NearEqual(y[0],std::cos(x0),eps99,eps99));\n    CppAD::ADFun<double> fcos(x, y);\n  \n    CPPAD_TESTVECTOR(double) x_eval(1);\n    x_eval[0] = x0;\n    CPPAD_TESTVECTOR(double) dy(1);\n    dy = fcos.Jacobian(x_eval);\n    BOOST_CHECK(NearEqual(dy[0],-std::sin(x0),eps99,eps99));\n\n    CppAD::Independent(x);\n    z[0] = CppAD::sin(x[0]);\n    BOOST_CHECK(NearEqual(z[0],std::sin(x0),eps99,eps99));\n    \n    CppAD::ADFun<double> fsin(x, z);\n\n    CPPAD_TESTVECTOR(double) dz(1);\n    dz = fsin.Jacobian(x_eval);\n    BOOST_CHECK(NearEqual(dz[0],std::cos(x0),eps99,eps99));\n  }\n\n  BOOST_AUTO_TEST_CASE(test_eigen_support)\n  {\n    using namespace CppAD;\n    \n    // use a special object for source code generation\n    typedef AD<double> ADScalar;\n    \n    typedef Eigen::Matrix<ADScalar,Eigen::Dynamic,1> ADVector;\n    \n    ADVector vec_zero(ADVector::Zero(100));\n    BOOST_CHECK(vec_zero.isZero());\n    \n    ADVector vec_ones(100);\n    vec_ones.fill(1);\n    BOOST_CHECK(vec_ones.isOnes());\n    \n  }\n\n  BOOST_AUTO_TEST_CASE(test_abs)\n  {\n    CppAD::AD<double> ad_value;\n    ad_value = -1.;\n    abs(ad_value);\n  }\n\nBOOST_AUTO_TEST_CASE(test_atan2)\n{\n  CppAD::AD<double> theta,x,y;\n  x = pinocchio::math::cos(theta); y = pinocchio::math::sin(theta);\n  \n  pinocchio::math::atan2(y,x);\n  \n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "f6558201617bb87c2a9b22fb3490fb2956213e70", "size": 5758, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/cppad-basic.cpp", "max_stars_repo_name": "ikalevatykh/pinocchio", "max_stars_repo_head_hexsha": "2c22ca240e78e5a6c20e7b2cb6c44e7a45658d38", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-04-07T07:23:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-07T07:23:34.000Z", "max_issues_repo_path": "unittest/cppad-basic.cpp", "max_issues_repo_name": "ikalevatykh/pinocchio", "max_issues_repo_head_hexsha": "2c22ca240e78e5a6c20e7b2cb6c44e7a45658d38", "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": "unittest/cppad-basic.cpp", "max_forks_repo_name": "ikalevatykh/pinocchio", "max_forks_repo_head_hexsha": "2c22ca240e78e5a6c20e7b2cb6c44e7a45658d38", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-26T14:29:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-26T14:29:02.000Z", "avg_line_length": 27.5502392344, "max_line_length": 108, "alphanum_fraction": 0.5837096214, "num_tokens": 1765, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774768002981829, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.7234462112322557}}
{"text": "// Copyright 2021, Autonomous Space Robotics Lab (ASRL)\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n/**\n * \\file register_svd.hpp\n * \\brief Header for registerSVD function\n * \\details Calculates rigid transformation given two sets of points. Used in\n * stereo_transform_model\n *\n * \\author Kirk MacTavish, Autonomous Space Robotics Lab (ASRL)\n */\n#pragma once\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/SVD>\n\nnamespace vtr {\nnamespace vision {\n\n// Returns tf s.t. a = tf * b\ntemplate <unsigned int N>\nbool registerSVD(const Eigen::Matrix<double, N, Eigen::Dynamic>& a,\n                 const Eigen::Matrix<double, N, Eigen::Dynamic>& b,\n                 Eigen::Matrix<double, N + 1, N + 1>* tf,\n                 const Eigen::Array<double, 1, Eigen::Dynamic>& weights =\n                     Eigen::Array<double, 1, Eigen::Dynamic>(1, 0),\n                 bool scaling = false) {\n  // Types\n  // typedef Eigen::Matrix<double,N+1,N+1> Transform;\n  typedef Eigen::Matrix<double, N, 1> Point;\n  typedef Eigen::Matrix<double, N, Eigen::Dynamic> Points;\n  typedef Eigen::Matrix<double, N, N> Square;\n\n  // Check output allocation\n  if (!tf) return false;\n\n  // Are we weighting points?\n  bool use_weights = weights.cols() > 0;\n\n  // Check input (1 pt for 1D, 2 pts for 2D, 3 pts for 3D)\n  if (a.cols() < N || a.cols() != b.cols() ||\n      (use_weights && a.cols() != weights.cols()))\n    return false;\n\n  // Switch based on whether we're weighting the points\n  // See https://igl.ethz.ch/projects/ARAP/svd_rot.pdf\n  Point ca, cb;\n  Points a0, b0;\n  Square cov;\n  if (use_weights) {\n    // Weight points\n    Points aw = a.array().rowwise() * weights;\n    Points bw = b.array().rowwise() * weights;\n\n    // Compute centroids\n    double w_sum = weights.sum();\n    ca = aw.rowwise().sum() / w_sum;\n    cb = bw.rowwise().sum() / w_sum;\n\n    // Demean\n    a0 = a.colwise() - ca;\n    b0 = b.colwise() - cb;\n\n    // Covariance\n    cov =\n        (a0.array().rowwise() * weights).matrix() * b0.transpose();  // a0*W*b0'\n  } else {\n    // Compute centroids\n    ca = a.rowwise().mean();\n    cb = b.rowwise().mean();\n\n    // Demean\n    a0 = a.colwise() - ca;\n    b0 = b.colwise() - cb;\n\n    // Covariance\n    cov = a0 * b0.transpose();\n  }\n\n  // SVD\n  Eigen::JacobiSVD<Square> svd(cov, Eigen::ComputeFullU | Eigen::ComputeFullV);\n  Square V = svd.matrixV();\n  // Normally V * U', but then we have to use R'.\n  Square R = svd.matrixU() * V.transpose();\n\n  // Check for proper right-hand rotation\n  double det = R.determinant();\n  if (det < 0. || use_weights) {\n    // If we use the weights, we have to remove their influence here\n    V.col(N - 1) *= use_weights ? det : -1.;\n    // Normally V * U', but then we have to use R'.\n    R = svd.matrixU() * V.transpose();\n  }\n\n  // Apply scaling if necessary\n  if (scaling) {\n    double scale = b0.norm() / a0.norm();\n    R /= scale;\n  }\n\n  // Translation\n  Point t = ca - R * cb;\n\n  // Build final transform\n  tf->row(N).setZero();\n  (*tf)(N, N) = 1.;\n  tf->template topLeftCorner<N, N>() = R;\n  tf->template topRightCorner<N, 1>() = t;\n\n  // Return\n  return true;\n}\n\n// Explicit instantiation for common params\nextern template bool registerSVD<2>(\n    const Eigen::Matrix<double, 2, Eigen::Dynamic>& a,\n    const Eigen::Matrix<double, 2, Eigen::Dynamic>& b,\n    Eigen::Matrix<double, 2 + 1, 2 + 1>* tf,\n    const Eigen::Array<double, 1, Eigen::Dynamic>& weights, bool scaling);\nextern template bool registerSVD<3>(\n    const Eigen::Matrix<double, 3, Eigen::Dynamic>& a,\n    const Eigen::Matrix<double, 3, Eigen::Dynamic>& b,\n    Eigen::Matrix<double, 3 + 1, 3 + 1>* tf,\n    const Eigen::Array<double, 1, Eigen::Dynamic>& weights, bool scaling);\n\n}  // namespace vision\n}  // namespace vtr\n", "meta": {"hexsha": "bc4cefe5f2068173fd04fd3ba30d9d135ae01abd", "size": 4248, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "main/src/vtr_vision/include/vtr_vision/sensors/register_svd.hpp", "max_stars_repo_name": "utiasASRL/vtr3", "max_stars_repo_head_hexsha": "b4edca56a19484666d3cdb25a032c424bdc6f19d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2021-09-15T03:42:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:40:01.000Z", "max_issues_repo_path": "main/src/vtr_vision/include/vtr_vision/sensors/register_svd.hpp", "max_issues_repo_name": "shimp-t/vtr3", "max_issues_repo_head_hexsha": "bdcad784ffe26fabfa737d0e195bcb3bacb930c3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2021-09-18T19:18:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-02T11:15:40.000Z", "max_forks_repo_path": "main/src/vtr_vision/include/vtr_vision/sensors/register_svd.hpp", "max_forks_repo_name": "shimp-t/vtr3", "max_forks_repo_head_hexsha": "bdcad784ffe26fabfa737d0e195bcb3bacb930c3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2021-09-18T01:31:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T05:09:37.000Z", "avg_line_length": 30.3428571429, "max_line_length": 80, "alphanum_fraction": 0.6287664783, "num_tokens": 1198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632916317102, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.7233367834290126}}
{"text": "#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <sstream>\n\n#include <Eigen/Eigen>\n\n#include <unsupported/Eigen/NonLinearOptimization>\n\n#include <ros/ros.h>\n\n\nstruct LMFunctor\n{\n\t// 'm' pairs of (x, f(x))\n\tEigen::MatrixXf measuredValues;\n\n\t// Compute 'm' errors, one for each data point, for the given parameter values in 'x'\n\tint operator()(const Eigen::VectorXf &x, Eigen::VectorXf &fvec) const\n\t{\n\t\t// 'x' has dimensions n x 1\n\t\t// It contains the current estimates for the parameters.\n\n\t\t// 'fvec' has dimensions m x 1\n\t\t// It will contain the error for each data point.\n\n\t\tfloat aParam = x(0);\n\t\tfloat bParam = x(1);\n\t\tfloat cParam = x(2);\n\n\t\tfor (int i = 0; i < values(); i++) {\n\t\t\tfloat xValue = measuredValues(i, 0);\n\t\t\tfloat yValue = measuredValues(i, 1);\n\n\t\t\tfvec(i) = yValue - (aParam * xValue * xValue + bParam * xValue + cParam);\n\t\t}\n\t\treturn 0;\n\t}\n\n\t// Compute the jacobian of the errors\n\tint df(const Eigen::VectorXf &x, Eigen::MatrixXf &fjac) const\n\t{\n\t\t// 'x' has dimensions n x 1\n\t\t// It contains the current estimates for the parameters.\n\n\t\t// 'fjac' has dimensions m x n\n\t\t// It will contain the jacobian of the errors, calculated numerically in this case.\n\n\t\tfloat epsilon;\n\t\tepsilon = 1e-7f;\n\n\t\tfor (int i = 0; i < x.size(); i++) {\n\t\t\tEigen::VectorXf xPlus(x);\n\t\t\txPlus(i) += epsilon;\n\t\t\tEigen::VectorXf xMinus(x);\n\t\t\txMinus(i) -= epsilon;\n\n\t\t\tEigen::VectorXf fvecPlus(values());\n\t\t\toperator()(xPlus, fvecPlus);\n\n\t\t\tEigen::VectorXf fvecMinus(values());\n\t\t\toperator()(xMinus, fvecMinus);\n\n\t\t\tEigen::VectorXf fvecDiff(values());\n\t\t\tfvecDiff = (fvecPlus - fvecMinus) / (2.0f * epsilon);\n\n\t\t\tfjac.block(0, i, values(), 1) = fvecDiff;\n\t\t}\n\n\t\treturn 0;\n\t}\n\n\t// Number of data points, i.e. values.\n\tint m;\n\n\t// Returns 'm', the number of values.\n\tint values() const { return m; }\n\n\t// The number of parameters, i.e. inputs.\n\tint n;\n\n\t// Returns 'n', the number of inputs.\n\tint inputs() const { return n; }\n\n};\n\n\nint main(int argc, char *argv[])\n{\n    // ros::init(argc, argv, \"LM_node\");\n    // ros::start();\n\t// //\n\t// Goal\n\t//\n\t// Given a non-linear equation: f(x) = a(x^2) + b(x) + c\n\t// and 'm' data points (x1, f(x1)), (x2, f(x2)), ..., (xm, f(xm))\n\t// our goal is to estimate 'n' parameters (3 in this case: a, b, c)\n\t// using LM optimization.\n\t//\n\n\t//\n\t// Read values from file.\n\t// Each row has two numbers, for example: 5.50 223.70\n\t// The first number is the input value (5.50) i.e. the value of 'x'.\n\t// The second number is the observed output value (223.70),\n\t// i.e. the measured value of 'f(x)'.\n\t\n\n\t// 'm' is the number of data points.\n\tint m = 100;\n\n\t// Move the data into an Eigen Matrix.\n\t// The first column has the input values, x. The second column is the f(x) values.\n    float a = 0.1;\n    float b = 0.2;\n    float c = 0.3;\n\tEigen::MatrixXf measuredValues(m, 2);\n\tfor (int i = 0; i < m; i++) {\n\t\tmeasuredValues(i, 0) = (float) rand()/RAND_MAX * 10;\n\t\tmeasuredValues(i, 1) = a*measuredValues(i, 0)*measuredValues(i, 0) + b*measuredValues(i, 0) + c + (float) rand()/RAND_MAX/10;\n\t}\n\n\t// 'n' is the number of parameters in the function.\n\t// f(x) = a(x^2) + b(x) + c has 3 parameters: a, b, c\n\tint n = 3;\n\n\t// 'x' is vector of length 'n' containing the initial values for the parameters.\n\t// The parameters 'x' are also referred to as the 'inputs' in the context of LM optimization.\n\t// The LM optimization inputs should not be confused with the x input values.\n\tEigen::VectorXf x(n);\n\tx(0) = 0.0;             // initial value for 'a'\n\tx(1) = 0.0;             // initial value for 'b'\n\tx(2) = 0.0;             // initial value for 'c'\n\n\t//\n\t// Run the LM optimization\n\t// Create a LevenbergMarquardt object and pass it the functor.\n\t//\n\n\tLMFunctor functor;\n\tfunctor.measuredValues = measuredValues;\n\tfunctor.m = m;\n\tfunctor.n = n;\n\n\tEigen::LevenbergMarquardt<LMFunctor, float> lm(functor);\n\tint status = lm.minimize(x);\n\tstd::cout << \"LM optimization status: \" << status << std::endl;\n\n\t//\n\t// Results\n\t// The 'x' vector also contains the results of the optimization.\n\t//\n\tstd::cout << \"Optimization results\" << std::endl;\n\tstd::cout << \"\\ta: \" << x(0) << std::endl;\n\tstd::cout << \"\\tb: \" << x(1) << std::endl;\n\tstd::cout << \"\\tc: \" << x(2) << std::endl;\n    \n    // ros::shutdown();\n\treturn 0;\n}", "meta": {"hexsha": "79ccdaf46f86cb4ebc4e60cf9fd4c32d56f9a7dc", "size": 4249, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cad_replacement/map_proc/deprecated/LM_test.cpp", "max_stars_repo_name": "OneOneEleven/Interactive-Scene-Reconstruction", "max_stars_repo_head_hexsha": "dade6e95eea56e04a5d39441f4e03e1667fe37ef", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 62.0, "max_stars_repo_stars_event_min_datetime": "2021-04-04T13:44:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T08:13:42.000Z", "max_issues_repo_path": "cad_replacement/map_proc/deprecated/LM_test.cpp", "max_issues_repo_name": "OneOneEleven/Interactive-Scene-Reconstruction", "max_issues_repo_head_hexsha": "dade6e95eea56e04a5d39441f4e03e1667fe37ef", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-11-23T23:10:07.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T17:29:07.000Z", "max_forks_repo_path": "cad_replacement/map_proc/deprecated/LM_test.cpp", "max_forks_repo_name": "hmz-15/Interactive-Scene-Reconstruction", "max_forks_repo_head_hexsha": "70412c8f5e9ce1c2543fe866f3c5728a723d6478", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2021-09-28T12:44:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T10:55:29.000Z", "avg_line_length": 26.55625, "max_line_length": 127, "alphanum_fraction": 0.6227347611, "num_tokens": 1374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.7232780055177958}}
{"text": "/*\n * Copyright Nick Thompson, 2020\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 <boost/math/tools/cohen_acceleration.hpp>\n#include <boost/math/constants/constants.hpp>\n#ifdef BOOST_HAS_FLOAT128\n#include <boost/multiprecision/float128.hpp>\nusing boost::multiprecision::float128;\n#endif\n#include <boost/multiprecision/cpp_bin_float.hpp>\n\nusing boost::math::tools::cohen_acceleration;\nusing boost::multiprecision::cpp_bin_float_100;\nusing boost::math::constants::pi;\n\ntemplate<typename Real>\nclass G {\npublic:\n    G(){\n        k_ = 0;\n    }\n    \n    Real operator()() {\n        k_ += 1;\n        return 1/(k_*k_);\n    }\n\nprivate:\n    Real k_;\n};\n\ntemplate<typename Real>\nvoid test_pisq_div12()\n{\n    auto g = G<Real>();\n    Real x = cohen_acceleration(g);\n    CHECK_ULP_CLOSE(pi<Real>()*pi<Real>()/12, x, 3);\n}\n\ntemplate<typename Real>\nclass Divergent {\npublic:\n    Divergent(){\n        k_ = 0;\n    }\n\n    // See C3 of: https://people.mpim-bonn.mpg.de/zagier/files/exp-math-9/fulltext.pdf\n    Real operator()() {\n        using std::log;\n        k_ += 1;\n        return log(k_);\n    }\n\nprivate:\n    Real k_;\n};\n\ntemplate<typename Real>\nvoid test_divergent()\n{\n    auto g = Divergent<Real>();\n    Real x = -cohen_acceleration(g);\n    CHECK_ULP_CLOSE(log(pi<Real>()/2)/2, x, 80);\n}\n\nint main()\n{\n    test_pisq_div12<float>();\n    test_pisq_div12<double>();\n    test_pisq_div12<long double>();\n\n    test_divergent<float>();\n    test_divergent<double>();\n    test_divergent<long double>();\n\n    #ifdef BOOST_HAS_FLOAT128\n    test_pisq_div12<float128>();\n    test_divergent<float128>();\n    #endif\n    return boost::math::test::report_errors();\n}\n", "meta": {"hexsha": "291cb85b6490368e715b5e77eb360b99917ea809", "size": 1825, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/test/cohen_acceleration_test.cpp", "max_stars_repo_name": "armdevvel/boost", "max_stars_repo_head_hexsha": "30d0930951181ef5bc5aad2231ebac8575db0720", "max_stars_repo_licenses": ["BSL-1.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": "libs/math/test/cohen_acceleration_test.cpp", "max_issues_repo_name": "armdevvel/boost", "max_issues_repo_head_hexsha": "30d0930951181ef5bc5aad2231ebac8575db0720", "max_issues_repo_licenses": ["BSL-1.0"], "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": "libs/math/test/cohen_acceleration_test.cpp", "max_forks_repo_name": "armdevvel/boost", "max_forks_repo_head_hexsha": "30d0930951181ef5bc5aad2231ebac8575db0720", "max_forks_repo_licenses": ["BSL-1.0"], "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": 20.9770114943, "max_line_length": 86, "alphanum_fraction": 0.6608219178, "num_tokens": 497, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941988938413, "lm_q2_score": 0.8006920068519378, "lm_q1q2_score": 0.7232604448900233}}
{"text": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union\u2019s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n\n#include \"../util/AlgorithmUtils.hpp\"\n#include \"../util/FluidEigenMappings.hpp\"\n#include \"../../data/FluidIndex.hpp\"\n#include \"../../data/TensorTypes.hpp\"\n#include <Eigen/Eigen>\n#include <cmath>\n\nnamespace fluid {\nnamespace algorithm {\n\nclass SpectralShape\n{\n\n  using ArrayXd = Eigen::ArrayXd;\n\npublic:\n  SpectralShape(index maxFrame) : mMagBuffer(maxFrame) {}\n\n  void processFrame(Eigen::Ref<ArrayXd> in)\n  {\n    using namespace std;\n    double const epsilon = std::numeric_limits<double>::epsilon();\n\n    ArrayXd x = in.max(epsilon);\n    index   size = x.size();\n    double  xSum = x.sum();\n    ArrayXd xSquare = x.square();\n    ArrayXd lin = ArrayXd::LinSpaced(size, 0, size - 1);\n    double  centroid = (x * lin).sum() / xSum;\n    double  spread = (x * (lin - centroid).square()).sum() / xSum;\n    double  skewness =\n        (x * (lin - centroid).pow(3)).sum() / (spread * sqrt(spread) * xSum);\n    double kurtosis =\n        (x * (lin - centroid).pow(4)).sum() / (spread * spread * xSum);\n    double flatness = exp(x.log().mean()) / x.mean();\n    double rolloff = size - 1;\n    double cumSum = 0;\n    double target = 0.95 * xSquare.sum();\n    for (index i = 0; cumSum <= target && i < size; i++)\n    {\n      cumSum += xSquare(i);\n      if (cumSum > target)\n      {\n        rolloff = i - (cumSum - target) / xSquare(i);\n        break;\n      }\n    }\n    double crest = x.maxCoeff() / sqrt(x.square().mean());\n\n    mOutputBuffer(0) = centroid;\n    mOutputBuffer(1) = sqrt(spread);\n    mOutputBuffer(2) = skewness;\n    mOutputBuffer(3) = kurtosis;\n    mOutputBuffer(4) = rolloff;\n    mOutputBuffer(5) = 20 * log10(max(flatness, epsilon));\n    mOutputBuffer(6) = 20 * log10(max(crest, epsilon));\n  }\n\n  void processFrame(const RealVector& input, RealVectorView output)\n  {\n    assert(output.size() == 7); // TODO\n    ArrayXd in = _impl::asEigen<Eigen::Array>(input);\n    processFrame(in);\n    output = _impl::asFluid(mOutputBuffer);\n  }\n\nprivate:\n  ArrayXd mMagBuffer;\n  ArrayXd mOutputBuffer{7};\n};\n\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "bc9ec4dac5411499c50127d0949d3bcdfd418ddb", "size": 2469, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/public/SpectralShape.hpp", "max_stars_repo_name": "elgiano/flucoma-core", "max_stars_repo_head_hexsha": "d34a04e7a68f24eaf09b24df57020d45664061fc", "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": "include/algorithms/public/SpectralShape.hpp", "max_issues_repo_name": "elgiano/flucoma-core", "max_issues_repo_head_hexsha": "d34a04e7a68f24eaf09b24df57020d45664061fc", "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": "include/algorithms/public/SpectralShape.hpp", "max_forks_repo_name": "elgiano/flucoma-core", "max_forks_repo_head_hexsha": "d34a04e7a68f24eaf09b24df57020d45664061fc", "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": 28.7093023256, "max_line_length": 77, "alphanum_fraction": 0.6472255974, "num_tokens": 681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582554941719, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.7232450680243011}}
{"text": "/*\n * TPSInterpolate.hpp\n * license: http://www.boost.org/LICENSE_1_0.txt\n *  Created on: 18 Aug 2010\n *      Author: Peter Stroia-Williams\n */\n\n#ifndef TPSINTERPOLATE_HPP_\n#define TPSINTERPOLATE_HPP_\n\n#include <vector>\n#include <cmath>\n\n#include <boost/array.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/vector_expression.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/triangular.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n//using namespace boost::numeric::ublas;\n//using namespace boost;\n//using namespace std;\n\ndouble\nradial_basis(double r)\n{\n  if(r==0.0)\n    return 0.0;\n  return pow(r, 2) * log(r);\n}\n\ntemplate<typename T1, typename T2, int Dim>\n  double\n  radialbasis(const boost::array<T1, Dim> & v1, const boost::array<T2, Dim> & v2)\n  {\n    boost::numeric::ublas::vector<double> v(Dim);\n    for(unsigned int i(0); i < v.size(); ++i)\n    {\n      v(i) = v1[i] - v2[i];\n    }\n    return radial_basis(norm_2(v));\n  }\n\n\ntemplate<int PosDim, int ValDim, typename WorkingType = double>\n  class ThinPlateSpline\n  {\n  public:\n    boost::numeric::ublas::matrix<WorkingType> Wa;\n    std::vector<boost::array<WorkingType, PosDim> > refPositions;\n\n    ThinPlateSpline()\n    {}\n\n    ThinPlateSpline(std::vector<boost::array<WorkingType, PosDim> > positions,\n        std::vector<boost::array<WorkingType, ValDim> > values)\n    {\n      boost::numeric::ublas::matrix<WorkingType> L;\n\n      refPositions = positions;\n\n      const int numPoints((int)refPositions.size());\n      const int WaLength(numPoints + PosDim + 1);\n\n      L = boost::numeric::ublas::matrix<WorkingType> (WaLength, WaLength);\n\n      // Calculate K and store in L\n      for(int i(0); i < numPoints; i++)\n      {\n        L(i,i) = 0.0;\n        // K is symmetrical so no point in calculating things twice\n        int j(i + 1);\n        for(; j < numPoints; ++j)\n        {\n\n          L(i,j) = L(j,i) = radialbasis<WorkingType, WorkingType, PosDim>(refPositions[i], refPositions[j]);\n        }\n\n        // construct P and store in K\n        L(j,i) = L(i,j) = 1.0;\n        ++j;\n        for(int posElm(0); j < WaLength; ++posElm, ++j)\n          L(j,i) = L(i,j) = positions[i][posElm];\n      }\n\n      // O\n      for(int i(numPoints); i < WaLength; i++)\n        for(int j(numPoints); j < WaLength; j++)\n          L(i,j) = 0.0;\n\n      // Solve L^-1 Y = W^T\n\n      typedef boost::numeric::ublas::permutation_matrix<std::size_t> pmatrix;\n\n      boost::numeric::ublas::matrix<WorkingType> A(L);\n      pmatrix pm(A.size1());\n      int res = (int)lu_factorize(A, pm);\n      if(res != 0)\n\t  {\n        ;//TODO catch this error\n\t  }\n\n      boost::numeric::ublas::matrix<WorkingType> invL(boost::numeric::ublas::identity_matrix<WorkingType>(A.size1()));\n      lu_substitute(A, pm, invL);\n\n\n      Wa = boost::numeric::ublas::matrix<WorkingType>(WaLength, ValDim );\n\n      boost::numeric::ublas::matrix<WorkingType> Y(WaLength, ValDim);\n      int i(0);\n      for(; i < numPoints; i++)\n        for(int j(0); j < ValDim; ++j)\n          Y(i, j) = values[i][j];\n\n      for(; i < WaLength; i++)\n        for(int j(0); j < ValDim; ++j)\n          Y(i, j) = 0.0;\n\n      Wa = prod(invL,Y);\n\n    }\n\n    boost::array<WorkingType, ValDim>\n    interpolate(const boost::array<WorkingType, PosDim> &position) const\n    {\n      boost::array<WorkingType, ValDim> result;\n      // Init result\n      for(int j(0); j < ValDim; ++j)\n        result[j] = 0;\n\n      unsigned int i(0);\n      for(; i < Wa.size1() - (PosDim+1); ++i)\n      {\n        for(int j(0); j < ValDim; ++j)\n          result[j] += Wa(i,j) * radialbasis<WorkingType, WorkingType, PosDim>(refPositions[i], position);\n      }\n\n      for(int j(0); j < ValDim; ++j)\n        result[j] += Wa(i,j);\n      ++i;\n\n      for(int k(0); k < PosDim; ++k, ++i)\n      {\n        for(int j(0); j < ValDim; ++j)\n          result[j] += Wa(i,j) * position[k];\n      }\n      return result;\n    }\n\n  };\n\n#endif /* TPSINTERPOLATE_HPP_ */\n", "meta": {"hexsha": "77b74941d8750024ee23d4f0216a7adae162161b", "size": 4088, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "wbs/src/Geomatic/TPSInterpolate.hpp", "max_stars_repo_name": "RNCan/WeatherBasedSimulationFramework", "max_stars_repo_head_hexsha": "19df207d11b1dddf414d78e52bece77f31d45df8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2017-05-26T21:19:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-03T14:17:29.000Z", "max_issues_repo_path": "wbs/src/Geomatic/TPSInterpolate.hpp", "max_issues_repo_name": "RNCan/WeatherBasedSimulationFramework", "max_issues_repo_head_hexsha": "19df207d11b1dddf414d78e52bece77f31d45df8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2016-02-18T12:39:58.000Z", "max_issues_repo_issues_event_max_datetime": "2016-03-13T12:57:45.000Z", "max_forks_repo_path": "wbs/src/Geomatic/TPSInterpolate.hpp", "max_forks_repo_name": "RNCan/WeatherBasedSimulationFramework", "max_forks_repo_head_hexsha": "19df207d11b1dddf414d78e52bece77f31d45df8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-06-16T02:49:20.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-16T02:49:20.000Z", "avg_line_length": 26.0382165605, "max_line_length": 118, "alphanum_fraction": 0.5863502935, "num_tokens": 1235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582554941719, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.7232450680243011}}
{"text": "// Copyright Matt Overby 2021.\n// Distributed under the MIT License.\n\n#ifndef MCL_COMPUTEROOTS_HPP\n#define MCL_COMPUTEROOTS_HPP 1\n\n#include <Eigen/Core>\n//#include <cmath>\n#include <complex>\n\nnamespace mcl\n{\n\n// Returns the smallest, positive, real root for quadratic\n// a x^2 + b x + c\n// Returns a negative value if no roots found\n// from https://github.com/mike323zyf/BCQN\nstatic inline double compute_quad_roots(double a, double b, double c, double tol=1e-16)\n{\n\tdouble t = -1;\n\tif( std::abs(a) <= tol ){ t = -c / b; }\n\telse {\n\t\tdouble desc = b*b - 4.0 * a*c;\n\t\tif( desc > 0.0 ){\n\t\t\tt = (-b - std::sqrt(desc)) / (2.0 * a);\n\t\t\tif (t < 0.0){\n\t\t\t\tt = (-b + std::sqrt(desc)) / (2.0 * a);\n\t\t\t}\n\t\t}\n\t\telse{ // linear\n\t\t\tt = -b / (2.0*a);\n\t\t}\n\t}\n\treturn t;\n}\n\n// Returns a negative value if no roots found\n// from: https://github.com/libigl/libigl/blob/main/include/igl/flip_avoiding_line_search.cpp\nstatic inline double compute_quad_roots_2(double a, double b, double c)\n{\n\tdouble t1 = 0, t2 = 0;\n\tconst double polyCoefEps = 1e-16;\n\tconst double max_time = 2;\n\tif (abs(a) > polyCoefEps)\n  {\n\t\tdouble delta_in = pow(b, 2) - 4 * a*c;\n\t\tif (delta_in < 0) {\n\t\t\treturn -1;\n\t\t}\n\t\tdouble delta = sqrt(delta_in);\n\t\tt1 = (-b + delta) / (2 * a);\n\t\tt2 = (-b - delta) / (2 * a);\n\t}\n\telse if (abs(b) > polyCoefEps){\n\t\t t1 = t2 = -c / b;\n\t} else {\n\t\treturn -1; \n\t}\n\tif (t1 < 0) t1 = max_time;\n\tif (t2 < 0) t2 = max_time;\n\n\tif (!std::isfinite(t1) || !std::isfinite(t2))\n\t\treturn -1;\n\n\tdouble tmp_n = std::min(t1, t2);\n\tt1 = std::max(t1, t2); t2 = tmp_n;\n\tif (t1 > 0) {\n\t\tif (t2 > 0) {\n\t\t\treturn t2;\n\t\t}\n\t\telse {\n\t\t\treturn t1;\n\t\t}\n\t}\n\telse {\n\t\treturn -1;\n\t}\n}\n\n// Returns the smallest, positive, real root for cubic\n// a x^3 + b x^2 + c x + d\n// Returns a negative value if no roots found\n// from https://github.com/mike323zyf/BCQN\nstatic inline double compute_cubic_roots(double a, double b, double c, double d, double tol=1e-16)\n{\n\tdouble t = -1;\n\tif(std::abs(a) <= tol){ t = compute_quad_roots(b, c, d, tol); }\n\telse {\n\t\tstd::complex<double> i(0, 1);\n\t\tstd::complex<double> delta0(b*b - 3 * a*c, 0);\n\t\tstd::complex<double> delta1(2 * b*b*b - 9 * a*b*c + 27 * a*a*d, 0);\n\t\tstd::complex<double> C = pow((delta1 + sqrt(delta1*delta1 - 4.0 * delta0*delta0*delta0)) / 2.0, 1.0 / 3.0);\n\n\t\tstd::complex<double> u2 = (-1.0 + sqrt(3.0)*i) / 2.0;\n\t\tstd::complex<double> u3 = (-1.0 - sqrt(3.0)*i) / 2.0;\n\n\t\tstd::complex<double> t1 = (b + C + delta0 / C) / (-3.0*a);\n\t\tstd::complex<double> t2 = (b + u2*C + delta0 / (u2*C)) / (-3.0*a);\n\t\tstd::complex<double> t3 = (b + u3*C + delta0 / (u3*C)) / (-3.0*a);\n\n\t\tif ((std::abs(std::imag(t1))<tol) && (std::real(t1)>0))\n\t\t\tt = std::real(t1);\n\t\tif ((std::abs(std::imag(t2))<tol) && (std::real(t2)>0) && ((std::real(t2) < t) || (t < 0)))\n\t\t\tt = std::real(t2);\n\t\tif ((std::abs(std::imag(t3))<tol) && (std::real(t3)>0) && ((std::real(t3) < t) || (t < 0)))\n\t\t\tt = std::real(t3);\n\t}\n\treturn t;\n}\n\n// src: https://github.com/libigl/libigl/blob/main/include/igl/flip_avoiding_line_search.cpp\nstatic inline double compute_min_pos_root_2D(const Eigen::MatrixXd& x, const Eigen::MatrixXi& E, Eigen::MatrixXd& p, int f)\n{\n\tint v1 = E(f,0);\n\tint v2 = E(f,1);\n\tint v3 = E(f,2);\n\tconst double& U11 = x(v1,0);\n\tconst double& U12 = x(v1,1);\n\tconst double& U21 = x(v2,0);\n\tconst double& U22 = x(v2,1);\n\tconst double& U31 = x(v3,0);\n\tconst double& U32 = x(v3,1);\n\tconst double& V11 = p(v1,0);\n\tconst double& V12 = p(v1,1);\n\tconst double& V21 = p(v2,0);\n\tconst double& V22 = p(v2,1);\n\tconst double& V31 = p(v3,0);\n\tconst double& V32 = p(v3,1);\n\tdouble a = V11*V22 - V12*V21 - V11*V32 + V12*V31 + V21*V32 - V22*V31;\n\tdouble b = U11*V22 - U12*V21 - U21*V12 + U22*V11 - U11*V32 + U12*V31 + U31*V12 - U32*V11 + U21*V32 - U22*V31 - U31*V22 + U32*V21;\n\tdouble c = U11*U22 - U12*U21 - U11*U32 + U12*U31 + U21*U32 - U22*U31;\n  double root = compute_quad_roots_2(a,b,c);\n  if (root < 0) { return std::numeric_limits<float>::max(); }\n  return root;\n}\n\n} // end mcl\n\n#endif\n", "meta": {"hexsha": "18ecf6a4b507386757f865a84932bd21226b317c", "size": 3960, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/MCL/ComputeRoots.hpp", "max_stars_repo_name": "mattoverby/mclgeom", "max_stars_repo_head_hexsha": "d3ecd2a878900f33ba1412b8d82e643895201e51", "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/MCL/ComputeRoots.hpp", "max_issues_repo_name": "mattoverby/mclgeom", "max_issues_repo_head_hexsha": "d3ecd2a878900f33ba1412b8d82e643895201e51", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-26T22:44:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T02:54:23.000Z", "max_forks_repo_path": "include/MCL/ComputeRoots.hpp", "max_forks_repo_name": "mattoverby/mclgeom", "max_forks_repo_head_hexsha": "d3ecd2a878900f33ba1412b8d82e643895201e51", "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.2857142857, "max_line_length": 130, "alphanum_fraction": 0.5914141414, "num_tokens": 1561, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953003183443, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7232122235497211}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n\nvoid testEuclideanNorm()\n{\n  Eigen::Matrix<double, 3, 5> A;\n  A << 1, 2, 3, 4, 5,\n       2, 3, 4, 5, 6,\n       7, 9, 10, 11, 12;\n\n  std::cout << A.colwise().norm() << std::endl << std::endl;\n\n  Eigen::Matrix<double, 3, 5> B;\n  B = A.array().rowwise() / A.colwise().norm().array();\n  std::cout << B << std::endl;\n\n  for(int i=0; i<A.cols(); ++i)\n  {\n    Eigen::Vector3d b = A.col(i)/A.col(i).norm();\n    std::cout << b.transpose() << std::endl;\n    std::cout << b.norm() << std::endl;\n  }\n\n}\n\nint main(int argc, char** argv)\n{\n  testEuclideanNorm();\n  return 0;\n}\n", "meta": {"hexsha": "86cfb4a171ce54b24652683a01915a2002a59672", "size": 607, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "svo_vikit/vikit_common/test/test_common.cpp", "max_stars_repo_name": "jsz0913/rpg_dvs_evo_open", "max_stars_repo_head_hexsha": "93edc7a2d215ed097e3f6a9abbefd0b572958b74", "max_stars_repo_licenses": ["BSD-2-Clause-Patent"], "max_stars_count": 97.0, "max_stars_repo_stars_event_min_datetime": "2021-06-24T09:34:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T01:58:09.000Z", "max_issues_repo_path": "svo_vikit/vikit_common/test/test_common.cpp", "max_issues_repo_name": "jsz0913/rpg_dvs_evo_open", "max_issues_repo_head_hexsha": "93edc7a2d215ed097e3f6a9abbefd0b572958b74", "max_issues_repo_licenses": ["BSD-2-Clause-Patent"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2021-06-14T13:01:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T01:49:57.000Z", "max_forks_repo_path": "svo_vikit/vikit_common/test/test_common.cpp", "max_forks_repo_name": "jsz0913/rpg_dvs_evo_open", "max_forks_repo_head_hexsha": "93edc7a2d215ed097e3f6a9abbefd0b572958b74", "max_forks_repo_licenses": ["BSD-2-Clause-Patent"], "max_forks_count": 32.0, "max_forks_repo_forks_event_min_datetime": "2021-06-24T09:34:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T15:23:29.000Z", "avg_line_length": 19.5806451613, "max_line_length": 60, "alphanum_fraction": 0.5321252059, "num_tokens": 229, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.8056321866478978, "lm_q1q2_score": 0.7232122211239653}}
{"text": "/**\n * @ file pointEvaluation.cc\n * @ brief NPDE homework PointEvaluationRhs code\n * @ author Christian Mitsch, Liaowang Huang (refactoring)\n * @ date 22/03/2019, 06/01/2020 (refactoring)\n * @ copyright Developed at ETH Zurich\n */\n\n#include \"pointevaluationrhs.h\"\n\n#include <lf/assemble/assemble.h>\n#include <lf/base/base.h>\n#include <lf/geometry/geometry.h>\n#include <lf/mesh/mesh.h>\n#include <lf/mesh/utils/utils.h>\n#include <lf/uscalfe/uscalfe.h>\n\n#include <Eigen/Core>\n#include <Eigen/LU>\n#include <Eigen/SparseLU>\n#include <cmath>\n#include <utility>\n\n#include \"pointevaluationrhs_norms.h\"\n\nnamespace PointEvaluationRhs {\n\n/* SAM_LISTING_BEGIN_5 */\nEigen::Vector2d GlobalInverseTria(Eigen::Matrix<double, 2, 3> mycorners,\n                                  Eigen::Vector2d x) {\n  Eigen::Vector2d x_hat;\n\n  //====================\n  // Your code goes here\n  //====================\n  return x_hat;\n}\n/* SAM_LISTING_END_5 */\n\n/** @brief Numerically stable solution of a quadratic equation in R\n * @param a,b,c coefficients of quadratic polynomias ax^2+bx+c\n * @return both zeros, NaN if complex\n */\n/* SAM_LISTING_BEGIN_4 */\nstd::pair<double, double> solveQuadraticEquation(double a, double b, double c) {\n  // Implement the cases which are solvable and return their solutions\n  //====================\n  // Your code goes here\n  //====================\n  // Return NAN if there are no (real) roots\n  return {NAN, NAN};\n}\n\n/* SAM_LISTING_END_4 */\n\n/** @brief Computes the area of a triangle\n * @param a,b,c vertex coordinate vectors\n */\ninline double triaArea(const Eigen::Vector2d a, const Eigen::Vector2d b,\n                       const Eigen::Vector2d c) {\n  double result = 0;\n  //====================\n  // Your code goes here\n  //====================\n  return result;\n}\n\nEigen::Vector2d GlobalInverseQuad(Eigen::Matrix<double, 2, 4> vert,\n                                  Eigen::Vector2d x) {\n  constexpr double kEPS = 1.0E-8;\n  Eigen::Vector2d x_hat;\n\n  // Implement and use the functions triaArea and solveQuadraticEquation\n  //====================\n  // Your code goes here\n  //====================\n  return x_hat;\n}\n\nstd::pair<double, double> normsSolutionPointLoadDirichletBVP(\n    const lf::assemble::DofHandler &dofh, Eigen::Vector2d source_point,\n    Eigen::VectorXd &sol_vec) {\n  std::pair<double, double> result(0, 0);\n  const unsigned int N_dofs = dofh.NumDofs();\n  sol_vec.resize(N_dofs);\n  sol_vec.setZero();\n  //====================\n  // Your code goes here\n  //====================\n  return result;\n}\n\n/* SAM_LISTING_BEGIN_6 */\nEigen::VectorXd DeltaLocalVectorAssembler::Eval(const lf::mesh::Entity &cell) {\n  Eigen::VectorXd result;\n  // get the coordinates of the corners of this cell\n  const lf::geometry::Geometry *geo_ptr = cell.Geometry();\n  auto vertices = lf::geometry::Corners(*geo_ptr);\n  //====================\n  // Your code goes here\n  //====================\n  return result;\n}\n/* SAM_LISTING_END_6 */\n\n}  // namespace PointEvaluationRhs\n", "meta": {"hexsha": "5e8f6a7c5db5f179330a1d154e4d570719ecd4c9", "size": 2968, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/PointEvaluationRhs/templates/pointevaluationrhs.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": "homeworks/PointEvaluationRhs/templates/pointevaluationrhs.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": "homeworks/PointEvaluationRhs/templates/pointevaluationrhs.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": 27.738317757, "max_line_length": 80, "alphanum_fraction": 0.6290431267, "num_tokens": 773, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.8723473680407889, "lm_q1q2_score": 0.723122587706055}}
{"text": "/*\n * Website:\n *      https://github.com/wo3kie/dojo\n *\n * Author:\n *      Lukasz Czerwinski\n *\n * Compilation:\n *      g++ --std=c++11 interpolation.cpp -o interpolation -lgsl -lgslcblas -lm\n *\n * Usage:\n *      $ ./interpolation\n */\n\n#include <algorithm>\n#include <vector>\n\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n\n#include <gsl/gsl_linalg.h>\n\n#include \"./feq.hpp\"\n\nnamespace ublas = boost::numeric::ublas;\n\nstruct Point\n{\n    double x_;\n    double y_;\n};\n\nublas::vector< double > linear_interpolation_ublas(\n    std::vector< Point > const & points\n){\n    assert( points.size() == 2 );\n\n    ublas::vector< double > X( 2 );\n\n    Point const & p1 = points[ 0 ];\n    Point const & p2 = points[ 1 ];\n\n    double const a = (p1.y_ - p2.y_) / (p1.x_ - p2.x_);\n    double const b = p1.y_ - p1.x_ * ((p1.y_ - p2.y_) / (p1.x_ - p2.x_));\n\n    X( 0 ) = a;\n    X( 1 ) = b;\n\n    return X;\n}\n\nublas::vector< double > polynominal_interpolation_ublas( std::vector< Point > const & points ){\n    std::size_t const size = points.size();\n\n    ublas::matrix< double > A( size, size );\n\n    for( std::size_t i = 0 ; i < size ; ++ i ){\n        for( std::size_t j = 0 ; j < size ; ++ j ){\n            A( i, j ) = std::pow( points[ i ].x_, j );\n        }\n    }\n\n    ublas::vector< double > Y( size );\n\n    for( std::size_t i = 0 ; i < size ; ++ i ){\n        Y( i ) = points[ i ].y_;\n    }\n\n    ublas::permutation_matrix< double > PM( size );\n    ublas::lu_factorize( A, PM );\n    ublas::lu_substitute( A, PM, Y );\n\n    return Y;\n}\n\ngsl_vector * linear_interpolation_gsl( std::vector< Point > const & points ){\n    assert( points.size() == 2 );\n\n    gsl_vector * X = gsl_vector_alloc( 2 );\n\n    Point const & p1 = points[ 0 ];\n    Point const & p2 = points[ 1 ];\n\n    double const a = (p1.y_ - p2.y_) / (p1.x_ - p2.x_);\n    double const b = p1.y_ - p1.x_ * ((p1.y_ - p2.y_) / (p1.x_ - p2.x_));\n\n    gsl_vector_set( X, 0, a );\n    gsl_vector_set( X, 1, b );\n\n    return X;\n}\n\ngsl_vector * polynominal_interpolation_gsl( std::vector< Point > const & points ){\n    std::size_t const size = points.size();\n\n    gsl_matrix * A = gsl_matrix_alloc( size, size );\n\n    for( std::size_t i = 0 ; i < size ; ++ i ){\n        for( std::size_t j = 0 ; j < size ; ++ j ){\n            gsl_matrix_set( A, i, j, std::pow( points[ i ].x_, j ) );\n        }\n    }\n\n    gsl_vector * Y = gsl_vector_alloc( size );\n\n    for( std::size_t i = 0 ; i < size ; ++ i ){\n        gsl_vector_set( Y, i, points[ i ].y_ );\n    }\n\n    gsl_vector * X = gsl_vector_alloc( size );\n    gsl_permutation * PM = gsl_permutation_alloc( size );\n\n    int s = 0;\n    gsl_linalg_LU_decomp( A, PM, &s );\n    gsl_linalg_LU_solve( A, PM, Y, X );\n\n    gsl_permutation_free( PM );\n    gsl_vector_free( Y );\n    gsl_matrix_free( A );\n\n    return X;\n}\n\nvoid linear_interpolation_ublas_test(){\n    ublas::vector< double > expected( 2 );\n    expected( 0 ) = 5.0 / 2;\n    expected( 1 ) = -13.0 / 2;\n\n    ublas::vector< double > const actual = linear_interpolation_ublas(\n        std::vector< Point >{ { 5, 6 }, { 7, 11 } }\n    );\n\n    auto feqDouble = [](double d1, double d2){\n        return feq(d1, d2);\n    };\n\n    assert(\n        std::equal(\n            actual.begin(),\n            actual.end(),\n            expected.begin(),\n            feqDouble\n        )\n    );\n}\n\nvoid polynominal_interpolation_ublas_test(){\n    ublas::vector< double > expected( 3 );\n    expected( 0 ) = 7;\n    expected( 1 ) = 6;\n    expected( 2 ) = -1;\n\n    ublas::vector< double > const actual = polynominal_interpolation_ublas(\n        std::vector< Point >{ { 1, 12 }, { 2, 15 }, { 3, 16 } }\n    );\n\n    auto feqDouble = [](double d1, double d2){\n        return feq(d1, d2);\n    };\n\n    assert(\n        std::equal(\n            actual.begin(),\n            actual.end(),\n            expected.begin(),\n            feqDouble\n        )\n    );\n}\n\nvoid linear_interpolation_gsl_test(){\n    gsl_vector * expected = gsl_vector_alloc( 2 );\n    gsl_vector_set( expected, 0, 5.0 / 2 );\n    gsl_vector_set( expected, 1, -13.0 / 2 );\n\n    gsl_vector * actual = linear_interpolation_gsl(\n        std::vector< Point >{ { 5, 6 }, { 7, 11 } }\n    );\n\n    for( std::size_t i = 0 ; i < 2 ; ++ i ){\n        assert((\n            feq(\n                gsl_vector_get( actual, i ),\n                gsl_vector_get( expected, i )\n            )\n        ));\n    }\n\n    gsl_vector_free( actual );\n    gsl_vector_free( expected );\n}\n\nvoid polynominal_interpolation_gsl_test(){\n    gsl_vector * expected = gsl_vector_alloc( 3 );\n    gsl_vector_set( expected, 0, 7 );\n    gsl_vector_set( expected, 1, 6 );\n    gsl_vector_set( expected, 2, -1 );\n\n    gsl_vector * actual = polynominal_interpolation_gsl(\n        std::vector< Point >{ { 1, 12 }, { 2, 15 }, { 3, 16 } }\n    );\n\n    for( std::size_t i = 0 ; i < 3 ; ++ i ){\n        assert((\n            feq(\n                gsl_vector_get( actual, i ),\n                gsl_vector_get( expected, i )\n            )\n        ));\n    }\n\n    gsl_vector_free( actual );\n    gsl_vector_free( expected );\n}\n\n#include <vector>\n\nint main(){\n    linear_interpolation_ublas_test();\n    linear_interpolation_gsl_test();\n\n    polynominal_interpolation_ublas_test();\n    polynominal_interpolation_gsl_test();\n}\n", "meta": {"hexsha": "b3e0aa05b982008fb4a3ccdca6e36c51e6180512", "size": 5334, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gsl/interpolation.cpp", "max_stars_repo_name": "wo3kie/cxxDojo", "max_stars_repo_head_hexsha": "c63388eb37a62272bfb9ca5c0b207fc5387a29ad", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-10-26T22:06:11.000Z", "max_stars_repo_stars_event_max_datetime": "2015-11-25T14:35:00.000Z", "max_issues_repo_path": "gsl/interpolation.cpp", "max_issues_repo_name": "wo3kie/dojo", "max_issues_repo_head_hexsha": "c63388eb37a62272bfb9ca5c0b207fc5387a29ad", "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": "gsl/interpolation.cpp", "max_forks_repo_name": "wo3kie/dojo", "max_forks_repo_head_hexsha": "c63388eb37a62272bfb9ca5c0b207fc5387a29ad", "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.4977973568, "max_line_length": 95, "alphanum_fraction": 0.5517435321, "num_tokens": 1629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.920789673717312, "lm_q2_score": 0.7853085909370422, "lm_q1q2_score": 0.7231040412163211}}
{"text": "/*\n * Website:\n *      https://github.com/wo3kie/dojo\n *\n * Author:\n *      Lukasz Czerwinski\n *\n * Compilation:\n *      g++ --std=c++11 bond.cpp -o bond -lboost_date_time\n *\n * Usage:\n *      $ ./bond 2015/12/31 100 0.08 0.08 2014/12/31\n *        PV( F ): 92.5926\n *        PV( Coupon ): 7.40741\n *      P: 100\n */\n\n/*\n *                                                                      Maturity Date\n *                                                                       |\n *                     /-- 1 year -----------    -- 1 year------------\\  |\n *                    /                      \\  /                      \\ |\n *                   v                        \\v                        \\v\n * ... - 2 - 4 - 6 - 8 - 10 - 12 - 2 - 4 - 6 - 8 - 10 - 12 - 2 - 4 - 6 - 8 - 10 - ...\n *       ^           ^                         ^                         ^\n *       |           |                         |                         |\n *       |          Coupon                    Coupon                    Face Value\n *      Price Day                                                       Coupon\n */\n\n#include <cmath>\n#include <iostream>\n\n#include <boost/date_time/gregorian/gregorian.hpp>\n\nnamespace date = boost::gregorian;\nnamespace date_time = boost::date_time;\n\ndouble bondPrice(\n    date::date maturityDate,\n    double faceValue,\n    double yield,\n    double intrestRate,\n    date::date priceDay\n)\n{\n    using std::pow;\n\n    int days = ( maturityDate - priceDay ).days();\n\n    if( days < 0 ){\n        return 0;\n    }\n\n    double result = 0;\n\n    {\n        /*\n         * Face value\n         */\n\n        result = faceValue / pow( ( 1.0 + intrestRate ), 1.0 * days / 365 );\n\n        std::cout << \"  PV( F ): \" << result << std::endl;\n    }\n\n    while( days > 0 )\n    {       \n        /*\n         * Coupons\n         */\n\n        double coupon =\n            ( faceValue * yield ) / pow( ( 1.0 + intrestRate ), 1.0 * days / 365 );\n\n        std::cout << \"  PV( Coupon ): \" << coupon << std::endl;\n\n        result += coupon;\n\n        maturityDate = maturityDate - date::years( 1 );\n        \n        days = ( maturityDate - priceDay ).days();\n    }\n\n    std::cout << \"P: \" << result << std::endl;\n\n    return result;\n}\n\nint main( int argc, char* argv[] )\n{\n    if( argc != 6 )\n    {\n        std::cerr << \"Usage: \" << argv[0] << \" maturityDate faceValue yield intrestRate priceDate\" << std::endl;\n        std::cerr << \"       \" << argv[0] << \" 2015/12/31 100 0.08 0.08 2014/12/31\" << std::endl;\n\n        return 1;\n    }\n\n    bondPrice(\n        date::from_string( argv[1] ),\n        std::stoi( argv[2] ),\n        std::stof( argv[3] ),\n        std::stof( argv[4] ),\n        date::from_string( argv[5] )\n    );\n\n    return 0;\n}\n\n", "meta": {"hexsha": "f45be899c1926e8b6b77717a33c16c4ede626ac1", "size": 2729, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bond.cpp", "max_stars_repo_name": "wo3kie/cxxDojo", "max_stars_repo_head_hexsha": "c63388eb37a62272bfb9ca5c0b207fc5387a29ad", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-10-26T22:06:11.000Z", "max_stars_repo_stars_event_max_datetime": "2015-11-25T14:35:00.000Z", "max_issues_repo_path": "bond.cpp", "max_issues_repo_name": "wo3kie/dojo", "max_issues_repo_head_hexsha": "c63388eb37a62272bfb9ca5c0b207fc5387a29ad", "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": "bond.cpp", "max_forks_repo_name": "wo3kie/dojo", "max_forks_repo_head_hexsha": "c63388eb37a62272bfb9ca5c0b207fc5387a29ad", "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.5855855856, "max_line_length": 112, "alphanum_fraction": 0.384756321, "num_tokens": 732, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.808067204308405, "lm_q1q2_score": 0.7230500200509552}}
{"text": "#pragma once\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include \"coordinate_transform.hpp\"\n#include \"integrate.hpp\"\n#include \"shape.hpp\"\n#include <functional>\n\n//----------------compVectorBegin----------------\n//! Evaluate the load vector on the triangle spanned by\n//! the points (a, b, c).\n//!\n//! Here, the load vector is a vector $(v_i)$ of\n//! three components, where \n//! \n//! $$v_i = \\int_{K} \\lambda_i^K(x, y) f(x, y) \\; dV$$\n//! \n//! where $K$ is the triangle spanned by (a, b, c).\n//!\n//! @param[out] loadVector should be a vector of length 3. \n//!                        At the end, will contain the integrals above.\n//!\n//! @param[in] a the first corner of the triangle\n//! @param[in] b the second corner of the triangle\n//! @param[in] c the third corner of the triangle\n//! @param[in] f the function f (LHS).\ntemplate<class Vector, class Point>\nvoid computeLoadVector(Vector& loadVector,\n                    const Point& a, const Point& b, const Point& c,\n                    const std::function<double(double, double)>& f)\n{\n    Eigen::Matrix2d coordinateTransform = makeCoordinateTransform(b - a, c - a);\n    double volumeFactor = std::abs(coordinateTransform.determinant());\n// (write your solution here)\n\n}\n//----------------compVectorEnd----------------\n", "meta": {"hexsha": "4f3c6a7ada882a11cbe0b76d535c99a21acaa293", "size": 1275, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "series0_handout/2d-poissonlFEM/load_vector.hpp", "max_stars_repo_name": "BeatHubmann/19H-AdvNCSE", "max_stars_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-05T22:38:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-05T22:38:47.000Z", "max_issues_repo_path": "series0_handout/2d-poissonlFEM/load_vector.hpp", "max_issues_repo_name": "BeatHubmann/19H-AdvNCSE", "max_issues_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "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": "series0_handout/2d-poissonlFEM/load_vector.hpp", "max_forks_repo_name": "BeatHubmann/19H-AdvNCSE", "max_forks_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-08T20:43:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-08T20:43:27.000Z", "avg_line_length": 33.5526315789, "max_line_length": 80, "alphanum_fraction": 0.6180392157, "num_tokens": 315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818864, "lm_q2_score": 0.7956581073313275, "lm_q1q2_score": 0.7229492000987036}}
{"text": "// Copyright Yamaha 2021\n// MIT License\n// https://github.com/yamaha-bps/cbr_math/blob/master/LICENSE\n\n#ifndef CBR_MATH__MATH_HPP_\n#define CBR_MATH__MATH_HPP_\n\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n\n#include <algorithm>\n#include <array>\n#include <cmath>\n#include <exception>\n#include <limits>\n#include <type_traits>\n\nnamespace cbr\n{\n\n/***************************************************************************\n * \\brief Converts degrees to radians\n ***************************************************************************/\ntemplate<typename T>\nconstexpr T deg2rad(const T deg) noexcept\n{\n  static_assert(std::is_floating_point_v<T>, \"Input type must be a floating point.\");\n  return deg * M_PI / 180.;\n}\n\n/***************************************************************************\n * \\brief Converts radians to degrees\n ***************************************************************************/\ntemplate<typename T>\nconstexpr T rad2deg(const T rad) noexcept\n{\n  static_assert(std::is_floating_point_v<T>, \"Input type must be a floating point.\");\n  return rad * 180. / M_PI;\n}\n\n/***************************************************************************\n * \\brief Computes b^e\n ***************************************************************************/\ntemplate<typename TBase, typename TExp>\nconstexpr TBase powFast(const TBase b, const TExp e) noexcept\n{\n  static_assert(std::is_unsigned_v<TExp>, \"Exponent type must be unsigned.\");\n\n  if (e == 0) {\n    return TBase(1.);\n  }\n\n  if (e == 1) {\n    return b;\n  }\n\n  TBase out = b;\n  for (TExp i = 2; i <= e; i++) {\n    out *= b;\n  }\n\n  return out;\n}\n\nnamespace detail\n{\n\ntemplate<typename T, std::size_t ... Is>\nconstexpr T powFastImpl([[maybe_unused]] T val, std::index_sequence<Is...>)\n{\n  #pragma GCC diagnostic push\n  #pragma GCC diagnostic ignored \"-Wunused-value\"\n  #pragma GCC diagnostic ignored \"-Wconversion\"\n  // *INDENT-OFF*\n  return ((Is, val) * ... * T{1});\n  // *INDENT-ON*\n  #pragma GCC diagnostic pop\n}\n\n}  // namespace detail\n\n// /***************************************************************************\n//  * \\brief Computes b^e via expansion to e-length product  b * ... * b\n//  ***************************************************************************/\ntemplate<std::size_t e = 2, typename TBase>\nconstexpr TBase powFast(const TBase b) noexcept\n{\n  return detail::powFastImpl(b, std::make_index_sequence<e>{});\n}\n\n/***************************************************************************\n* \\brief Wraps angle in radians between 0 and 2*pi\n***************************************************************************/\ntemplate<typename T>\nT wrap2Pi(const T in) noexcept\n{\n  static_assert(std::is_floating_point_v<T>, \"Input type must be a floating point.\");\n  return in - std::floor(in / T(2. * M_PI)) * T(2. * M_PI);\n}\n\n/***************************************************************************\n* \\brief Wraps angle in radians between -pi and pi\n***************************************************************************/\ntemplate<typename T>\nT wrapPi(const T in) noexcept\n{\n  static_assert(std::is_floating_point_v<T>, \"Input type must be a floating point.\");\n  return wrap2Pi(in + M_PI) - M_PI;\n}\n\n/***************************************************************************\n * \\brief Converts yaw in radians to heading in degrees\n ***************************************************************************/\ntemplate<typename T>\nT yaw2heading(const T rad) noexcept\n{\n  static_assert(std::is_floating_point_v<T>, \"Input type must be a floating point.\");\n  return rad2deg(wrap2Pi(-rad));\n}\n\n/***************************************************************************\n * \\brief Computes truncated factorial : product from x0(default: 1) to x.\n ***************************************************************************/\ntemplate<typename T>\nconstexpr T factorial(const T x, const T x0 = T(1)) noexcept\n{\n  static_assert(std::is_unsigned_v<T>, \"Type must be unsigned.\");\n\n  if (x == 0 || x0 > x) {\n    return T(1);\n  }\n\n  if (x0 >= x) {\n    return x;\n  }\n\n  T out = x0;\n  for (T i = x0 + T(1); i <= x; i++) {\n    out *= i;\n  }\n  return out;\n}\n\n\n/***************************************************************************\n * \\brief Converts probability to log odds\n ***************************************************************************/\ntemplate<typename T>\nconstexpr T prob_to_log_odds(const T p)\n{\n  static_assert(std::is_floating_point_v<T>, \"Input type must be a floating point.\");\n  return log(p / (1. - p));\n}\n\n/***************************************************************************\n * \\brief Converts to log odds to probability\n ***************************************************************************/\ntemplate<typename T>\nconstexpr T log_odds_to_prob(const T l)\n{\n  static_assert(std::is_floating_point_v<T>, \"Input type must be a floating point.\");\n  return 1. - (1. / (1. + exp(l)));\n}\n\n/***************************************************************************\n * \\brief Converts a quaternion to euler angles using the ZYX decomposition\n * The returned vector contains the angles in [roll, pitch, yaw] order\n ***************************************************************************/\ntemplate<typename derived>\nEigen::Matrix<typename derived::Scalar, 3, 1>\nquat2eulZYX(const Eigen::QuaternionBase<derived> & q) noexcept\n{\n  const auto qn = q.normalized();\n  using T = typename derived::Scalar;\n  Eigen::Matrix<T, 3, 1> eul;\n\n  // roll\n  eul[0] = atan2(\n    T(2.) * (qn.w() * qn.x() + qn.y() * qn.z()),\n    T(1.) - T(2.) * (powFast<2>(qn.x()) + powFast<2>(qn.y())));\n\n  // pitch\n  const T sinp = T(2.) * (qn.w() * qn.y() - qn.z() * qn.x());\n  // Autodiff friendly manner of handling numerical errors\n  if (abs(sinp) >= T(1.)) {\n    if (sinp > T(0.)) {\n      eul[1] = T(M_PI_2);\n    } else {\n      eul[1] = -T(M_PI_2);\n    }\n  } else {\n    eul[1] = asin(sinp);\n  }\n\n  // yaw\n  eul[2] = atan2(\n    T(2.) * (qn.w() * qn.z() + qn.x() * qn.y()),\n    T(1.) - T(2.) * (powFast<2>(qn.y()) + powFast<2>(qn.z())));\n\n  return eul;\n}\n\n\n/***************************************************************************\n * \\brief Converts a quaternion to euler angles using the ZYX decomposition\n * The returned vector contains the angles in [roll, pitch, yaw] order\n ***************************************************************************/\ntemplate<typename derived>\nvoid quat2eulZYX(\n  const Eigen::QuaternionBase<derived> & q,\n  Eigen::Matrix<typename derived::Scalar, 3, 1> & eul) noexcept\n{\n  eul = quat2eulZYX<derived>(q);\n}\n\n/***************************************************************************\n * \\brief Converts euler angles to a quaternion using the ZYX decomposition\n * The input vector must contain the angles in [roll, pitch, yaw] order\n ***************************************************************************/\ntemplate<typename T>\nEigen::Quaternion<T> eul2quatZYX(const Eigen::Matrix<T, 3, 1> & eul) noexcept\n{\n  Eigen::Quaternion<T> q;\n\n  T cy = cos(eul[2] * .5);\n  T sy = sin(eul[2] * .5);\n  T cp = cos(eul[1] * .5);\n  T sp = sin(eul[1] * .5);\n  T cr = cos(eul[0] * .5);\n  T sr = sin(eul[0] * .5);\n\n  q.w() = cy * cp * cr + sy * sp * sr;\n  q.x() = cy * cp * sr - sy * sp * cr;\n  q.y() = sy * cp * sr + cy * sp * cr;\n  q.z() = sy * cp * cr - cy * sp * sr;\n\n  return q;\n}\n\ntemplate<typename T, typename derived>\nvoid eul2quatZYX(\n  const Eigen::Matrix<T, 3, 1> & eul,\n  Eigen::QuaternionBase<derived> & q) noexcept\n{\n  q = eul2quatZYX<T>(eul);\n}\n\n/***************************************************************************\n * \\brief Converts a pure yaw to a quaternion\n ***************************************************************************/\ntemplate<typename T>\nEigen::Quaternion<T> yaw2quat(const T & yaw) noexcept\n{\n  return Eigen::Quaternion<T>(cos(yaw * T(.5)), T(0.0), T(0.0), sin(yaw * T(.5)));\n}\n\n/***************************************************************************\n * \\brief Extract the yaw component of a quaternion\n ***************************************************************************/\ntemplate<typename derived>\ntypename derived::Scalar quat2yaw(const Eigen::QuaternionBase<derived> & q) noexcept\n{\n  using T = typename derived::Scalar;\n\n  const auto qn = q.normalized();\n  return atan2(\n    T(2.) * (qn.w() * qn.z() + qn.x() * qn.y()),\n    T(1.) - T(2.) * (powFast<2>(qn.y()) + powFast<2>(qn.z())));\n}\n\n\n/***************************************************************************\n * \\brief Convert subscripts to linear indices\n ***************************************************************************/\ntemplate<typename T, std::size_t N>\nconstexpr T sub2ind(const std::array<T, N> & sz, const std::array<T, N> & idx)\n{\n  static_assert(std::is_arithmetic_v<T>, \"Type must be arithmetic.\");\n  static_assert(N > 1, \"Size of inputs must be > 1.\");\n\n  T ind = idx[0] + idx[1] * sz[0];\n\n  if constexpr (N > 2) {\n    T stride = sz[0];\n    for (std::size_t i = 2; i < N; i++) {\n      stride *= sz[i - 1];\n      ind += idx[i] * stride;\n    }\n  }\n\n  return ind;\n}\n\n/***************************************************************************\n * \\brief Convert linear indices to subscripts\n ***************************************************************************/\ntemplate<typename T, std::size_t N>\nconstexpr std::array<T, N> ind2sub(const std::array<T, N> & sz, T idx)\n{\n  static_assert(std::is_arithmetic_v<T>, \"Type must be arithmetic.\");\n  static_assert(N > 1, \"Size of first input must be > 1.\");\n\n  std::array<T, N> sub{};\n\n  if constexpr (N > 2) {\n    std::array<T, N - 2> strides{};\n    strides[0] = sz[0] * sz[1];\n    for (std::size_t i = 1; i < N - 2; i++) {\n      strides[i] = strides[i - 1] * sz[i + 1];\n    }\n    for (std::size_t i = N - 1; i > 1; i--) {\n      sub[i] = idx / strides[i - 2];\n      idx = idx % strides[i - 2];\n    }\n  }\n\n  sub[1] = idx / sz[0];\n  sub[0] = idx % sz[0];\n\n  return sub;\n}\n\n/***************************************************************************\n * \\brief Antisymmetric power function\n ***************************************************************************/\ntemplate<typename T1, typename T2>\nauto powAntisym(T1 base, T2 exp)\n{\n  static_assert(std::is_arithmetic_v<T1>, \"Base type must be arithmetic.\");\n  static_assert(std::is_arithmetic_v<T2>, \"Exponent type must be arithmetic.\");\n\n  if (base >= T1(0)) {\n    return std::pow(base, exp);\n  } else {\n    return -std::pow(-base, exp);\n  }\n}\n\n\n/***************************************************************************\n * \\brief Over-approximate a body bounding box with a world bounding box\n ***************************************************************************/\ntemplate<typename S, typename T, int I>\nEigen::AlignedBox<T, I> overapp_bbox(S && pose, Eigen::AlignedBox<T, I> bbox_B)\n{\n  Eigen::Array<T, I, 1> bbmin = std::numeric_limits<T>::max() * Eigen::Array<T, I, 1>::Ones();\n  Eigen::Array<T, I, 1> bbmax = std::numeric_limits<T>::min() * Eigen::Array<T, I, 1>::Ones();\n  for (int n = 0; n != pow(2, I); ++n) {  // find min/max coordinates of bounding box in world frame\n    auto p = pose * bbox_B.corner(static_cast<typename Eigen::AlignedBox<T, I>::CornerType>(n));\n    bbmin = bbmin.min(p.array());\n    bbmax = bbmax.max(p.array());\n  }\n  return Eigen::AlignedBox<T, I>{bbmin, bbmax};\n}\n\n/***************************************************************************\n * \\brief Smooth saturation function\n ***************************************************************************/\ntemplate<typename T1, typename T2>\nconstexpr void smoothSatInPlace(\n  T1 & x,\n  const T2 & mi,\n  const T2 & ma,\n  const T2 & satSmoothCoeff = T2(0.1))\n{\n  static_assert(std::is_floating_point_v<T2>, \"Input type must be a floating point.\");\n\n  if (satSmoothCoeff < T2(0.) || T2(1.) < satSmoothCoeff) {\n    throw std::invalid_argument(\"satSmoothCoeff must be between 0 and 1.\");\n  }\n  if (ma < mi) {\n    throw std::invalid_argument(\"max must be greated or equal to min.\");\n  }\n\n  constexpr T2 alpha = M_PI / 8.;\n  constexpr T2 beta = M_PI / 4.;\n  const T2 r = satSmoothCoeff * M_SQRT2 / tan(alpha);\n  const T2 bevelL = r * tan(alpha);\n  const T2 bevelStart = 1. - cos(beta) * bevelL;\n  const T2 bevelStop = 1. + bevelL;\n  const T2 bevelXc = bevelStop;\n  const T2 bevelYc = 1. - r;\n\n  const T2 range = ma - mi;\n  const T2 middle = (ma + mi) / 2.;\n  const T1 uc = 2. * (x - middle) / range;\n\n  if (uc >= bevelStop) {\n    x = ma;\n  } else if (uc <= -bevelStop) {\n    x = mi;\n  } else if (uc > bevelStart) {\n    x = 0.5 * (sqrt(r * r - (uc - bevelXc) * (uc - bevelXc)) + bevelYc) * range + middle;\n  } else if (uc < -bevelStart) {\n    x = 0.5 * (-sqrt(r * r - (uc + bevelXc) * (uc + bevelXc)) - bevelYc) * range + middle;\n  } else {\n    return;\n  }\n}\n\ntemplate<typename T1, typename T2>\nconstexpr T1 smoothSat(\n  const T1 & x,\n  const T2 & mi,\n  const T2 & ma,\n  const T2 & satSmoothCoeff = T2{0.1})\n{\n  T1 out{x};\n  smoothSatInPlace<T1, T2>(out, mi, ma, satSmoothCoeff);\n  return out;\n}\n\n/***************************************************************************\n * \\brief Check if point is inside polygon\n ***************************************************************************/\ntemplate<typename ForwardIterator, typename Point>\nbool point_in_polygon(\n  ForwardIterator first,\n  ForwardIterator last,\n  const Point & point)\n{\n  ForwardIterator current = first;\n  if (current == last) {return false;}  // empty list of vertices\n\n  ForwardIterator next = current; ++next;\n  if (next == last) {return false;}  // only 1 vertex\n\n  ForwardIterator next_plus_1 = next; ++next_plus_1;\n  if (next_plus_1 == last) {return false;}  // only 2 vertex\n\n  auto which_side_in_slab =\n    [](\n    const auto & pt,\n    const auto & low,\n    const auto & high) -> int\n    {\n      const double cross_product =\n        (high[0] - low[0]) * (pt[1] - low[1]) - (high[1] - low[1]) * (pt[0] - low[0]);\n\n      if (cross_product > 0.) {\n        return 1;\n      }\n\n      if (cross_product < 0.) {\n        return -1;\n      }\n\n      return 0;\n    };\n\n  auto compare_x_2 = [](const auto & p1, const auto & p2) -> int {\n      if (p1[0] < p2[0]) {\n        return -1;\n      } else if (p1[0] > p2[0]) {\n        return 1;\n      }\n      return 0;\n    };\n\n  auto compare_y_2 = [](const auto & p1, const auto & p2) -> int {\n      if (p1[1] < p2[1]) {\n        return -1;\n      } else if (p1[1] > p2[1]) {\n        return 1;\n      }\n      return 0;\n    };\n\n  bool IsInside = false;\n  int cur_y_comp_res = compare_y_2(*current, point);\n\n  do {\n    int next_y_comp_res = compare_y_2(*next, point);\n\n    switch (cur_y_comp_res) {\n      case -1:\n        switch (next_y_comp_res) {\n          case -1:\n            break;\n          case 0:\n            switch (compare_x_2(point, *next)) {\n              case -1:\n                {IsInside = !IsInside; break;}\n              case 0:\n                return true;\n              case 1:\n                break;\n            }\n            break;\n          case 1:\n            switch (which_side_in_slab(point, *current, *next)) {\n              case -1:\n                {IsInside = !IsInside; break;}\n              case 0:\n                return true;\n            }\n            break;\n        }\n        break;\n      case 0:\n        switch (next_y_comp_res) {\n          case -1:\n            switch (compare_x_2(point, *current)) {\n              case -1:\n                {IsInside = !IsInside; break;}\n              case 0:\n                return true;\n              case 1:\n                break;\n            }\n            break;\n          case 0:\n            switch (compare_x_2(point, *current)) {\n              case -1:\n                if (compare_x_2(point, *next) != -1) {\n                  return true;\n                }\n                break;\n              case 0:\n                return true;\n              case 1:\n                if (compare_x_2(point, *next) != 1) {\n                  return true;\n                }\n                break;\n            }\n            break;\n          case 1:\n            if (compare_x_2(point, *current) == 0) {\n              return true;\n            }\n            break;\n        }\n        break;\n      case 1:\n        switch (next_y_comp_res) {\n          case -1:\n            switch (which_side_in_slab(point, *next, *current)) {\n              case -1:\n                {IsInside = !IsInside; break;}\n              case 0:\n                return true;\n            }\n            break;\n          case 0:\n            if (compare_x_2(point, *next) == 0) {\n              return true;\n            }\n            break;\n          case 1:\n            break;\n        }\n        break;\n    }\n    current = next;\n    cur_y_comp_res = next_y_comp_res;\n    ++next;\n    if (next == last) {next = first;}\n  } while (current != first);\n\n  return IsInside;\n}\n\n/***************************************************************************\n * \\brief Compute distance from point to segment\n ***************************************************************************/\ntemplate<typename Point_t>\nconstexpr auto point_to_segment_dist_squared(\n  const Point_t & pt,\n  const Point_t & seg_pt1,\n  const Point_t & seg_pt2)\n{\n  using scalar_t = std::decay_t<decltype(pt[0])>;\n\n  const scalar_t pt_x = pt[0] - seg_pt1[0];\n  const scalar_t pt_y = pt[1] - seg_pt1[1];\n\n  if (seg_pt1[0] == seg_pt2[0] && seg_pt1[1] == seg_pt2[1]) {\n    return pt_x * pt_x + pt_y * pt_y;\n  }\n\n  const scalar_t seg_x = seg_pt2[0] - seg_pt1[0];\n  const scalar_t seg_y = seg_pt2[1] - seg_pt1[1];\n\n  const scalar_t l2 = seg_x * seg_x + seg_y * seg_y;\n  const scalar_t proj = (pt_x * seg_x + pt_y * seg_y) / l2;\n  const scalar_t t = std::min(std::max(proj, scalar_t(0.)), scalar_t(1.));\n\n  const scalar_t dist_x = t * seg_x - pt_x;\n  const scalar_t dist_y = t * seg_y - pt_y;\n\n  return dist_x * dist_x + dist_y * dist_y;\n}\n\n\n/***************************************************************************\n * \\brief Checks if 2 segments intersect\n ***************************************************************************/\ntemplate<typename Point_t>\nconstexpr bool segments_intersect(\n  const Point_t & seg1_pt1,\n  const Point_t & seg1_pt2,\n  const Point_t & seg2_pt1,\n  const Point_t & seg2_pt2)\n{\n  if (seg1_pt1[0] == seg1_pt2[0] && seg1_pt1[1] == seg1_pt2[1]) {\n    throw std::invalid_argument(\"First segment has no length\");\n  }\n\n  if (seg2_pt1[0] == seg2_pt2[0] && seg2_pt1[1] == seg2_pt2[1]) {\n    throw std::invalid_argument(\"Second segment has no length\");\n  }\n  using scalar_t = std::decay_t<decltype(seg1_pt1[0])>;\n\n  const scalar_t seg1_x = seg1_pt2[0] - seg1_pt1[0];\n  const scalar_t seg1_y = seg1_pt2[1] - seg1_pt1[1];\n\n  const scalar_t seg2_x = seg2_pt2[0] - seg2_pt1[0];\n  const scalar_t seg2_y = seg2_pt2[1] - seg2_pt1[1];\n\n  const scalar_t det = seg1_y * seg2_x - seg1_x * seg2_y;\n  if (det == scalar_t(0.)) {\n    return false;\n  }\n\n  const scalar_t pt1_dx = seg2_pt1[0] - seg1_pt1[0];\n  const scalar_t pt1_dy = seg2_pt1[1] - seg1_pt1[1];\n\n  const scalar_t alpha = (pt1_dy * seg2_x - pt1_dx * seg2_y) / det;\n  const scalar_t beta = (pt1_dy * seg1_x - pt1_dx * seg1_y) / det;\n\n  if (\n    alpha < scalar_t(0.) ||\n    alpha > scalar_t(1.) ||\n    beta < scalar_t(0.) ||\n    beta > scalar_t(1.))\n  {\n    return false;\n  }\n\n  return true;\n}\n\ntemplate<typename PointPair>\nbool segments_intersect(\n  const PointPair & seg1,\n  const PointPair & seg2)\n{\n  return segments_intersect(seg1.first, seg1.second, seg2.first, seg2.second);\n}\n\n\n/***************************************************************************\n * \\brief Checks if segment intersects a polygon\n ***************************************************************************/\ntemplate<typename ForwardIterator, typename Point>\nbool segment_inter_polygon(\n  ForwardIterator first,\n  ForwardIterator last,\n  const Point & point1,\n  const Point & point2)\n{\n  ForwardIterator current = first;\n  ForwardIterator next = current; ++next;\n\n  do {\n    if (segments_intersect(point1, point2, *current, *next)) {\n      return true;\n    }\n\n    current = next;\n    ++next;\n    if (next == last) {next = first;}\n  } while (current != first);\n\n  return false;\n}\n\ntemplate<typename ForwardIterator, typename PointPair>\nbool segment_inter_polygon(\n  ForwardIterator first,\n  ForwardIterator last,\n  const PointPair & seg)\n{\n  return segment_inter_polygon(first, last, seg.first, seg.second);\n}\n\n/***************************************************************************\n * \\brief Checks if segment is in the interior of a polygon\n ***************************************************************************/\ntemplate<typename ForwardIterator, typename Point>\nbool segment_in_polygon(\n  ForwardIterator first,\n  ForwardIterator last,\n  const Point & point1,\n  const Point & point2)\n{\n  if (!point_in_polygon(first, last, point1)) {\n    return false;\n  }\n\n  return !segment_inter_polygon(first, last, point1, point2);\n}\n\ntemplate<typename ForwardIterator, typename PointPair>\nbool segment_in_polygon(\n  ForwardIterator first,\n  ForwardIterator last,\n  const PointPair & seg)\n{\n  return segment_in_polygon(first, last, seg.first, seg.second);\n}\n\n/***************************************************************************\n * \\brief Array of N evenly spaced numbers\n ***************************************************************************/\ntemplate<std::size_t N, typename T>\nconstexpr std::array<T, N> linspace(T x0, T xT)\n{\n  static_assert(std::is_floating_point_v<T>, \"T must be floating-point number\");\n  static_assert(N >= 2, \"N must be greater or equal to 2\");\n\n  T dx = (xT - x0) / static_cast<T>(N - 1);\n  std::array<T, N> ret{x0};\n  for (std::size_t i = 1; i != N; ++i) {\n    ret[i] = x0 += dx;\n  }\n  return ret;\n}\n\n/***************************************************************************\n * \\brief Sigmoid with center and steepness\n ***************************************************************************/\ntemplate<typename T>\nT sigmoid(T x, T center, T k)\n{\n  static_assert(std::is_floating_point_v<T>, \"T must be an arithmetic type\");\n  using std::exp;\n\n  return T(1) / (T(1) + exp(-k * (x - center)));\n}\n\n\nnamespace detail\n{\nconstexpr Eigen::StorageOptions layout(size_t N)\n{\n  if (N > 1) {\n    return Eigen::RowMajor;\n  }\n  return Eigen::ColMajor;\n}\n}   // namespace detail\n\n/**\n * Calculate sample error covariance matrix \\Sigma for a dataset and an error functions\n * @param data container with samples of type X, e.g. std::vector<X>\n * @param fcn mapping X -> ErrT where ErrT is an Eigen column vector/array of size D\n * @return covariance matrix of size D x D\n *\n *  \\Sigma = (1/N-1) * \\sum_i (fcn(x_i) - \\bar x) * (fcn(x_i) - \\bar x).transpose()\n *\n *   where  \\bar x = (1/N) * \\sum_i fcn(x_i)\n *\n */\ntemplate<typename DataContainerT, typename ErrorFcnT>\nauto sample_covariance(\n  const DataContainerT & data,\n  ErrorFcnT && fcn = [](const auto & x) {return x;})\n{\n  using ResT = typename std::result_of_t<\n    ErrorFcnT(typename DataContainerT::value_type)\n    >::PlainMatrix;\n  static_assert(ResT::ColsAtCompileTime == 1, \"fcn must map to column vector\");\n  static_assert(std::is_base_of_v<Eigen::MatrixBase<ResT>, ResT>, \"fcn must map to eigen type\");\n\n  static constexpr int N = ResT::RowsAtCompileTime;\n  using InfT = Eigen::Matrix<typename ResT::Scalar, N, N>;\n\n  InfT cov = InfT::Zero();\n\n  if (data.size() > 1) {\n    using CompT = Eigen::Matrix<\n      typename ResT::Scalar, Eigen::Dynamic, N, detail::layout(N)\n    >;\n    CompT errs(data.size(), N);\n    for (decltype(data.size()) i = 0; i != data.size(); ++i) {\n      errs.row(static_cast<Eigen::Index>(i)) = fcn(data[i]);\n    }\n\n    CompT centered = errs.rowwise() - errs.colwise().mean();\n    cov = (centered.adjoint() * centered) / (errs.rows() - 1);\n  }\n\n  return cov;\n}\n\n/**\n * Calculate sample square root information matrix I = \\Sigma^{-1/2}\n * @param cov covariance\n * @param min_eig lower bound for eigenvalues of \\Sigma (smaller eigenvalues are set to this value)\n * @return square root information matrix of size D x D\n */\ntemplate<typename Derived>\nauto sqrt_information(const Eigen::MatrixBase<Derived> & cov, typename Derived::Scalar min_eig)\n{\n  Eigen::SelfAdjointEigenSolver<typename Derived::PlainMatrix> es(cov);\n  return (es.eigenvectors() *\n         es.eigenvalues().cwiseMax(min_eig).cwiseSqrt().cwiseInverse().asDiagonal() *\n         es.eigenvectors().transpose()).eval();\n}\n\n}  // namespace cbr\n\n#endif  // CBR_MATH__MATH_HPP_\n", "meta": {"hexsha": "55ddc393efd8569d969af68b27558bb3d1184cf5", "size": 24342, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/cbr_math/math.hpp", "max_stars_repo_name": "yamaha-bps/cbr_math", "max_stars_repo_head_hexsha": "cf1ad7d4661f4b0063d07e00a4e0052454518931", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-24T17:41:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-24T17:41:16.000Z", "max_issues_repo_path": "include/cbr_math/math.hpp", "max_issues_repo_name": "yamaha-bps/cbr_math", "max_issues_repo_head_hexsha": "cf1ad7d4661f4b0063d07e00a4e0052454518931", "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": "include/cbr_math/math.hpp", "max_forks_repo_name": "yamaha-bps/cbr_math", "max_forks_repo_head_hexsha": "cf1ad7d4661f4b0063d07e00a4e0052454518931", "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.8308823529, "max_line_length": 100, "alphanum_fraction": 0.5061211076, "num_tokens": 6236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.908617906830944, "lm_q2_score": 0.7956581000631542, "lm_q1q2_score": 0.722949197432469}}
{"text": "/*\r\n######################################################\r\nIntroduction to Criptography - 2021 - Homework2\r\nLast modification (18-Mar-2021)\r\n\r\nAuthor: Gaina Robert-Adrian \r\nContact: gainarobertadrian@gmail.com\r\n\r\nPseudo Random Number Generators:\r\n1. Blum-Blum-Shub\r\n2. Jacobi generator (a) with p&q b)with generalized components p1,p2,...pi) \r\n######################################################\r\n\r\nResources: \r\n1. https://pdfs.semanticscholar.org/c19b/91cdc1da67c52e606cd4752472ce0db83131.pdf\r\n2. https://link.springer.com/content/pdf/10.1007/0-387-34799-2_13.pdf\r\n3. https://libntl.org/ (Big number library)\r\n4. https://en.wikipedia.org/wiki/Blum_Blum_Shub\r\n5. https://asecuritysite.com/encryption/blum\r\n\r\n*/\r\n#include <NTL/ZZ.h>\r\n#include <iostream>\r\n#include <fstream>\r\n#include <vector>\r\n#include <string>\r\n#include <utility>\r\n\r\nusing namespace std;\r\nusing namespace NTL;\r\n\r\nconst int RUNS = 5;\r\n\r\nclass blum_blum_shub {\r\nprivate:\r\n\t ZZ p;\r\n\t ZZ q;\r\n\t ZZ m;\r\n\t ZZ seed;\r\n\t ZZ random;\r\n\t int length;\r\n\r\n\t ZZ primeCongruentTo3Mod4(int length) {\r\n\t\t ZZ aux;\r\n\t\t GenPrime(aux, length);\r\n\t\t while (aux % 4 != 3) {\r\n\t\t\t GenPrime(aux, length);\r\n\t\t }\r\n\t\t return aux;\r\n\t }\r\n\r\n\t ZZ seedGenerator(ZZ& p, ZZ& q) {\r\n\t\t ZZ aux;\r\n\t\t ZZ m = p * q;\r\n\t\t aux = RandomBnd(m);\r\n\t\t while (aux % p == 0 || aux % q == 0) {\r\n\t\t\t aux = RandomBnd(m);\r\n\t\t }\r\n\t\t return aux;\r\n\t }\r\n\r\npublic:\r\n\tblum_blum_shub(int& length) {\r\n\t\tthis->length = length;\r\n\t\tp = primeCongruentTo3Mod4(length);\r\n\t\tq = primeCongruentTo3Mod4(length);\r\n\t\tm = p * q;\r\n\t\tseed = seedGenerator(p, q);\r\n\t\trandom = seed;\r\n\t}\r\n\r\n\tZZ random_bbs() {\r\n\t\trandom = PowerMod(random, 2, m);\r\n\t\treturn random;\r\n\t}\r\n\t\t\r\n\tvoid printAll() {\r\n\t\tcout << \"------------------------------------------------------------------------------\\n\";\r\n\t\tcout << \"P:\" << p << '\\n';\r\n\t\tcout << \"Q:\" << q << '\\n';\r\n\t\tcout << \"M:\" << m << '\\n';\r\n\t\tcout << \"Seed:\" << seed << '\\n';\r\n\t\tcout << \"Random:\" << random << '\\n';\r\n\t\tcout << \"------------------------------------------------------------------------------\\n\";\r\n\t\tcout << \"\\n\\n\\n\";\r\n\t}\r\n\r\n};\r\n\r\n/* \r\n1.Modulus division by a power-of-2-number can be optimized.\r\n\t\t a % (power_of_2) == a & (power_of_2-1)\r\n 2. Division and multiplication by powers of two can also be optimized by shifting bits.\r\n\t\ta / (power_of_2) == a >>= n where 2^n= power_of_2\r\n */\r\nZZ jacobi_calculator(ZZ a, ZZ n) {\r\n\tif (n % 2 == 0) {\r\n\t\tcout << \"Second parameter must be odd\";\r\n\t\treturn (ZZ)0;\r\n\t}\r\n\tZZ b = a % n;\r\n\tZZ c = n;\r\n\tZZ s = (ZZ)1;\r\n\twhile (b >= 2) {\r\n\r\n\t\twhile ((b & 3) == 0) {\t\t\t\t\t\t// b % 4    \r\n\t\t\tb >>= 2;\t\t\t\t\t\t\t\t// b /= 4\r\n\t\t}\r\n\t\tif ((b & 1) == 0) {\t\t\t\t\t\t\t// b % 2\r\n\t\t\tif ((c & 7) == 3 || (c & 7) == 5) {\t\t// c % 8\r\n\t\t\t\ts = -s;\r\n\t\t\t}\r\n\t\t\tb >>= 1;\t\t\t\t\t\t\t\t// b /= 2\r\n\t\t}\r\n\t\tif (b == 1) break;\r\n\t\tif ((b & 3) == 3 && (c & 3) == 3) {\t\t\t// b % 4\r\n\t\t\ts = -s;\r\n\t\t}\r\n\t\tif (c % b == 0) {\r\n\t\t\tb = 0;\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tZZ aux = b;\r\n\t\tb = c % b;\r\n\t\tc = aux;\r\n\t}\r\n\treturn s * b;\r\n}\r\n\r\nclass jacobi {\r\nprivate:\r\n\tZZ p;\r\n\tZZ q;\r\n\tZZ m;\r\n\tZZ seed;\r\n\tZZ random;\r\n\tvector<ZZ> m_components;\r\n\tint length;\r\n\tint l;\r\n\tvector<bool> generated_binary;\r\npublic:\r\n\tjacobi(int length, int l) {\r\n\t\tthis->length = length;\r\n\t\tthis->l = l;\r\n\t\tGenPrime(p, length);\r\n\t\tGenPrime(q, length);\r\n\t\twhile (q % 2!=1) {\r\n\t\t\tGenPrime(q, length);\r\n\t\t}\r\n\t\tm = p * q;\r\n\t}\r\n\r\n\tjacobi(int NR_OF_PRIMES, int PRIME_LENGTH,bool second) {\r\n\t\tm = 1;\r\n\t\tfor (int i = 0; i < NR_OF_PRIMES; ++i) {\r\n\t\t\tZZ aux;\r\n\t\t\tGenPrime(aux, PRIME_LENGTH);\r\n\t\t\tm_components.push_back(aux);\r\n\t\t\tm *= aux;\r\n\t\t}\r\n\t\tl = PRIME_LENGTH * NR_OF_PRIMES;\r\n\t}\r\n\r\n\tvector<bool> generate_random(int LENGTH) {\r\n\t\tvector<ZZ> a_components;\r\n\t\tfor (int i = 0; i < m_components.size(); ++i) {\r\n\t\t\tZZ aux;\r\n\t\t\taux = RandomBnd(m);\r\n\t\t\ta_components.push_back(aux);\r\n\t\t}\r\n\t\tZZ seed = a_components[0];\r\n\t\tZZ p = m_components[0];\r\n\t\tfor (int i = 1; i < m_components.size(); ++i) {\r\n\t\t\tCRT(seed, p, a_components[i], m_components[i]);\r\n\t\t}\r\n\t\tseed = seed % m;\r\n\t\tif (seed < 0)\r\n\t\t\tseed += m;\r\n\r\n\t\tvector<bool> aux_vector;\r\n\t\tfor (int i = 0; i < LENGTH; ++i) {\r\n\t\t\tZZ aux = jacobi_calculator(seed + (ZZ)i, m);\r\n\t\t\tif (aux == -1)\r\n\t\t\t\taux_vector.push_back(0);\r\n\t\t\telse if (aux == 1)\r\n\t\t\t\taux_vector.push_back(1);\r\n\t\t}\r\n\t\tgenerated_binary = aux_vector;\r\n\t\treturn generated_binary;\r\n\t}\r\n\r\n\tvector<bool> generate_random() {\r\n\t\tvector<bool> aux_vector;\r\n\t\tGenPrime(seed, RandomBnd(NumBits(m)));\r\n\t\tfor (int i = 0; i < l; ++i) {\r\n\t\t\tZZ aux = jacobi_calculator(seed + (ZZ)i, m);\r\n\t\t\tif (aux == -1)\r\n\t\t\t\taux_vector.push_back(0);\r\n\t\t\telse if (aux == 1)\r\n\t\t\t\taux_vector.push_back(1);\r\n\t\t}\r\n\t\tgenerated_binary = aux_vector;\r\n\t\treturn generated_binary;\r\n\t}\r\n};\r\n\r\nvector<bool> convertToBinary(ZZ& number) {\r\n\tunsigned int number_size = NumBits(number);\r\n\tvector<bool> binary_representation(number_size);\r\n\tfor (int i = 0; i < number_size; ++i) {\r\n\t\tbinary_representation[number_size - (i + 1)] = bit(number, i);\r\n\t}\r\n\treturn binary_representation;\r\n}\r\n\r\nvoid printBinary(const vector<bool>& v) {\r\n\tcout << \"Binary format: \";\r\n\tfor (int i = 0; i < v.size(); ++i)\r\n\t\tcout << v[i];\r\n\tcout << \"\\n\\n\";\r\n}\r\n\r\nvoid elementaryTest(const vector<bool>& v) {\r\n\tcout << \"Elementary test:\\n\";\r\n\tint nr_of_0 = 0;\r\n\tfor (int i = 0; i < v.size(); ++i) {\r\n\t\tif (v[i] == 0)\r\n\t\t\t++nr_of_0;\r\n\t}\r\n\tdouble percentage_of_0 = 100 * (double)nr_of_0 / v.size();\r\n\tcout << \"Number of 0: \" << nr_of_0<<'\\n';\r\n\tcout << \"Number of 1: \" << v.size() - nr_of_0<<'\\n';\r\n\tcout << \"Percentages:\\n0=\" << percentage_of_0 << \"%\\n\";\r\n\tcout << \"1=\" << 100 - percentage_of_0 << \"%\\n\\n\";\r\n}\r\n\r\npair<string,string> printToFiles(const vector<bool>& v,const int& iteration,string generator) {\r\n\tstring filename= generator + \"_\" + to_string(iteration)+\".txt\";\r\n\tstring default_file = generator + \"_Only1_\" + to_string(iteration) + \".txt\";\r\n\tofstream fout(filename);\r\n\tofstream f(default_file);\r\n\tfor (int i = 0; i < v.size(); ++i)\r\n\t{\r\n\t\tfout << v[i];\r\n\t\tf << 1;\r\n\t}\r\n\treturn make_pair(filename, default_file);\r\n}\r\n\r\nint getSize(ifstream& file) {\r\n\tfile.seekg(0, ios::end);\r\n\tint size = file.tellg();\r\n\tfile.seekg(0);\r\n\treturn size;\r\n}\r\n\r\nvoid compressionTest(const vector<bool>& v,const int& i,string generator) {\r\n\tcout << \"File compression test:\\n\";\r\n\tpair <string,string> files=printToFiles(v, i,generator);\r\n\tpair<string, string> zip_files = make_pair(files.first.substr(0, files.first.size() - 4)+\".zip\", files.second.substr(0, files.second.size() - 4)+\".zip\");\r\n\tsystem((\"powershell Compress-Archive -Force \" + files.first+ \" \" + zip_files.first).c_str());\r\n\tsystem((\"powershell Compress-Archive -Force \" + files.second + \" \" + zip_files.second).c_str());\r\n\r\n\t/*Default file size equals the generated one*/\r\n\tifstream gin(files.first, ios::binary);\r\n\tifstream zip_gin(zip_files.first, ios::binary);\r\n\tifstream zip_din(zip_files.second, ios::binary);\r\n\r\n\tint g_size=getSize(gin);\r\n\tint zip_g_size=getSize(zip_gin);\r\n\tint zip_d_size=getSize(zip_din);\r\n\r\n\r\n\tdouble g_comp_ratio = ((double)zip_g_size / (double)g_size) * 100;\r\n\tdouble s_comp_ratio= ((double)zip_d_size / (double)g_size) * 100;\r\n\r\n\tprintf(\"Initial files size: %d\\nArchived file zie: %d\\nDefault archived size: %d\\n\", g_size, zip_g_size, zip_d_size);\r\n\tprintf(\"Generated file compression ratio: %.2f%%\\n\",g_comp_ratio);\r\n\tprintf(\"Default file compression ratio: %.2f%%\\n\", s_comp_ratio);\r\n}\r\n\r\nvoid bbs_test(int bit_length) {\r\n\tblum_blum_shub generator(bit_length);\r\n\tZZ a;\r\n\tgenerator.printAll();\r\n\tfor (int i = 0; i < RUNS; ++i) {\r\n\t\tcout << \"------------------------------------------------------------------------------\\n\";\r\n\t\tcout << \"Iteration:\" << i << \"\\t\\t*bbs*\\n\";\r\n\t\ta = generator.random_bbs();\r\n\t\tcout << \"Generated number=\" << a << \"\\n\\n\";\r\n\t\tvector<bool> binary;\r\n\t\tbinary = convertToBinary(a);\r\n\t\tprintBinary(binary);\r\n\t\telementaryTest(binary);\r\n\t\tcompressionTest(binary,i,\"bbs\");\r\n\t\tcout << \"------------------------------------------------------------------------------\\n\";\r\n\t\tcout << \"\\n\\n\\n\";\r\n\t}\r\n}\r\n\r\nvoid jacobi_test(int p_q_size,int nr_bit_length) {\r\n\tjacobi j(p_q_size, nr_bit_length);\r\n\tvector<bool> binary;\r\n\tfor (int i = 0; i < RUNS; ++i) {\r\n\t\tcout << \"------------------------------------------------------------------------------\\n\";\r\n\t\tcout << \"Iteration:\" << i << \"\\t*jacobi*\\n\";\r\n\t\tbinary = j.generate_random();\r\n\t\tprintBinary(binary);\r\n\t\telementaryTest(binary);\r\n\t\tcompressionTest(binary, i,\"jcb\");\r\n\t\tcout << \"------------------------------------------------------------------------------\\n\";\r\n\t\tcout << \"\\n\\n\\n\";\r\n\t}\r\n}\r\n\r\nvoid jacobi_test_b(int NR_OF_PRIMES, int PRIME_LENGTH,int RANDOM_LENGTH) {\r\n\tjacobi j(NR_OF_PRIMES,PRIME_LENGTH,1);\r\n\tvector<bool> binary;\r\n\tfor (int i = 0; i < RUNS; ++i) {\r\n\t\tcout << \"------------------------------------------------------------------------------\\n\";\r\n\t\tcout << \"Iteration:\" << i << \"\\t*jacobi multiple components*\\n\";\r\n\t\tbinary = j.generate_random(RANDOM_LENGTH);\r\n\t\tprintBinary(binary);\r\n\t\telementaryTest(binary);\r\n\t\tcompressionTest(binary, i, \"jcb_comp\");\r\n\t\tcout << \"------------------------------------------------------------------------------\\n\";\r\n\t\tcout << \"\\n\\n\\n\";\r\n\t}\r\n}\r\n\r\nvoid jacobi_symbol_test(int bit_length,int runs) {\r\n\tblum_blum_shub generator(bit_length);\r\n\tZZ a = generator.random_bbs();\r\n\tZZ b = generator.random_bbs();\r\n\twhile (b % 2 != 1) { b = generator.random_bbs(); }\r\n\tfor (int i = 0; i < runs; ++i)\r\n\t{\r\n\t\tZZ aux1, aux2;\r\n\t\tif ((aux1=jacobi_calculator(a, b)) != (aux2=Jacobi(a, b))) {\r\n\t\t\tcout << \"Something is wrong\";\r\n\t\t\tcout << aux1 << \" \" << aux2<<'\\n';\r\n\t\t\tcout << \"A:\" << a << \" B:\" << b;\r\n\t\t\treturn;\r\n\t\t}\r\n\t\ta = generator.random_bbs();\r\n\t\tb = generator.random_bbs();\r\n\t\twhile (b % 2 != 1) { b = generator.random_bbs(); }\r\n\t}\r\n\tprintf(\"%d symbols calculated correctly\\n\", runs);\r\n}\r\n\r\nint main()\r\n{\r\n\tbbs_test(1024);\r\n\tjacobi_test(1024,2048);\r\n\tjacobi_test_b(5,512,2048);\r\n}", "meta": {"hexsha": "5005970b68914c330138ae062a44d5f8f0998d1b", "size": 9757, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2.PRNG_generators/Source.cpp", "max_stars_repo_name": "robertadriang/-Introduction_to_Cryptography", "max_stars_repo_head_hexsha": "b14750309ba6705d3e6d357b1771bdc3018a2681", "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": "2.PRNG_generators/Source.cpp", "max_issues_repo_name": "robertadriang/-Introduction_to_Cryptography", "max_issues_repo_head_hexsha": "b14750309ba6705d3e6d357b1771bdc3018a2681", "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": "2.PRNG_generators/Source.cpp", "max_forks_repo_name": "robertadriang/-Introduction_to_Cryptography", "max_forks_repo_head_hexsha": "b14750309ba6705d3e6d357b1771bdc3018a2681", "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.3305322129, "max_line_length": 155, "alphanum_fraction": 0.5460694886, "num_tokens": 2918, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178994073575, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.7229491871231705}}
{"text": "#include <svgpp/svgpp.hpp>\n#include <boost/version.hpp>\n#if BOOST_VERSION >= 106400\n#include <boost/serialization/array_wrapper.hpp>\n#endif\n#include <boost/math/constants/constants.hpp>\n#include <boost/numeric/ublas/assignment.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\nusing namespace svgpp;\nnamespace ublas = boost::numeric::ublas;\n\ntypedef ublas::matrix<double> matrix_t;\n\nstruct TransformEventsPolicy\n{\n  typedef matrix_t context_type;\n\n  static void transform_matrix(matrix_t & transform, const boost::array<double, 6> & matrix)\n  {\n    matrix_t m(3, 3);\n    m <<=\n      matrix[0], matrix[2], matrix[4],\n      matrix[1], matrix[3], matrix[5],\n      0, 0, 1;\n    transform = ublas::prod(transform, m);\n  }\n\n  static void transform_translate(matrix_t & transform, double tx, double ty)\n  {\n    matrix_t m = ublas::identity_matrix<double>(3, 3);\n    m(0, 2) = tx; m(1, 2) = ty;\n    transform = ublas::prod(transform, m);\n  }\n\n  static void transform_scale(matrix_t & transform, double sx, double sy)\n  {\n    matrix_t m = ublas::identity_matrix<double>(3, 3);\n    m(0, 0) = sx; m(1, 1) = sy; \n    transform = ublas::prod(transform, m);\n  }\n\n  static void transform_rotate(matrix_t & transform, double angle)\n  {\n    angle *= boost::math::constants::degree<double>();\n    matrix_t m(3, 3);\n    m <<=\n      std::cos(angle), -std::sin(angle), 0,\n      std::sin(angle),  std::cos(angle), 0,\n      0, 0, 1;\n    transform = ublas::prod(transform, m);\n  }\n\n  static void transform_skew_x(matrix_t & transform, double angle)\n  {\n    angle *= boost::math::constants::degree<double>();\n    matrix_t m = ublas::identity_matrix<double>(3, 3);\n    m(0, 1) = std::tan(angle);\n    transform = ublas::prod(transform, m);\n  }\n\n  static void transform_skew_y(matrix_t & transform, double angle)\n  {\n    angle *= boost::math::constants::degree<double>();\n    matrix_t m = ublas::identity_matrix<double>(3, 3);\n    m(1, 0) = std::tan(angle);\n    transform = ublas::prod(transform, m);\n  }\n};\n\nint main()\n{\n  matrix_t transform(ublas::identity_matrix<double>(3, 3));\n  value_parser<\n    tag::type::transform_list,\n    transform_policy<policy::transform::minimal>,\n    transform_events_policy<TransformEventsPolicy>\n  >::parse(tag::attribute::transform(), transform,\n    std::string(\"translate(-10,-20) scale(2) rotate(45) translate(5,10)\"), tag::source::attribute());\n  std::cout << transform << \"\\n\";\n  return 0;\n}\n", "meta": {"hexsha": "6bff240f9311046c80e0652c9d5c9507ea9056b5", "size": 2439, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/samples/sample_transform02.cpp", "max_stars_repo_name": "RichardCory/svgpp", "max_stars_repo_head_hexsha": "801e0142c61c88cf2898da157fb96dc04af1b8b0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 428.0, "max_stars_repo_stars_event_min_datetime": "2015-01-05T17:13:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:25:47.000Z", "max_issues_repo_path": "src/samples/sample_transform02.cpp", "max_issues_repo_name": "andrew2015/svgpp", "max_issues_repo_head_hexsha": "1d2f15ab5e1ae89e74604da08f65723f06c28b3b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 61.0, "max_issues_repo_issues_event_min_datetime": "2015-01-08T14:32:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-06T16:55:11.000Z", "max_forks_repo_path": "src/samples/sample_transform02.cpp", "max_forks_repo_name": "andrew2015/svgpp", "max_forks_repo_head_hexsha": "1d2f15ab5e1ae89e74604da08f65723f06c28b3b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 90.0, "max_forks_repo_forks_event_min_datetime": "2015-05-19T04:56:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T16:42:50.000Z", "avg_line_length": 29.0357142857, "max_line_length": 101, "alphanum_fraction": 0.6613366134, "num_tokens": 692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133531922389, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.7228687894737735}}
{"text": "// Copyright 2008 Gautam Sewani\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#define BOOST_MATH_UNDERFLOW_ERROR_POLICY throw_on_error\n#define BOOST_MATH_OVERFLOW_ERROR_POLICY throw_on_error\n#include <boost/math/concepts/real_concept.hpp> // for real_concept\n#include <boost/math/distributions/logistic.hpp>\n    using boost::math::logistic_distribution;\n\n#include <boost/test/test_exec_monitor.hpp> // Boost.Test\n#include <boost/test/floating_point_comparison.hpp>\n#include \"test_out_of_range.hpp\"\n\n\n#include <iostream>\n   using std::cout;\n   using std::endl;\n   using std::setprecision;\n\n\ntemplate <class RealType>\nvoid test_spot(RealType location, RealType scale, RealType x, RealType p, RealType q, RealType tolerance)\n{\n   BOOST_CHECK_CLOSE(\n      ::boost::math::cdf(\n      logistic_distribution<RealType>(location,scale),      \n      x),\n      p,\n      tolerance); // %\n   BOOST_CHECK_CLOSE(\n      ::boost::math::cdf(\n      complement(logistic_distribution<RealType>(location,scale),      \n      x)),\n      q,\n      tolerance); // %\n   if(p < 0.999)\n   {\n      BOOST_CHECK_CLOSE(\n         ::boost::math::quantile(\n         logistic_distribution<RealType>(location,scale),      \n         p),\n         x,\n         tolerance); // %\n   }\n   if(q < 0.999)\n   {\n      BOOST_CHECK_CLOSE(\n         ::boost::math::quantile(\n         complement(logistic_distribution<RealType>(location,scale),      \n         q)),\n         x,\n         2 * tolerance); // %\n   }\n}\n\n\ntemplate <class RealType>\nvoid test_spots(RealType T)\n{\n   // Basic sanity checks.\n   // 50 eps as a percentage, up to a maximum of double precision\n   // Test data taken from Mathematica 6\n   RealType tolerance = (std::max)(\n      static_cast<RealType>(1e-33L),\n      boost::math::tools::epsilon<RealType>());\n   cout<<\"Absolute tolerance:\"<<tolerance<<endl;\n\n   tolerance *= 50 * 100; \n   // #  pragma warning(disable: 4100) // unreferenced formal parameter.\n   // prevent his spurious warning.\n   if (T != 0)\n   {\n      cout << \"Expect parameter T == 0!\" << endl;\n   }\n   cout << \"Tolerance for type \" << typeid(T).name()  << \" is \" << tolerance << \" %\" << endl;\n\n   test_spot(\n      static_cast<RealType>(1), // location\n      static_cast<RealType>(0.5L), // scale\n      static_cast<RealType>(0.1L), // x\n      static_cast<RealType>(0.141851064900487789594278108470953L), // p\n      static_cast<RealType>(0.858148935099512210405721891529047L), //q\n      tolerance);\n\n   test_spot(\n      static_cast<RealType>(5), // location\n      static_cast<RealType>(2), // scale\n      static_cast<RealType>(3.123123123L),//x \n      static_cast<RealType>(0.281215878622547904873088053477813L), // p\n      static_cast<RealType>(0.718784121377452095126911946522187L), //q\n      tolerance);\n\n   test_spot(\n      static_cast<RealType>(1.2345L), // location\n      static_cast<RealType>(0.12345L), // scale\n      static_cast<RealType>(3.123123123L),//x\n      static_cast<RealType>(0.999999773084685079723328282229357L), // p\n      static_cast<RealType>(2.26915314920276671717770643005212e-7L), //q\n      tolerance);\n\n\n   //High probability\n   test_spot(\n      static_cast<RealType>(1), // location\n      static_cast<RealType>(0.5L), // scale\n      static_cast<RealType>(10), // x\n      static_cast<RealType>(0.99999998477002048723965105559179L), // p  \n      static_cast<RealType>(1.5229979512760348944408208801237e-8L), //q\n      tolerance);\n\n   //negative x\n   test_spot(\n      static_cast<RealType>(5), // location\n      static_cast<RealType>(2), // scale\n      static_cast<RealType>(-0.1L), // scale\n      static_cast<RealType>(0.0724264853615177178439235061476928L), // p\n      static_cast<RealType>(0.927573514638482282156076493852307L), //q\n      tolerance);\n\n\n   test_spot(\n      static_cast<RealType>(5), // location\n      static_cast<RealType>(2), // scale\n      static_cast<RealType>(-20), // x\n      static_cast<RealType>(3.72663928418656138608800947863869e-6L), // p\n      static_cast<RealType>(0.999996273360715813438613911990521L), //q\n      tolerance);\n\n\n   //test value to check cancellation error in straight/complimented quantile \n   //the subtraction in the formula location-scale*log term introduces catastrophics cancellator error if location and scale*log term are close\n   //For these values, the tests fail at tolerance, but work at 100*tolerance\n   test_spot(\n      static_cast<RealType>(-1.2345L), // location\n      static_cast<RealType>(1.4555L), // scale\n      static_cast<RealType>(-0.00125796420642514024493852425918807L),//x\n      static_cast<RealType>(0.7L), // p\n      static_cast<RealType>(0.3L), //q\n      80*tolerance);   \n\n   test_spot(\n      static_cast<RealType>(1.2345L), // location\n      static_cast<RealType>(0.12345L), // scale\n      static_cast<RealType>(0.0012345L), // x\n      static_cast<RealType>(0.0000458541039469413343331170952855318L), // p\n      static_cast<RealType>(0.999954145896053058665666882904714L), //q\n      80*tolerance);\n\n\n\n   test_spot(\n      static_cast<RealType>(5L), // location\n      static_cast<RealType>(2L), // scale\n      static_cast<RealType>(0.0012345L), // x\n      static_cast<RealType>(0.0759014628704232983512906076564256L), // p\n      static_cast<RealType>(0.924098537129576701648709392343574L), //q\n      80*tolerance);\n\n   //negative location\n   test_spot(\n      static_cast<RealType>(-123.123123L), // location\n      static_cast<RealType>(2.123L), // scale\n      static_cast<RealType>(3), // x\n      static_cast<RealType>(0.999999999999999999999999984171276L), // p\n      static_cast<RealType>(1.58287236765203121622150720373972e-26L), //q\n      tolerance);\n   //PDF Testing\n   BOOST_CHECK_CLOSE(\n      ::boost::math::pdf(\n      logistic_distribution<RealType>(5,2),      \n         static_cast<RealType>(0.125L) ),//x\n         static_cast<RealType>(0.0369500730133475464584898192104821L),              // probability\n      tolerance); // %\n\n   BOOST_CHECK_CLOSE(\n      ::boost::math::pdf(\n         logistic_distribution<RealType>(static_cast<RealType>(1.2345L), static_cast<RealType>(0.12345L)),      \n         static_cast<RealType>(0.0012345L) ),//x\n         static_cast<RealType>(0.000371421639109700748742498671686243L),              // probability\n      tolerance); // %\n   BOOST_CHECK_CLOSE(\n      ::boost::math::pdf(\n      logistic_distribution<RealType>(2,1),      \n         static_cast<RealType>(2L) ),//x\n         static_cast<RealType>(0.25L),              // probability\n      tolerance); // %\n\n   //Extreme value testing\n\n   if(std::numeric_limits<RealType>::has_infinity)\n   {\n      BOOST_CHECK_EQUAL(pdf(logistic_distribution<RealType>(), +std::numeric_limits<RealType>::infinity()), 0); // x = + infinity, pdf = 0\n      BOOST_CHECK_EQUAL(pdf(logistic_distribution<RealType>(), -std::numeric_limits<RealType>::infinity()), 0); // x = - infinity, pdf = 0\n      BOOST_CHECK_EQUAL(cdf(logistic_distribution<RealType>(), +std::numeric_limits<RealType>::infinity()), 1); // x = + infinity, cdf = 1\n      BOOST_CHECK_EQUAL(cdf(logistic_distribution<RealType>(), -std::numeric_limits<RealType>::infinity()), 0); // x = - infinity, cdf = 0\n      BOOST_CHECK_EQUAL(cdf(complement(logistic_distribution<RealType>(), +std::numeric_limits<RealType>::infinity())), 0); // x = + infinity, c cdf = 0\n      BOOST_CHECK_EQUAL(cdf(complement(logistic_distribution<RealType>(), -std::numeric_limits<RealType>::infinity())), 1); // x = - infinity, c cdf = 1\n   }\n   BOOST_CHECK_THROW(quantile(logistic_distribution<RealType>(), static_cast<RealType>(1)), std::overflow_error); // x = + infinity, cdf = 1\n   BOOST_CHECK_THROW(quantile(logistic_distribution<RealType>(), static_cast<RealType>(0)), std::overflow_error); // x = - infinity, cdf = 0\n   BOOST_CHECK_THROW(quantile(complement(logistic_distribution<RealType>(), static_cast<RealType>(1))), std::overflow_error); // x = - infinity, cdf = 0\n   BOOST_CHECK_THROW(quantile(complement(logistic_distribution<RealType>(), static_cast<RealType>(0))), std::overflow_error); // x = + infinity, cdf = 1\n   BOOST_CHECK_EQUAL(cdf(logistic_distribution<RealType>(), +boost::math::tools::max_value<RealType>()), 1); // x = + infinity, cdf = 1\n   BOOST_CHECK_EQUAL(cdf(logistic_distribution<RealType>(), -boost::math::tools::max_value<RealType>()), 0); // x = - infinity, cdf = 0\n   BOOST_CHECK_EQUAL(cdf(complement(logistic_distribution<RealType>(), +boost::math::tools::max_value<RealType>())), 0); // x = + infinity, c cdf = 0\n   BOOST_CHECK_EQUAL(cdf(complement(logistic_distribution<RealType>(), -boost::math::tools::max_value<RealType>())), 1); // x = - infinity, c cdf = 1\n   BOOST_CHECK_EQUAL(pdf(logistic_distribution<RealType>(), +boost::math::tools::max_value<RealType>()), 0); // x = + infinity, pdf = 0\n   BOOST_CHECK_EQUAL(pdf(logistic_distribution<RealType>(), -boost::math::tools::max_value<RealType>()), 0); // x = - infinity, pdf = 0\n\n   //\n   // Things that are errors:\n   //1. domain errors for scale and location\n   //2. x being NAN\n   //3. Probabilies being outside (0,1)\n   check_out_of_range<logistic_distribution<RealType> >(0, 1);\n   if(std::numeric_limits<RealType>::has_infinity)\n   {\n      RealType inf = std::numeric_limits<RealType>::infinity();\n      BOOST_CHECK_EQUAL(pdf(logistic_distribution<RealType>(0, 1), inf), 0);\n      BOOST_CHECK_EQUAL(pdf(logistic_distribution<RealType>(0, 1), -inf), 0);\n      BOOST_CHECK_EQUAL(cdf(logistic_distribution<RealType>(0, 1), inf), 1);\n      BOOST_CHECK_EQUAL(cdf(logistic_distribution<RealType>(0, 1), -inf), 0);\n      BOOST_CHECK_EQUAL(cdf(complement(logistic_distribution<RealType>(0, 1), inf)), 0);\n      BOOST_CHECK_EQUAL(cdf(complement(logistic_distribution<RealType>(0, 1), -inf)), 1);\n   }\n\n   //location/scale can't be infinity\n   if(std::numeric_limits<RealType>::has_infinity) {\n      BOOST_CHECK_THROW(\n         logistic_distribution<RealType> dist(std::numeric_limits<RealType>::infinity(),0.5),\n         std::domain_error);\n      BOOST_CHECK_THROW(\n         logistic_distribution<RealType> dist(0.5,std::numeric_limits<RealType>::infinity()),\n         std::domain_error);\n   }\n   //scale can't be negative or 0\n   BOOST_CHECK_THROW(\n      logistic_distribution<RealType> dist(0.5,-0.5),\n      std::domain_error);\n   BOOST_CHECK_THROW(\n      logistic_distribution<RealType> dist(0.5,0),\n      std::domain_error);\n\n   logistic_distribution<RealType> dist(0.5,0.5);\n   //x can't be NaN,p can't be NaN\n\n   if (std::numeric_limits<RealType>::has_quiet_NaN)\n   {\n      // No longer allow x to be NaN, then these tests should throw.\n      BOOST_CHECK_THROW(pdf(dist, +std::numeric_limits<RealType>::quiet_NaN()), std::domain_error); // x = NaN\n      BOOST_CHECK_THROW(cdf(dist, +std::numeric_limits<RealType>::quiet_NaN()), std::domain_error); // x = NaN\n      BOOST_CHECK_THROW(cdf(complement(dist, +std::numeric_limits<RealType>::quiet_NaN())), std::domain_error); // x = + infinity\n      BOOST_CHECK_THROW(quantile(dist, +std::numeric_limits<RealType>::quiet_NaN()), std::domain_error); // p = + infinity\n      BOOST_CHECK_THROW(quantile(complement(dist, +std::numeric_limits<RealType>::quiet_NaN())), std::domain_error); // p = + infinity\n   }\n\n   //p can't be outside (0,1)\n   BOOST_CHECK_THROW(quantile(dist, static_cast<RealType>(1.1)), std::domain_error); \n   BOOST_CHECK_THROW(quantile(dist, static_cast<RealType>(-0.1)), std::domain_error);\n   BOOST_CHECK_THROW(quantile(dist, static_cast<RealType>(1)), std::overflow_error); \n   BOOST_CHECK_THROW(quantile(dist, static_cast<RealType>(0)), std::overflow_error);\n\n   BOOST_CHECK_THROW(quantile(complement(dist, static_cast<RealType>(1.1))), std::domain_error); \n   BOOST_CHECK_THROW(quantile(complement(dist, static_cast<RealType>(-0.1))), std::domain_error);\n   BOOST_CHECK_THROW(quantile(complement(dist, static_cast<RealType>(1))), std::overflow_error); \n   BOOST_CHECK_THROW(quantile(complement(dist, static_cast<RealType>(0))), std::overflow_error); \n\n   //Tests for mean,mode,median,variance,skewness,kurtosis\n   //mean\n   BOOST_CHECK_CLOSE(\n      ::boost::math::mean(\n      logistic_distribution<RealType>(2,1)      \n      ),//x\n      static_cast<RealType>(2),              // probability\n      tolerance); // %\n   //median\n   BOOST_CHECK_CLOSE(\n      ::boost::math::median(\n      logistic_distribution<RealType>(2,1)      \n      ),//x\n      static_cast<RealType>(2),              // probability\n      tolerance);\n   //mode\n   BOOST_CHECK_CLOSE(\n      ::boost::math::mode(\n      logistic_distribution<RealType>(2,1)      \n      ),//x\n      static_cast<RealType>(2),              // probability\n      tolerance);\n   //variance\n   BOOST_CHECK_CLOSE(\n      ::boost::math::variance(\n      logistic_distribution<RealType>(2,1)      \n      ),//x\n      static_cast<RealType>(3.28986813369645287294483033329205L),              // probability\n      tolerance);\n   //skewness\n   BOOST_CHECK_CLOSE(\n      ::boost::math::skewness(\n      logistic_distribution<RealType>(2,1)      \n      ),//x\n      static_cast<RealType>(0),              // probability\n      tolerance);\n   BOOST_CHECK_CLOSE(\n      ::boost::math::kurtosis_excess(\n      logistic_distribution<RealType>(2,1)      \n      ),//x\n      static_cast<RealType>(1.2L),              // probability\n      tolerance);\n\n} // template <class RealType>void test_spots(RealType)\n\n\nint test_main(int, char* [])\n{\n  // Check that can generate logistic distribution using the two convenience methods:\n   boost::math::logistic mycexp1(1.); // Using typedef\n   logistic_distribution<> myexp2(1.); // Using default RealType double.\n\n    // Basic sanity-check spot values.\n   // (Parameter value, arbitrarily zero, only communicates the floating point type).\n  test_spots(0.0F); // Test float. OK at decdigits = 0 tolerance = 0.0001 %\n  test_spots(0.0); // Test double. OK at decdigits 7, tolerance = 1e07 %\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n  test_spots(0.0L); // Test long double.\n#if !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x582))\n  test_spots(boost::math::concepts::real_concept(0.)); // Test real concept.\n#endif\n#else\n   std::cout << \"<note>The long double tests have been disabled on this platform \"\n      \"either because the long double overloads of the usual math functions are \"\n      \"not available at all, or because they are too inaccurate for these tests \"\n      \"to pass.</note>\" << std::cout;\n#endif\n\n   return 0;\n} // int test_main(int, char* [])\n\n", "meta": {"hexsha": "6132eed88bd164cdea852d51601ca745c9b40179", "size": 14477, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/math/test/test_logistic_dist.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2016-04-12T16:29:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-28T11:01:57.000Z", "max_issues_repo_path": "boost/libs/math/test/test_logistic_dist.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-10-31T19:35:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-04T17:11:27.000Z", "max_forks_repo_path": "boost/libs/math/test/test_logistic_dist.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-09-09T02:38:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-30T00:24:24.000Z", "avg_line_length": 42.2069970845, "max_line_length": 152, "alphanum_fraction": 0.6740346757, "num_tokens": 3926, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146761176671, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7228249111730359}}
{"text": "/*!\n * \\file misc.cpp\n * \\author Jun Yoshida\n * \\copyright (c) 2019 Jun Yoshida.\n * The project is released under the MIT License.\n * \\date Descember 21, 2019: created\n */\n\n#pragma once\n\n#include <type_traits>\n#include <Eigen/Dense>\n\n/*************************\n *** Utility functions ***\n *************************/\n\n/*\ndouble cross2D(Eigen::Ref<Eigen::Vector2d> const &x, Eigen::Ref<Eigen::Vector2d> const &y)\n{\n    return x(0)*y(1)-x(1)*y(0);\n}\n*/\n\ninline double cross2D(Eigen::Vector2d &&x, Eigen::Vector2d &&y)\n{\n    return x(0)*y(1)-x(1)*y(0);\n}\n\ntemplate<class T, int n, size_t... is>\nEigen::Matrix<T,n+1,1> affWrap_impl(Eigen::Matrix<T,n,1> const &mat, std::index_sequence<is...>)\n{\n    return Eigen::Matrix<T,n+1,1>{mat(is)...,1.0};\n}\n\ntemplate<class T,int n>\nEigen::Matrix<T,n+1,1> affWrap(Eigen::Matrix<T,n,1> const &mat)\n{\n    return affWrap_impl(mat, std::make_index_sequence<n>());\n}\n\n//! Check if two triangles overwraps with each other.\n//! Based on the idea suggested in https://stackoverflow.com/questions/2778240/detection-of-triangle-collision-in-2d-space.\ninline bool trianglesIntersection2D(std::array<Eigen::Vector2d,3> const &t1_, std::array<Eigen::Vector2d,3> const &t2_)\n{\n    /*** Preparation ***/\n    // Rotation matrix of M_PI/2 in radian.\n    Eigen::Matrix<double,2,2> mat;\n    mat << 0, 1, -1, 0;\n\n    // We may assume the vertices are given counter-clockwisely around triangles.\n    bool is_ccwise1 = static_cast<double>((t1_[1]-t1_[0]).adjoint()*mat*(t1_[2]-t1_[0])) > 0;\n    bool is_ccwise2 = static_cast<double>((t2_[1]-t2_[0]).adjoint()*mat*(t2_[2]-t2_[0])) > 0;\n    std::array<std::array<Eigen::Vector2d const*, 3>,2> t{\n        &(t1_[0]),\n        is_ccwise1 ? &(t1_[1]) : &(t1_[2]),\n        is_ccwise1 ? &(t1_[2]) : &(t1_[1]),\n        &(t2_[0]),\n        is_ccwise2 ? &(t2_[1]) : &(t2_[2]),\n        is_ccwise2 ? &(t2_[2]) : &(t2_[1])\n    };\n\n    /*** The algorithm begins here ***/\n\n    // Find an edge in one triangle which separates the opposite vertex and the vertices of the other triangle.\n    // If found, this means two triangles are disjoint.\n    for(size_t i = 0; i < 3; ++i) {\n        Eigen::RowVector2d rv = (*(t[0][(i+1)%3])-*(t[0][i])).adjoint()*mat;\n        if (static_cast<double>(rv*(*(t[1][0])-*(t[0][i]))) < 0\n            && static_cast<double>(rv*(*(t[1][1])-*(t[0][i]))) < 0\n            && static_cast<double>(rv*(*(t[1][2])-*(t[0][i]))) < 0)\n            return false;\n    }\n\n    for(size_t i = 0; i < 3; ++i) {\n        Eigen::RowVector2d rv = (*(t[1][(i+1)%3])-*(t[1][i])).adjoint()*mat;\n        if (static_cast<double>(rv*(*(t[0][0])-*(t[1][i]))) < 0\n            && static_cast<double>(rv*(*(t[0][1])-*(t[1][i]))) < 0\n            && static_cast<double>(rv*(*(t[0][2])-*(t[1][i]))) < 0)\n            return false;\n    }\n\n    return true;\n}\n", "meta": {"hexsha": "188149b93b95d06c8a21887edf57d5b644ec372b", "size": 2796, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/math/misc.hpp", "max_stars_repo_name": "Junology/bord2", "max_stars_repo_head_hexsha": "0068885144032d4a8e30c6f2c5898918d00b1d8f", "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/misc.hpp", "max_issues_repo_name": "Junology/bord2", "max_issues_repo_head_hexsha": "0068885144032d4a8e30c6f2c5898918d00b1d8f", "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/misc.hpp", "max_forks_repo_name": "Junology/bord2", "max_forks_repo_head_hexsha": "0068885144032d4a8e30c6f2c5898918d00b1d8f", "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.8941176471, "max_line_length": 123, "alphanum_fraction": 0.5661659514, "num_tokens": 940, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870287, "lm_q2_score": 0.8104789086703224, "lm_q1q2_score": 0.7227940381856885}}
{"text": "// Copyright Matt Overby 2021.\n// Distributed under the MIT License.\n\n#ifndef MCL_SIGNEDVOLUME_HPP\n#define MCL_SIGNEDVOLUME_HPP 1\n\n#include <Eigen/Dense>\n#include <vector>\n\nnamespace mcl\n{\n\nstatic inline double signed_triangle_area(\n\tconst Eigen::Vector2d &p1,\n\tconst Eigen::Vector2d &p2,\n\tconst Eigen::Vector2d &p3);\n\n// Returns (unscaled) first derivative of signed triangle area\nstatic inline std::vector<Eigen::Vector2d> signed_triangle_area_gradients(\n\tconst Eigen::Vector2d &p1,\n\tconst Eigen::Vector2d &p2,\n\tconst Eigen::Vector2d &p3);\n\nstatic inline double triangle_perimeter(\n\tconst Eigen::Vector2d &p1,\n\tconst Eigen::Vector2d &p2,\n\tconst Eigen::Vector2d &p3);\n\nstatic inline double triangle_area(\n\tconst Eigen::Vector3d &p1,\n\tconst Eigen::Vector3d &p2,\n\tconst Eigen::Vector3d &p3);\n\nstatic inline double signed_tet_volume(\n\tconst Eigen::Vector3d &p1,\n\tconst Eigen::Vector3d &p2,\n\tconst Eigen::Vector3d &p3,\n\tconst Eigen::Vector3d &p4);\n\n// Returns (unscaled) first derivative of signed tet volume\nstatic inline std::vector<Eigen::Vector3d> signed_tet_volume_gradients(\n\tconst Eigen::Vector3d &p1,\n\tconst Eigen::Vector3d &p2,\n\tconst Eigen::Vector3d &p3,\n\tconst Eigen::Vector3d &p4);\n\nstatic inline double tet_surface_area(\n\tconst Eigen::Vector3d &p1,\n\tconst Eigen::Vector3d &p2,\n\tconst Eigen::Vector3d &p3,\n\tconst Eigen::Vector3d &p4);\n\n// Probably not where this belongs but oh well.\n// Returns the faces of a tet\nstatic inline std::vector<Eigen::Vector3i>\n\tfaces_from_tet(const Eigen::RowVector4i &t);\n\n//\n// Implementation\n//\n\ninline double signed_triangle_area(const Eigen::Vector2d &p1, const Eigen::Vector2d &p2, const Eigen::Vector2d &p3)\n{\n\treturn 0.5 * ( -p2[0]*p1[1] + p3[0]*p1[1] + p1[0]*p2[1] - p3[0]*p2[1] - p1[0]*p3[1] + p2[0]*p3[1] );\n}\n\ninline std::vector<Eigen::Vector2d> signed_triangle_area_gradients(\n\tconst Eigen::Vector2d &a, const Eigen::Vector2d &b, const Eigen::Vector2d &c)\n{\n\tstd::vector<Eigen::Vector2d> g(3);\n\tg[0] = 0.5 * Eigen::Vector2d(b[1]-c[1], -b[0]+c[0]);\n\tg[1] = 0.5 * Eigen::Vector2d(-a[1]+c[1], a[0]-c[0]);\n\tg[2] = 0.5 * Eigen::Vector2d(a[1]-b[1], -a[0]+b[0]);\n\treturn g;\n}\n\ninline double triangle_perimeter(const Eigen::Vector2d &p1, const Eigen::Vector2d &p2, const Eigen::Vector2d &p3)\n{\n\treturn (p1-p2).norm() + (p2-p3).norm() + (p3-p1).norm();\n}\n\n// https://en.wikipedia.org/wiki/Heron%27s_formula\ninline double triangle_area(const Eigen::Vector3d &p1, const Eigen::Vector3d &p2, const Eigen::Vector3d &p3)\n{\n\tdouble a = (p1-p2).norm();\n\tdouble b = (p2-p3).norm();\n\tdouble c = (p3-p1).norm();\n\tdouble s = (a+b+c) * 0.5;\n\treturn std::sqrt(s*(s-a)*(s-b)*(s-c));\n}\n\ninline double signed_tet_volume(\n\tconst Eigen::Vector3d &p1, const Eigen::Vector3d &p2,\n\tconst Eigen::Vector3d &p3, const Eigen::Vector3d &p4)\n{\n\tEigen::Matrix3d edges;\n\tedges.col(0) = p2 - p1;\n\tedges.col(1) = p3 - p1;\n\tedges.col(2) = p4 - p1;\n\treturn (1.0/6.0) * edges.determinant();\n}\n\ninline std::vector<Eigen::Vector3d> signed_tet_volume_gradients(\n\tconst Eigen::Vector3d &a, const Eigen::Vector3d &b,\n\tconst Eigen::Vector3d &c, const Eigen::Vector3d &d)\n{\n\tstd::vector<Eigen::Vector3d> grads(4);\n\tconst Eigen::Vector3d &p0 = a;\n\tconst Eigen::Vector3d &p1 = b;\n\tconst Eigen::Vector3d &p2 = c;\n\tconst Eigen::Vector3d &p3 = d;\n\tstatic const double sixth = (1.0/6.0);\n\tgrads[0] = sixth * (p1 - p2).cross(p3 - p2);\n\tgrads[1] = sixth * (p2 - p0).cross(p3 - p0);\n\tgrads[2] = sixth * (p0 - p1).cross(p3 - p1);\n\tgrads[3] = sixth * (p1 - p0).cross(p2 - p0);\n\treturn grads;\n}\n\ninline double tet_surface_area(\n\t\tconst Eigen::Vector3d &p1,\n\t\tconst Eigen::Vector3d &p2,\n\t\tconst Eigen::Vector3d &p3,\n\t\tconst Eigen::Vector3d &p4)\n{\n\tdouble a1 = triangle_area(p2,p3,p4);\n\tdouble a2 = triangle_area(p2,p3,p1);\n\tdouble a3 = triangle_area(p3,p4,p1);\n\tdouble a4 = triangle_area(p4,p2,p1);\n\treturn (a1+a2+a3+a4);\n}\n\ninline std::vector<Eigen::Vector3i> faces_from_tet(const Eigen::RowVector4i &t)\n{\n\tusing namespace Eigen;\n\tstd::vector<Vector3i> f = {\n\t\tVector3i(t[0], t[1], t[3]),\n\t\tVector3i(t[0], t[2], t[1]),\n\t\tVector3i(t[0], t[3], t[2]),\n\t\tVector3i(t[1], t[2], t[3]) };\n\treturn f;\n}\n\n} // ns mcl\n\n#endif\n", "meta": {"hexsha": "429d446b44b55c6e6e2cf058871e77d2984d74df", "size": 4105, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/MCL/SignedMeasure.hpp", "max_stars_repo_name": "mattoverby/mclgeom", "max_stars_repo_head_hexsha": "d3ecd2a878900f33ba1412b8d82e643895201e51", "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/MCL/SignedMeasure.hpp", "max_issues_repo_name": "mattoverby/mclgeom", "max_issues_repo_head_hexsha": "d3ecd2a878900f33ba1412b8d82e643895201e51", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-26T22:44:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T02:54:23.000Z", "max_forks_repo_path": "include/MCL/SignedMeasure.hpp", "max_forks_repo_name": "mattoverby/mclgeom", "max_forks_repo_head_hexsha": "d3ecd2a878900f33ba1412b8d82e643895201e51", "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.925170068, "max_line_length": 115, "alphanum_fraction": 0.6855054811, "num_tokens": 1452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237605, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.7226620480656334}}
{"text": "#include <tuple>\n#include <complex>\n# include <iostream>\n#include <Eigen/Dense>\nusing namespace Eigen;\nusing namespace std;\n\ntuple<MatrixXcd, MatrixXcd> qr_reduced(const MatrixXcd& A)\n{\n    // reduced QR decomposition using Modified Gram-Schmidt with Reortogonalization\n    // reference: W. Ganter 1980, Algorithms for QR-Decomposition, research report no.80-02\n    // A is  m x n  complex matrix\n    int n= A.cols();\n    MatrixXcd R= MatrixXcd::Zero(n,n);\n    MatrixXcd Q= A;\n    for(int k= 0; k < n; ++k){\n        complex<double> tt {(0.0,0.0)};\n        for(int j= 0; j < 2; ++j){\n            for(int i= 0; i < k; ++i){\n                complex<double> s= Q.col(i).adjoint()*Q.col(k);\n                if(tt == (0.0,0.0)) R(i,k)= s;\n                Q.col(k)= Q.col(k)-s*Q.col(i);\n            }\n            tt= Q.col(k).norm();\n        }\n        R(k,k)= tt;\n        Q.col(k)= Q.col(k)/R(k,k);\n    }\n    return forward_as_tuple(Q,R);\n}\n", "meta": {"hexsha": "edde458621186be87d9ae6621c3f8c3936d3431b", "size": 934, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "qr_reduced.cpp", "max_stars_repo_name": "nmoteki/block-Krylov-linear-solvers", "max_stars_repo_head_hexsha": "0c123f474296219c1b944ad83f8e3c7abbf0c2b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-27T08:44:06.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-27T08:44:06.000Z", "max_issues_repo_path": "qr_reduced.cpp", "max_issues_repo_name": "nmoteki/block-Krylov-linear-solvers", "max_issues_repo_head_hexsha": "0c123f474296219c1b944ad83f8e3c7abbf0c2b0", "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": "qr_reduced.cpp", "max_forks_repo_name": "nmoteki/block-Krylov-linear-solvers", "max_forks_repo_head_hexsha": "0c123f474296219c1b944ad83f8e3c7abbf0c2b0", "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.1290322581, "max_line_length": 91, "alphanum_fraction": 0.5417558887, "num_tokens": 288, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797100118214, "lm_q2_score": 0.7931059438487663, "lm_q1q2_score": 0.7226620439247708}}
{"text": "#include <NTL/ZZXFactoring.h>\n\nNTL_CLIENT\n\n\nlong compare(const ZZX& a, const ZZX& b)\n{\n   if (deg(a) < deg(b))\n      return 0;\n\n   if (deg(a) > deg(b))\n      return 1;\n\n   long n = a.rep.length();\n   long i;\n\n   for (i = 0; i < n; i++) {\n      if (a.rep[i] < b.rep[i]) return 0;\n      if (a.rep[i] > b.rep[i]) return 1;\n   }\n\n   return 0;\n}\n      \n\nvoid sort(vec_pair_ZZX_long& v)\n{\n   long n = v.length();\n   long i, j;\n\n   for (i = 0; i < n-1; i++)\n      for (j = 0; j < n-1-i; j++)\n         if (compare(v[j].a, v[j+1].a)) {\n            swap(v[j].a, v[j+1].a);\n            swap(v[j].b, v[j+1].b);\n         }\n}\n            \n \n\nint main(int argc, char **argv)\n{\n   ZZX f1, f;\n\n   if (argc > 1) \n      ZZXFac_MaxPrune = atoi(argv[1]);\n\n   cin >> f;\n\n   vec_pair_ZZX_long factors;\n   ZZ c;\n\n   double t;\n\n   t = GetTime();\n   factor(c, factors, f, 0);\n   t = GetTime()-t;\n\n   cerr << \"total time: \" << t << \"\\n\";\n\n\n   mul(f1, factors);\n   mul(f1, f1, c);\n\n   if (f != f1)\n      Error(\"FACTORIZATION INCORRECT!!!\");\n\n\n\n   sort(factors);\n\n   cout << c << \"\\n\";\n   cout << factors << \"\\n\";\n\n   return 0;\n}\n\n", "meta": {"hexsha": "c5dbfa4b1979bd14b1a621d6a94aa2e5343c478d", "size": 1102, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RUNETag/WinNTL/tests/ZZXFacTest.cpp", "max_stars_repo_name": "vshesh/RUNEtag", "max_stars_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "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": "RUNETag/WinNTL/tests/ZZXFacTest.cpp", "max_issues_repo_name": "vshesh/RUNEtag", "max_issues_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "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": "RUNETag/WinNTL/tests/ZZXFacTest.cpp", "max_forks_repo_name": "vshesh/RUNEtag", "max_forks_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "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": 14.1282051282, "max_line_length": 42, "alphanum_fraction": 0.4564428312, "num_tokens": 398, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797100118214, "lm_q2_score": 0.7931059414036511, "lm_q1q2_score": 0.7226620416968315}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// QuickBook Example\n\n// Copyright (c) 2014, Oracle and/or its affiliates\n\n// Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle\n\n// Licensed under the Boost Software License version 1.0.\n// http://www.boost.org/users/license.html\n\n//[num_segments\n//` Get the number of segments in a geometry\n\n#include <iostream>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n\n\nint main()\n{\n    boost::geometry::model::multi_polygon\n        <\n            boost::geometry::model::polygon\n                <\n                    boost::geometry::model::d2::point_xy<double>, true, false // cw, open polygon\n                >\n        > mp;\n    boost::geometry::read_wkt(\"MULTIPOLYGON(((0 0,0 10,10 0),(1 1,8 1,1 8)),((10 10,10 20,20 10)))\", mp);\n    std::cout << \"Number of segments: \" << boost::geometry::num_segments(mp) << std::endl;\n    return 0;\n}\n\n//]\n\n\n//[num_segments_output\n/*`\nOutput:\n[pre\n Number of segments: 9\n]\n*/\n//]\n", "meta": {"hexsha": "c5861b7d9a7259638c66103a7c45a0a7df4f8d71", "size": 1020, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/src/examples/algorithms/num_segments.cpp", "max_stars_repo_name": "jonasdmentia/geometry", "max_stars_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1155.0, "max_stars_repo_stars_event_min_datetime": "2015-01-10T19:04:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:30:30.000Z", "max_issues_repo_path": "doc/src/examples/algorithms/num_segments.cpp", "max_issues_repo_name": "jonasdmentia/geometry", "max_issues_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "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": "doc/src/examples/algorithms/num_segments.cpp", "max_forks_repo_name": "jonasdmentia/geometry", "max_forks_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 228.0, "max_forks_repo_forks_event_min_datetime": "2015-01-13T12:55:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T11:11:05.000Z", "avg_line_length": 22.6666666667, "max_line_length": 105, "alphanum_fraction": 0.6323529412, "num_tokens": 279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021708, "lm_q2_score": 0.8333245891029456, "lm_q1q2_score": 0.7225222182747043}}
{"text": "#ifndef MLT_MODELS_REGRESSORS_LEAST_SQUARES_LINEAR_REGRESSION_HPP\n#define MLT_MODELS_REGRESSORS_LEAST_SQUARES_LINEAR_REGRESSION_HPP\n\n#include <type_traits>\n\n#include <Eigen/Core>\n\n#include \"linear_regressor.hpp\"\n#include \"../../utils/linear_solvers.hpp\"\n\nnamespace mlt {\nnamespace models {\nnamespace regressors {\n\tusing namespace utils::linear_solvers;\n\n\ttemplate <class Solver = SVDSolver>\n    class LeastSquaresLinearRegression : public LinearRegressor<LeastSquaresLinearRegression<Solver>> {\n    public:         \n        explicit LeastSquaresLinearRegression(bool fit_intercept = true) : LinearRegressor(fit_intercept), _solver(Solver()) {}\n\n        template <class S, class = enable_if<is_same<decay_t<S>, Solver>::value>>\n\t\texplicit LeastSquaresLinearRegression(const S&& solver, bool fit_intercept = true) : LinearRegressor(fit_intercept), _solver(forward<S>(solver)) {}\n\n        Self& fit(Features input, Target target, bool = true) {\n            MatrixXd input_prime(input.rows() + (_fit_intercept ? 1 : 0), input.cols());\n\t\t\tinput_prime.topRows(input.rows()) << input;\n\n\t\t\tif (_fit_intercept) {\n\t\t\t\tinput_prime.bottomRows<1>() = VectorXd::Ones(input.cols());\n\t\t\t}\n\n\t\t\t_set_coefficients(_solver.compute(input_prime * input_prime.transpose()).solve(input_prime * target.transpose()).transpose());\n\n\t\t\treturn _self();\n        }\n\n\tprotected:\n\t\tSolver _solver;\n    };\n}\n}\n}\n#endif", "meta": {"hexsha": "46782fdf9c464c508d60aa6cf5a4e76f7a91d8a2", "size": 1384, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/mlt/models/regressors/least_squares_linear_regression.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/models/regressors/least_squares_linear_regression.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/models/regressors/least_squares_linear_regression.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": 32.1860465116, "max_line_length": 149, "alphanum_fraction": 0.7297687861, "num_tokens": 324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404038127071, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.7224539016486792}}
{"text": "/*\n * Copyright 2020 \u00a9 Centre Interdisciplinaire de d\u00e9veloppement en Cartographie des Oc\u00e9ans (CIDCO), Tous droits r\u00e9serv\u00e9s\n */\n\n/* \n * File:   PlaneFitter.hpp\n * Author: Jordan McManus\n */\n\n#ifndef PLANEFITTER_HPP\n#define PLANEFITTER_HPP\n\n#include <Eigen/Dense>\n\nclass PlaneFitter {\npublic:\n\n    static void convertPlaneZform2GeneralForm(Eigen::Vector3d & zForm, Eigen::Vector4d & generalForm) {\n        /*\n         * Z-form is z = Ax + By + C\n         * General form is ax + by + cz + d = 0 with (a*a + b*b + c*c = 1 i.e. unit normal vector)\n         */\n        \n        double c = 1.0 / zForm.norm();\n        double a = -zForm(0) * c;\n        double b = -zForm(1) * c;\n        double d = -zForm(2) * c;\n        double f = sqrt(a * a + b * b + c * c);\n        a = a / f;\n        b = b / f;\n        c = c / f;\n        d = d / f;\n\n        generalForm << a, b, c, d;\n    }\n\n    static void convertPlaneGeneralForm2Zform(Eigen::Vector4d & generalForm, Eigen::Vector3d & zForm) {\n        /*\n         * Z-form is z = Ax + By + C\n         * General form is ax + by + cz + d = 0 with (a*a + b*b + c*c = 1 i.e. unit normal vector)\n         */\n        double f = 1.0 / generalForm(2);\n        double A = -generalForm(0) * f;\n        double B = -generalForm(1) * f;\n        double C = -generalForm(3) * f;\n        \n        zForm << A, B, C;\n    }\n\n    static void calculatePlaneResidualsFromMatrix(Eigen::VectorXd & residuals, Eigen::MatrixXd & cloud, Eigen::Vector4d & planarGeneralForm) {\n        /*\n         * General form is ax + by + cz + d = 0 with (a*a + b*b + c*c = 1 i.e. unit normal vector)\n         */\n        \n        Eigen::MatrixXd augmentedCloud(cloud.rows(), 4);\n        augmentedCloud.col(0) = cloud.col(0);\n        augmentedCloud.col(1) = cloud.col(1);\n        augmentedCloud.col(2) = cloud.col(2);\n        augmentedCloud.col(3) = Eigen::VectorXd::Ones(cloud.rows());\n\n        residuals = augmentedCloud*planarGeneralForm;\n    }\n    \n    static void fitPlane(Eigen::MatrixXd & xyz, Eigen::Vector4d & planeGeneralFormParams) {\n        \n        Eigen::MatrixXd A(xyz.rows(), 3);\n        A.col(0) = xyz.col(0);\n        A.col(1) = xyz.col(1);\n        A.col(2) = Eigen::VectorXd::Ones(xyz.rows());\n        \n        Eigen::VectorXd b = xyz.col(2);\n        \n        Eigen::Vector3d planeParameterEstimation = A.bdcSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(b);\n        \n        convertPlaneZform2GeneralForm(planeParameterEstimation, planeGeneralFormParams);\n    }\n\n    static void fitPlane(Eigen::MatrixXd & A, Eigen::VectorXd & b, Eigen::Vector4d & planeGeneralFormParams) {\n        Eigen::Vector3d planeParameterEstimation = A.bdcSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(b);\n        convertPlaneZform2GeneralForm(planeParameterEstimation, planeGeneralFormParams);\n    }\n\n};\n\n#endif /* PLANEFITTER_HPP */\n\n", "meta": {"hexsha": "0e135ee7c475ef56513000790dd54c572686e47f", "size": 2831, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/math/PlaneFitter.hpp", "max_stars_repo_name": "JordanMcManus/MBES-lib", "max_stars_repo_head_hexsha": "618d64f4e042bf5660015819f89537cdd70e696d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2019-10-29T14:16:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T06:44:37.000Z", "max_issues_repo_path": "src/math/PlaneFitter.hpp", "max_issues_repo_name": "JordanMcManus/MBES-lib", "max_issues_repo_head_hexsha": "618d64f4e042bf5660015819f89537cdd70e696d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 62.0, "max_issues_repo_issues_event_min_datetime": "2019-04-16T13:53:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T19:44:23.000Z", "max_forks_repo_path": "src/math/PlaneFitter.hpp", "max_forks_repo_name": "JordanMcManus/MBES-lib", "max_forks_repo_head_hexsha": "618d64f4e042bf5660015819f89537cdd70e696d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2019-04-10T19:51:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T21:42:22.000Z", "avg_line_length": 32.5402298851, "max_line_length": 142, "alphanum_fraction": 0.5814199929, "num_tokens": 814, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404096760998, "lm_q2_score": 0.7772998508568416, "lm_q1q2_score": 0.7224538918215541}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include <math.h>\n//#include <unsupported/Eigen/MatrixFunctions>\n\n//Euler angles to DCM\n//e = [phi, theta, psi]\n//3-1-2 rotation\n//ref: Todd Humphreys euler2dcm MATLAB function, \"Aerial Robotics,\" 2019\nusing Eigen::Matrix3f;\nusing Eigen::Vector3f;\nMatrix3f euler2dcm(Vector3f e)\n{\n  std::cout << \"Calculating trig values...\" << std::endl;\n  float cPhi = cos(e(0)); \n  float sPhi = sin(e(0));\n  float cThe = cos(e(1)); \n  float sThe = sin(e(1));\n  float cPsi = cos(e(2)); \n  float sPsi = sin(e(2));\n  std::cout << \"Building DCM...\" << std::endl;\n  Matrix3f DCM; \n  DCM << (cPhi*cThe - sPhi*sPsi*sThe), (cThe*sPsi + cPsi * sPhi*sThe), (-cPhi*sThe), \n         (-cPhi*sPsi),                                    (cPhi*cPsi),         sPhi,\n         (cPsi*sThe + cThe*sPhi*sPsi), (sPsi*sThe - cPsi*cThe*sPhi),    (cPhi*cThe);\n  return DCM;\n}\n\n\nint main()\n{\n  using Eigen::Vector3f; \n  using Eigen::Matrix3f;\n  using Eigen::Quaternionf;\n  /*Matrix3f A;\n  A << 1, 2, 3, 4, 5, 6, 7, 8, 9;\n  std::cout << (A*5) << std::endl;*/\n  Vector3f v(1.5708, -1.5708, 0.7854);\n  Matrix3f DCM = euler2dcm(v);\n  std::cout << DCM << std::endl;\n}", "meta": {"hexsha": "12c251c07ce50de83750dde7fb62632798188e56", "size": 1162, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "euler2dcm.cpp", "max_stars_repo_name": "nearlab/rover_visual_od", "max_stars_repo_head_hexsha": "5b945e0ba9694e53bf0533bcf7ba065fd57d4198", "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": "euler2dcm.cpp", "max_issues_repo_name": "nearlab/rover_visual_od", "max_issues_repo_head_hexsha": "5b945e0ba9694e53bf0533bcf7ba065fd57d4198", "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": "euler2dcm.cpp", "max_forks_repo_name": "nearlab/rover_visual_od", "max_forks_repo_head_hexsha": "5b945e0ba9694e53bf0533bcf7ba065fd57d4198", "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.3414634146, "max_line_length": 85, "alphanum_fraction": 0.5886402754, "num_tokens": 428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391579526934, "lm_q2_score": 0.7826624688140726, "lm_q1q2_score": 0.7224281061753178}}
{"text": "///////////////////////////////////////////////////////////////////////////////\r\n//  Copyright Christopher Kormanyos 2015 - 2016.\r\n//  Copyright Paul A. Bristow 2015 - 2016.\r\n//  Distributed under the Boost Software License,\r\n//  Version 1.0. (See accompanying file LICENSE_1_0.txt\r\n//  or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n// This file is written to be included from a Quickbook .qbk document.\r\n// It can be compiled by the C++ compiler, and run. Any output can\r\n// also be added here as comment or included or pasted in elsewhere.\r\n// Caution: this file contains Quickbook markup as well as code\r\n// and comments: don't change any of the special comment markups!\r\n\r\n// For additional details, see C.M. Kormanyos,\r\n// Real-Time C++: Efficient Object-Oriented and\r\n// Template Microcontroller Programming (Springer, Heidelberg, 2013).\r\n// in Section 12.7 and Chapter 13.\r\n// See http://link.springer.com/chapter/10.1007/978-3-642-34688-0_13\r\n\r\n#define USE_BARE_METAL\r\n\r\n#include <cstdint>\r\n\r\n#if defined(USE_BARE_METAL)\r\n#else\r\n  #include <iostream>\r\n  #include <iomanip>\r\n#endif\r\n\r\n// Configure Boost.Fixed_point for a bare-metal system.\r\n\r\n#if defined(USE_BARE_METAL)\r\n  #define BOOST_FIXED_POINT_DISABLE_MULTIPRECISION // Do not use Boost.Multiprecision.\r\n  #define BOOST_FIXED_POINT_DISABLE_IOSTREAM       // Do not use I/O streaming.\r\n#endif\r\n\r\n#include <boost/fixed_point/fixed_point.hpp>\r\n\r\nnamespace local\r\n{\r\n  /*! Evaluate first derivative of real_function\r\n      using a three-point central-difference rule of O(dx^6), for more details\r\n     \\see http://www.boost.org/doc/libs/release/libs/multiprecision/doc/html/boost_multiprecision/tut/floats/fp_eg/nd.html.\r\n\r\n    \\tparam RealValueType Type of value, for example, a fixed_point_type.\r\n    \\tparam RealFunctionType Type of parameter @c real function.\r\n    \\param x Value of x.\r\n    \\param dx Step size.\r\n    \\param real_function Real Function.\r\n    \\return First derivative at x value.\r\n  */\r\n\r\n  //[fixed_point_derivative_function\r\n  template<typename RealValueType,\r\n           typename RealFunctionType>\r\n  RealValueType first_derivative(const RealValueType& x,\r\n                                 const RealValueType& dx,\r\n                                 RealFunctionType real_function)\r\n  {\r\n    const RealValueType dx2(dx  + dx);\r\n    const RealValueType dx3(dx2 + dx);\r\n\r\n    const RealValueType m1((  real_function(x + dx)\r\n                            - real_function(x - dx))  / 2U);\r\n    const RealValueType m2((  real_function(x + dx2)\r\n                            - real_function(x - dx2)) / 4U);\r\n    const RealValueType m3((  real_function(x + dx3)\r\n                            - real_function(x - dx3)) / 6U);\r\n\r\n    const RealValueType fifteen_m1(m1 * 15U);\r\n    const RealValueType six_m2    (m2 *  6U);\r\n    const RealValueType ten_dx    (dx * 10U);\r\n\r\n    return ((fifteen_m1 - six_m2) + m3) / ten_dx;\r\n  }\r\n//] [/fixed_point_derivative_function]\r\n} // namespace local\r\n\r\n// Implement a tiny simulated subset of the mcal (microcontroller abstraction layer).\r\nnamespace mcal\r\n{\r\n  namespace wdg\r\n  {\r\n    void trigger();\r\n  }\r\n} // namespace mcal::wdg\r\n\r\nvoid mcal::wdg::trigger()\r\n{\r\n  // Simulate a fake watchdog trigger mechanism doing nothing here.\r\n}\r\n\r\n// Declare a global Boolean test variable.\r\nbool global_result_is_ok;\r\n\r\nextern \"C\" int main()\r\n{\r\n//[fixed_point_derivative_coeffic\r\n  typedef boost::fixed_point::negatable<6, -9> fixed_point_type;\r\n\r\n  const fixed_point_type a = fixed_point_type(12) / 10;\r\n  const fixed_point_type b = fixed_point_type(34) / 10;\r\n  const fixed_point_type c = fixed_point_type(56) / 10;\r\n\r\n  // Compute the approximate derivative of (a * x^2) + (b * x) + c\r\n  // evaluated at 1/2, where the approximate values of the coefficients\r\n  // are: a = 1.2, b = 3.4, and c = 5.6. The numerical tolerance is set\r\n  // to a value of approximately 1/4.\r\n//] [/fixed_point_derivative_coeffic]\r\n  // See http://link.springer.com/chapter/10.1007/978-3-642-34688-0_12 page 219-220.\r\n\r\n//[fixed_point_derivative_evalution\r\n  const fixed_point_type d =\r\n    local::first_derivative(fixed_point_type(1) / 2, // x\r\n                            fixed_point_type(1) / 4,  // Step size dx.\r\n                            [&a, &b, &c](const fixed_point_type& x) -> fixed_point_type\r\n                            {\r\n                              return (((a * x) + b) * x) + c;\r\n                            });\r\n//] [/fixed_point_derivative_evalution]\r\n\r\n  // The expected result is ((2 * a) + b) = (2.4 + 3.4) = 4.6 (exact).\r\n  // We obtain a fixed-point result of approximately 4.5938.\r\n\r\n  // Verify that the result lies within (4.5 < result < 4.7).\r\n  // The expected result is 4.6, so this is a wide tolerance.\r\n\r\n//[fixed_point_verify\r\n  global_result_is_ok = ((d > (fixed_point_type(45) / 10)) && (d < (fixed_point_type(47) / 10)));\r\n//] [/fixed_point_verify]\r\n\r\n  #if defined(USE_BARE_METAL)\r\n    // We can not print the fixed-point number to the output stream\r\n    // because I/O-streaming is disabled for fixed-point in this\r\n    // Boost configuration.\r\n  #else\r\n    // But if we could print to the output stream, it might look\r\n    // similar to the lines below. When attempting to print to\r\n    // the output stream, however, we would need to add <iostream>\r\n    // and deactivate #define BOOST_FIXED_POINT_DISABLE_IOSTREAM.\r\n    std::cout << std::setprecision(std::numeric_limits<fixed_point_type>::digits10)\r\n              << std::fixed\r\n              << d\r\n              << std::endl;\r\n  #endif\r\n\r\n  // Is the result of taking the derivative of the quadratic function OK?\r\n  if(global_result_is_ok)\r\n  {\r\n    // Here we could take some action in the microcontroller\r\n    // such as toggle a digital output port to high, indicating\r\n    // success of the test case.\r\n  }\r\n\r\n  #if defined(USE_BARE_METAL)\r\n    // In this bare-metal OS-less system, do not return from main().\r\n    for(;;)\r\n    {\r\n      mcal::wdg::trigger();\r\n    }\r\n  #endif\r\n}\r\n", "meta": {"hexsha": "62eb04eb83e2c1bd0dafbb4106694855f5898c36", "size": 5971, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/fixed_point_bare_metal_derivative_example.cpp", "max_stars_repo_name": "BoostGSoC15/fixed-point", "max_stars_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_stars_repo_licenses": ["BSL-1.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": "example/fixed_point_bare_metal_derivative_example.cpp", "max_issues_repo_name": "BoostGSoC15/fixed-point", "max_issues_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_issues_repo_licenses": ["BSL-1.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": "example/fixed_point_bare_metal_derivative_example.cpp", "max_forks_repo_name": "BoostGSoC15/fixed-point", "max_forks_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.6319018405, "max_line_length": 124, "alphanum_fraction": 0.6385865014, "num_tokens": 1510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127566694178, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.7223610436005949}}
{"text": "#include <iostream>\n#include <eigen3/Eigen/Dense>\n#include <vector>\n#include <cmath>\n#include <boost/numeric/odeint.hpp>\n#include \"gnuplot-iostream.h\"\n#include \"system_function.h\"\nnamespace odeint = boost::numeric::odeint;\nint main()\n{\n\tstate_type x(2); // a vector with size 2.\n\tx[0] = 1.0;\t\t // start at x=1.0, p=0.0\n\tx[1] = 0.0;\n\tstd::vector<state_type> x_vec;\n\tstd::vector<double> times;\n\n\tsize_t steps = odeint::integrate(harmonic_oscillator,\n\t\t\t\t\t\t\t\t\t x, 0.0, 10.0, 0.1,\n\t\t\t\t\t\t\t\t\t push_back_state_and_time(x_vec, times));\n\n\tstd::vector<double> position;\n\tfor (size_t i = 0; i <= steps; i++)\n\t{\n\t\tposition.push_back(x_vec[i][0]);\n\t}\n\t/* output */\n\tGnuplot gp;\n\tgp << \"plot '-' using 1:2 with linespoint\" << std::endl;\n\tgp.send1d(std::make_tuple(times, position));\n\n\t// for (size_t i = 0; i <= steps; i++)\n\t// {\n\t// \tstd::cout << times[i] << '\\t' << x_vec[i][0] << '\\t' << x_vec[i][1] << '\\n';\n\t// }\n\n\treturn 0;\n}\n", "meta": {"hexsha": "9418cf1714190879633f4609024ecf8e5b979b7c", "size": 918, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "HW/hw1/src/main.cpp", "max_stars_repo_name": "amirnn/Engineering-Mathematics", "max_stars_repo_head_hexsha": "99dd270dba8ca3357259afb9195a9136b33510d8", "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": "HW/hw1/src/main.cpp", "max_issues_repo_name": "amirnn/Engineering-Mathematics", "max_issues_repo_head_hexsha": "99dd270dba8ca3357259afb9195a9136b33510d8", "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": "HW/hw1/src/main.cpp", "max_forks_repo_name": "amirnn/Engineering-Mathematics", "max_forks_repo_head_hexsha": "99dd270dba8ca3357259afb9195a9136b33510d8", "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.1578947368, "max_line_length": 81, "alphanum_fraction": 0.6100217865, "num_tokens": 317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.913676530465412, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.7222889942808036}}
{"text": "#include <limits>\n#include <numeric>\n\n#include <Eigen/Core>\n\n#include \"UtilMath.hpp\"\n\nnamespace RGM\n{\n\ntemplate<typename T>\nT MathUtil_<T>::median(std::vector<T> & vData, int num/*=std::numeric_limits<int>::max()*/, bool sortData/*=false*/)\n{\n\n    if (vData.size()==0 || num==0) {\n        return std::numeric_limits<T>::quiet_NaN();\n    }\n\n    num = std::max<int>(std::min<int>(vData.size(), num), 1);\n\n    if ( vData.size()==1 || num==1 ) {\n        return vData[0];\n    }\n\n    std::vector<T> * p=0;\n\n    if ( sortData ) {\n        std::sort(vData.begin(), vData.begin()+num); // Ascending\n\n        if ( num % 2 == 0) {\n            int idx = num / 2;\n            return (vData[idx-1] + vData[idx]) / (T)2;\n        } else {\n            int idx = (num-1) / 2;\n            return vData[idx];\n        }\n    } else {\n        std::vector<T> tmp(num);\n        std::copy(vData.begin(), vData.begin()+num, tmp.begin());\n        std::sort(tmp.begin(), tmp.end());\n\n        if ( num % 2 == 0) {\n            int idx = num / 2;\n            return (tmp[idx-1] + tmp[idx]) / (T)2;\n        } else {\n            int idx = (num-1) / 2;\n            return tmp[idx];\n        }\n    }\n}\n\n\ntemplate<typename T>\nstd::vector<float> MathUtil_<T>::pdist(const std::vector<cv::Point_<T> > & pts, int num)\n{\n\n    std::vector<float> dist;\n\n    num = std::min<int>(pts.size(), num);\n\n    for ( int i=0; i<num-1; ++i ) {\n        const cv::Point_<T> & pt1( pts[i] );\n        for ( int j=i+1; j<num; ++j ) {\n            const cv::Point_<T> & pt2( pts[j] );\n            dist.push_back( sqrt((float)(pt1.x-pt2.x)*(pt1.x-pt2.x)+(pt1.y-pt2.y)*(pt1.y-pt2.y)) );\n        }\n    }\n\n    return dist;\n}\n\ntemplate<typename T>\nstd::vector<T> MathUtil_<T>::linspace(T s, T e, T interval)\n{\n\n    std::vector<T> x;\n\n    for ( T i=s; i<=e; i+=interval ) {\n        x.push_back(i);\n    }\n\n    return x;\n}\n\n\ntemplate<typename T>\nstd::vector<T> MathUtil_<T>::hist(std::vector<T> & y, std::vector<T> & x)\n{\n\n    std::vector<T> n(x.size(), 0);\n\n    std::vector<T> xx(x.size()+1);\n    xx[0]           = -std::numeric_limits<T>::infinity();\n    std::copy(x.begin(), x.end(), xx.begin()+1);\n\n    for ( int i=0; i<y.size(); ++i ) {\n\n        int j=0;\n        for ( ; j<xx.size()-1; ++j ) {\n            if (y[i]>xx[j] && y[i]<=xx[j+1]) {\n                break;\n            }\n        }\n\n        n[j]++;\n    }\n\n    return n;\n}\n\ntemplate<typename T>\nstd::vector<T> MathUtil_<T>::convnSame(std::vector<T> & x, std::vector<T> & filter)\n{\n\n    std::vector<T> xx(x.size()+2*filter.size(), 0);\n    std::copy(x.begin(), x.end(), xx.begin()+filter.size());\n\n    std::reverse(filter.begin(), filter.end());\n\n    std::vector<T> result(xx.size()-filter.size());\n    for ( int i=0; i<result.size(); ++i) {\n        result[i] = std::inner_product(filter.begin(), filter.end(), xx.begin()+i, 0.0F);\n    }\n\n    std::vector<T> r(x.size());\n\n    int istart = floor(filter.size()/2.0F);\n    std::copy(result.begin()+istart, result.begin()+istart+x.size(), r.begin());\n\n    return r;\n}\n\ntemplate<typename T>\nT MathUtil_<T>::calcErr(std::vector<T> & pscores, std::vector<T> & nscores, T & thr)\n{\n    T minerr = 1.0;\n\n    int numpos = pscores.size();\n    int numneg = nscores.size();\n    int num = numpos+numneg;\n\n    std::vector<std::pair<T, int> > scores(num);\n\n    for ( int i=0; i<numpos; ++i ) {\n        scores[i] = std::pair<T, int>(-pscores[i], i);\n    }\n    for ( int i=numpos, j=0; j<numneg; ++i, ++j ) {\n        scores[i] = std::pair<T, int>(-nscores[j], i);\n    }\n\n    std::sort(scores.begin(), scores.end());\n\n    std::vector<int> tp(num, 0), fp(num, 0);\n\n    for (int i=0; i<num; ++i ) {\n        if ( scores[i].second < numpos ) {\n            tp[i] = 1;\n            fp[i] = 0;\n        } else {\n            fp[i] = 1;\n            tp[i] = 0;\n        }\n    }\n\n    Eigen::VectorXd tpr(num), fpr(num), err(num);\n\n    tpr(0) = tp[0];\n    fpr(0) = fp[0];\n    for ( int i=1; i<num; ++i ) {\n        tpr(i) = tpr(i-1) + tp[i];\n        fpr(i) = fpr(i-1) + fp[i];\n    }\n\n    tpr /= numpos;\n    // to fnr\n    tpr.array() = 1 - tpr.array();\n    fpr /= numneg;\n\n    err = tpr+fpr;\n\n    int r, c;\n    minerr = err.minCoeff(&r, &c) / 2.0f;\n\n    thr = std::max<T>(-scores[r].first, *std::min_element(pscores.begin(), pscores.end()));\n\n    return minerr;\n}\n\ntemplate<typename T>\nT MathUtil_<T>::calcVar(std::vector<T> & pscores, T & thr)\n{\n    int num = pscores.size();\n\n    //thr = std::numeric_limits<T>::max();\n\n    T  m = 0;\n    for ( int i=0; i<num; ++i) {\n        m += pscores[i];\n        //thr = std::min<T>(thr, pscores[i]);\n    }\n\n    m /= num;\n\n    T v = 0;\n    for ( int i=0; i<num; ++i) {\n        v += std::pow(pscores[i]-m, 2.0F);\n    }\n\n    v /= (num-1);\n\n    v = sqrt(v);\n\n    thr = m - v;\n\n    return v;\n}\n\n/// Specification\ntemplate class MathUtil_<int>;\ntemplate class MathUtil_<float>;\ntemplate class MathUtil_<double>;\n\n} // namespace RGM\n", "meta": {"hexsha": "07a4c94369f79ff87bd179425aef2e3b917386dd", "size": 4866, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/core/UtilMath.cpp", "max_stars_repo_name": "hyz331/Stats232B-Project1", "max_stars_repo_head_hexsha": "516ef4441923dd88e8689bdff5259c81a228b443", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 33.0, "max_stars_repo_stars_event_min_datetime": "2016-01-11T22:42:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-27T17:19:26.000Z", "max_issues_repo_path": "src/core/UtilMath.cpp", "max_issues_repo_name": "mrgloom/AOGDetector", "max_issues_repo_head_hexsha": "296bdeefa3e111596ea824396203d15c5c0c4577", "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/core/UtilMath.cpp", "max_forks_repo_name": "mrgloom/AOGDetector", "max_forks_repo_head_hexsha": "296bdeefa3e111596ea824396203d15c5c0c4577", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2015-11-15T14:48:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-16T12:59:07.000Z", "avg_line_length": 21.7232142857, "max_line_length": 116, "alphanum_fraction": 0.4936292643, "num_tokens": 1570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765187126079, "lm_q2_score": 0.7905303186696748, "lm_q1q2_score": 0.7222889894988771}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#include \"topology.hpp\"\n\nusing namespace Eigen;\n\n/**\n * @brief Calcola la direzione normale di ogni corner di ogni triangolo nella\n * mesh in input.\n *\n * Data una mesh di triangoli M = (V, F), dove V e' un array di posizioni 3D\n * (i vertici) e F e' un array di triple di indici ai vertici (ogni tripla\n * rappresenta una faccia triangolare), questa funzione calcola la direzione\n * normale di ogni corner di ogni triangolo come una somma pesata delle normali\n * dei triangoli adiacenti nello stesso settore.\n * Ogni triangolo ha 3 corner.\n * Un settore e' costituito da un insieme di triangoli incidenti su uno stesso\n * vertice, uno adiacente al successivo, che approssimano una superficie smooth:\n * due triangoli adiacenti tra loro (incidono sullo stesso lato) fanno parte\n * dello stesso settore se l'angolo fra le loro rispettive direzioni normali e'\n * inferiore ad una data soglia (il coseno, o prodotto scalare, - e' maggiore\n * di una soglia).\n * Il peso \u00e8 dato dall'area del triangolo moltiplicato l'angolo incidente sul\n * vertice.\n *\n * L'area di un triangolo viene calcolata come meta' della lunghezza (norma)\n * del prodotto vettoriale tra due lati.\n * L'angolo incidente su un vertice viene calcolato come l'arcocoseno del\n * prodotto scalare tra i due lati incidenti (intesi come vettori unitari\n * centrati su di esso), oppure come l'arcotangente del seno e coseno:\n * - il seno e' proporzionale alla normal del prodotto vettoriale\n * - il cose e' proporzionale al prodotto scalare.\n *\n * @param V I vertici della mesh. Per ogni riga della matrice V, la posizione\n *          del vertice e' costituita dalle coordinate x,y,z memorizzate nelle\n *          3 colonne della riga.\n * @param F I triangoli della mesh. Per ogni riga della matrice F, il triangolo\n *          e' descritto dagli indici i,j,k memorizzati nelle 3 colonne della\n *          riga. Gli indici i,j,k si riferiscono ai 3 vertici A, B, C del\n *          triangolo, memorizzati in V.row(i), V.row(j) e V.row(k),\n *          rispettivamente. NOTA: per ogni triangolo, i 3 vertici sono da\n *          considerarsi indicati in senso antiorario.\n * @return MatrixXd La matrice restituita ha tre righe per ogni triangolo\n *                  (N.rows() == F.rows() * 3) e 3 colonne. Ogni riga corrisponde\n *                  alla direzione normale di un corner di un triangolo, avente\n *                  le 3 coordinate x,y,z.\n */\nMatrixXd perCornerNormals(MatrixXd const &V, MatrixXi const &F)\n{\n    MatrixXd N = MatrixXd::Zero(F.rows() * 3, 3);\n\n    // coseno di 30 gradi:\n    const double cos_thr = std::sqrt(3) / 2;\n\n    // suggerimento: e' necessario trovare le facce adiacenti intorno ad un vertice\n    // se non vuoi scrivere il codice che fa questo, puoi includere il file\n    // #include \"topology.hpp\"\n    // e chiamare le funzioni `vertex_face_adjacency()` e `face_face_adjacency()`\n\n    std::vector<std::vector<int>> VF, VFi;\n    MatrixXi FF, FFi;\n\n    vertex_face_adjacency(V, F, VF, VFi);\n    face_face_adjacency(V, F, VF, VFi, FF, FFi);\n\n    MatrixXd FN(F.rows(), 3);\n    VectorXd Fareas(F.rows());\n    MatrixXd Fangles(F.rows(), 3);\n\n    for (int f = 0; f < F.rows(); ++f)\n    {\n        int i = F(f, 0);\n        int j = F(f, 1);\n        int k = F(f, 2);\n\n        Vector3d A = V.row(i);\n        Vector3d B = V.row(j);\n        Vector3d C = V.row(k);\n\n        Vector3d e0 = B - A;\n        Vector3d e1 = C - B;\n        Vector3d e2 = A - C;\n\n        Vector3d c0 = e0.cross(-e2);\n        Vector3d c1 = e1.cross(-e0);\n        Vector3d c2 = e2.cross(-e1);\n\n        Fareas(f) = c0.norm() / 2.0;\n\n        FN.row(f) = c0.normalized();\n\n        Fangles(f, 0) = std::atan2(c0.norm(), e0.dot(-e2));\n        Fangles(f, 1) = std::atan2(c1.norm(), e1.dot(-e0));\n        Fangles(f, 2) = std::atan2(c2.norm(), e2.dot(-e1));\n    }\n\n    MatrixXd FF_cosines(F.rows(), 3);\n    for (int f = 0; f < F.rows(); ++f) {\n        auto const& fn = FN.row(f);\n        for (int p = 0; p < 3; ++p) {\n            auto const& ffn = FN.row(FF(f, p));\n            FF_cosines(f, p) = fn.dot(ffn);\n        }\n    }\n\n    for (int f = 0; f < F.rows(); ++f) {\n        auto const& fn = FN.row(f);\n        for (int p = 0; p < 3; ++p) {\n            auto n = Fareas(f) * Fangles(f, p) * fn;\n\n            N.row(3 * f + p) += n;\n\n            // contribusci alle normali di tutte le facce adiacenti intorno\n            // al corner p, il cui angolo diedrale non supera la soglia\n            int nf = FF(f, (3 + p - 1) % 3);\n            if (nf >= 0) {\n                int nfi = FFi(f, (3 + p - 1) % 3);\n                // prima le facce in senso antiorario\n                do {\n                    if (FF_cosines(nf, nfi) >= cos_thr) {\n                        N.row(3 * nf + nfi) += n;\n                        int nnf = FF(nf, (3 + nfi - 1) % 3);\n                        nfi = FFi(nf, (3 + nfi - 1) % 3);\n                        nf = nnf;\n                    } else {\n                        break;\n                    }\n                } while (nf >= 0 && nf != f);\n\n                // poi le facce in senso orario, eventualmente\n                if (nf != f) {\n                    nf = f;\n                    nfi = p;\n                    while (nf >= 0 && FF_cosines(nf, nfi) >= cos_thr) {\n                        int nnf = FF(nf, nfi);\n                        nfi = (FFi(nf, nfi) + 1) % 3;\n                        nf = nnf;\n                        N.row(3 * nf + nfi) += n;\n                    }\n                }\n            }\n        }\n    }\n\n    for (int n = 0; n < N.rows(); ++n) {\n        N.row(n).normalize();\n    }\n\n    return N;\n}", "meta": {"hexsha": "4e90f82a0d7a14f7381f0021abfdd65a374aaccb", "size": 5643, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "perCornerNormals.hpp", "max_stars_repo_name": "giorgiomarcias/WS_geo_3D", "max_stars_repo_head_hexsha": "ea34450ed0daa38504df5c0d723ab41ac347abd3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-03-11T16:16:28.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-11T16:16:28.000Z", "max_issues_repo_path": "perCornerNormals.hpp", "max_issues_repo_name": "giorgiomarcias/WS_geo_3D", "max_issues_repo_head_hexsha": "ea34450ed0daa38504df5c0d723ab41ac347abd3", "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": "perCornerNormals.hpp", "max_forks_repo_name": "giorgiomarcias/WS_geo_3D", "max_forks_repo_head_hexsha": "ea34450ed0daa38504df5c0d723ab41ac347abd3", "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.8823529412, "max_line_length": 83, "alphanum_fraction": 0.5514797094, "num_tokens": 1727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.7221606700774151}}
{"text": "//============================================================================\n// Name        : jacobian-matrix.cpp\n// Author      : Deborah Digges\n// Version     :\n// Copyright   : 2016\n// Description : Hello World in C++, Ansi-style\n//============================================================================\n\n#include <iostream>\n#include <Eigen/Dense>\n#include <math.h>\n#include <vector>\n\nusing namespace std;\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\n\nMatrixXd CalculateJacobian(const VectorXd& x_state);\n\nint main() {\n\n\t/*\n\t * Compute the Jacobian Matrix\n\t */\n\n\t//predicted state  example\n\t//px = 1, py = 2, vx = 0.2, vy = 0.4\n\tVectorXd x_predicted(4);\n\tx_predicted << 1, 2, 0.2, 0.4;\n\n\tMatrixXd Hj = CalculateJacobian(x_predicted);\n\n\tcout << \"Hj:\" << endl << Hj << endl;\n\n\treturn 0;\n}\n\nMatrixXd CalculateJacobian(const VectorXd& x_state) {\n\n\tMatrixXd Hj(3,4);\n\t//recover state parameters\n\tfloat px = x_state(0);\n\tfloat py = x_state(1);\n\tfloat vx = x_state(2);\n\tfloat vy = x_state(3);\n\n\tif(px == 0 && py == 0) {\n\t\treturn Hj;\n\t}\n\n\tfloat px2py2 = pow(px, 2) + pow(py, 2);\n\n\tHj(0, 0) = px/sqrt(px2py2);\n\tHj(0, 1) = py/sqrt(px2py2);\n\n\tHj(1, 0) = -py/px2py2;\n\tHj(1, 1) = px/px2py2;\n\n\tHj(2, 0) = py* (vx*py - vy*px)/pow(px2py2, 3/2);\n\tHj(2, 1) = px * (vy*px - vx*py)/pow(px2py2, 3/2);\n\tHj(2, 2) = px/sqrt(px2py2);\n\tHj(2, 3) = py/sqrt(px2py2);\n\n\treturn Hj;\n}\n", "meta": {"hexsha": "e2823f71f7e0a6ba3a2a833ced80b9c3949931c8", "size": 1364, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "P1-Extended-Kalman-Filter/class-notes/jacobian-matrix/src/jacobian-matrix.cpp", "max_stars_repo_name": "Deborah-Digges/SDC-ND-term-2", "max_stars_repo_head_hexsha": "ebed581914957f1ab615edfedea0052dc55b0939", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-10-26T01:57:36.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-22T08:50:11.000Z", "max_issues_repo_path": "P1-Extended-Kalman-Filter/class-notes/jacobian-matrix/src/jacobian-matrix.cpp", "max_issues_repo_name": "Deborah-Digges/SDC-ND-term-2", "max_issues_repo_head_hexsha": "ebed581914957f1ab615edfedea0052dc55b0939", "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": "P1-Extended-Kalman-Filter/class-notes/jacobian-matrix/src/jacobian-matrix.cpp", "max_forks_repo_name": "Deborah-Digges/SDC-ND-term-2", "max_forks_repo_head_hexsha": "ebed581914957f1ab615edfedea0052dc55b0939", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2017-05-28T20:36:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-27T09:01:54.000Z", "avg_line_length": 20.6666666667, "max_line_length": 78, "alphanum_fraction": 0.5395894428, "num_tokens": 460, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012701768145, "lm_q2_score": 0.7634837527911057, "lm_q1q2_score": 0.7221039031491888}}
{"text": "#include <NTL/ZZ.h>\n#include <NTL/ZZ_p.h>\n\n/**\n * Get most significant byte of n.\n * @param n\n * @return only the most significant byte of n set\n */\nuint64_t msb(uint64_t n) {\n    if (n == 0)\n        return 0;\n\n    uint64_t tmp;\n    tmp = n >> (uint) 1;\n\n    uint64_t mask = 1;\n    while (tmp != 0) {\n        tmp >>= (uint) 1;\n        mask <<= (uint) 1;\n    }\n\n    return mask;\n}\n\n/**\n * Algorithm by Marc Joye and Jean-Jacques Quisquater in Efficient computation of full Lucas sequences.\n */\nNTL::ZZ fibonacci1(uint64_t n) {\n    if (n == 0)\n        return (NTL::ZZ) 0;\n\n    NTL::ZZ Uh;\n    Uh = 1;\n    NTL::ZZ Vl;\n    Vl = 2;\n    NTL::ZZ Vh;\n    Vh = 1;\n    NTL::ZZ Ql;\n    Ql = 1;\n    NTL::ZZ Qh;\n    Qh = 1;\n\n    uint64_t s = 0;\n    while (n % 2 == 0) {\n        n /= 2;\n        s++;\n    }\n\n    uint64_t mask = msb(n);\n    while (mask != 1) {\n        Ql = Ql * Qh;\n        if (n & mask) {\n            Qh = -Ql;\n            Uh = Uh * Vh;\n            Vl = Vh * Vl - Ql;\n            Vh = Vh * Vh - 2*Qh; // mistake in the original paper\n        }\n        else {\n            Qh = Ql;\n            Uh = Uh * Vl - Ql;\n            Vh = Vh * Vl - Ql;\n            Vl = Vl * Vl - 2 * Ql;\n        }\n\n        mask >>= (uint) 1;\n    }\n\n    Ql = Ql * Qh;\n    Qh = -Ql;\n    Uh = Uh * Vl - Ql;\n    Vl = Vh * Vl - Ql;\n    Ql = Ql * Qh;\n\n    for (uint64_t i = 1; i <= s; i++) {\n        Uh = Uh * Vl;\n        Vl = Vl * Vl - 2*Ql;\n        Ql = Ql * Ql;\n    }\n\n    return Uh;\n}\n\n/**\n * Algorithm by Aleksey Koval in On Lucas Sequences Computation.\n */\nNTL::ZZ fibonacci2(uint64_t n) {\n    NTL::ZZ V_l;\n    V_l = 2;\n    NTL::ZZ V_h;\n    V_h = 1;\n\n    NTL::ZZ Q_l;\n    Q_l = 1;\n    NTL::ZZ Q_h;\n    Q_h = 1;\n\n    uint64_t mask = msb(n);\n    while (mask != 0) {\n        Q_l = Q_l * Q_h;\n        if (n & mask) {\n            Q_h = -Q_l;\n            V_l = V_h * V_l - Q_l;\n            V_h = V_h * V_h - 2 * Q_h;\n        }\n        else {\n            Q_h = Q_l;\n            V_h = V_h * V_l - Q_l;\n            V_l = V_l * V_l - 2 * Q_h;\n        }\n\n        mask >>= (uint) 1;\n    }\n\n    return (2 * V_h - V_l) / 5;\n}\n\n/**\n * Algorithm derived from matrix multiplication.\n */\nNTL::ZZ fibonacci3(uint64_t n) {\n    NTL::ZZ x;\n    x = 0;\n    NTL::ZZ y;\n    y = 1;\n\n    NTL::ZZ tmp;\n\n    uint64_t mask = msb(n);\n    while (mask != 0) {\n        tmp = x;\n        x = x*(2*y-x);\n        y = (tmp * tmp + y * y);\n\n        if (n & mask) {\n            tmp = x;\n            x = y;\n            y = (tmp + y);\n        }\n\n        mask >>= (uint) 1;\n    }\n\n    return x;\n}\n\n/**\n * Adjusted algorithm derived from matrix multiplication.\n */\nNTL::ZZ fibonacci4(uint64_t n) {\n    NTL::ZZ x;\n    x = 0;\n    NTL::ZZ y;\n    y = 1;\n\n    NTL::ZZ x2;\n    NTL::ZZ y2;\n\n    uint64_t mask = msb(n);\n    while (mask != 0) {\n        x2 = x*x;\n        y2 = y*y;\n\n        if (n & mask) {\n            y = 2*x*y + y2;\n            x = x2+y2;\n        }\n        else {\n            x = 2*x*y - x2;\n            y = x2+y2;\n        }\n\n        mask >>= (uint) 1;\n    }\n\n    return x;\n}\n\n/**\n * Modular version of algorithm by Marc Joye and Jean-Jacques Quisquater in Efficient computation of full Lucas sequences.\n */\nNTL::ZZ fibonacci_mod1(uint64_t n, uint64_t m) {\n    NTL::ZZ_p::init((NTL::ZZ) m);\n\n    if (n == 0)\n        return (NTL::ZZ) 0;\n\n    NTL::ZZ_p Uh;\n    Uh = 1;\n    NTL::ZZ_p Vl;\n    Vl = 2;\n    NTL::ZZ_p Vh;\n    Vh = 1;\n    NTL::ZZ_p Ql;\n    Ql = 1;\n    NTL::ZZ_p Qh;\n    Qh = 1;\n\n    uint64_t s = 0;\n    while (n % 2 == 0) {\n        n /= 2;\n        s++;\n    }\n\n    uint64_t mask = msb(n);\n    while (mask != 1) {\n        Ql = Ql * Qh;\n        if (n & mask) {\n            Qh = -Ql;\n            Uh = Uh * Vh;\n            Vl = Vh * Vl - Ql;\n            Vh = Vh * Vh - 2*Qh; // mistake in the original paper\n        }\n        else {\n            Qh = Ql;\n            Uh = Uh * Vl - Ql;\n            Vh = Vh * Vl - Ql;\n            Vl = Vl * Vl - 2 * Ql;\n        }\n\n        mask >>= (uint) 1;\n    }\n\n    Ql = Ql * Qh;\n    Qh = -Ql;\n    Uh = Uh * Vl - Ql;\n    Vl = Vh * Vl - Ql;\n    Ql = Ql * Qh;\n\n    for (uint64_t i = 1; i <= s; i++) {\n        Uh = Uh * Vl;\n        Vl = Vl * Vl - 2*Ql;\n        Ql = Ql * Ql;\n    }\n\n    return rep(Uh);\n}\n\n/**\n * Modular version of algorithm by Aleksey Koval in On Lucas Sequences Computation.\n */\nNTL::ZZ fibonacci_mod2(uint64_t n, uint64_t m) {\n    NTL::ZZ_p::init((NTL::ZZ) m);\n\n    NTL::ZZ_p V_l;\n    V_l = 2;\n    NTL::ZZ_p V_h;\n    V_h = 1;\n\n    NTL::ZZ_p Q_l;\n    Q_l = 1;\n    NTL::ZZ_p Q_h;\n    Q_h = 1;\n\n    uint64_t tmp;\n    tmp = n >> (uint) 1;\n\n    uint64_t mask = 1;\n    while (tmp != 0) {\n        tmp >>= (uint) 1;\n        mask <<= (uint) 1;\n    }\n\n    while (mask != 0) {\n        Q_l = Q_l * Q_h;\n        if (n & mask) {\n            Q_h = -Q_l;\n            V_l = V_h * V_l - Q_l;\n            V_h = V_h * V_h - 2 * Q_h;\n        }\n        else {\n            Q_h = Q_l;\n            V_h = V_h * V_l - Q_l;\n            V_l = V_l * V_l - 2 * Q_h;\n        }\n\n        mask >>= (uint) 1;\n    }\n\n    return rep((2 * V_h - V_l) / 5);  // fails if 5 divides m\n}\n\n/**\n * Modular version of algorithm derived from matrix multiplication.\n */\nNTL::ZZ fibonacci_mod3(uint64_t n, uint64_t m) {\n    NTL::ZZ_p::init((NTL::ZZ) m);\n\n    NTL::ZZ_p x;\n    x = 0;\n    NTL::ZZ_p y;\n    y = 1;\n\n    NTL::ZZ_p tmp;\n\n    uint64_t mask = msb(n);\n    while (mask != 0) {\n        tmp = x;\n        x = x*(2*y-x);\n        y = (tmp * tmp + y * y);\n\n        if (n & mask) {\n            tmp = x;\n            x = y;\n            y = (tmp + y);\n        }\n\n        mask >>= (uint) 1;\n    }\n\n    return rep(x);\n}\n\n/**\n * Modular version of adjusted algorithm derived from matrix multiplication.\n */\nNTL::ZZ fibonacci_mod4(uint64_t n, uint64_t m) {\n    NTL::ZZ_p::init((NTL::ZZ) m);\n\n    NTL::ZZ_p x;\n    x = 0;\n    NTL::ZZ_p y;\n    y = 1;\n\n    uint64_t tmp;\n    tmp = n >> (uint) 1;\n\n    uint64_t mask = 1;\n    while (tmp != 0) {\n        tmp >>= (uint) 1;\n        mask <<= (uint) 1;\n    }\n\n    NTL::ZZ_p x2;\n    NTL::ZZ_p y2;\n\n    while (mask != 0) {\n        x2 = x*x;\n        y2 = y*y;\n\n        if (n & mask) {\n            y = 2*x*y + y2;\n            x = x2+y2;\n        }\n        else {\n            x = 2*x*y - x2;\n            y = x2+y2;\n        }\n\n        mask >>= (uint) 1;\n    }\n\n    return rep(x);\n}", "meta": {"hexsha": "f182fd2754137dcc5f4320231a216c5ee86f260d", "size": 6248, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "alg_cmp/fibonacci.hpp", "max_stars_repo_name": "okrcma/pseudoprimes", "max_stars_repo_head_hexsha": "a700c3dd2d16e11bb460314be7683828411e0458", "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": "alg_cmp/fibonacci.hpp", "max_issues_repo_name": "okrcma/pseudoprimes", "max_issues_repo_head_hexsha": "a700c3dd2d16e11bb460314be7683828411e0458", "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": "alg_cmp/fibonacci.hpp", "max_forks_repo_name": "okrcma/pseudoprimes", "max_forks_repo_head_hexsha": "a700c3dd2d16e11bb460314be7683828411e0458", "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.6997167139, "max_line_length": 122, "alphanum_fraction": 0.408290653, "num_tokens": 2287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008904, "lm_q2_score": 0.7981867873410141, "lm_q1q2_score": 0.7220801042785091}}
{"text": "//          Copyright Carl Philipp Reh 2009 - 2016.\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#include <fcppt/math/interpolation/linear.hpp>\n#include <fcppt/math/interpolation/trigonometric.hpp>\n#include <fcppt/math/vector/arithmetic.hpp>\n#include <fcppt/math/vector/length.hpp>\n#include <fcppt/math/vector/object_impl.hpp>\n#include <fcppt/math/vector/static.hpp>\n#include <fcppt/preprocessor/disable_gcc_warning.hpp>\n#include <fcppt/preprocessor/pop_warning.hpp>\n#include <fcppt/preprocessor/push_warning.hpp>\n#include <fcppt/config/external_begin.hpp>\n#include <boost/test/unit_test.hpp>\n#include <cmath>\n#include <fcppt/config/external_end.hpp>\n\n\nnamespace\n{\ntypedef\nfcppt::math::vector::static_<double,2>\nvector2;\n\ndouble const epsilon = 0.001;\n}\n\nFCPPT_PP_PUSH_WARNING\nFCPPT_PP_DISABLE_GCC_WARNING(-Weffc++)\n\nBOOST_AUTO_TEST_CASE(linear_interpolation)\n{\nFCPPT_PP_POP_WARNING\n\n\tBOOST_CHECK(\n\t\tstd::abs(\n\t\t\tfcppt::math::interpolation::linear(\n\t\t\t\t0.0,\n\t\t\t\t1.0,\n\t\t\t\t2.0) - 1.0) < epsilon);\n\n\tBOOST_CHECK(\n\t\tstd::abs(\n\t\t\tfcppt::math::interpolation::linear(\n\t\t\t\t1.0,\n\t\t\t\t1.0,\n\t\t\t\t2.0) - 2.0) < epsilon);\n\n\tBOOST_CHECK(\n\t\tstd::abs(\n\t\t\tfcppt::math::interpolation::linear(\n\t\t\t\t0.5,\n\t\t\t\t1.0,\n\t\t\t\t2.0) - 1.5) < epsilon);\n\n\tBOOST_CHECK(\n\t\tstd::abs(\n\t\t\tfcppt::math::interpolation::linear(\n\t\t\t\t0.25,\n\t\t\t\t1.0,\n\t\t\t\t2.0) - 1.25) < epsilon);\n\n\t// One test for vectors\n\tBOOST_CHECK(\n\t\tfcppt::math::vector::length(\n\t\t\tfcppt::math::interpolation::linear(\n\t\t\t\t0.25,\n\t\t\t\tvector2(1.0,1.0),\n\t\t\t\tvector2(2.0,2.0)) - vector2(1.25,1.25)) < epsilon);\n}\n\nFCPPT_PP_PUSH_WARNING\nFCPPT_PP_DISABLE_GCC_WARNING(-Weffc++)\n\nBOOST_AUTO_TEST_CASE(trigonometric_interpolation)\n{\nFCPPT_PP_POP_WARNING\n\n\tBOOST_CHECK(\n\t\tstd::abs(\n\t\t\tfcppt::math::interpolation::trigonometric(\n\t\t\t\t0.0,\n\t\t\t\t1.0,\n\t\t\t\t2.0) - 1.0) < epsilon);\n\n\tBOOST_CHECK(\n\t\tstd::abs(\n\t\t\tfcppt::math::interpolation::trigonometric(\n\t\t\t\t1.0,\n\t\t\t\t1.0,\n\t\t\t\t2.0) - 2.0) < epsilon);\n\n\tBOOST_CHECK(\n\t\tstd::abs(\n\t\t\tfcppt::math::interpolation::trigonometric(\n\t\t\t\t0.5,\n\t\t\t\t1.0,\n\t\t\t\t2.0) - 1.5) < epsilon);\n\n\t// One test for vectors\n\tBOOST_CHECK(\n\t\tfcppt::math::vector::length(\n\t\t\tfcppt::math::interpolation::trigonometric(\n\t\t\t\t1.0,\n\t\t\t\tvector2(1.0,1.0),\n\t\t\t\tvector2(2.0,2.0)) - vector2(2.0,2.0)) < epsilon);\n}\n", "meta": {"hexsha": "99de149e4349dbdbfcc02011054fc85391fb3321", "size": 2355, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/math/interpolation.cpp", "max_stars_repo_name": "vinzenz/fcppt", "max_stars_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_stars_repo_licenses": ["BSL-1.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": "test/math/interpolation.cpp", "max_issues_repo_name": "vinzenz/fcppt", "max_issues_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_issues_repo_licenses": ["BSL-1.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": "test/math/interpolation.cpp", "max_forks_repo_name": "vinzenz/fcppt", "max_forks_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.2162162162, "max_line_length": 61, "alphanum_fraction": 0.6777070064, "num_tokens": 801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505325302034, "lm_q2_score": 0.7981867801399694, "lm_q1q2_score": 0.7220800957121917}}
{"text": "#include <stan/math/rev/scal.hpp>\n#include <gtest/gtest.h>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <test/unit/math/rev/scal/fun/nan_util.hpp>\n#include <test/unit/math/rev/scal/util.hpp>\n\nTEST(AgradRev,atan2_var_var) {\n  AVAR a = 1.2;\n  AVAR b = 3.9;\n  AVAR f = atan2(a,b);\n  EXPECT_FLOAT_EQ(atan2(1.2,3.9),f.val());\n\n  AVEC x = createAVEC(a,b);\n  VEC g;\n  f.grad(x,g);\n  EXPECT_FLOAT_EQ(3.9 / (1.2 * 1.2 + 3.9 * 3.9), g[0]);\n  EXPECT_FLOAT_EQ(-1.2 / (1.2 * 1.2 + 3.9 * 3.9), g[1]);\n}\n\nTEST(AgradRev,atan2_dvd) {\n  AVAR sigma = 1;\n  AVEC x = createAVEC(sigma);\n  AVAR f = atan2(1.0,sigma) / 3.14;\n  VEC g;\n  f.grad(x,g);\n\n  AVAR sigma1 = 1;\n  AVEC x1 = createAVEC(sigma1);\n  AVAR f1 = atan2(1.0,sigma1);\n  VEC g1;\n  f1.grad(x1,g1);\n\n  EXPECT_FLOAT_EQ(3.14 * g[0],g1[0]);\n}\nTEST(AgradRev,atan2_var_var__integration) {\n  double c = 5.0;\n  AVAR a = 1.2;\n  AVAR b = 3.9;\n  AVAR f = atan2(a,b) * c;\n  EXPECT_FLOAT_EQ(atan2(1.2,3.9)*c,f.val());\n\n  AVEC x = createAVEC(a,b);\n  VEC g;\n  f.grad(x,g);\n  EXPECT_FLOAT_EQ(3.9 / (1.2 * 1.2 + 3.9 * 3.9) * c, g[0]);\n  EXPECT_FLOAT_EQ(-1.2 / (1.2 * 1.2 + 3.9 * 3.9) * c, g[1]);\n}\n\n\nTEST(AgradRev,atan2_var_double) {\n  AVAR a = 1.2;\n\n  double b = 3.9;\n  AVAR f = atan2(a,b);\n  EXPECT_FLOAT_EQ(atan2(1.2,3.9),f.val());\n\n  AVEC x = createAVEC(a);\n  VEC g;\n  f.grad(x,g);\n  EXPECT_FLOAT_EQ(3.9 / (1.2 * 1.2 + 3.9 * 3.9), g[0]);\n}\n\nTEST(AgradRev,atan2_double_var) {\n  double a = 1.2;\n  AVAR b = 3.9;\n  AVAR f = atan2(a,b);\n  EXPECT_FLOAT_EQ(atan2(1.2,3.9),f.val());\n\n  AVEC x = createAVEC(b);\n  VEC g;\n  f.grad(x,g);\n  EXPECT_FLOAT_EQ(-1.2 / (1.2 * 1.2 + 3.9 * 3.9), g[0]);\n}\n\nstruct atan2_fun {\n  template <typename T0, typename T1>\n  inline \n  typename stan::return_type<T0,T1>::type\n  operator()(const T0& arg1,\n             const T1& arg2) const {\n    return atan2(arg1,arg2);\n  }\n};\n\nTEST(AgradRev, atan2_nan) {\n  atan2_fun atan2_;\n  test_nan(atan2_,3.0,5.0,false,true);\n\n}\n\nTEST(AgradRev, check_varis_on_stack) {\n  AVAR a = 1.2;\n  AVAR b = 3.9;\n  test::check_varis_on_stack(stan::math::atan2(a, b));\n  test::check_varis_on_stack(stan::math::atan2(a, 3.9));\n  test::check_varis_on_stack(stan::math::atan2(1.2, b));\n}\n", "meta": {"hexsha": "30c3b4ed521beb802f74140181069de8642a2b2a", "size": 2175, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/rev/scal/fun/atan2_test.cpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "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": "cmdstan/stan/lib/stan_math/test/unit/math/rev/scal/fun/atan2_test.cpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "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": "cmdstan/stan/lib/stan_math/test/unit/math/rev/scal/fun/atan2_test.cpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "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.193877551, "max_line_length": 60, "alphanum_fraction": 0.6068965517, "num_tokens": 929, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314647623015, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.7219955456544637}}
{"text": "#include <boost/math/distributions/normal.hpp>\n#include <boost/math/distributions/students_t.hpp>\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <map>\n#include <utility>\n#include <vector>\n// this header for all except for ch8\n// MIT LICENSE\n#ifndef STATISTICS_HPP\n#define STATISTICS_HPP\nusing namespace std;\n#define yes true\n#define no false\n\ndouble genPValue(double z_value, bool isTwoTail = false, bool tailInvertSign = false) {\n    // need to add two tail test!\n    // add bool isTwotail = false\n    // this is the conjugate function of genZValue\n    boost::math::normal Ndistribution(0, 1);\n    auto P = boost::math::cdf(boost::math::complement(Ndistribution, fabs(z_value)));\n    if (isTwoTail && tailInvertSign)\n        throw \"error range\";\n    if (tailInvertSign)\n        P = 1 - P;\n    if (isTwoTail)\n        P *= 2;\n    return P;\n}\n\ndouble genPValue(double degree, double t_value, bool isTwoTail = false, bool tailInvertSign = false) {\n    // this is the conjugate function of genTValue\n    // @degree: the degree of freedom\n    boost::math::students_t Tdistribution(degree);\n    auto P = boost::math::cdf(boost::math::complement(Tdistribution, fabs(t_value)));\n    if (isTwoTail && tailInvertSign)\n        throw \"error range\";\n    if (tailInvertSign)\n        P = 1 - P;\n    if (isTwoTail)\n        P *= 2;\n    return P;\n}\n\ndouble genZValue(double subscript, bool isSingleTail) {\n    /*\n    * @subscript: the score below the \"z\", which means the cumulative distribution function of the area. \n    *             if subscript is negative meaning it is left tail, possitive otherwise\n    * @isSingleTail: is only sigle tail of the reject area\n    * return the z-score which lookup from the z-table \n    */\n    boost::math::normal Ndistribution(0, 1);\n    if (!isSingleTail)\n        subscript /= 2;\n    auto Z = boost::math::quantile(boost::math::complement(Ndistribution, fabs(subscript)));\n    if (subscript < 0)\n        Z = -Z;\n    return Z;\n}\n\ndouble genTValue(int degree, double upperTailArea) {\n    boost::math::students_t Tdistribution(degree);\n    auto T = boost::math::quantile(boost::math::complement(Tdistribution, upperTailArea));\n    return T;\n}\n\ntemplate <typename Iteratable>\ndouble genMean(Iteratable& _dataSet) {\n    double sum = 0;\n    for (auto i : _dataSet)\n        sum += i;\n    return sum / _dataSet.size();\n}\n\ntemplate <typename Iteratable>\ndouble genSampleStandardDeviation(Iteratable& _dataSet, double sampleMean, double size) {\n    double sxx = 0;\n    for (auto i : _dataSet)\n        sxx += (i - sampleMean) * (i - sampleMean);\n    return sqrt(1 / (size - 1) * sxx);\n}\n\ndouble genPercentageStandardDeviation(double p, int sampleSize) {\n    return sqrt(p * (1 - p) / sampleSize);\n}\n\nint twoPopulationDegreeFreedom(double ssd1, double ssd2, int n1, int n2) {\n    auto sampleVariation1 = (ssd1 * ssd1 / n1);\n    auto sampleVariation2 = (ssd2 * ssd2 / n2);\n    return (sampleVariation1 + sampleVariation2) * (sampleVariation1 + sampleVariation2) /\n           (sampleVariation1 * sampleVariation1 / (n1 - 1) + sampleVariation2 * sampleVariation2 / (n2 - 1));\n}\ntemplate <typename Iteratable>\nint twoPopulationDegreeFreedom(Iteratable& _dataSet1, Iteratable& _dataSet2) {\n    auto ssd1 = genSampleStandardDeviation(_dataSet1, genMean(_dataSet1), _dataSet1.size());\n    auto ssd2 = genSampleStandardDeviation(_dataSet2, genMean(_dataSet2), _dataSet2.size());\n    return twoPopulationDegreeFreedom(ssd1, ssd2, _dataSet1.size(), _dataSet2.size());\n}\n\ndouble errorRadius(vector<double>& _dataSet, int degree, int sampleSize, double upperTailArea) {\n    double mean = genMean(_dataSet);\n    double ssd = genSampleStandardDeviation(_dataSet, mean, sampleSize);\n    return ssd / sqrt(sampleSize) * genTValue(degree, upperTailArea);\n}\n\ndouble errorRadius(vector<double>& _dataSet, double upperTailArea = 0.025) {\n    /*\n    * giving data set and the upper tail area of Student-T distribution\n    * return the error radius\n    * for too lazy to only input data set\n    */\n    int sampleSize = _dataSet.size();\n    return errorRadius(_dataSet, sampleSize - 1, sampleSize, upperTailArea);\n}\n\ndouble errorRadius(double knownSigma, double alpha, int sampleSize, bool isSingleTail = false, bool isSample = false) {\n    /*\n    * @knownSigma: the population sigma, which over sqrt(n)\n    * giving alpha return the error radius for known Sigma of Z distribution\n    * return the error radius\n    */\n\n    if (isSample) {\n        if (!isSingleTail)\n            alpha /= 2;\n        return knownSigma / sqrt(sampleSize) * genTValue(sampleSize - 1, alpha);\n    }\n    return knownSigma / sqrt(sampleSize) * genZValue(alpha, isSingleTail);\n}\n\npair<double, double> genConfidenceInterval(double theta, double errorRadius, int tailOrient = 0) {\n    /*\n     * @theta: the sample variable\n     * @errorRadius: a radius of error, which might greater than 1,\n     *               means the standardDeviation times (z or t) over sqrt(n)\n     * @tailOrient: if (tailOrient > 0) will reject right tail\n     *              else if (tailOrient < 0) will reject left tail\n     *              else will reject two tail\n     */\n    if (tailOrient > 0)\n        return make_pair(-numeric_limits<double>::infinity(), theta + errorRadius);\n    else if (tailOrient < 0)\n        return make_pair(theta - errorRadius, numeric_limits<double>::infinity());\n    else\n        return make_pair(theta - errorRadius, theta + errorRadius);\n}\n\nvector<pair<double, double>> invertInterval(pair<double, double> originInterval) {\n    if (originInterval.first == -numeric_limits<double>::infinity())\n        return {make_pair(originInterval.second, numeric_limits<double>::infinity())};\n    else if (originInterval.second == numeric_limits<double>::infinity())\n        return {make_pair(-numeric_limits<double>::infinity(), originInterval.first)};\n    else\n        return {make_pair(-numeric_limits<double>::infinity(), originInterval.first),\n                make_pair(originInterval.second, numeric_limits<double>::infinity())};\n}\n\npair<double, double> standardlizeInterval(pair<double, double> originInterval, double mu, double standardDeviation) {\n    /**\n     * @originInterval: the interval need to be standardlized\n     * @mu: the mean\n     * @standardDeviation: the standard deviation of mu\n     */\n    return make_pair((originInterval.first - mu) / standardDeviation, (originInterval.second - mu) / standardDeviation);\n}\n\ndouble intervalProbability(pair<double, double> standardlizedInterval) {\n    /*\n    * this will return the probability with z distribution in some interval\n    * @standardlizedInterval: the standardlized interval which want to get the probability\n    */\n    double leftTail = genPValue(standardlizedInterval.first, false, false),\n           rightTail = genPValue(standardlizedInterval.second, false, false);\n    return 1 - leftTail - rightTail;\n}\n\ntemplate <typename T, typename S>\nostream& operator<<(ostream& os, const pair<T, S>& v) {\n    pair<char, char> boundSign('[', ']');\n    if (v.first == -numeric_limits<double>::infinity())\n        boundSign.first = '(';\n    if (v.second == numeric_limits<double>::infinity())\n        boundSign.second = ')';\n    os << boundSign.first << v.first << \", \" << v.second << boundSign.second;\n    return os;\n}\n\nnamespace needingSampleSize {\nint p(double alpha, double p = 0.5, double marginError = 0.95) {\n    /*\n    * @p: the p bar of sample proportions, which might be iid Ber(P) (Bernoulli distribution)\n    * @marginError: the margin error of confidence interval\n    */\n    double q = 1 - p, z = genZValue(alpha, false);\n    auto sampleSize = p * q * z * z / marginError / marginError;\n    return ceil(sampleSize);\n}\n\nint x_bar(double alpha, double knownTheta, double marginError) {\n    /*\n    * @knownTheta: the sigma which is the population standard deviation\n    * @marginError: the margin error of confidence interval\n    */\n    double z = genZValue(alpha, false);\n    auto sampleSize = z * z * knownTheta * knownTheta / marginError / marginError;\n    return ceil(sampleSize);\n}\nint hypothesis(double mu_0, double mu_a, double za, double zb, double sigma) {\n    return ceil(pow((za + zb) * sigma / (mu_0 - mu_a), 2));\n}\n}  // namespace needingSampleSize\n\ndouble testStatistic(double x_bar, double mu_0, double sd, int sampleSize, bool isSample = false) {\n    /**\n     * @x_bar: sampleMean\n     * @sd: standard deviation\n     * @mu_0: the null hypotheses\n     * @sampleSize: the sample size which want to againest the H0\n     * @isSample: Are we not know the population @sd?\n     *          if(false): we don't know the population standard deviation\n     */\n    if (isSample)\n        sampleSize -= 1;\n    return (x_bar - mu_0) / (sd / sqrt(sampleSize));\n}\n\ntemplate <class T>\nstring readSingleLineCSV(vector<T>& _dataSet, string fileName) {\n    /* will return the file's title\n    * read only single line csv file\n    * @_dataSet: a container you want to storge at\n    * @fileName: fileName\n    */\n    ifstream inFile(fileName, ios::in);\n    if (inFile.fail()) {\n        cerr << \"Open file failed\" << endl;\n        return \"\";\n    }\n    string title;\n    T rawdata;\n    getline(inFile, title);\n    while (inFile >> rawdata)\n        _dataSet.push_back(rawdata);\n    inFile.close();\n    return title;\n}\n\ntemplate <class T>\nstring readSingleLineCSV(map<T, int>& proportionDataSet, string fileName) {\n    /* \n    * only for reading proportion Data\n    * will return the file's title\n    * read only single line csv file\n    * @proportionDataSet: a container you want to storge at\n    * @fileName: fileName\n    */\n    ifstream inFile(fileName, ios::in);\n    if (inFile.fail()) {\n        cerr << \"Open file failed\" << endl;\n        return \"\";\n    }\n    string title;\n    T rawData;\n    getline(inFile, title);\n    while (getline(inFile, rawData)) {\n        auto isInMap = proportionDataSet.find(rawData);\n        if (isInMap != proportionDataSet.end())\n            proportionDataSet.at(isInMap->first)++;\n        else\n            proportionDataSet.insert(pair<T, int>(rawData, 1));\n    }\n    inFile.close();\n    return title;\n}\n\nstring readMultiLineCSV(map<string, map<string, int>>& proportionDataSet, string fileName) {\n    // @proportionDataSet: {title, {data, freq}}\n    // return file name\n    ifstream inFile(fileName, ios::in);\n    if (inFile.fail()) {\n        cerr << \"Open file failed\" << endl;\n        return \"\";\n    }\n    string titles, singleLine;\n    vector<string> titlesContainer;\n    getline(inFile, titles);\n    for (auto index = titles.find(','); index != string::npos; index = titles.find(',')) {\n        string firstSubstring(titles.substr(0, index));\n        titlesContainer.push_back(firstSubstring);\n        titles.erase(0, firstSubstring.length() + 1);\n    }\n    titlesContainer.push_back(titles);  //push last title\n\n    while (getline(inFile, singleLine)) {\n        for (auto i : titlesContainer) {\n            auto index = singleLine.find(',');\n            string tmp;\n            if (index != string::npos)\n                tmp = singleLine.substr(0, index);\n            else\n                tmp = singleLine;  //the last element\n\n            if (tmp.length()) {\n                auto isTitleInTable = proportionDataSet.find(i);\n                if (isTitleInTable != proportionDataSet.end()) {\n                    auto isInMap = isTitleInTable->second.find(tmp);\n                    if (isInMap != isTitleInTable->second.end())\n                        isTitleInTable->second.at(isInMap->first)++;\n                    else\n                        isTitleInTable->second.insert(make_pair(tmp, 1));\n                } else {\n                    auto inMap = make_pair(tmp, 1);\n                    proportionDataSet[i].insert(inMap);\n                }\n            }\n            singleLine.erase(0, tmp.length() + 1);\n        }\n    }\n    inFile.close();\n    return fileName;\n}\n#endif\n", "meta": {"hexsha": "587fbc1bf055b7d1476cfc9b6a5ba6a03173d7dd", "size": 11857, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "statistics.hpp", "max_stars_repo_name": "25077667/statistics_BM_NSYSU", "max_stars_repo_head_hexsha": "2c6c462727d9bf4bcff5844e785fd165a82c5a2d", "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": "statistics.hpp", "max_issues_repo_name": "25077667/statistics_BM_NSYSU", "max_issues_repo_head_hexsha": "2c6c462727d9bf4bcff5844e785fd165a82c5a2d", "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": "statistics.hpp", "max_forks_repo_name": "25077667/statistics_BM_NSYSU", "max_forks_repo_head_hexsha": "2c6c462727d9bf4bcff5844e785fd165a82c5a2d", "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.5956790123, "max_line_length": 120, "alphanum_fraction": 0.6511765202, "num_tokens": 2978, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122313857378, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.7219103217921019}}
{"text": "#include \"utils.hpp\"\n#include <cmath>\n#include <fstream>\n#include <boost/range/numeric.hpp>\n\nusing namespace std;\n\nnamespace delphi::utils {\n\n/**\n * Returns the square of a number.\n */\ndouble sqr(double x) { return x * x; }\n\n/**\n * Returns the sum of a vector of doubles.\n */\ndouble sum(std::vector<double> v) { return boost::accumulate(v, 0.0); }\n\n/**\n * Returns the arithmetic mean of a vector of doubles.\n */\ndouble mean(std::vector<double> v) { return sum(v) / v.size(); }\n\ndouble log_normpdf(double x, double mean, double sd) {\n  double var = pow(sd, 2);\n  double log_denom = -0.5 * log(2 * M_PI) - log(sd);\n  double log_nume = pow(x - mean, 2) / (2 * var);\n\n  return log_denom - log_nume;\n}\n\nnlohmann::json load_json(string filename) {\n  ifstream i(filename);\n  nlohmann::json j = nlohmann::json::parse(i);\n  return j;\n}\n\n} // namespace delphi::utils\n", "meta": {"hexsha": "78523a13f7d7e6731154adb7815a2c22d573aa67", "size": 857, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/utils.cpp", "max_stars_repo_name": "mikiec84/delphi", "max_stars_repo_head_hexsha": "2e517f21e76e334c7dfb14325d25879ddf26d10d", "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": "lib/utils.cpp", "max_issues_repo_name": "mikiec84/delphi", "max_issues_repo_head_hexsha": "2e517f21e76e334c7dfb14325d25879ddf26d10d", "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": "lib/utils.cpp", "max_forks_repo_name": "mikiec84/delphi", "max_forks_repo_head_hexsha": "2e517f21e76e334c7dfb14325d25879ddf26d10d", "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": 21.425, "max_line_length": 71, "alphanum_fraction": 0.6581096849, "num_tokens": 243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480666, "lm_q2_score": 0.7956581049086031, "lm_q1q2_score": 0.7219103186199272}}
{"text": "/*\n    boost::math::fft example 03.\n    \n    FFT plan-like API,\n    default engine\n*/\n\n#include <boost/math/fft/bsl_backend.hpp>\n\n#include <iostream>\n#include <vector>\n#include <complex>\n\nnamespace fft = boost::math::fft;\n\ntemplate<class T>\nvoid print(const std::vector< std::complex<T> >& V)\n{\n    for(auto i=0UL;i<V.size();++i)\n        std::cout << \"V[\" << i << \"] = \" \n            << V[i].real() << \", \" << V[i].imag() << '\\n';\n}\n\nint main()\n{\n    std::vector< std::complex<double> > A{1.0,2.0,3.0,4.0},B(A.size());\n    \n    // default engine, create plan\n    fft::bsl_dft<std::complex<double>> P(A.size());\n    \n    // forward transform, out-of-place\n    P.forward(A.cbegin(),A.cend(),B.begin());\n    \n    print(B);\n    \n    // backward transform, in-place\n    P.backward(B.cbegin(),B.cend(),B.begin());\n    \n    print(B);\n    return 0;\n}\n\n\n", "meta": {"hexsha": "1bb3157e9a35f2470fed8f7f99eec06f1f9d2e0b", "size": 845, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/fft_ex03.cpp", "max_stars_repo_name": "BoostGSoC21/math", "max_stars_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_stars_repo_licenses": ["BSL-1.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": "example/fft_ex03.cpp", "max_issues_repo_name": "BoostGSoC21/math", "max_issues_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 30.0, "max_issues_repo_issues_event_min_datetime": "2021-06-22T12:59:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-02T09:27:49.000Z", "max_forks_repo_path": "example/fft_ex03.cpp", "max_forks_repo_name": "BoostGSoC21/math", "max_forks_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-07T21:15:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-07T21:15:02.000Z", "avg_line_length": 19.2045454545, "max_line_length": 71, "alphanum_fraction": 0.5443786982, "num_tokens": 250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093975331752, "lm_q2_score": 0.8080672227971211, "lm_q1q2_score": 0.7218540439632023}}
{"text": "#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <algorithm>\n#include <iostream>\n#include <vector>\n\nusing namespace std;\nusing namespace Eigen;\n\nint main(int argc, char** argv) {\n  Quaterniond q1(0.35, 0.2, 0.3, 0.1), q2(-0.5, 0.4, -0.1, 0.2);\n  // Always normalize quaternions before using them\n  q1.normalize();\n  q2.normalize();\n  Vector3d t1(0.3, 0.1, 0.1), t2(-0.1, 0.5, 0.3);\n  Vector3d p1(0.5, 0, 0.2);\n\n  // Note here T1w is the transform from the world to frame 1\n  // This will transform a point from world coordinate frame to frame 1\n  // Robot poses generally mean the opposite\n  Isometry3d T1w(q1), T2w(q2);\n  T1w.pretranslate(t1);\n  T2w.pretranslate(t2);\n\n  Vector3d p2 = T2w * T1w.inverse() * p1;\n  cout << endl << p2.transpose() << endl;\n  return 0;\n}\n", "meta": {"hexsha": "8aaf488cc27892adeb12ef0b4d73dcbce4f74021", "size": 776, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch3/examples/coordinateTransform.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/examples/coordinateTransform.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/examples/coordinateTransform.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": 26.7586206897, "max_line_length": 71, "alphanum_fraction": 0.6636597938, "num_tokens": 282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096181702031, "lm_q2_score": 0.7879311881731379, "lm_q1q2_score": 0.7218313399416878}}
{"text": "/*\n * Copyright 2021 MusicScience37 (Kenta Kabashima)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/*!\n * \\file\n * \\brief Test of euclidean_distance class.\n */\n#include \"num_collect/interp/kernel/euclidean_distance.h\"\n\n#include <Eigen/Core>\n#include <catch2/catch_test_macros.hpp>\n#include <catch2/matchers/catch_matchers_floating.hpp>\n\nTEST_CASE(\"num_collect::interp::kernel::euclidean_distance\") {\n    using num_collect::interp::kernel::euclidean_distance;\n\n    SECTION(\"calculate distance of double\") {\n        const auto dist = euclidean_distance<double>();\n        constexpr double var1 = 1.234;\n        constexpr double var2 = 3.1415;\n        constexpr double expected = var2 - var1;\n        REQUIRE_THAT(dist(var1, var2), Catch::Matchers::WithinRel(expected));\n        REQUIRE_THAT(dist(var2, var1), Catch::Matchers::WithinRel(expected));\n    }\n\n    SECTION(\"calculate distance of vectors\") {\n        const auto dist = euclidean_distance<Eigen::Vector3d>();\n        const auto var1 = Eigen::Vector3d(1.234, 2.345, 3.456);\n        const auto var2 = Eigen::Vector3d(1.357, 2.468, 3.579);\n        const double expected = (var1 - var2).norm();\n        REQUIRE_THAT(dist(var1, var2), Catch::Matchers::WithinRel(expected));\n        REQUIRE_THAT(dist(var2, var1), Catch::Matchers::WithinRel(expected));\n    }\n}\n", "meta": {"hexsha": "ea3b861a9a3a340588f2ffbe5b9c1ef7d6e5d876", "size": 1828, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/units/interp/kernel/euclidean_distance_test.cpp", "max_stars_repo_name": "MusicScience37/numerical-collection-cpp", "max_stars_repo_head_hexsha": "490c24aae735ba25f1060b2941cff39050a41f8f", "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": "test/units/interp/kernel/euclidean_distance_test.cpp", "max_issues_repo_name": "MusicScience37/numerical-collection-cpp", "max_issues_repo_head_hexsha": "490c24aae735ba25f1060b2941cff39050a41f8f", "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": "test/units/interp/kernel/euclidean_distance_test.cpp", "max_forks_repo_name": "MusicScience37/numerical-collection-cpp", "max_forks_repo_head_hexsha": "490c24aae735ba25f1060b2941cff39050a41f8f", "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": 38.8936170213, "max_line_length": 77, "alphanum_fraction": 0.7018599562, "num_tokens": 444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934408, "lm_q2_score": 0.8289388125473629, "lm_q1q2_score": 0.7216718603151465}}
{"text": "#pragma once\n\n#include \"random_engine.hpp\"\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/optional.hpp>\n\nnamespace cryptb\n{\n\tclass rsa\n\t{\n\t\t// Private key- for decrypting / digital signing\n\t\t// DON'T SHARE d WITH THE CLIENT!\n\t\t// Tends to be a number with around 2048 bits.\n\t\tboost::multiprecision::cpp_int d{ 0 };\n\n\t\t// It's completely safe to share e and N with the entire world.\n\t\t// In fact, you should.\n\n\t\t// Public key- for encrypting / verifying digital signature\n\t\t// Tends to be a very small number. Choosing the number 3 for example, is common.\n\t\tboost::multiprecision::cpp_int e{ 0 };\n\n\t\t// Public key- for everything. N is needed for all operations.\n\t\t// Tends to be a number with about 4096 bits.\n\t\tboost::multiprecision::cpp_int N{ 0 };\n\n\t\t// A pure mathematical function to solve for d such that:\n\t\t// ((e * d) modulo PhiN) == 1\n\t\t// e and PhiN must already be coprime.\n\t\tstatic boost::multiprecision::cpp_int findd(const boost::multiprecision::cpp_int& PhiN, const boost::multiprecision::cpp_int& e);\n\n\tpublic:\n\t\trsa(const rsa&) = default;\n\t\trsa(rsa&&) = default;\n\t\trsa& operator=(const rsa&) = default;\n\t\trsa& operator=(rsa&&) = default;\n\n\t\t// Constructor for generating RSA public-private key pair using the given random engine.\n\t\t//\n\t\t// When \"num_bytes_in_prime_number\" == 128 that's 2048-bit RSA\n\t\t// Should take a second and a half (very expensive function, call on an asynchronous thread).\n\t\t// \n\t\t// \"num_bytes_in_prime_number\" must be at least 2\n\t\t//\n\t\trsa(random_engine& rand, const int num_bytes_in_prime_number = 128);\n\n\t\t// Constructor for loading RSA public-private key pairs from values\n\t\trsa(boost::multiprecision::cpp_int&& e, boost::multiprecision::cpp_int&& d, boost::multiprecision::cpp_int&& N) :\n\t\t\te(std::move(e)), d(std::move(d)), N(std::move(N)) {}\n\n\t\t// Private secret key, don't share.\n\t\tconst boost::multiprecision::cpp_int& get_d() const\n\t\t{\n\t\t\treturn this->d;\n\t\t}\n\n\t\t// Public key, no danger. Allowed to reveal to the entire world.\n\t\tconst boost::multiprecision::cpp_int& get_e() const\n\t\t{\n\t\t\treturn this->e;\n\t\t}\n\n\t\t// Public key, no danger. Allowed to reveal to the entire world.\n\t\tconst boost::multiprecision::cpp_int& get_N() const\n\t\t{\n\t\t\treturn this->N;\n\t\t}\n\n\t\t// powm(a, b, c) == power(a, b) modulo c\n\t\t// When computing powm in one operation that can reduce the\n\t\t// computation time down from millions of years to mere microseconds.\n\t\t//\n\t\t// Technically powm treats negative exponents differently than power(a, b)\n\t\t// but in the function \"rsa::findd()\" we made sure that the returned\n\t\t// d is positive so in our use case we're only dealing with positive numbers.\n\t\t//\n\n\t\t// \"original_message\" should either be a large random number\n\t\t// otherwise the entire algorithm will be insecure.\n\t\t// That's because if the same clear-text message is sent to e or more recipients in an encrypted way,\n\t\t// and the receivers share the same exponent e, but different p, q, and therefore n,\n\t\t// then it's easy to decrypt the original clear-text message via the Chinese remainder theorem.\n\t\t// \n\t\t// Basically: only use the \"encrypt\" function with an original_message that is a large\n\t\t// random number.\n\t\t//\n\t\t// You should check that:\n\t\t// 0 <= \"original_message\" < N\n\t\t// and that:\n\t\t// is_valid_public_key(e, N) == true\n\t\t// Otherwise the function will return boost::none\n\t\tstatic boost::optional<boost::multiprecision::cpp_int> encrypt(\n\t\t\tconst boost::multiprecision::cpp_int& original_message,\n\t\t\tconst boost::multiprecision::cpp_int& e,\n\t\t\tconst boost::multiprecision::cpp_int& N)\n\t\t{\n\t\t\tif (!rsa::is_valid_public_key(e, N) || original_message >= N || original_message < 0)\n\t\t\t\treturn boost::none;\n\t\t\treturn static_cast<boost::multiprecision::cpp_int>(boost::multiprecision::powm(original_message, e, N));\n\t\t}\n\n\t\t// You should check that:\n\t\t// 0 <= \"encrypted_message\" < this->N\n\t\t// Otherwise the function will return boost::none\n\t\tboost::optional<boost::multiprecision::cpp_int> decrypt(const boost::multiprecision::cpp_int& encrypted_message)\n\t\t{\n\t\t\tif (encrypted_message >= this->N || encrypted_message < 0)\n\t\t\t\treturn boost::none;\n\t\t\treturn static_cast<boost::multiprecision::cpp_int>(boost::multiprecision::powm(encrypted_message, this->d, this->N));\n\t\t}\n\n\t\t// RSA digital signature.\n\t\t// message_hash must be a cryptographic hash of a message\n\t\t// and not the message itself.\n\t\t// Otherwise the digital signature won't be secure.\n\t\t// \n\t\t// You should check that:\n\t\t// 0 <= \"message_hash\" < this->N\n\t\t// Otherwise the function will return boost::none\n\t\tboost::optional<boost::multiprecision::cpp_int> sign(const boost::multiprecision::cpp_int& message_hash)\n\t\t{\n\t\t\t// It's the same algorithm. Isn't that convenient!\n\t\t\treturn this->decrypt(message_hash);\n\t\t}\n\n\t\t// Verify an RSA digital signature.\n\t\tstatic bool is_valid_signature(\n\t\t\tconst boost::multiprecision::cpp_int& message_hash,\n\t\t\tconst boost::multiprecision::cpp_int& signature_of_hash,\n\t\t\tconst boost::multiprecision::cpp_int& e,\n\t\t\tconst boost::multiprecision::cpp_int& N)\n\t\t{\n\t\t\t// It's the same algorithm. Isn't that convenient!\n\t\t\tconst boost::optional<boost::multiprecision::cpp_int> result = rsa::encrypt(signature_of_hash, e, N);\n\t\t\tif (result == boost::none)\n\t\t\t\treturn false;\n\t\t\t// If the signature matches then it's legit.\n\t\t\treturn result.get() == message_hash;\n\t\t}\n\n\t\t// Recommended to check the validity of public keys taken\n\t\t// from an untrusted source.\n\t\t// We wouldn't want to store an invalid public key\n\t\t// in the database of known public keys.\n\t\t// That would cause functions such as rsa::encrypt\n\t\t// to return boost::none\n\t\tstatic bool is_valid_public_key(\n\t\t\tconst boost::multiprecision::cpp_int& e,\n\t\t\tconst boost::multiprecision::cpp_int& N)\n\t\t{\n\t\t\tif (e < 2 || N < (2*3))\n\t\t\t\treturn false;\n\t\t\treturn true;\n\t\t}\n\t};\n}\n", "meta": {"hexsha": "a99b7322a808454d4601c82725b5c9ee4a8864fe", "size": 5774, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "rsa_cpp/rsa.hpp", "max_stars_repo_name": "BigBIueWhale/rsa_cpp", "max_stars_repo_head_hexsha": "9711456119ec0a79f5931153c32bde2ea4082bb5", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-08T18:16:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T18:16:06.000Z", "max_issues_repo_path": "rsa_cpp/rsa.hpp", "max_issues_repo_name": "BigBIueWhale/rsa_cpp", "max_issues_repo_head_hexsha": "9711456119ec0a79f5931153c32bde2ea4082bb5", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-12-29T18:07:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-08T18:15:42.000Z", "max_forks_repo_path": "rsa_cpp/rsa.hpp", "max_forks_repo_name": "BigBIueWhale/rsa_cpp", "max_forks_repo_head_hexsha": "9711456119ec0a79f5931153c32bde2ea4082bb5", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-12-29T10:42:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-06T13:46:46.000Z", "avg_line_length": 36.7770700637, "max_line_length": 131, "alphanum_fraction": 0.7024593003, "num_tokens": 1572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625069680098, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.7214953808700245}}
{"text": "#define EIGEN_USE_MKL_ALL\n\n#include <iostream>\n\n#include <Eigen/Core>\n\n#include \"../misc.hpp\"\n\n#include \"models/regressors/least_squares_linear_regression.hpp\"\n#include \"models/regressors/ridge_regression.hpp\"\n#include \"models/regressors/optimizable_linear_regressor.hpp\"\n#include \"utils/optimizers/stochastic_gradient_descent.hpp\"\n#include \"utils/loss_functions.hpp\"\n\nvoid benchmark_linear_solvers() {\n\tEigen::MatrixXd XN = Eigen::MatrixXd::Random(100, 100000);\n\tEigen::RowVectorXd YN = Eigen::RowVectorXd::Random(100000);\n\n\tmlt::models::regressors::LeastSquaresLinearRegression<mlt::utils::linear_solvers::SVDSolver> linear_regressor_svd(false);\n\tbenchmark(linear_regressor_svd, XN, YN, 100);\n\tmlt::models::regressors::LeastSquaresLinearRegression<mlt::utils::linear_solvers::LDLTSolver> linear_regressor_ldlt(false);\n\tbenchmark(linear_regressor_ldlt, XN, YN, 100);\n\tstd::cout << std::endl;\n\tmlt::models::regressors::LeastSquaresLinearRegression<mlt::utils::linear_solvers::CGSolver> linear_regressor_cg(false);\n\tbenchmark(linear_regressor_cg, XN, YN, 100);\n\tstd::cout << std::endl;\n\n\tstd::cout << \"Diff: \" << (linear_regressor_svd.coefficients() - linear_regressor_ldlt.coefficients()).squaredNorm() << std::endl;\n\tstd::cout << \"Diff: \" << (linear_regressor_svd.coefficients() - linear_regressor_cg.coefficients()).squaredNorm() << std::endl;\n\tstd::cout << \"Diff: \" << (linear_regressor_ldlt.coefficients() - linear_regressor_cg.coefficients()).squaredNorm() << std::endl;\n}\n\nvoid test_optimizable_linear_regressors() {\n\tauto samples = 100;\n\tEigen::MatrixXd input = Eigen::MatrixXd::Random(3, samples) * 100;\n\tEigen::MatrixXd output = Eigen::MatrixXd::Random(2, samples).array();\n\toutput = (output.array() > 0.0).cast<double>();\n\toutput.row(1) = 1 - output.row(0).array();\n\n\tmlt::utils::optimizers::StochasticGradientDescent<> sgd;\n\tmlt::utils::loss_functions::SquaredLoss loss;\n\n\tmlt::models::regressors::OptimizableLinearRegressor<mlt::utils::loss_functions::SquaredLoss, mlt::utils::optimizers::StochasticGradientDescent<>> model(loss, sgd, 0, false);\n\teval_numerical_gradient(model, Eigen::MatrixXd::Random(2, 3) * 0.05, input, output);\n\n\tmlt::models::regressors::OptimizableLinearRegressor<mlt::utils::loss_functions::SquaredLoss, mlt::utils::optimizers::StochasticGradientDescent<>> model2(loss, sgd, 0, true);\n\teval_numerical_gradient(model2, Eigen::MatrixXd::Random(2, 4) * 0.05, input, output);\n}\n\nvoid lr_examples() {\n\tbenchmark_linear_solvers();\n\n\tEigen::MatrixXd X1(2, 3);\n\tEigen::MatrixXd Y1(1, 3);\n\n\tX1.row(0) << 0, 1, 2;\n\tX1.row(1) << 0, 1, 2;\n\tY1 << 0, 1, 2;\n\n\tmlt::models::regressors::LeastSquaresLinearRegression<> linear_regressor(false);\n\tlinear_regressor.fit(X1, Y1);\n\n\tstd::cout << \"LinearRegression: \" << std::endl;\n\tstd::cout << linear_regressor.coefficients() << std::endl;\n\tif (linear_regressor.fit_intercept()) {\n\tstd::cout << linear_regressor.intercepts() << std::endl;\n\t}\n\tstd::cout << linear_regressor.predict(X1.col(0)) << std::endl;\n\n\tEigen::MatrixXd X2(2, 3);\n\tEigen::MatrixXd Y2(1, 3);\n\n\tX2.row(0) << 0, 0, 1;\n\tX2.row(1) << 0, 0, 1;\n\tY2 << 0, .1, 1;\n\n\tmlt::models::regressors::RidgeRegression<> ridge_regressor(0.5, true);\n\tridge_regressor.fit(X2, Y2);\n\n\tstd::cout << \"RidgeRegression: \" << std::endl;\n\tstd::cout << ridge_regressor.coefficients() << std::endl;\n\tstd::cout << ridge_regressor.intercepts() << std::endl;\n\tstd::cout << ridge_regressor.predict(X2.col(0)) << std::endl;\n\n\tmlt::utils::optimizers::StochasticGradientDescent<> grad_descent(10, 2000, 0.001, 1);\n\tmlt::utils::loss_functions::SquaredLoss loss;\n\tmlt::models::regressors::OptimizableLinearRegressor<mlt::utils::loss_functions::SquaredLoss, mlt::utils::optimizers::StochasticGradientDescent<>> sgd(loss, grad_descent, 0.5, true);\n\n\tsgd.fit(X2, Y2, true);\n\n\tstd::cout << \"OptimizableLinearRegressor<SquaredLoss, SGD>: \" << std::endl;\n\tstd::cout << ridge_regressor.coefficients() << std::endl;\n\tstd::cout << ridge_regressor.intercepts() << std::endl;\n\tstd::cout << sgd.predict(X2.col(0)) << std::endl;\n\n\tstd::cout << \"loss with closed form: \" << sgd.loss(ridge_regressor.all_coefficients(), X2, Y2) << std::endl;\n\tstd::cout << \"loss with SGD: \" << sgd.loss(sgd.all_coefficients(), X2, Y2) << std::endl;\n}", "meta": {"hexsha": "b497b65c9b793861c762d7dd42d557a7b07c95f0", "size": 4208, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/examples/linear_regression.cpp", "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/examples/linear_regression.cpp", "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/examples/linear_regression.cpp", "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": 42.9387755102, "max_line_length": 182, "alphanum_fraction": 0.7250475285, "num_tokens": 1293, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947117065458, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.7214881190326171}}
{"text": "\n#include \"Debug.h\"\n#include \"SolverEigen.h\"\n#include \"SolverTime.h\"\n#include \"ComputerTime.h\"\n#include \"util.h\"\n\n\n//#include <Eigen/SuperLUSupport>\n#include <Eigen/SparseExtra>\n#include <Eigen/IterativeSolvers>\n\n\nextern SolverTime      solverTime;\nextern ComputerTime    computerTime;\n\nusing namespace std;\nusing namespace Eigen;\n\n\n\nvoid SolverEigen::computeConditionNumber()\n{\n/*\n    MatrixXd  globalK;\n    \n    globalK.resize(nRow, nCol);\n    globalK.setZero();\n\n    int k, ii, jj;\n\n    for(k=0; k<mtx.outerSize(); ++k)\n    {\n      for(SparseMatrixXd::InnerIterator it(mtx,k); it; ++it)\n      {\n        ii = it.row();\n        jj = it.col();\n        \n        //cout << ii << '\\t' << jj << '\\t' << it.value() << endl;\n\n        globalK.coeffRef(ii, jj) = it.value();\n      }\n    }\n\n\n    VectorXd sing_vals = globalK.jacobiSvd().singularValues();\n\n    //printf(\"\\n Matrix condition number = %12.6E \\n\", sing_vals(0)/sing_vals(sing_vals.size()-1) );\n    \n    //printf(\"\\n Minimum eigenvalue = %12.6f \\n\", sing_vals.minCoeff() );\n    //printf(\"\\n Minimum eigenvalue = %12.6f \\n\", sing_vals.maxCoeff() );\n    printf(\"\\n Matrix condition number = %12.6E \\n\", sing_vals.maxCoeff() / sing_vals.minCoeff() );\n    printf(\"\\n\\n\\n\\n\");\n*/\n\n  //myCondNumMatlab(mtx);\n\n  return;\n}\n\n\n\n\n\n\n\n", "meta": {"hexsha": "ff8b053c4d53d4fb510c5cea03fac73cbd48b562", "size": 1275, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mySolvers/SolverEigen2.cpp", "max_stars_repo_name": "chennachaos/mpap", "max_stars_repo_head_hexsha": "99d02bc9075b72b899a167d1bbc2bf73584b85bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-12-30T16:45:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T23:27:29.000Z", "max_issues_repo_path": "src/mySolvers/SolverEigen2.cpp", "max_issues_repo_name": "chennachaos/mpap", "max_issues_repo_head_hexsha": "99d02bc9075b72b899a167d1bbc2bf73584b85bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-11-22T12:57:55.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-04T22:01:42.000Z", "max_forks_repo_path": "src/mySolvers/SolverEigen2.cpp", "max_forks_repo_name": "chennachaos/mpap", "max_forks_repo_head_hexsha": "99d02bc9075b72b899a167d1bbc2bf73584b85bc", "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.0298507463, "max_line_length": 100, "alphanum_fraction": 0.6054901961, "num_tokens": 356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767746654974, "lm_q2_score": 0.8221891261650248, "lm_q1q2_score": 0.7214518625923297}}
{"text": "#include \"logreg.hpp\"\n#include <cmath>\n#include <random>\n#include <fstream>\n#include <Eigen/Dense>\n#include <stdio.h>\n#include <iostream>\n\nusing namespace std;\nusing namespace Eigen;\n\nmt19937 rng;\n\nlrsgd::lrsgd()\n{\n\t//set training parameters\n\tnum_iter = 20;\n\tlambda = (float) 1e-4;\n\ttheta = VectorXf::Random(2, 1);\n\tcost = 0.0;\n\tgrad = VectorXf::Zero(2, 1);\n\n\t//generate training data\n\tgenerate_data(X, y);\n\n\t//learning rate schedule\n\ttau0 = 10;\n\tkappa = 1;  //(0.5, 1]\n\teta = VectorXf::Zero(num_iter,1);\n\tfor (int i = 0; i < num_iter; i++)\n\t{\n\t\teta[i] = (float) pow((tau0 + i), (-kappa));\n\t}\t\n}\n\nVectorXf lrsgd::sigmoid(VectorXf& a)\n{\n\treturn (1 + (-1*a.array()).exp()).inverse();  // 1/(1 + exp(-a))\n}\n\nvoid lrsgd::lr_objective(float& cost, VectorXf& grad, VectorXf& theta)\n{\n\tfloat n = (float) y.size();\n\tVectorXi y01 = (y.array() + 1) / 2;  //y \\in {0, 1}\n\tVectorXf h = X * theta;\n\tVectorXf mu = sigmoid(h);\n\n\tmu = mu.cwiseMax((float) 1e-7);       //bound away from zero: max(mu, eps)\n\tmu = mu.cwiseMin((float)(1 - 1e-7));  //bound away from one:  min(mu, 1-eps)\n\n\tArrayXf t1 = y01.array().cast<float>() * mu.array().log();\n\tArrayXf t2 = (1 - y01.array().cast<float>()) * ((1 - mu.array()).log());\n\tcost = -(t1 + t2).sum() / n;  //NLL\n\tcost += lambda * theta.norm();  //regularizer\n\t//cout << \"cost: \" << cost << endl;\n\n\tgrad = X.transpose() * (mu - y01.cast<float>()) + 2 * lambda * theta;  //gradient of LR objective\n\t//cout << \"grad norm: \" << grad.norm() << endl;\n}\n\nvoid lrsgd::fit()\n{\n\tVectorXf obj_hist = VectorXf::Zero(num_iter, 1);\n\tVectorXf theta_norm_hist = VectorXf::Zero(num_iter, 1);\n\n\tfor (int i = 0; i < num_iter; ++i)\n\t{\n\t\tlr_objective(cost, grad, theta);\n\t\ttheta = theta - eta[i] * grad;\n\t\t\n\t\tcout << \"grad: \" << endl << grad << endl;\n\t\tcout << \"theta: \" << endl << theta << endl;\n\n\t\tobj_hist[i] = cost;\n\t\ttheta_norm_hist[i] = theta.norm();\n\t\tprintf(\"iteration: %d, cost: %.4f, eta: %.4f, theta_norm: %.4f, grad_norm: %.4f\\n\", i, obj_hist[i], eta[i], theta.norm(), grad.norm());\n\t}\n}\n\nvoid lrsgd::generate_data(MatrixXf& X, VectorXi& y)\n{\n\tint n = 32, d = 2;\n\tX = MatrixXf::Zero(n, 2);\n\ty = VectorXi::Zero(n, 1);\n\n\tVector2f mu1(1, 1), mu2(-1, -1);\n\tVector2f pik(0.4, 0.6), cpik(0.4, 1.0); //cumsum(pik)\n\n\tcout << \"mu1: \" << endl << mu1 << endl;\n\tcout << \"mu2: \" << endl << mu2 << endl;\n\n\tuniform_real_distribution<float> dis01(0, 1);\n\tVector2f xn(0, 0);\n\n\tfor (int i = 0; i < n; i++)\n\t{\n\t\tfloat z01 = dis01(rng);\n\t\t//cout << \"z01: \" << z01 << endl;\n\n\t\tif (z01 < cpik[0])\n\t\t{\n\t\t\tX.row(i) = xn.setRandom() + mu1;\n\t\t\ty(i) = 1;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tX.row(i) = xn.setRandom() + mu2;\n\t\t\ty(i) = -1;\n\t\t}\n\t}\n\n\tcout << \"y: \" << endl << y << endl;\n\tcout << \"X: \" << endl << X << endl;\n\n\tofstream fout(\"./input.txt\");\n\tif (fout.is_open())\n\t{\n\t\tfout << X.size() << endl;\n\t\tfout << X << endl;\n\t\tfout << y.size() << endl;\n\t\tfout << y << endl;\n\t}\n\telse\n\t\tcout << \"Unable to open fout.\\n\";\n}\n\n\nint main()\n{\n    cout << \"Binary Logistic Regression\\n\"; \n\tlrsgd LR = lrsgd();\n\tLR.fit();\n\tcout << \"Learned weights: \" << endl << LR.theta << endl;\n\n\tcout << \"Predicting on training data: \" << endl;\n\tVectorXf mu = LR.X * LR.theta;\n\tVectorXf h = LR.sigmoid(mu);\n\tVectorXf y_pred = 2.0 * (h.array() >= 0.5).cast<float>() - 1.0;\n\tfloat y_err = (y_pred - LR.y.cast<float>()).sum() / (float) y_pred.size();\n        cout << \"LR classification error: \" << y_err << endl;\n\n\treturn 0;\n}\n", "meta": {"hexsha": "88d4e91752a33f948dda60b973dd6ef0bac866a1", "size": 3374, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "machine_learning/logreg/logreg.cpp", "max_stars_repo_name": "vishalbelsare/cpp", "max_stars_repo_head_hexsha": "772178d911e8f90c23e9d3c1d8d32482bc397fc5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 39.0, "max_stars_repo_stars_event_min_datetime": "2017-11-14T03:20:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-06T09:46:17.000Z", "max_issues_repo_path": "machine_learning/logreg/logreg.cpp", "max_issues_repo_name": "kunalyadav684/cpp", "max_issues_repo_head_hexsha": "3ce14b012acb2dcdf91459fb677de4bd0cb46170", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-10-01T22:30:50.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-01T22:30:50.000Z", "max_forks_repo_path": "machine_learning/logreg/logreg.cpp", "max_forks_repo_name": "kunalyadav684/cpp", "max_forks_repo_head_hexsha": "3ce14b012acb2dcdf91459fb677de4bd0cb46170", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2018-02-07T22:44:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-19T10:18:16.000Z", "avg_line_length": 23.4305555556, "max_line_length": 137, "alphanum_fraction": 0.5678719621, "num_tokens": 1228, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544912, "lm_q2_score": 0.8175744739711884, "lm_q1q2_score": 0.7214504987340488}}
{"text": "//\n//  EigenEx2DenseLinearSolve.cpp\n//  \n//\n//  Created by Zac Schulwolf on 12/26/16.\n//\n// Compile by g++ -I \"$(brew --prefix eigen)/include/eigen3\" EigenEx2DenseLinearSolve.cpp -o EigenEx2LinearSolve\n//\n// From https://eigen.tuxfamily.org/dox/group__TutorialLinearAlgebra.html\n//\n\n#include <iostream>\n#include <Eigen/Dense>\n\nusing namespace std;\nusing namespace Eigen;\n\nint main()\n{\n    //1\n    //General Decomposition using ColPivHouseholderQR\n    Matrix3f m1; //m1 is 3 by 3 of floats\n    Vector3f v1a; //B is 1 by 3 of floats\n    m1 << 1,2,3,  4,5,6,  7,8,10;\n    v1a << 3, 3, 4;\n    cout << \"Here is the matrix m1:\\n\" << m1 << endl;\n    cout << \"Here is the vector v1a:\\n\" << v1a << endl;\n    Vector3f v1b = m1.colPivHouseholderQr().solve(v1a); //A QR decomposition with column pivoting and solve\n    cout << \"The solution is:\\n\" << v1b << endl;\n    cout << endl << endl;\n    \n    \n    //2\n    //Decomposition if matix is positive definite use LLT or LDLT\n    Matrix2f m2a, m2b; //using 2 matrices, m2a could also be a vector\n    m2a << 2, -1, -1, 3;\n    m2b << 1, 2, 3, 1;\n    cout << \"Here is the matrix m2a:\\n\" << m2a << endl;\n    cout << \"Here is the right hand side m2b:\\n\" << m2b << endl;\n    Matrix2f x = m2a.ldlt().solve(m2b);\n    cout << \"The solution is:\\n\" << x << endl;\n    cout << endl << endl;\n    \n    \n    //3\n    //Error margin\n    MatrixXd m3a = MatrixXd::Random(100,100);\n    MatrixXd m3b = MatrixXd::Random(100,50);\n    MatrixXd m3c = m3a.fullPivLu().solve(m3b);\n    double relative_error = (m3a*m3c - m3b).norm() / m2b.norm(); //norm() is L2 norm\n    cout << \"The relative error is:\\n\" << relative_error << endl;\n    cout << endl << endl;\n    \n    \n    //4\n    //eigenvalues() and eginvectors() by SelfAdjointEigenSolver and EigenSolver\n    Matrix2f m4a;\n    m4a << 1, 2, 2, 3;\n    cout << \"Here is the matrix m4a:\\n\" << m4a << endl;\n    SelfAdjointEigenSolver<Matrix2f> eigensolver(m4a); //SelfAdjointEigenSolver\n    if (eigensolver.info() != Success) abort(); //eigensolver\n    cout << \"The eigenvalues of m4a are:\\n\" << eigensolver.eigenvalues() << endl; //eigenvalues()\n    cout << \"Here's a matrix whose columns are eigenvectors of m4a \\n\";\n    cout << \"corresponding to these eigenvalues:\\n\";\n    cout << eigensolver.eigenvectors() << endl; //eigenvecotors()\n    cout << endl << endl;\n    \n    //5\n    //Inverse and Determinant\n    Matrix3f m5;\n    m5 << 1, 2, 1, 2, 1, 0, -1, 1, 2;\n    cout << \"Here is the matrix m5:\\n\" << m5 << endl;\n    cout << \"The determinant of m5 is \" << m5.determinant() << endl;\n    cout << \"The inverse of m5 is:\\n\" << m5.inverse() << endl;\n    cout << endl << endl;\n    \n    \n    //6\n    //Least squares solving using JocobiSVD\n    MatrixXf m6 = MatrixXf::Random(3, 2);\n    cout << \"Here is the matrix m6:\\n\" << m6 << endl;\n    VectorXf v6 = VectorXf::Random(3);\n    cout << \"Here is the right hand side b:\\n\" << v6 << endl;\n    cout << \"The least-squares solution is:\\n\";\n    cout << m6.jacobiSvd(ComputeThinU | ComputeThinV).solve(v6) << endl;\n    cout << endl << endl;\n    \n    //7\n    //Separating the computation from the construction\n    Matrix2f m7a, m7b;\n    LLT<Matrix2f> llt;\n    m7a << 2, -1, -1, 3;\n    m7b << 1, 2, 3, 1;\n    cout << \"Here is the matrix m7a:\\n\" << m7a << endl;\n    cout << \"Here is the right hand side m7b:\\n\" << m7b << endl;\n    cout << \"Computing LLT decomposition...\" << endl;\n    llt.compute(m7a);\n    cout << \"The solution is:\\n\" << llt.solve(m7b) << endl;\n    m7a(1,1)++;\n    cout << \"The matrix m7a is now:\\n\" << m7a << endl;\n    cout << \"Computing LLT decomposition...\" << endl;\n    llt.compute(m7a);\n    cout << \"The solution is now:\\n\" << llt.solve(m7b) << endl;\n    cout << endl << endl;\n    \n    \n    //8\n    //Rank-revealing decompositions\n    Matrix3f m8a;\n    m8a << 1, 2, 5, 2, 1, 4, 3, 0, 3;\n    cout << \"Here is the matrix m8a:\\n\" << m8a << endl;\n    FullPivLU<Matrix3f> lu_decomp(m8a);\n    cout << \"The rank of m8a is \" << lu_decomp.rank() << endl;\n    cout << \"Here is a matrix whose columns form a basis of the null-space of m8a:\\n\"\n    << lu_decomp.kernel() << endl;\n    cout << \"Here is a matrix whose columns form a basis of the column-space of m8a:\\n\"\n    << lu_decomp.image(m8a) << endl; // yes, have to pass the original m8a\n    \n    Matrix2d m8b;\n    m8b << 2, 1,\n    2, 0.9999999999;\n    FullPivLU<Matrix2d> lu(m8b);\n    cout << \"By default, the rank of m8b is found to be \" << lu.rank() << endl;\n    lu.setThreshold(1e-5);\n    cout << \"With threshold 1e-5, the rank of m8b is found to be \" << lu.rank() << endl;\n    cout << endl << endl;\n    \n    \n    \n}\n", "meta": {"hexsha": "d11579c3bd585555b8fe71bc1868e9298a066987", "size": 4576, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Eigen/EigenEx2DenseLinearSolve.cpp", "max_stars_repo_name": "zacswolf/MNISTNeuralNetwork", "max_stars_repo_head_hexsha": "9eae847f3fb756329ce26c2ca3062aa7f29c83c2", "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": "Eigen/EigenEx2DenseLinearSolve.cpp", "max_issues_repo_name": "zacswolf/MNISTNeuralNetwork", "max_issues_repo_head_hexsha": "9eae847f3fb756329ce26c2ca3062aa7f29c83c2", "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": "Eigen/EigenEx2DenseLinearSolve.cpp", "max_forks_repo_name": "zacswolf/MNISTNeuralNetwork", "max_forks_repo_head_hexsha": "9eae847f3fb756329ce26c2ca3062aa7f29c83c2", "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.9312977099, "max_line_length": 112, "alphanum_fraction": 0.5920017483, "num_tokens": 1611, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391386, "lm_q2_score": 0.7905303285397349, "lm_q1q2_score": 0.7213084614780321}}
{"text": "/**\n * @file    euler080.cpp\n * @author  Marvin Smith\n * @date    5/9/2015\n*/\n\n// C++ Standard Libraries\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n\n// Boost Libraries\n#include <boost/multiprecision/cpp_dec_float.hpp>\n\n// Common Libraries\n#include \"../common/StringUtilities.hpp\"\n\n\nusing namespace std;\nusing namespace boost::multiprecision;\ntypedef number<cpp_dec_float<200>> cpp_dec_float_200;\n\n/**\n * @brief Main Function\n*/\nint main( int argc, char* argv[] )\n{\n    // Misc Values\n    int root;\n    int max_value = 100;\n    int64_t sum = 0;\n    int64_t counter;\n\n    // Iterate from 2 - 100\n    for( int n=2; n<=max_value; n++ )\n    {\n        // Check if rational or irrational\n        root = std::sqrt(n);\n        if( n != root*root )\n        {\n            // Compute the square root\n            cpp_dec_float_200 value = boost::multiprecision::sqrt( cpp_dec_float_200(n) );\n            \n            // Convert to a string\n            std::string value_str = num2str(value, 200);\n            \n            // Sum the digits\n            counter = 0;\n            for( int j=0; j<value_str.size() && counter < 100; j++ )\n            {\n                if( value_str[j] != '.' ){\n                    sum += (value_str[j] - '0');\n                    counter++;\n                }\n            }\n        }\n    }\n\n    // Print Result\n    std::cout << sum << std::endl;\n\n    // Exit\n    return 0;\n}\n\n", "meta": {"hexsha": "7b4799fc5b9245c5c3b4e288a9a46b4d6f1b8921", "size": 1405, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/euler080/euler080.cpp", "max_stars_repo_name": "marvins/ProjectEuler", "max_stars_repo_head_hexsha": "55a377bb9702067bac6908c1316c578498402668", "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/euler080/euler080.cpp", "max_issues_repo_name": "marvins/ProjectEuler", "max_issues_repo_head_hexsha": "55a377bb9702067bac6908c1316c578498402668", "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": "cpp/euler080/euler080.cpp", "max_forks_repo_name": "marvins/ProjectEuler", "max_forks_repo_head_hexsha": "55a377bb9702067bac6908c1316c578498402668", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-16T09:25:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-16T09:25:19.000Z", "avg_line_length": 21.2878787879, "max_line_length": 90, "alphanum_fraction": 0.5238434164, "num_tokens": 356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252812, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.7212904216239697}}
{"text": "#include \"gaussianXd.h\"\n#include <Eigen/Dense>\n#include <iostream>\n\n\nusing namespace Eigen;\n\nnamespace filters\n\n{\n    void mean(MatrixXd& data, VectorXd& mean){\n        // X_bar = X_transpose * j/N ; where J is a N*1 vector of ones and N is the totl number of data points\n        int N = data.rows();\n        const VectorXd J = VectorXd::Ones(N);\n        mean = data.transpose() * J / N;\n    }\n    double mean(VectorXd& data){\n        float N = data.rows();\n        auto sum = data.sum();\n        return sum/N;\n    }\n\n    void covariance(MatrixXd& data, MatrixXd& covariance){\n        // cov = X_transpose * (I - J/n) * X\n        // I = Identity\n        // J = Ones matrix\n\n        int N = data.rows();\n        MatrixXd J = MatrixXd::Ones(N, N);\n        MatrixXd I = MatrixXd::Identity(N, N);\n        covariance = (data.transpose() * (I - (J/N)) * data)/(N-1);\n    }\n\n    void covariance(VectorXd& data1, VectorXd& data2, MatrixXd& cov){\n        // construct a hstack\n        MatrixXd M(data1.rows(), data1.cols() + data2.cols());\n        M << data1, data2;\n        \n        covariance(M, cov);\n    }\n\n    MultivariateGaussian::MultivariateGaussian(MatrixXd& data) : data_(data)\n    {\n        mean(data, mean_);\n        covariance(data, covariance_);\n\n    }\n\n    MultivariateGaussian::MultivariateGaussian(VectorXd& mean, MatrixXd& cov) : mean_(mean), covariance_(cov)\n    {}\n\n    VectorXd MultivariateGaussian::get_mean(){\n        return mean_;\n    }\n\n    MatrixXd MultivariateGaussian::get_covariance(){\n        return covariance_;\n    }\n\n    double MultivariateGaussian::probability(VectorXd& x){\n        MatrixXd in = (x-mean_).transpose() * covariance_.inverse() * (x-mean_) * (-0.5);\n        int N = x.rows();\n        double denom = std::sqrt(std::pow(2*M_PI, N) * covariance_.norm());\n\n        std::cout << in << std::endl;\n\n        std:: cout << std::exp(in.value()) << std::endl;\n        return 0.0;\n    }\n}\n", "meta": {"hexsha": "76f113998e52e4d71d5083e9c6aed7a51b189c10", "size": 1917, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "filtermath/src/gaussianXd.cpp", "max_stars_repo_name": "SuhrudhSarathy/filters", "max_stars_repo_head_hexsha": "25b025a97e1edcf31a0195cb956c41f6d82e7764", "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": "filtermath/src/gaussianXd.cpp", "max_issues_repo_name": "SuhrudhSarathy/filters", "max_issues_repo_head_hexsha": "25b025a97e1edcf31a0195cb956c41f6d82e7764", "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": "filtermath/src/gaussianXd.cpp", "max_forks_repo_name": "SuhrudhSarathy/filters", "max_forks_repo_head_hexsha": "25b025a97e1edcf31a0195cb956c41f6d82e7764", "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.0, "max_line_length": 110, "alphanum_fraction": 0.5758998435, "num_tokens": 505, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.8006919925839875, "lm_q1q2_score": 0.7210469845529617}}
{"text": "#ifndef __MATRIX_UTIL_HH__\n#define __MATRIX_UTIL_HH__\n/********************************* TRICK HEADER *******************************\nPURPOSE:\n      (Matrix utility functions)\nLIBRARY DEPENDENCY:\n      ((../../src/matrix/utility.cpp))\n*******************************************************************************/\n#include <armadillo>\n\n/** Returns polar from cartesian coordinates.\n * magnitude = POLAR(0,0) = |V|\n * azimuth   = POLAR(1,0) = atan2(V2,V1)\n * elevation = POLAR(2,0) = atan2(-V3,sqrt(V1^2+V2^2)\n * Example: POLAR = VEC.pol_from_cart();\n */\narma::vec3 pol_from_cart(arma::vec3 in);\n\n/// @return the angle between two 3x1 vectors\ndouble angle(arma::vec3 VEC1, arma::vec3 VEC2);\n\n/// @return skew symmetric matrix of a Vector3\narma::mat33 skew_sym(arma::vec3 vec);\n\n/// @return the T.M. of the psivg -> thtvg sequence\narma::mat33 build_psivg_thtvg_TM(const double &psivg, const double &thtvg);\n\n/// @return the Euler T.M. of the psi->tht->phi sequence\narma::mat33 build_psi_tht_phi_TM(const double &psi, const double &tht, const double &phi);\n\narma::vec4 Matrix2Quaternion(arma::mat33 Matrix_in);\narma::mat33 Quaternion2Matrix(arma::vec4 Quaternion_in);\narma::vec4 Quaternion_conjugate(arma::vec4 Quaternion_in);\narma::vec4 Quaternion_cross(arma::vec4 Quaternion_in1, arma::vec4 Quaternion_in2);\nvoid Quaternion2Euler(arma::vec4 Quaternion_in, double &Roll, double &Pitch, double &Yaw);\narma::vec4 Euler2Quaternion(double Roll, double Pitch, double Yaw);\narma::vec4 QuaternionMultiply(arma::vec4 Q_in1, arma::vec4 Q_in2);\narma::vec4 QuaternionInverse(arma::vec4 Q_in);\narma::vec4 QuaternionTranspose(arma::vec4 Q_in);\narma::vec3 QuaternionRotation(arma::vec4 Q_in, arma::vec3 V_in);\narma::mat33 cross_matrix(arma::vec3 in);\narma::mat33 TMX(double ang);\narma::mat33 TMY(double ang);\narma::mat33 TMZ(double ang);\n\n#define STORE_MAT33(dest, src) \\\n    do { \\\n        auto cpy = src; \\\n        trans(cpy); \\\n        double *in = cpy.memptr(); \\\n        memcpy(dest, in, sizeof(dest)); \\\n    } while (0);\n\n\n#define STORE_VEC(dest, src) \\\n    do { \\\n        double *in = src.memptr(); \\\n        memcpy(dest, in, sizeof(dest)); \\\n    } while (0);\n\n#define GRAB_VAR(x) [&]() { return x; }\n#define GRAB_VEC3(x) [&]() { return arma::vec3(x); }\n#define GRAB_MAT33(x) [&]() { return arma::mat33((const double *)(&x)); }\n\n#endif  // __MATRIX_UTIL_HH__\n", "meta": {"hexsha": "a9133a3e967c13d75cce6d1e6a848656d6b5d75b", "size": 2352, "ext": "hh", "lang": "C++", "max_stars_repo_path": "models/math/include/matrix/utility.hh", "max_stars_repo_name": "cihuang123/Next-simulation", "max_stars_repo_head_hexsha": "e8552a5804184b30022d103d47c8728fb242b5bc", "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": "models/math/include/matrix/utility.hh", "max_issues_repo_name": "cihuang123/Next-simulation", "max_issues_repo_head_hexsha": "e8552a5804184b30022d103d47c8728fb242b5bc", "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": "models/math/include/matrix/utility.hh", "max_forks_repo_name": "cihuang123/Next-simulation", "max_forks_repo_head_hexsha": "e8552a5804184b30022d103d47c8728fb242b5bc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-05-05T14:59:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-17T03:19:45.000Z", "avg_line_length": 35.6363636364, "max_line_length": 90, "alphanum_fraction": 0.6488095238, "num_tokens": 671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009503523291, "lm_q2_score": 0.7879311956428946, "lm_q1q2_score": 0.7208789997059312}}
{"text": "// ec_ellipse.hpp\n// Andrew Wang, beandrewang@gmail.com\n\n#ifndef ECARE_ELLIPSE_Hh_\n#define ECARE_ELLIPSE_Hh_\n\n#include <armadillo>\n\nnamespace ecare\n{\n\tusing namespace std;\n\tusing namespace arma;\n\t\n\tclass ellipse\n\t{\n\t\tstruct feature\n\t\t{\n\t\t\tdouble\t\t\t\t\tcx;\n\t\t\tdouble\t\t\t\t\tcy;\n\t\t\tdouble\t\t\t\t\ta;\n\t\t\tdouble \t\t\t\t\tb;\n\t\t\tdouble\t\t\t\t\ttheta;\n\t\t};\n\n\tpublic:\n\t\tellipse();\n\t\tellipse(const mat &points);\n\t\tfeature read_features() { return f; }\n\tprivate:\n\t\tbool ellipse_fitting();\n\t\tbool generate_points();\n\t\tbool design_matrix(const vec &x, const vec &y, mat &S);\n\t\tbool solve_equation(const mat &S, vec &A);\n\t\tbool normalize(vec &x, vec &y);\n\t\tbool unnormalize(const vec &A, vec &par);\n\t\tbool computer_geometry(const vec &par);\n\tprivate:\n\t\tfeature f;\n\t\tmat scatter;\n\t\tdouble mx;\n\t\tdouble my;\n\t\tdouble sx;\n\t\tdouble sy;\n\t};\n}\n\n#endif", "meta": {"hexsha": "6f83254325593ee4cfeced4c8dedc0ce61116631", "size": 814, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ellipse.hpp", "max_stars_repo_name": "beandrewang/ecare", "max_stars_repo_head_hexsha": "00a684efb9f9484d3d5ebaacd9d1153a38c5da3b", "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/ellipse.hpp", "max_issues_repo_name": "beandrewang/ecare", "max_issues_repo_head_hexsha": "00a684efb9f9484d3d5ebaacd9d1153a38c5da3b", "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": "include/ellipse.hpp", "max_forks_repo_name": "beandrewang/ecare", "max_forks_repo_head_hexsha": "00a684efb9f9484d3d5ebaacd9d1153a38c5da3b", "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": 17.3191489362, "max_line_length": 57, "alphanum_fraction": 0.6633906634, "num_tokens": 234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9372107861416413, "lm_q2_score": 0.7690802370707283, "lm_q1q2_score": 0.7207902935910571}}
{"text": "/*\nReed Solomon coding \n*/\n\n\n#ifndef ReedSolomon\n#define ReedSolomon\n\n#include <boost/operators.hpp>\n#include <iostream>\n#include <ostream>\n#include <vector>\n#include <cassert>\n#include \"polynomial.hpp\"\n\n\nusing namespace std;\n\n\n\ntemplate<class GFE,class Dft>\nclass RScode{\n\tpublic:\n\tRScode(){};\n\tRScode(unsigned n_, unsigned k_,const GFE& primitive_el,Dft dft_){\n\t\tn = n_; k = k_; a = primitive_el; dftd = dft_;\n\t\tn_u = n_; \n\t\tk_u = k_;\n\t}\n\t\tRScode(unsigned n_, unsigned k_,const GFE& primitive_el,Dft dft_,unsigned n_u_){\n\t\tn = n_; k = k_; a = primitive_el; dftd = dft_;\n\t\tn_u = n_u_; \n\t\tk_u = k + n_u - n;\n\t}\n\tunsigned n;\n\tunsigned n_u;\n\tunsigned k_u;\n\tunsigned k;\n\tGFE a; // primitive element\n\tDft dftd; // class providing Fourier transform\n\ttypedef GFE Symbol; // Symbols of the code\n\t\n\t\n\t\n\t// GF: coefficients of the RS code, GF(p^m)\n\t// infvec: vector with k entries, containing the information\n\tvector<GFE>& RSencode(const vector<GFE>& infvec, vector<GFE>& c);\n\t\n\t// endode a shortened RS code \n\t// infvec: contains the information, length k\n\t// n: the length of cw\n\t// n_u: length of the underlying RS code \n\tvector<GFE>& RS_shortened_encode(const vector<GFE>& infvec, vector<GFE>& c);\n\n\t// GF: coefficients of the RS code, GF(p^m)\n\t// infvec: vector with k entries, containing the information\n\tvector<GFE>& RS_systematic_encode(const vector<GFE>& infvec, vector<GFE>& c);\n\n\t// decoding when the first n-k entries of the Fourier transform of c are equal zero\n\t// c: received vector \n\t// crec: recovered vector\n\t// retured is a pair, where pair.fist is the number of erasures and pair.second the number of errors\n\tpair<unsigned,unsigned> RSdecode(vector<GFE>& crec, const vector<GFE>& c); \n\n\t// decode a shortened RS code \n\t// infvec: contains the information, length k\n\t// n: the length of cw\n\t// n_u: length of the underlying RS code \n\tpair<unsigned,unsigned> RS_shortened_decode(vector<GFE>& infvec, vector<GFE>& c);\n\n\t// decode when information is encoded in the spectrum of c, that is C\n\tpair<unsigned,unsigned> RS_decode_spec(vector<GFE>& infvec, const vector<GFE>& c);\n};\n\n\ntemplate<class GFE, class Dft > \nvector<GFE>& RScode<GFE,Dft>::RSencode(const vector<GFE>& infvec, vector<GFE>& c){\n\tassert(infvec.size() == k);\n\n\t// encode\n\tc.resize(n); // c is the codeword\n\tvector<GFE> C(n); // Fourier transform of codeword\n\t// first n-k entries are zero\n\tfor(unsigned i=0;i<n-k;++i) C[i] = GFE(0); \n\t// next k entries contain information \n\tfor(unsigned i=0;i<k;++i) {\n\t\tC[i+n-k] = infvec[i]; \n\t}\n\tdftd.idft(c,C);\n\treturn c;\n}\n\n\n\ntemplate<class GFE,class Dft>\n//vector<GFE>& RS_shortened_encode(const vector<GFE>& infvec, vector<GFE>& c, const GFE& a, unsigned k, unsigned n, unsigned n_u){\nvector<GFE>& RScode<GFE,Dft>::RS_shortened_encode(const vector<GFE>& infvec, vector<GFE>& c){\n\tvector<GFE> extrazeros(n_u-n, GFE(0));\n\tvector<GFE> infvec_u = infvec;\n\t// append zeros to the information vector\n\tinfvec_u.insert(infvec_u.end(), extrazeros.begin(), extrazeros.end());\n\n\n\t// systematic encoding\n\tRS_systematic_encode(infvec_u,c);//a, k+n_u-n,n_u);\n\t// the last nu-n entries are zero, so erase them\n\tc.resize(n);\n\treturn c;\n}\n\n// GF: coefficients of the RS code, GF(p^m)\n// infvec: vector with k entries, containing the information\ntemplate<class GFE,class Dft>\nvector<GFE>& RScode<GFE,Dft>::RS_systematic_encode(const vector<GFE>& infvec, vector<GFE>& c){\n\tassert(infvec.size() == k_u);\n\n\t// compute the generator polynomial \n\tpolynomial<GFE> gp = polynomial<GFE>(1);\n\tGFE ai = GFE(a); \n\tfor(unsigned i=1;i <= n_u-k_u; ++i){\n\t\tvector<GFE> prov(2);\n\t\tprov[0] = GFE(0) - ai;\n\t\tprov[1] = GFE(1);\n\t\tgp *= polynomial<GFE>(prov);\n\t\tai *= a;\n\t}\n\t// generate message polynomial\n\tpolynomial<GFE> mp(infvec);\n\n\t// construct the polynomial x^(n-k)\n\tvector<GFE> xnmkv(n_u-k_u+1,GFE(0));\n\txnmkv[n_u-k_u] = GFE(1);\n\tpolynomial<GFE> xnmk(xnmkv);\n\n\tpolynomial<GFE> sp = mp*xnmk; // the codeword polynomial\n\t\n\t// obtain s_r(x) = p(x)*x^(n-k) mod g(x) as res.second \n\tpair<polynomial<GFE>, polynomial<GFE> > res = divide<GFE>(sp ,gp);\n\n\t// c(x) = p(x)*x^(n-k) - s_r(x)\n\tsp -= res.second; \n\t\n\t// make sure the cw has length n\n\n\t\n\tc = sp.poly;\n\tunsigned oldsize = c.size();\n\tc.resize(n_u);\n\tfor(unsigned i=oldsize;i<n_u;++i) c[i]=GFE(0);\n\treturn c; \n}\n\n\n\n// decoding when the first n-k entries of the Fourier transform of c are equal zero\n// c: received vector \n// crec: recovered vector\n// retured is a pair, where pair.first is the number of erasurs and pair.second the number of errors\ntemplate<class GFE, class Dft>\npair<unsigned,unsigned> RScode<GFE,Dft>::RScode<GFE,Dft>::RSdecode(vector<GFE>& crec, const vector<GFE>& c){\n\t\n\tpair<unsigned, unsigned> erctr;\n\t// codeword received\n\tcrec = c; // this will be the recoverd vector\n\n\tGFE am = a.inverse(); // am is the inverse of primitive element \n\tassert(n_u == crec.size());\n\tunsigned d = n_u-k_u+1;\n\t\n\t// the positions of the erasures\n\tvector<unsigned> er_pos(n_u);\n\tunsigned j=0;\n\tfor(unsigned i=0;i<n_u;++i) \n\t\tif(crec[i].isempty()) {\n\t\t\ter_pos[j] = i;\n\t\t\tj++;\n\t\t\tcrec[i] = GFE(0); // set to zero\n\t\t}\n\ter_pos.resize(j);\n\t\n\terctr.first = j;\n\t// compute the erasure locator polynomial\n\tpolynomial<GFE> elp = polynomial<GFE>(1);\n\tfor(unsigned i=0;i<er_pos.size(); ++i){\n\t\tvector<GFE> prov(2);\n\t\t/////// here I lose time when computing the powers.. \n\t\tprov[0] = GFE(0) - pow(am,er_pos[i]);\n\t\tprov[1] = GFE(1);\n\t\t//prov[0] = GFE(1);\n\t\t//prov[1] = GFE(0) - pow(a,er_pos[i]);\n\t\telp *= polynomial<GFE>(prov);\n\t}\n\t\n\n\t// obtain Crec from the received vector crec\n\tvector<GFE> Crec(n_u);\n\tdftd.dft(crec,Crec); \n\n\t// compute syndrome from received C\n\tvector<GFE> syndv(n_u-k_u); //syndrome vector\n\tfor(unsigned i=1; i<= n_u-k_u  ;++i)\n\t\tsyndv[i-1] = Crec[i];\n\tpolynomial<GFE> synd(syndv);\n\n\tsynd *= elp; \n\tsynd.poly.resize(n_u-k_u); // mod x^{n-k}\n\n\t//// solving the key equation by Euclid's method \n\n\t// construct polynomial x^(d-1)\n\tvector<GFE> xdm1(d,GFE(0)); \n\txdm1[d-1] = GFE(1);\n\n\tpolynomial<GFE> rem1 = xdm1;\n\tpolynomial<GFE> rem2 = synd;\n\tpolynomial<GFE> aux1 = polynomial<GFE>(0);\n\tpolynomial<GFE> aux2 = polynomial<GFE>(1);\n\t//polynomial<GFE> aux2 = elp;//polynomial<GFE>(1);\n\t\n\t\n\twhile(! (rem2.degree() < (d-1+j)/2  )  ){\n\t\tpair<polynomial<GFE>, polynomial<GFE> > res = divide<GFE>(rem1,rem2);\n\t\tpolynomial<GFE> aux_new = polynomial<GFE>(0) - res.first*aux2 + aux1;\n\t\t// prepare for the next step\n\t\trem1 = rem2;\n\t\trem2 = res.second;\n\t\taux1 = aux2;\n\t\taux2 = aux_new;\n\t}\n\n\t// aux2 is the error locator\n\t// rem2 is the errata evaluator polynomial\n\t\n\terctr.second = aux2.degree();\n\t\n\t//cout << \"erasures: \" << erctr.first << \" errors: \" << erctr.second << endl;\n\n\n\t// obtain the errata locator as the product of the error evaluator and the errata evaluator\n\telp *= aux2;\n\t\n    // Get the lowest coefficient in the polynomial elp\n\tpolynomial<GFE> A0 = polynomial<GFE>(elp.poly[0]);\n\t// rem2 is polynomial Omega\n\tpair<polynomial<GFE>, polynomial<GFE> > res_tmp= divide<GFE>(rem2, A0);\n\tpair<polynomial<GFE>, polynomial<GFE> > res_tmp2= divide<GFE>(elp, A0);\n\tpolynomial<GFE> Omega = res_tmp.first;\n\telp = res_tmp2.first;\n\t//// Forney's algorithm to find the error values\n\n\tpolynomial<GFE> elpder = elp;\n\telpder.derive(); // derivative of the error locator polynomial\n\n\t// compute the error values\n\t\n\t//vector<GFE> err_val(n);\n\tGFE ami = GFE(1);\t\n\tfor(unsigned i=0;i<n_u; ++i){\n\t\tif( elp.evaluate(ami) == GFE(0)  ){\n\t\t\t// e_j = a^i \\Gamma(a^-i) / \\Lambda'(a^-i)\n\t\t\t//err_val[i] = GFE(0) -  ai*( rem2.evaluate(ami)/ elpder.evaluate(ami) );\n\t\t\t//cout << \"errata at: \" << i << endl;\n\t\t\t// correct the error\n\t\t\t//cout << \"corrected at \" << i << endl;\n\t\t\tGFE elpderval = elpder.evaluate(ami); \n\t\t\tif(! elpderval.iszero()){ \n\t\t\t\tcrec[i] += ( Omega.evaluate(ami)/ elpderval);\n\t\t\t}else{ // otherwise something did go wrong, we cannot divide by zero..\n\t\t\t\terctr.second = n_u; // this marks an decoding error\n\t\t\t}\n\t\t}\n\t\tami *= am;\n\t}\n\treturn erctr;\n}\n\n\n//\ntemplate<class GFE, class Dft>\npair<unsigned,unsigned> RScode<GFE,Dft>::RS_shortened_decode(vector<GFE>& infvec, vector<GFE>& c){\n\t\n\tvector<GFE> extrazeros(n_u-n, GFE(0));\n\t// append the zeros to the received vector\n\tc.insert(c.end(), extrazeros.begin(), extrazeros.end());\n\t\n\tvector<GFE> crec(n_u);\n\tpair<unsigned,unsigned> erctr = RSdecode(crec,c);\n\t\n\t// copy the information; recall that c is endoded systematically.. \t\n\tinfvec = vector<GFE>(crec.begin()+n-k, crec.begin()+n );\n\tinfvec.resize(k);\n\treturn erctr;\n}\n\n\n//\ntemplate<class GFE, class Dft>\npair<unsigned,unsigned> RScode<GFE,Dft>::RS_decode_spec(vector<GFE>& infvec, const vector<GFE>& c){\n\t\n\tpair<unsigned,unsigned> erctr;\n\n\tassert(n == c.size());\n\tvector<GFE> crec; // the recovered codeword\n\tcout << \"start RS decode.. \" << endl;\n\terctr = RSdecode(crec,c);\n\tcout << \"..end RS decode.. \" << endl;\n\n\tvector<GFE> Crec(n);\n\tdftd.dft(crec,Crec); // obtain C from the recovered codeword\n\n\t// recover the information from C\n\tinfvec.resize(k);\n\tfor(unsigned i=0;i<k;++i) infvec[i] = Crec[i+n-k]; \n\t\n\treturn erctr;\n}\n\n#endif\n", "meta": {"hexsha": "4d86afdc177bbd54ff93485474889cbf37d0601d", "size": 8968, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ReedSolomon.hpp", "max_stars_repo_name": "zhaofeng-shu33/dna_data_storage", "max_stars_repo_head_hexsha": "87ae439c6a5d90701a9c26060776fa364dac5582", "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": "include/ReedSolomon.hpp", "max_issues_repo_name": "zhaofeng-shu33/dna_data_storage", "max_issues_repo_head_hexsha": "87ae439c6a5d90701a9c26060776fa364dac5582", "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": "include/ReedSolomon.hpp", "max_forks_repo_name": "zhaofeng-shu33/dna_data_storage", "max_forks_repo_head_hexsha": "87ae439c6a5d90701a9c26060776fa364dac5582", "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": 28.1128526646, "max_line_length": 130, "alphanum_fraction": 0.6673728814, "num_tokens": 2850, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582593509316, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.7207175025105125}}
{"text": "#include <Eigen/Dense>\r\n#include <iostream>\r\n\r\nusing namespace std;\r\nusing namespace Eigen;\r\n\r\nint main()\r\n{\r\n  Array22f m;\r\n  m << 1,2,\r\n       3,4;\r\n  Array44f a = Array44f::Constant(0.6);\r\n  cout << \"Here is the array a:\" << endl << a << endl << endl;\r\n  a.block<2,2>(1,1) = m;\r\n  cout << \"Here is now a with m copied into its central 2x2 block:\" << endl << a << endl << endl;\r\n  a.block(0,0,2,3) = a.block(2,1,2,3);\r\n  cout << \"Here is now a with bottom-right 2x3 block copied into top-left 2x2 block:\" << endl << a << endl << endl;\r\n}\r\n", "meta": {"hexsha": "a7f2f1a87a82bcbf12bc042c46dd433e4f2932da", "size": 541, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/eigen-eigen-323c052e1731/doc/examples/Tutorial_BlockOperations_block_assignment.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_BlockOperations_block_assignment.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_BlockOperations_block_assignment.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": 28.4736842105, "max_line_length": 116, "alphanum_fraction": 0.5804066543, "num_tokens": 181, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.8519527944504227, "lm_q1q2_score": 0.7207030167913016}}
{"text": "#include <Eigen/Sparse>\n#include <Eigen/Eigenvalues>\n\n#include <cmath>\n\n#include <iomanip>\n#include <iostream>\n\n#define PI  M_PI\n\nusing vector = Eigen::VectorXd;\n\n//! \\brief Golub-Welsh implementation 5.3.35\n//! \\param[in] n number of Gauss nodes\n//! \\param[out] w weights\n//! \\param[out] x nodes for interval [-1,1]\nvoid golubwelsh(int n, vector & w, vector & x) {\n    // TODO: implement Golub-Welsh\n}\n\n//! \\brief Compute \\int_a^b f(x) dx \\approx \\sum w_i f(x_i) (with scaling of w and x)\n//! \\tparam func template type for function handle f (e.g. lambda func.)\n//! \\param[in] f integrand\n//! \\param[in] w weights\n//! \\param[in] x nodes for interval [-1,1]\n//! \\param[in] a left boundary in [a,b]\n//! \\param[in] b right boundary in [a,b]\n//! \\return Approximation of integral \\int_a^b f(x) dx\ntemplate <class func>\ndouble quad(func&& f, const vector & w, const vector & x, double a, double b) {\n    // TODO: implement generic quadrature\n    // WARNING: careful scaling\n}\n\n//! \\brief Compute \\int_{-infty}^\\infty f(x) dx using transformation x = cot(t)\n//! \\tparam func template type for function handle f (e.g. lambda func.)\n//! \\param[in] n number of Gauss points\n//! \\param[in] f integrand\n//! \\return Approximation of integral \\int_{-infty}^\\infty f(x) dx\ntemplate <class func>\ndouble quadinf(int n, func&& f) {\n    // TODO: implement tranformation of f and call to quad\n}\n\nint main() {\n    // TODO: test integration of h with 1 to 100 Gaussian points\n}\n", "meta": {"hexsha": "ddf25e297435653509630126babf232530eb565c", "size": 1458, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/PS11/solutions_ps11/quadinf_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/PS11/solutions_ps11/quadinf_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/PS11/solutions_ps11/quadinf_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": 30.375, "max_line_length": 85, "alphanum_fraction": 0.6728395062, "num_tokens": 420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460332, "lm_q2_score": 0.8152324803738429, "lm_q1q2_score": 0.7206975364057292}}
{"text": "#ifndef InitCondLV_CC_\n#define InitCondLV_CC_\n/**\n * @file initcondlv.cc\n * @brief NPDE homework InitCondLV code\n * @author lfilippo, tille, jgacon, dcasati\n * @copyright Developed at ETH Zurich\n */\n\n#include <Eigen/Core>\n#include <iostream>\n#include <utility>\n\n#include \"../../../lecturecodes/Ode45/ode45.h\"\n\nnamespace InitCondLV {\n\n/* Compute the maps Phi(t,y0) and W(t,y0) at final time T.\n * Use initial data given by u0 and v0. */\n/* SAM_LISTING_BEGIN_1 */\nstd::pair<Eigen::Vector2d, Eigen::Matrix2d> PhiAndW(double u0, double v0,\n                                                    double T) {\n  // Save the values of Phi and W at time T in PaW.first and PaW.second resp.\n  std::pair<Eigen::Vector2d, Eigen::Matrix2d> PaW;\n\n  auto y_dot = [&](Eigen::Vector2d y) {\n  \treturn Eigen::Vector2d((2 - y[1]) * y[0], (y[0] - 1) * y[1]);\n  };\n\n  auto Df = [&](Eigen::Vector2d y, Eigen::Matrix2d W) {\n\n  \tEigen::Matrix2d Df;\n\n  \tDf <<   2 - y[1], -y[0],\n  \t        y[1],  y[0] - 1;\n\n  \treturn Df;\n  };\n\n  auto yW_dot = [&](Eigen::Matrix<double, 2, 3> state) {\n\n  \tauto y = state.col(0);\n  \tauto W = state.rightCols<2>();\n\n  \treturn (Eigen::Matrix<double, 2, 3>() << y_dot(y), Df(y, W) * W).finished();\n  };\n\n  auto integrator = Ode45<Eigen::Matrix<double, 2, 3>>(yW_dot);\n\n  integrator.options.atol = 1e-12;\n  integrator.options.rtol = 1e-14;\n\n  Eigen::Matrix<double, 2, 3> yW_0;\n  yW_0 << Eigen::Vector2d(u0,v0), Eigen::Matrix2d::Identity();\n\n  auto [y, _t] = integrator.solve(yW_0, T).back();\n\n  return std::pair(y.col(0), y.rightCols<2>());\n}\n/* SAM_LISTING_END_1 */\n\n}  // namespace InitCondLV\n\n#endif  // #define InitCondLV_CC_\n", "meta": {"hexsha": "dc5ed7f0b32930a1caa028666a62b47f5cc6cfb3", "size": 1629, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/InitCondLV/mysolution/initcondlv.cc", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "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": "homeworks/InitCondLV/mysolution/initcondlv.cc", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "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": "homeworks/InitCondLV/mysolution/initcondlv.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "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.0615384615, "max_line_length": 79, "alphanum_fraction": 0.6108041743, "num_tokens": 550, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451835, "lm_q2_score": 0.8311430394931456, "lm_q1q2_score": 0.7206307481736345}}
{"text": "/* Simple program for solving the two-dimensional diffusion \n   equation or Poisson equation using Jacobi's iterative method\n   Note that this program does not contain a loop over the time \n   dependence.\n*/\n\n#include <iostream>\n#include <iomanip>\n#include <armadillo>\nusing namespace std;\nusing namespace arma;\n\nint JacobiSolver(int, double, double, mat &, mat &, double);\n\nint main(int argc, char * argv[]){\n  int Npoints = 40;\n  double ExactSolution;\n  double dx = 1.0/(Npoints-1);\n  double dt = 0.25*dx*dx;\n  double tolerance = 1.0e-14;\n  mat A = zeros<mat>(Npoints,Npoints);\n  mat q = zeros<mat>(Npoints,Npoints);\n\n  // setting up an additional source term\n  for(int i = 0; i < Npoints; i++)\n    for(int j = 0; j < Npoints; j++)\n      q(i,j) = -2.0*M_PI*M_PI*sin(M_PI*dx*i)*sin(M_PI*dx*j);\n    \n  int itcount = JacobiSolver(Npoints,dx,dt,A,q,tolerance);\n \n  // Testing against exact solution\n  double sum = 0.0;\n  for(int i = 0; i < Npoints; i++){\n    for(int j=0;j < Npoints; j++){\n      ExactSolution = -sin(M_PI*dx*i)*sin(M_PI*dx*j);\n      sum += fabs((A(i,j) - ExactSolution));\n    }\n  }\n  cout << setprecision(5) << setiosflags(ios::scientific);\n  cout << \"Jacobi: L2 Error is \" << sum/Npoints << \" in \" << itcount << \" iterations\" << endl;\n}\n\n\n// Function for setting up the iterative Jacobi solver\nint JacobiSolver(int N, double dx, double dt, mat &A, mat &q, double abstol)\n{\n  int MaxIterations = 100000;\n  mat Aold = zeros<mat>(N,N);\n  \n  double D = dt/(dx*dx);\n  \n  for(int i=1;  i < N-1; i++)\n    for(int j=1; j < N-1; j++)\n      Aold(i,j) = 1.0;\n  \n  // Boundary Conditions -- all zeros\n  for(int i=0; i < N; i++){\n    A(0,i) = 0.0;\n    A(N-1,i) = 0.0;\n    A(i,0) = 0.0;\n    A(i,N-1) = 0.0;\n  }\n  // Start the iterative solver\n  for(int k = 0; k < MaxIterations; k++){\n    for(int i = 1; i < N-1; i++){\n      for(int j=1; j < N-1; j++){\n\tA(i,j) = dt*q(i,j) + Aold(i,j) +\n\t  D*(Aold(i+1,j) + Aold(i,j+1) - 4.0*Aold(i,j) + \n\t     Aold(i-1,j) + Aold(i,j-1));\n      }\n    }\n    double sum = 0.0;\n    for(int i = 0; i < N;i++){\n      for(int j = 0; j < N;j++){\n\tsum += (Aold(i,j)-A(i,j))*(Aold(i,j)-A(i,j));\n\tAold(i,j) = A(i,j);\n      }\n    }\n    if(sqrt (sum) <abstol){\n      return k;\n    }\n  }\n  cerr << \"Jacobi: Maximum Number of Interations Reached Without Convergence\\n\";\n  return MaxIterations;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "1272bd50a0734fcebbbc03bc546ee0f80f01734a", "size": 2330, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/src/pde/pde/Programs/cpp/diffusion2dim.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/src/pde/pde/Programs/cpp/diffusion2dim.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/src/pde/pde/Programs/cpp/diffusion2dim.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": 23.5353535354, "max_line_length": 94, "alphanum_fraction": 0.5716738197, "num_tokens": 796, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026505426831, "lm_q2_score": 0.7853085708384735, "lm_q1q2_score": 0.7203656335240182}}
{"text": "/**\r\n *  @file    diffusion.hpp\r\n *  @brief   Collections of diffusion problem, definitions.\r\n *  @author  Francois Roy\r\n *  @date    12/01/2019\r\n */\r\n#ifndef DIFFUSION_H\r\n#define DIFFUSION_H\r\n\r\n#include <string>\r\n#include <Eigen/Core>\r\n#include \"spdlog/spdlog.h\"\r\n#include \"numerical/fdm/fdm.hpp\"\r\n\r\nnamespace bench{\r\nnamespace diffusion{\r\n\r\ntypedef Eigen::VectorXd Vec;\r\ntypedef Eigen::ArrayXd Arr;\r\n\r\n/**\r\n* Computes the 1D diffusion problem defined in @ref FDMDiffusionA::reference() \r\n* using the finite difference method and computes the L2-norm of the error\r\n* between the exact and computed solution.\r\n*\r\n* @return The L2-norm of the error between the computed and exact solution.\r\n* @see numerical::fdm::Parameters\r\n* @see numerical::fdm::FDMesh\r\n* @see numerical::fdm::SparseSolver\r\n*/\r\ndouble fdm_diffusion_a();\r\n/**\r\n* Computes the 1D diffusion problem defined in @ref FDMDiffusionB::reference() \r\n* using the finite difference method and computes the L2-norm of the error\r\n* between the exact and computed solution.\r\n*\r\n* @return The L2-norm of the error between the computed and exact solution.\r\n* @see numerical::fdm::Parameters\r\n* @see numerical::fdm::FDMesh\r\n* @see numerical::fdm::SparseSolver\r\n*/\r\ndouble fdm_diffusion_b();\r\n/**\r\n* Computes the 1D diffusion problem defined in @ref FDMDiffusionC::reference() \r\n* using the finite difference method and computes the L2-norm of the error\r\n* between the exact and computed solution.\r\n*\r\n* @return The L2-norm of the error between the computed and exact solution.\r\n* @see numerical::fdm::Parameters\r\n* @see numerical::fdm::FDMesh\r\n* @see numerical::fdm::SparseSolver\r\n*/\r\ndouble fdm_diffusion_c();\r\n/**\r\n* Computes the 1D diffusion problem defined in @ref FDMDiffusionD::reference() \r\n* using the finite difference method and computes the L2-norm of the error\r\n* between the exact and computed solution.\r\n*\r\n* @return The L2-norm of the error between the computed and exact solution.\r\n* @see numerical::fdm::Parameters\r\n* @see numerical::fdm::FDMesh\r\n* @see numerical::fdm::SparseSolver\r\n*/\r\ndouble fdm_diffusion_d();\r\n/**\r\n* Computes the 1D diffusion problem defined in @ref FDMDiffusionE::reference() \r\n* using the finite difference method and computes the L2-norm of the error\r\n* between the exact and computed solution.\r\n*\r\n* @return The L2-norm of the error between the computed and exact solution.\r\n* @see numerical::fdm::Parameters\r\n* @see numerical::fdm::FDMesh\r\n* @see numerical::fdm::SparseSolver\r\n*/\r\ndouble fdm_diffusion_e();\r\n\r\n/**\r\n* This class provides tools to compute the finite difference problem \r\n* defined in @ref FDMDiffusionA::reference().\r\n*\r\n* The class is derived form the @ref numerical::fdm::FDProblem class and \r\n* overrides the member function @ref numerical::fdm::FDProblem::left(),\r\n* @ref numerical::fdm::FDProblem::right(), \r\n* @ref numerical::fdm::FDProblem::initial_value(),\r\n* @ref numerical::fdm::FDProblem::source(), and \r\n* @ref numerical::fdm::FDProblem::reference().\r\n*/\r\nclass FDMDiffusionA : public numerical::fdm::Problem<double>{\r\npublic:\r\n    FDMDiffusionA(numerical::fdm::Parameters<double>* p): \r\n        numerical::fdm::Problem<double>(p){\r\n        }\r\n    double left(double y, double z, double t);\r\n    double right(double y, double z, double t);\r\n    double source(const Eigen::Matrix<double, 3, 1>& x, double t);\r\n    /**\r\n    * Reference solution for the 1D diffusion problem a, defined as:\r\n    *\r\n    * \\f[\r\n    *    \\frac{\\partial u}{\\partial t} = \\alpha \\frac{\\partial^2 u}\r\n    *                                 {\\partial x^2}\r\n    *                               + f(x,t)\\quad x \\in (0, L),~t \\in (0, T]\r\n    * \\f]\r\n    *\r\n    * with homogeneous Dirichlet boundary condition \\f$u(0, t) = 0\\f$ and  \r\n    * \\f$ u(L, t) = 0\\f$ for \\f$t>0\\f$.\r\n    *\r\n    * The diffusion coefficient, \\f$ \\alpha(L, t)\\f$ is constant and \r\n    * uniform over the interval (line).\r\n    *\r\n    * We define the source term and initial condition with a reference \r\n    * (manufactured) solution that respects the boundary conditions at the \r\n    * extremities of the interval:\r\n    *\r\n    * \\f[\r\n    *    u(x, t) = 5tx\\left(L-x\\right)\r\n    * \\f]\r\n    *\r\n    * We get the source term substituting the manufactured solution in the \r\n    * diffusion equation, i.e.:\r\n    *\r\n    * \\f[ \r\n    *    f(x, t) = 5x\\left(L-x\\right)+10\\alpha t\r\n    * \\f]\r\n    *\r\n    * The initial condition is simply set to the manufactured solution at \r\n    * \\f$t=0\\f$:\r\n    *\r\n    * \\f[ \r\n    *    u(x, 0) = u_0 = 0\r\n    * \\f] \r\n    *\r\n    * @param x The spatial mesh node coordinates.\r\n    * @param t The temporal mesh node.\r\n    * @return The reference solution.\r\n    */\r\n    double reference(const Eigen::Matrix<double, 3, 1>& x, double t);\r\n};\r\n\r\n/**\r\n* This class provides tools to compute the finite difference problem \r\n* defined in @ref FDMDiffusionB::reference().\r\n*\r\n* The class is derived form the @ref numerical::fdm::FDProblem class and \r\n* overrides the member function @ref numerical::fdm::FDProblem::left(),\r\n* @ref numerical::fdm::FDProblem::right(), \r\n* @ref numerical::fdm::FDProblem::initial_value(),\r\n* @ref numerical::fdm::FDProblem::source(), and \r\n* @ref numerical::fdm::FDProblem::reference().\r\n*/\r\nclass FDMDiffusionB : public numerical::fdm::Problem<double>{\r\npublic:\r\n    FDMDiffusionB(numerical::fdm::Parameters<double>* p): \r\n        numerical::fdm::Problem<double>(p){\r\n        }\r\n    double left(double y, double z, double t);\r\n    double right(double y, double z, double t);\r\n    double source(const Eigen::Matrix<double, 3, 1>& x, double t);\r\n    /**\r\n    * Reference solution for the 1D diffusion problem b, defined as:\r\n    *\r\n    * \\f[\r\n    *    \\frac{\\partial u}{\\partial t} = \\alpha \\frac{\\partial^2 u}\r\n    *                                 {\\partial x^2}\r\n    *                                 + f(x,t)\\quad x \\in (0, L),~t \\in (0, T]\r\n    * \\f]\r\n    *\r\n    * with homogeneous Neumann boundary condition \r\n    * \\f$\\left. \\frac{\\partial}{\\partial x}u(x, t)\\right|_{x=0} = 0\\f$ and  \r\n    * \\f$\\left. \\frac{\\partial}{\\partial x}u(x, t)\\right|_{x=L} = 0\\f$.\r\n    *\r\n    * The diffusion coefficient, \\f$ \\alpha(L, t)\\f$ is constant and \r\n    * uniform over the interval (line).\r\n    *\r\n    * We define the source term and initial condition with a reference \r\n    * (manufactured) solution that respects the boundary conditions at the \r\n    * extremities of the interval:\r\n    *\r\n    * \\f[\r\n    *    \\frac{\\partial}{\\partial x}u(x, t) = 5tx\\left(L-x\\right)\r\n    * \\f]\r\n    *\r\n    * which leads to\r\n    *\r\n    * \\f[\r\n    *    u(x, t) = 5tx\\left(\\frac{Lx}{2}-\\frac{x^2}{3}\\right)\r\n    * \\f]\r\n    *\r\n    * We get the source term substituting the manufactured solution in the \r\n    * diffusion equation, i.e.:\r\n    *\r\n    * \\f[ \r\n    *    f(x, t) = 5x\\left(\\frac{Lx}{2}-\\frac{x^2}{3}\\right)-\r\n    *      5\\alpha t\\left(L-2x\\right)\r\n    * \\f]\r\n    *\r\n    * The initial condition is simply set to the manufactured solution at \r\n    * \\f$t=0\\f$:\r\n    *\r\n    * \\f[ \r\n    *    u(x, 0) = u_0 = 0\r\n    * \\f] \r\n    *\r\n    * @param x The spatial mesh node coordinates.\r\n    * @param t The temporal mesh node.\r\n    * @return The reference solution.\r\n    */\r\n    double reference(const Eigen::Matrix<double, 3, 1>& x, double t);\r\n};\r\n\r\n/**\r\n* This class provides tools to compute the finite difference problem \r\n* defined in @ref FDMDiffusionC::reference().\r\n*\r\n* The class is derived form the @ref numerical::fdm::FDProblem class and \r\n* overrides the member function @ref numerical::fdm::FDProblem::left(),\r\n* @ref numerical::fdm::FDProblem::right(), \r\n* @ref numerical::fdm::FDProblem::initial_value(),\r\n* @ref numerical::fdm::FDProblem::source(), and \r\n* @ref numerical::fdm::FDProblem::reference().\r\n*/\r\nclass FDMDiffusionC : public numerical::fdm::Problem<double>{\r\npublic:\r\n    FDMDiffusionC(numerical::fdm::Parameters<double>* p): \r\n        numerical::fdm::Problem<double>(p){\r\n        }\r\n    double left(double y, double z, double t);\r\n    double right(double y, double z, double t);\r\n    double source(const Eigen::Matrix<double, 3, 1>& x, double t);\r\n    /**\r\n    * Reference solution for the 1D diffusion problem c, defined as:\r\n    *\r\n    * \\f[\r\n    *    \\frac{\\partial u}{\\partial t} = \\alpha \\frac{\\partial^2 u}\r\n    *                                 {\\partial x^2}\r\n    *                                 + f(x,t)\\quad x \\in (0, L),~t \\in (0, T]\r\n    * \\f]\r\n    *\r\n    * with non-homogeneous Neumann boundary condition \r\n    * \\f$\\mathbf{\\hat{n}}\\cdot\\left. \\frac{\\partial}{\\partial x}\r\n    *  u(x, t)\\right|_{x=0} = -5tL\\f$ and  \r\n    * \\f$\\mathbf{\\hat{n}}\\cdot\\left. \\frac{\\partial}{\\partial x}\r\n    *  u(x, t)\\right|_{x=L} = -5tL\\f$.\r\n    *\r\n    * The diffusion coefficient, \\f$ \\alpha(L, t)\\f$ is constant and \r\n    * uniform over the interval (line).\r\n    *\r\n    * We define the source term and initial condition with a reference \r\n    * (manufactured) solution that respects the boundary conditions at the \r\n    * extremities of the interval:\r\n    *\r\n    * \\f[\r\n    *    \\frac{\\partial}{\\partial x}u(x, t) = 5t\\left(L-2x\\right)\r\n    * \\f]\r\n    *\r\n    * which leads to\r\n    *\r\n    * \\f[\r\n    *    u(x, t) = 5tx\\left(L-x\\right)\r\n    * \\f]\r\n    *\r\n    * We get the source term substituting the manufactured solution in the \r\n    * diffusion equation, i.e.:\r\n    *\r\n    * \\f[ \r\n    *    f(x, t) = 5x\\left(L-x\\right)+10\\alpha t\r\n    * \\f]\r\n    *\r\n    * The initial condition is simply set to the manufactured solution at \r\n    * \\f$t=0\\f$:\r\n    *\r\n    * \\f[ \r\n    *    u(x, 0) = u_0 = 0\r\n    * \\f] \r\n    *\r\n    * @param x The spatial mesh node coordinates.\r\n    * @param t The temporal mesh node.\r\n    * @return The reference solution.\r\n    */\r\n    double reference(const Eigen::Matrix<double, 3, 1>& x, double t);\r\n};\r\n\r\n/**\r\n* This class provides tools to compute the finite difference problem \r\n* defined in @ref FDMDiffusionD::reference().\r\n*\r\n* The class is derived form the @ref numerical::fdm::FDProblem class and \r\n* overrides the member function @ref numerical::fdm::FDProblem::left(),\r\n* @ref numerical::fdm::FDProblem::right(), \r\n* @ref numerical::fdm::FDProblem::initial_value(),\r\n* @ref numerical::fdm::FDProblem::source(), and \r\n* @ref numerical::fdm::FDProblem::reference().\r\n*/\r\nclass FDMDiffusionD : public numerical::fdm::Problem<double>{\r\npublic:\r\n    FDMDiffusionD(numerical::fdm::Parameters<double>* p): \r\n        numerical::fdm::Problem<double>(p){\r\n        }\r\n    double left(double y, double z, double t);\r\n    double right(double y, double z, double t);\r\n    double source(const Eigen::Matrix<double, 3, 1>& x, double t);\r\n    /**\r\n    * Reference solution for the 1D diffusion problem d, defined as:\r\n    *\r\n    * \\f[\r\n    *    \\frac{\\partial u}{\\partial t} = \\alpha \\frac{\\partial^2 u}\r\n    *                                 {\\partial x^2}\r\n    *                                 + f(x,t)\\quad x \\in (0, L),~t \\in (0, T]\r\n    * \\f]\r\n    *\r\n    * with non-homogeneous Dirichlet boundary condition \r\n    * \\f$u(0, t) = 5tL^2/4\\f$ and \r\n    * \\f$\\mathbf{\\hat{n}}\\cdot\\left. \\alpha(u)\\frac{\\partial}{\\partial x}\r\n    *  u(x, t)\\right|_{x=L} = g\\f$.\r\n    *\r\n    * The diffusion coefficient, \\f$ \\alpha(u)=u\\f$.\r\n    *\r\n    * We define the source term and initial condition with a reference \r\n    * (manufactured) solution that respects the boundary conditions at the \r\n    * extremities of the interval:\r\n    *\r\n    * \\f[\r\n    *    u(x, t) = 5t\\left(x-\\frac{L}{2}\\right)^2\r\n    * \\f]\r\n    *\r\n    * We get the source term substituting the manufactured solution in the \r\n    * diffusion equation, i.e.:\r\n    *\r\n    * \\f[ \r\n    *    f(x, t) = 5\\left(x-\\frac{L}{2}\\right)^2-\r\n    *      10\\alpha t\r\n    * \\f]\r\n    *\r\n    * The initial condition is simply set to the manufactured solution at \r\n    * \\f$t=0\\f$:\r\n    *\r\n    * \\f[ \r\n    *    u(x, 0) = u_0 = 0\r\n    * \\f] \r\n    *\r\n    * @param x The spatial mesh node coordinates.\r\n    * @param t The temporal mesh node.\r\n    * @return The reference solution.\r\n    */\r\n    double reference(const Eigen::Matrix<double, 3, 1>& x, double t);\r\n};\r\n\r\n/**\r\n* This class provides tools to compute the finite difference problem \r\n* defined in @ref FDMDiffusionE::reference().\r\n*\r\n* The class is derived form the @ref numerical::fdm::FDProblem class and \r\n* overrides the member function @ref numerical::fdm::FDProblem::left(),\r\n* @ref numerical::fdm::FDProblem::right(), \r\n* @ref numerical::fdm::FDProblem::initial_value(),\r\n* @ref numerical::fdm::FDProblem::source(), and \r\n* @ref numerical::fdm::FDProblem::reference().\r\n*/\r\nclass FDMDiffusionE : public numerical::fdm::Problem<double>{\r\npublic:\r\n    FDMDiffusionE(numerical::fdm::Parameters<double>* p): \r\n        numerical::fdm::Problem<double>(p){\r\n        }\r\n    double left(double y, double z, double t);\r\n    double right(double y, double z, double t);\r\n    double source(const Eigen::Matrix<double, 3, 1>& x, double t);\r\n    /**\r\n    * Reference solution for the nonlinear 1D diffusion problem e, defined as:\r\n    *\r\n    * \\f[\r\n    *    \\frac{\\partial u}{\\partial t} = \\frac{\\partial}{\\partial x}\r\n    *        \\left(\\alpha(u)\\frac{\\partial u}{\\partial x}\\right)\r\n    *        + f(x,t)\\quad x \\in (0, L),~t \\in (0, T]\r\n    * \\f]\r\n    *\r\n    * with non-homogeneous mixed Dirichlet/Neumann boundary conditions \r\n    * \\f$u(0, t) = u_D\\f$ and \\f$u(L, t)= 5tL^2/4\\f$.\r\n    *\r\n    * The diffusion coefficient, \\f$ \\alpha(L, t)\\f$ is constant and \r\n    * uniform over the interval (line).\r\n    *\r\n    * We define the source term and initial condition with a reference \r\n    * (manufactured) solution that respects the boundary conditions at the \r\n    * extremities of the interval:\r\n    *\r\n    * \\f[\r\n    *    u(x, t) = 5t\\left(x-\\frac{L}{2}\\right)^2\r\n    * \\f]\r\n    *\r\n    * We get the source term substituting the manufactured solution in the \r\n    * diffusion equation, i.e.:\r\n    *\r\n    * \\f[ \r\n    *    f(x, t) = 5\\left(x-\\frac{L}{2}\\right)^2-\r\n    *      10\\alpha t\r\n    * \\f]\r\n    *\r\n    * The initial condition is simply set to the manufactured solution at \r\n    * \\f$t=0\\f$:\r\n    *\r\n    * \\f[ \r\n    *    u(x, 0) = u_0 = 0\r\n    * \\f] \r\n    *\r\n    * @param x The spatial mesh node coordinates.\r\n    * @param t The temporal mesh node.\r\n    * @return The reference solution.\r\n    */\r\n    double reference(const Eigen::Matrix<double, 3, 1>& x, double t);\r\n};\r\n\r\n}  // namespace diffusion\r\n}  // namespace bench\r\n\r\n#endif  // DIFFUSION_H\r\n", "meta": {"hexsha": "2d536c570f782282e3a804ac1897b4e057d38efe", "size": 14363, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "bench/diffusion/diffusion.hpp", "max_stars_repo_name": "frRoy/Numerical", "max_stars_repo_head_hexsha": "97e2167cf794eceaeba395bb1958fee72d8cbecf", "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": "bench/diffusion/diffusion.hpp", "max_issues_repo_name": "frRoy/Numerical", "max_issues_repo_head_hexsha": "97e2167cf794eceaeba395bb1958fee72d8cbecf", "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": "bench/diffusion/diffusion.hpp", "max_forks_repo_name": "frRoy/Numerical", "max_forks_repo_head_hexsha": "97e2167cf794eceaeba395bb1958fee72d8cbecf", "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.5264423077, "max_line_length": 80, "alphanum_fraction": 0.599248068, "num_tokens": 4129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760039, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.7203151852975532}}
{"text": "#include \"ExponentialForm.hpp\"\n#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace Eigen;\n\nPolynomial<double> ExponentialForm::taylorExpand(int degree) const {\n  VectorXd coefs = VectorXd::Zero(degree+1);\n  coefs(0) = m_a + m_c;\n\n  double factorial = 1.0;\n  for (int d=1; d < degree + 1; d++) {\n    factorial *= d;\n    coefs(d) = m_a * std::pow(m_b, d) / factorial;\n  }\n\n  return Polynomial<double>(coefs);\n}\n\ndouble ExponentialForm::value(double t) const {\n  return m_a * exp(m_b * t) + m_c;\n}", "meta": {"hexsha": "8295aa2b6261372303a21961bc7a366013e0e7f3", "size": 502, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "software/control/src/ExponentialForm.cpp", "max_stars_repo_name": "liangfok/oh-distro", "max_stars_repo_head_hexsha": "eeee1d832164adce667e56667dafc64a8d7b8cee", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 92.0, "max_stars_repo_stars_event_min_datetime": "2016-01-14T21:03:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-01T17:57:46.000Z", "max_issues_repo_path": "software/control/src/ExponentialForm.cpp", "max_issues_repo_name": "liangfok/oh-distro", "max_issues_repo_head_hexsha": "eeee1d832164adce667e56667dafc64a8d7b8cee", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 62.0, "max_issues_repo_issues_event_min_datetime": "2016-01-16T18:08:14.000Z", "max_issues_repo_issues_event_max_datetime": "2016-03-24T15:16:28.000Z", "max_forks_repo_path": "software/control/src/ExponentialForm.cpp", "max_forks_repo_name": "liangfok/oh-distro", "max_forks_repo_head_hexsha": "eeee1d832164adce667e56667dafc64a8d7b8cee", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2016-01-14T21:26:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T03:10:39.000Z", "avg_line_length": 22.8181818182, "max_line_length": 68, "alphanum_fraction": 0.6633466135, "num_tokens": 155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111796979521253, "lm_q2_score": 0.7905303162021596, "lm_q1q2_score": 0.7203151747390819}}
{"text": "//test_mcr.cpp\n\n//compute Monte Carlo sim\n\n#include <iostream>\n#include <string>\n#include <fstream>\n#include <sstream>\n#include <vector>\n#include<memory>\n\n#include <Eigen/Dense>\n\n#include \"compute_returns_eigen.h\"\n#include \"compute_var.h\"\n#include \"path.h\"\n#include \"mc_engine.h\"\n#include \"rng.h\"\n#include \"pca.h\"\n\nusing namespace Eigen;\nusing namespace std;\n\nvoid readCSV(std::istream &input, std::vector< std::vector<std::string> > &output)\n//https://www.gamedev.net/topic/444193-c-how-to-load-in-a-csv-file/\n{\n\tstd::string csvLine;\n\t// read every line from the stream\n\twhile( std::getline(input, csvLine) )\n\t{\n\t\tstd::istringstream csvStream(csvLine);\n\t\tstd::vector<std::string> csvColumn;\n\t\tstd::string csvElement;\n\t\t// read every element from the line that is seperated by commas\n\t\t// and put it into the vector or strings\n\t\twhile( std::getline(csvStream, csvElement, ',') )\n\t\t{\n\t\t\tcsvColumn.push_back(csvElement);\n\t\t}\n\t\toutput.push_back(csvColumn);\n\t}\n}\n\n\nint main()\n{\n\n    try{\n\n    // Read daily index level for major and emerging markets\n    // daily series obtained from Yahoo! Finance through\n\t//https://www.quandl.com\n\n\tstd::fstream file(\"/home/mrnoname/Documents/VaR/data/StockIndexData.csv\", ios::in);\n\tif(!file.is_open())\n\t{\n\t\tstd::cout << \"File not found!\\n\";\n\t\treturn 1;\n\t}\n\t// typedef to save typing for the following object\n\ttypedef std::vector< std::vector<std::string> > csvVector;\n\tcsvVector csvData;\n\n\treadCSV(file, csvData);\n\n    //test\n    for(size_t i = 0;i < 5; ++i){\n        for(size_t j = 0;j < csvData[i].size();++j){\n            cout << csvData[i][j] << '\\t';\n\n        }\n\n        cout << endl;\n    }\n    cout << endl;\n\n    // Remove lines with missing values\n\n    size_t n(csvData.size() - 1);\n    size_t m(csvData[0].size() - 1);\n\n    Mat _prices;\n    _prices.resize(m,Vec(n-1062));\n\n    for(size_t i = 1062;i < n;++i){\n        for(size_t j = 1;j < csvData[i].size();++j){\n            std::string tmp = csvData[i][j];\n            if(tmp.empty()){\n                _prices[j-1][i-1062] = 99999.;\n            }\n            else{\n                _prices[j-1][i-1062] = std::stod(tmp);\n            }\n        }\n    }\n\n    std::vector<std::string> indexNames(csvData[0].size() - 1);\n\n    for(size_t i = 1;i < csvData[0].size();++i){\n        indexNames[i-1] = csvData[0][i];\n    }\n\n\t//Remove missing values to compute trailling returns\n    //Asynchornous time series. Shift to the next value\n    Mat prices;\n    prices.resize(m,Vec(0));\n\n\tfor(size_t i = 0;i < _prices.size();++i){\n        for(size_t j = 0;j < _prices[i].size();++j){\n            if(!((_prices[i][j] == 99999) || (_prices[i][j] == 0)))\n                prices[i].push_back(_prices[i][j]);\n        }\n\t}\n\n    std::shared_ptr<ComputeReturn> cr(new ComputeReturn(prices,1,252,true));\n\t// 252 / 4 = 63 - 3 months\n    // 4 * 252 = 1008 use 4 years of data to compute mean, and std dev\n\n    //-------------------------------------------------------------------------\n    // single case\n\n\t// Simulate stock rtn using AR(1)xGARCH(1,1) through brute force Monte-Carlo\n    //\n\n\tAR1xGARCH11 process (-0.0003114, -0.0693, 0.01854, 0.10150, 0.88374); // DJIA\n\n\trng _rng;\n\n\tMCEngine<rng,AR1xGARCH11> engine(_rng, process);\n\n\tengine.setValues(cr->getReturns(1),cr->getStdDev(1));\n\n\tVec sim(10);\n\n\tsim = engine.DoSimulation(10,Gaussian);\n\n    for(auto& i : sim)   cout << i << endl;\n\n    engine.setValues(cr->getReturns(0),cr->getRollingStdDev(0).back());\n\n    Vec sim1(10);\n\n    sim1 = engine.DoSimulation(10,Gaussian);\n\n    cout << endl; for(auto& j : sim1)   cout << j << endl;\n\n    // --------------------------------------------------------------\n    // Multiple stock returns\n\n    Eigen::MatrixXd C = cr->getVarCov();\n\n    Eigen::MatrixXd A( C.llt().matrixL() );\n\n    std::vector<AR1xGARCH11> processes(7);\n\n    processes[0] = AR1xGARCH11(-0.0003114, -0.0693, 0.01854, 0.10150, 0.88374); // DJIA\n    processes[1] = AR1xGARCH11(-0.0003515,-0.0729,0.01979, 0.09502, 0.89028); // GSPC\n    processes[2] = AR1xGARCH11(-0.0004741,-0.1041,0.02788, 0.08605, 0.89754); // NDX\n    processes[3] = AR1xGARCH11(-1.37e-17, 0.,0.02614, 0.09003, 0.89950); // GDAXI\n    processes[4] = AR1xGARCH11(2.348e-17,0.,0.02476, 0.08731, 0.90240); // FCHI\n    processes[5] = AR1xGARCH11(2.468e-17,0.,0.02987, 0.07847, 0.91352); // SSEC\n    processes[6] = AR1xGARCH11(5.382e-18,0.,2.166e+00, 4.902e-01, 4.990e-15); // SENSEX\n\n    MCEngine<rng,AR1xGARCH11> engine1(_rng, processes, A, Cholesky);\n\n    Mat d = cr->getReturns();\n\n    Vec b;\n\n\tfor(size_t i = 0;i < m;++i) b.push_back(cr->getRollingStdDev(i).back());\n\n    engine1.setValues(d,b);\n\n    Mat sim2(7,Vec(10));\n\n    sim2 = engine1.DoMultiSimulation(10,Gaussian);\n\n    cout << endl;\n    for(size_t i =0;i < sim2.size();++i){\n        for(size_t j =0;j < sim2[i].size();++j)\n            cout << sim2[i][j] << '\\t';\n        cout << endl;\n    }\n\n    //-----------------------------------------------------------------\n    // test PCA case\n\n    // convert to req format\n    vector<float> vec;\n\n\tn = C.rows();\n\tm = C.cols();\n\n    for(size_t i = 0;i < n;++i)\n        for(size_t j = 0;j < m;++j)\n            vec.push_back(C(i,j));\n\n\tstd::shared_ptr<Pca> pca(new Pca());\n\n  \tint init_result = pca->Calculate(vec, n, m);\n\n  \tif(init_result == 1) cout << \"correl mat positive semi-definite \" << endl;\n\n    vector<float> scores = pca->scores(); //Rotated data\n\n  \tunsigned int kaiser = pca->kaiser(); //Kaiser criterion 99%\n\n    unsigned int nrows = pca->nrows();\n\n\tEigen::MatrixXd PC(nrows, kaiser);\n\n\tfor(size_t i = 0;i < nrows;++i)\n\t\tfor(size_t j = 0;j < kaiser;++j)\n\t\t\tPC(i,j) = scores[j + kaiser*i];\n\n    MCEngine<rng,AR1xGARCH11> engine2(_rng, processes, PC, pc);\n\n    engine2.setValues(d,b);\n\n    Mat sim3(7,Vec(10));\n\n    sim3 = engine2.DoMultiSimulation(10,Gaussian);\n\n    cout << endl;\n    for(size_t i =0;i < sim2.size();++i){\n        for(size_t j =0;j < sim2[i].size();++j)\n            cout << sim3[i][j] << '\\t';\n        cout << endl;\n    }\n\n    return 0;\n\n    } catch (const std::exception& e) { // caught by reference to base\n        std::cout << \" a standard exception was caught, with message '\"\n                  << e.what() << \"'\\n\";\n    }\n\n}\n\n\n", "meta": {"hexsha": "76d8329995bb9c3310ee5370c940de4107cf9921", "size": 6157, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/cpptests/test_mcr.cpp", "max_stars_repo_name": "vigor-ish/riskjs", "max_stars_repo_head_hexsha": "6f0aa646821272f64959553ea042819b74a21efc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-08-31T08:33:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-23T04:26:16.000Z", "max_issues_repo_path": "test/cpptests/test_mcr.cpp", "max_issues_repo_name": "vigor-ish/riskjs", "max_issues_repo_head_hexsha": "6f0aa646821272f64959553ea042819b74a21efc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-09-02T02:33:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-02T02:33:13.000Z", "max_forks_repo_path": "test/cpptests/test_mcr.cpp", "max_forks_repo_name": "vigor-ish/riskjs", "max_forks_repo_head_hexsha": "6f0aa646821272f64959553ea042819b74a21efc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-11-19T18:21:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-23T04:26:17.000Z", "avg_line_length": 25.5477178423, "max_line_length": 87, "alphanum_fraction": 0.5728439175, "num_tokens": 1955, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760039, "lm_q2_score": 0.7905303087996143, "lm_q1q2_score": 0.7203151718074551}}
{"text": "/**\n * @file laxwendroffscheme.cc\n * @brief NPDE homework \"LaxWendroffScheme\" code\n * @author Oliver Rietmann\n * @date 29.04.2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"laxwendroffscheme.h\"\n\n#include <Eigen/Core>\n#include <cmath>\n\nnamespace LaxWendroffScheme {\n\nnamespace Constant {\nconstexpr double e = 2.71828182845904523536;\nconstexpr double pi = 3.14159265358979323846;\n}  // namespace Constant\n\nconstexpr double Square(double x) { return x * x; }\n\n/**\n * @brief Computes the right-hand side according to the Lax-Wendroff scheme.\n * @param mu mu^(k-1) (i.e. mu at timestep k-1)\n * @param gamma tau / h, where tau = timestep size and h = spatial meshwidth\n * @return mu^(k) (i.e. mu at timestep k)\n */\n/* SAM_LISTING_BEGIN_0 */\nEigen::VectorXd LaxWendroffRhs(const Eigen::VectorXd &mu, double gamma) {\n  int N = mu.size();\n  Eigen::VectorXd result(N);\n\n#if SOLUTION\n  auto f = [](double x) { return std::exp(x); };\n  auto df2 = [](double x) { return Square(std::exp(x)); };\n\n  // Lax-Wendroff fully discrete evolution \\prbeqref{eq:12} for\n  // $\\cob{f(u)=e^u}$. Store the values of $f(x)$ and $(f'(x))^2$ from the\n  // previous iteration:\n\n  // We extend $\\texttt{mu}$ to the left by $\\texttt{mu(0)}$:\n  double mu_left = mu(0);\n\n  // $f'\\left(\\tfrac{1}{2}\\left(\\mu_j+\\mu_{j-1}\\right)\\right)^2$:\n  double df2_old = df2(0.5 * (mu(0) + mu_left));\n\n  // $f'\\left(\\tfrac{1}{2}\\left(\\mu_{j+1}+\\mu_j\\right)\\right)^2$:\n  double df2_new = df2(0.5 * (mu(1) + mu(0)));\n\n  double f_old = f(mu_left);  // $f\\left(\\mu_{j-1}\\right)$\n  double f_mid = f(mu(0));    // $f\\left(\\mu_j\\right)$\n  double f_new = f(mu(1));    // $f\\left(\\mu_{j+1}\\right)$\n\n  result(0) = mu(0) - 0.5 * gamma * (f_new - f_old) +\n              0.5 * Square(gamma) *\n                  (df2_new * (mu(1) - mu(0)) - df2_old * (mu(0) - mu_left));\n\n  for (int j = 1; j < N - 1; ++j) {\n    df2_old = df2_new;\n    df2_new = df2(0.5 * (mu(j + 1) + mu(j)));\n    f_old = f_mid;\n    f_mid = f_new;\n    f_new = f(mu(j + 1));\n    result(j) =\n        mu(j) - 0.5 * gamma * (f_new - f_old) +\n        0.5 * Square(gamma) *\n            (df2_new * (mu(j + 1) - mu(j)) - df2_old * (mu(j) - mu(j - 1)));\n  }\n\n  // We extend $\\texttt{mu}$ to the right by $\\texttt{mu(N-1)}$:\n  double mu_right = mu(N - 1);\n\n  df2_old = df2_new;\n  df2_new = df2(0.5 * (mu_right + mu(N - 1)));\n\n  f_old = f_mid;\n  f_new = f(mu_right);\n\n  result(N - 1) = mu(N - 1) - 0.5 * gamma * (f_new - f_old) +\n                  0.5 * Square(gamma) *\n                      (df2_new * (mu_right - mu(N - 1)) -\n                       df2_old * (mu(N - 1) - mu(N - 2)));\n#else\n  //====================\n  // Your code goes here\n  //====================\n#endif\n\n  return result;\n}\n\nEigen::VectorXd solveLaxWendroff(const Eigen::VectorXd &u0, double T,\n                                 unsigned int M) {\n  double gamma = 1.0 / Constant::e;\n  Eigen::VectorXd mu = u0;\n  // Main timestepping loop\n  for (int j = 0; j < M; ++j) mu = LaxWendroffRhs(mu, gamma);\n  return mu;\n}\n\n/* SAM_LISTING_END_0 */\n\n/* SAM_LISTING_BEGIN_2 */\n// Build spatial grid\nEigen::VectorXd getXValues(double T, unsigned int M) {\n  double tau = T / M;\n  double h = Constant::e * tau;\n  int j_max = (int)(std::ceil((3.0 * T + 1.0) / h) + 0.5);\n  int j_min = (int)(std::floor(-3.0 * T / h) - 0.5);\n  unsigned int N = j_max - j_min + 1;\n  return Eigen::VectorXd::LinSpaced(N, j_min * h, j_max * h);\n}\nEigen::VectorXd numexpLaxWendroffRP(const Eigen::VectorXi &M) {\n  const double T = 1.0;\n  const int M_size = M.size();\n  Eigen::VectorXd error(M_size);\n  // Initial values for the Riemann problem\n  auto u_initial = [](double x) { return 0.0 <= x ? 1.0 : 0.0; };\n  // Exact solution \\prbeqref{eq:solrp} at time $T = 1.0$\n  auto u_exact = [](double x) {\n    return (x <= 1.0) ? 0.0 : ((Constant::e <= x) ? 1.0 : std::log(x));\n  };\n#if SOLUTION\n  for (int i = 0; i < M_size; ++i) {\n    Eigen::VectorXd x = getXValues(T, M(i));\n    Eigen::VectorXd u0 = x.unaryExpr(u_initial);\n    Eigen::VectorXd uT = solveLaxWendroff(u0, T, M(i));\n\n    double tau = T / M(i);\n    double h = Constant::e * tau;\n    error(i) = h * (x.unaryExpr(u_exact) - uT).lpNorm<1>();\n  }\n#else\n  //====================\n  // Your code goes here\n  //====================\n#endif\n  return error;\n}\n/* SAM_LISTING_END_2 */\n\n/**\n * @brief Evaluates the discrete function u at position x by linear\n * interpolation\n * @param u descrete function values at spatial positions y\n * @param y vector of same length as u, representing the nodes of u\n * @return best linear interpolation of u at spacial position x\n */\ndouble eval(const Eigen::VectorXd &u, const Eigen::VectorXd &y, double x) {\n  int N = y.size();\n  double a = y(0);\n  double b = y(N - 1);\n\n  if (x <= a) return u(0);\n  if (b <= x) return u(N - 1);\n\n  double lambda = (x - a) / (b - a);\n  int k0 = (int)(lambda * (N - 1));\n  int k1 = k0 + 1;\n\n  lambda = (x - y(k0)) / (y(k1) - y(k0));\n  return lambda * u(k1) + (1.0 - lambda) * u(k0);\n}\n\n/* SAM_LISTING_BEGIN_9 */\ndouble smoothU0(double x) {\n  return (x < 0.0)\n             ? 0.0\n             : ((1.0 < x) ? 1.0 : Square(std::sin(0.5 * Constant::pi * x)));\n}\nEigen::VectorXd referenceSolution(const Eigen::VectorXd &x) {\n  double T = 1.0;\n  // Reference solution on a very fine mesh\n  unsigned int M = 3200;\n\n  Eigen::VectorXd y = getXValues(T, M);\n  Eigen::VectorXd u0 = y.unaryExpr(&smoothU0);\n  Eigen::VectorXd u = solveLaxWendroff(u0, T, M);\n  int N = x.size();\n  Eigen::VectorXd u_ref(N);\n  // The vector u is larger than u_ref. Use eval() from above the \"evaluate\" u\n  // at the positions x(i) and thus obtain the reference solution u_ref.\n#if SOLUTION\n  for (int i = 0; i < N; ++i) {\n    u_ref(i) = eval(u, y, x(i));\n  }\n#else\n  //====================\n  // Your code goes here\n  //====================\n#endif\n  return u_ref;\n}\n/* SAM_LISTING_END_9 */\n\n/* SAM_LISTING_BEGIN_1 */\nEigen::VectorXd numexpLaxWendroffSmoothU0(const Eigen::VectorXi &M) {\n  const double T = 1.0;\n  const int M_size = M.size();\n  Eigen::VectorXd error(M_size);\n\n#if SOLUTION\n  for (int i = 0; i < M_size; ++i) {\n    Eigen::VectorXd x = getXValues(T, M(i));\n    Eigen::VectorXd u0 = x.unaryExpr(&smoothU0);\n    Eigen::VectorXd uT = solveLaxWendroff(u0, T, M(i));\n\n    double tau = T / M(i);\n    double h = Constant::e * tau;\n    error(i) = h * (referenceSolution(x) - uT).lpNorm<1>();\n  }\n#else\n  //====================\n  // Your code goes here\n  //====================\n#endif\n  return error;\n}\n/* SAM_LISTING_END_1 */\n\n/* SAM_LISTING_BEGIN_7 */\nEigen::VectorXd solveGodunov(const Eigen::VectorXd &u0, double T,\n                             unsigned int M) {\n  double tau = T / M;\n  double h = Constant::e * tau;\n  unsigned int N = u0.size();\n  Eigen::VectorXd mu = u0;\n\n#if SOLUTION\n  for (int i = 0; i < M; ++i) {\n    for (int j = N - 1; 0 < j; --j) {\n      mu(j) = mu(j) - tau / h * (std::exp(mu(j)) - std::exp(mu(j - 1)));\n    }\n  }\n#else\n  //====================\n  // Your code goes here\n  //====================\n#endif\n  return mu;\n}\n\n/* SAM_LISTING_END_7 */\n\n/* SAM_LISTING_BEGIN_8 */\nEigen::VectorXd numexpGodunovSmoothU0(const Eigen::VectorXi &M) {\n  const double T = 1.0;\n  const int M_size = M.size();\n  Eigen::VectorXd error(M_size);\n\n#if SOLUTION\n  for (int i = 0; i < M_size; ++i) {\n    Eigen::VectorXd x = getXValues(T, M(i));\n    Eigen::VectorXd u0 = x.unaryExpr(&smoothU0);\n    Eigen::VectorXd uT = solveGodunov(u0, T, M(i));\n\n    double tau = T / M(i);\n    double h = Constant::e * tau;\n    error(i) = h * (referenceSolution(x) - uT).lpNorm<1>();\n  }\n#else\n  //====================\n  // Your code goes here\n  //====================\n#endif\n  return error;\n}\n/* SAM_LISTING_END_8 */\n\n}  // namespace LaxWendroffScheme\n", "meta": {"hexsha": "2d793a3c3009f19e9d219d00af8b8ceeb383a85b", "size": 7668, "ext": "cc", "lang": "C++", "max_stars_repo_path": "developers/LaxWendroffScheme/mastersolution/laxwendroffscheme.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": "developers/LaxWendroffScheme/mastersolution/laxwendroffscheme.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": "developers/LaxWendroffScheme/mastersolution/laxwendroffscheme.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": 28.1911764706, "max_line_length": 78, "alphanum_fraction": 0.5661189358, "num_tokens": 2599, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681158979306, "lm_q2_score": 0.83973396967765, "lm_q1q2_score": 0.7202970250258878}}
{"text": "//rng.cpp\n\n#include<memory>\n#include<math.h>\n#include<cmath>\n\n#include <boost/math/distributions.hpp>\n\n#include \"rng.h\"\n\nusing namespace std;\n\ncopulaRng::copulaRng(unsigned int _d, rng& _rng_)\n:d(_d)\n{\n    _rng = shared_ptr<GenFromDistr<rng>>(new GenFromDistr<rng>(_rng_));\n}\n\n// Gaussian\nVec copulaRng::getGaussiancopula(Eigen::MatrixXd C){\n\n\tboost::math::normal_distribution<> dist(0.,1.);\n\n\t//d dimension normal(0, cov)\n\tEigen::VectorXd X = _rng->getXGaussian(d );\n\n\tEigen::MatrixXd A( C.llt().matrixL() );\n\n\tEigen::VectorXd Z = X.transpose() * A ;\n\n\tVec sample;\n\n\tfor(size_t i = 0;i < d;++i)\n        sample.push_back(boost::math::cdf(dist,Z(i)));\n\t\n\treturn sample;\n}\n\n// Studen's t-distr\nVec copulaRng::getStudentcopula(Eigen::MatrixXd C, double v){\n\n\tboost::math::students_t_distribution<> dist(v);\n\n\t//d dimension t-distr(0, cov, degree of freedom) central\n\n\t//1. Find the Cholesky matrix of Sigma -> L\n\tEigen::MatrixXd L( C.llt().matrixL() );\n\n\t//2. Simulate a vector of n N(0,1) iid -> Y\n\tEigen::VectorXd Y = _rng->getXGaussian(d );\n\n\t//3. Simulate a Chi-Square(v) -> S\n\tdouble S = _rng->getOneChisquare(v);\n\t//4. Compute vector Z = sqrt(v/S) * L * Y\n\tEigen::VectorXd Z = L * Y;\n\tZ *= sqrt(v/S);\n\n\t//5. Finally, U = cdf_student(Z)\n\tVec sample;\n\n\tfor(size_t i = 0;i < d;++i)\n\t\tsample.push_back(boost::math::cdf(dist,Z(i)));\n\n\treturn sample;\n}\n\n// Clayton\nVec copulaRng::getClaytoncopula(double gamma){\n\n\tdouble X = _rng->getOneGamma(1./gamma, 1.); //1 dimension gamma_dist(1./gamma, 1.)\n\n\tEigen::VectorXd U = _rng->getXUniform(d); //d dimension uniform(0,1)\n\n\tVec sample;\n\n\tfor(size_t i = 0;i < d;++i)\n\t\tsample.push_back(pow(1.- log(U(i)/X) , -1./gamma));\n\n\treturn sample;\n}\n\n// Gumbel\nVec copulaRng::getGumbelcopula(double gamma){\n\n\tdouble theta = -pow(-cos(M_PI/(2. * gamma)),gamma); \n\n\t//1 dimension stable_dist(1./theta, 1.,gamma,0.)\n\tdouble X = getOneStableDist<shared_ptr<GenFromDistr<rng>>>(_rng,1./gamma, 1.,theta,0.); \n\n\t//d dimension uniform(0,1)\n\tEigen::VectorXd U = _rng->getXUniform(d);\n\n\tVec sample;\n\n\tfor(size_t i = 0;i < d;++i)\n        sample.push_back(exp(-pow(abs(log(abs(U(i)/X))) , 1./gamma)));\n\t\n\treturn sample;\n}\n\n", "meta": {"hexsha": "a0e9d7afa4a92dd9bfd39788760ae944492b6336", "size": 2143, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/rng.cpp", "max_stars_repo_name": "vigor-ish/VaR", "max_stars_repo_head_hexsha": "82e47d529415275fd673b611f1d6ffaff1296863", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-08-31T08:33:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-23T04:26:16.000Z", "max_issues_repo_path": "src/rng.cpp", "max_issues_repo_name": "vigor-ish/VaR", "max_issues_repo_head_hexsha": "82e47d529415275fd673b611f1d6ffaff1296863", "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/rng.cpp", "max_forks_repo_name": "vigor-ish/VaR", "max_forks_repo_head_hexsha": "82e47d529415275fd673b611f1d6ffaff1296863", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-11-19T18:21:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-23T04:26:17.000Z", "avg_line_length": 21.2178217822, "max_line_length": 89, "alphanum_fraction": 0.6542230518, "num_tokens": 696, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850039701653, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.7200782977746818}}
{"text": "///////////////////////////////////////////////////////////////\n//  Copyright 2021 John Maddock. Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt\n\n#include <iostream>\n#include <boost/math/special_functions/relative_difference.hpp>\n#include <boost/math/special_functions/next.hpp>\n#include <boost/multiprecision/mpfr.hpp>\n#include <boost/multiprecision/debug_adaptor.hpp>\n\n//[scoped_precision_1\n\n/*`\nAll our precision changing examples are based around `mpfr_float`.\nHowever, in order to make running this example a little easier to debug,\nwe'll use `debug_adaptor` throughout so that the values of all variables\ncan be displayed in your debugger of choice:\n*/\n\nusing mp_t = boost::multiprecision::debug_adaptor_t<boost::multiprecision::mpfr_float>;\n\n/*`\nOur first example will investigate calculating the Bessel J function via it's well known \nseries representation:\n\n[$../bessel2.svg]\n\nThis simple series suffers from catastrophic cancellation error\nnear the roots of the function, so we'll investigate slowly increasing the precision of\nthe calculation until we get the result to N-decimal places.  We'll begin by defining\na function to calculate the series for Bessel J, the details of which we'll leave in the\nsource code:\n*/\nmp_t calculate_bessel_J_as_series(mp_t x, mp_t v, mp_t* err)\n//<-\n{\n   mp_t sum        = pow(x / 2, v) / tgamma(v + 1);\n   mp_t abs_sum    = abs(sum);\n   mp_t multiplier = -x * x / 4;\n   mp_t divider    = v + 1;\n   mp_t term       = sum;\n   mp_t eps        = boost::math::tools::epsilon<mp_t>();\n   unsigned   m          = 1;\n\n   while (fabs(term / abs_sum) > eps)\n   {\n      term *= multiplier;\n      term /= m;\n      term /= divider;\n      ++divider;\n      ++m;\n      sum += term;\n      abs_sum += abs(term);\n   }\n   if (err)\n      *err = eps * fabs(abs_sum / sum);\n   /*\n   std::cout << eps << std::endl;\n   if (err)\n      std::cout << *err << std::endl;\n   std::cout << abs_sum << std::endl;\n   std::cout << sum << std::endl;\n   */\n   return sum;\n}\n//->\n\n/*`\nNext come some simple helper classes, these allow us to modify the current precision and precision-options\nvia scoped objects which will put everything back as it was at the end.  We'll begin with the class to\nmodify the working precision:\n*/\nstruct scoped_mpfr_precision\n{\n   unsigned saved_digits10;\n   scoped_mpfr_precision(unsigned digits10) : saved_digits10(mp_t::thread_default_precision())\n   {\n      mp_t::thread_default_precision(digits10);\n   }\n   ~scoped_mpfr_precision()\n   {\n      mp_t::thread_default_precision(saved_digits10);\n   }\n   void reset(unsigned digits10)\n   {\n      mp_t::thread_default_precision(digits10);\n   }\n   void reset()\n   {\n      mp_t::thread_default_precision(saved_digits10);\n   }\n};\n/*`\nAnd a second class to modify the precision options:\n*/\nstruct scoped_mpfr_precision_options\n{\n   boost::multiprecision::variable_precision_options saved_options;\n   scoped_mpfr_precision_options(boost::multiprecision::variable_precision_options opts) : saved_options(mp_t::thread_default_variable_precision_options())\n   {\n      mp_t::thread_default_variable_precision_options(opts);\n   }\n   ~scoped_mpfr_precision_options()\n   {\n      mp_t::thread_default_variable_precision_options(saved_options);\n   }\n   void reset(boost::multiprecision::variable_precision_options opts)\n   {\n      mp_t::thread_default_variable_precision_options(opts);\n   }\n};\n/*`\nWe can now begin writing a function to calculate J[sub v](z) to a specified precision.  \nIn order to keep the logic as simple as possible, we'll adopt a ['uniform precision computing] approach, \nwhich is to say, within the body of the function, all variables are always at the same working precision.\n*/\nmp_t Bessel_J_to_precision(mp_t v, mp_t x, unsigned digits10)\n{\n   //\n   // Begin by backing up digits10:\n   //\n   unsigned saved_digits10 = digits10;\n   // \n   //\n   // Start by defining 2 scoped objects to control precision and associated options.\n   // We'll begin by setting the working precision to the required target precision,\n   // and since all variables will always be of uniform precision, we can tell the\n   // library to ignore all precision control by setting variable_precision_options::assume_uniform_precision:\n   //\n   scoped_mpfr_precision           scoped(digits10);\n   scoped_mpfr_precision_options   scoped_opts(boost::multiprecision::variable_precision_options::assume_uniform_precision);\n\n   mp_t            result;\n   mp_t            current_error{1};\n   mp_t            target_error {std::pow(10., -static_cast<int>(digits10))};\n\n   while (target_error < current_error)\n   {\n      //\n      // Everything must be of uniform precision in here, including\n      // our input values, so we'll begin by setting their precision:\n      //\n      v.precision(digits10);\n      x.precision(digits10);\n      //\n      // Calculate our approximation and error estimate:\n      //\n      result = calculate_bessel_J_as_series(x, v, &current_error);\n      //\n      // If the error from the current approximation is too high we'll need \n      // to loop round and try again, in this case we use the simple heuristic\n      // of doubling the working precision with each loop.  More refined approaches\n      // are certainly available:\n      //\n      digits10 *= 2;\n      scoped.reset(digits10);\n   }\n   //\n   // We now have an accurate result, but it may have too many digits,\n   // so lets round the result to the requested precision now:\n   //\n   result.precision(saved_digits10);\n   //\n   // To maintain uniform precision during function return, lets\n   // reset the default precision now:\n   //\n   scoped.reset(saved_digits10);\n   return result;\n}\n\n/*`\nSo far, this is all well and good, but there is still a potential trap for the unwary here,\nwhen the function returns the variable [/result] may be copied/moved either once or twice\ndepending on whether the compiler implements the named-return-value optimisation.  And since this\nall happens outside the scope of this function, the precision of the returned value may get unexpected\nchanged - and potentially with different behaviour once optimisations are turned on!\n\nTo prevent these kinds of unintended consequences, a function returning a value with specified precision\nmust either:\n\n* Be called in a /uniform-precision-environment/, with the current working precision, the same as both\nthe returned value and the variable to which the result will be assigned.\n* Be called in an environment that has one of the following set:\n   * variable_precision_options::preserve_source_precision\n   * variable_precision_options::preserve_component_precision\n   * variable_precision_options::preserve_related_precision\n   * variable_precision_options::preserve_all_precision\n\nIn the case of our example program, we use a /uniform-precision-environment/ and call the function\nwith the value of `6541389046624379 / 562949953421312` which happens to be near a root of J[sub v](x)\nand requires a high-precision calculation to obtain low relative error in the result of \n`-9.31614245636402072613249153246313221710284959883647822724e-15`.\n\nYou will note in the example we have so far that there are a number of unnecessary temporaries\ncreated: we pass values to our functions by value, and we call the `.precision()` member function\nto change the working precision of some variables - something that requires a reallocation internally.\nWe'll now make our example just a little more efficient, by removing these temporaries, though in the\nprocess, we'll need just a little more control over how mixed-precision arithmetic behaves.\n\nIt's tempting to simply define the function that calculates the series to take arguments\nby constant reference like so:\n\n*/\n\nmp_t calculate_bessel_J_as_series_2(const mp_t& x, const mp_t& v, mp_t* err)\n//<-\n{\n   mp_t sum        = pow(x / 2, v) / tgamma(v + 1);\n   mp_t abs_sum    = abs(sum);\n   mp_t multiplier = -x * x / 4;\n   mp_t divider    = v + 1;\n   mp_t term       = sum;\n   mp_t eps        = boost::math::tools::epsilon<mp_t>();\n   unsigned   m          = 1;\n\n   while (fabs(term / abs_sum) > eps)\n   {\n      term *= multiplier;\n      term /= m;\n      term /= divider;\n      ++divider;\n      ++m;\n      sum += term;\n      abs_sum += abs(term);\n   }\n   if (err)\n      *err = eps * fabs(abs_sum / sum);\n\n   return sum;\n}\n//->\n\n/*`\nAnd to then pass our arguments to it, without first altering their precision to match\nthe current working default.  However, imagine that `calculate_bessel_J_as_series_2`\ncalculates x[super 2] internally, what precision is the result?  If it's the same as the\nprecision of /x/, then our calculation will loose precision, since we really want the result\ncalculated to the full current working precision, which may be significantly higher than\nthat of our input variables.  Our new version of Bessel_J_to_precision therefore uses\n`variable_precision_options::preserve_target_precision` internally, so that expressions\ncontaining only the low-precision input variables are calculated at the precision of\n(at least) the target - which will have been constructed at the current working precision.\n\nHere's our revised code:\n\n*/\n\nmp_t Bessel_J_to_precision_2(const mp_t& v, const mp_t& x, unsigned digits10)\n{\n   //\n   // Begin with 2 scoped objects, one to manage current working precision, one to\n   // manage mixed precision arithmetic.  Use of variable_precision_options::preserve_target_precision\n   // ensures that expressions containing only low-precision input variables are evaluated at the precision\n   // of the variable they are being assigned to (ie current working precision).\n   //\n   scoped_mpfr_precision scoped(digits10);\n   scoped_mpfr_precision_options scoped_opts(boost::multiprecision::variable_precision_options::preserve_target_precision);\n\n   mp_t                    result;\n   mp_t            current_error{1};\n   mp_t            target_error{std::pow(10., -static_cast<int>(digits10))};\n\n   while (target_error < current_error)\n   {\n      //\n      // The assignment here, rounds the high precision result\n      // returned by calculate_bessel_J_as_series_2, to the precision\n      // of variable result: ie to the target precision we specified in\n      // the function call.  This is only the case because we have\n      // variable_precision_options::preserve_target_precision set.\n      //\n      result = calculate_bessel_J_as_series_2(x, v, &current_error);\n\n      digits10 *= 2;\n      scoped.reset(digits10);\n   }\n   //\n   // There may be temporaries created when we return, we must make sure\n   // that we reset the working precision and options before we return.\n   // In the case of the options, we must preserve the precision of the source\n   // object during the return, not only here, but in the calling function too:\n   //\n   scoped.reset();\n   scoped_opts.reset(boost::multiprecision::variable_precision_options::preserve_source_precision);\n   return result;\n}\n\n/*`\nIn our final example, we'll look at a (somewhat contrived) case where we reduce the argument\nby N * PI, in this case we change the mixed-precision arithmetic options several times,\ndepending what it is we are trying to achieve at that moment in time:\n\n*/\nmp_t reduce_n_pi(const mp_t& arg)\n{\n   //\n   // We begin by estimating how many multiples of PI we will be reducing by, \n   // note that this is only an estimate because we're using low precision\n   // arithmetic here to get a quick answer:\n   //\n   unsigned n = static_cast<unsigned>(arg / boost::math::constants::pi<mp_t>());\n   //\n   // Now that we have an estimate for N, we can up the working precision and obtain\n   // a high precision value for PI, best to play safe and preserve the precision of the\n   // source here.  Though note that expressions are evaluated at the highest precision\n   // of any of their components: in this case that's the current working precision\n   // returned by boost::math::constants::pi, and not the precision of arg.\n   // However, should this function be called with assume_uniform_precision set\n   // then all bets are off unless we do this:\n   //\n   scoped_mpfr_precision            scope_1(mp_t::thread_default_precision() * 2);\n   scoped_mpfr_precision_options    scope_2(boost::multiprecision::variable_precision_options::preserve_source_precision);\n\n   mp_t reduced = arg - n * boost::math::constants::pi<mp_t>();\n   //\n   // Since N was only an estimate, we may have subtracted one PI too many,\n   // correct if that's the case now:\n   //\n   if (reduced < 0)\n      reduced += boost::math::constants::pi<mp_t>();\n   //\n   // Our variable \"reduced\" now has the correct answer, but too many digits precision, \n   // we can either call its .precision() member function, or assign to a new variable\n   // with variable_precision_options::preserve_target_precision set:\n   //\n   scope_1.reset();\n   scope_2.reset(boost::multiprecision::variable_precision_options::preserve_target_precision);\n   mp_t result = reduced;\n   //\n   // As with previous examples, returning the result may create temporaries, so lets\n   // make sure that we preserve the precision of result.  Note that this isn't strictly\n   // required if the calling context is always of uniform precision, but we can't be sure \n   // of our calling context:\n   //\n   scope_2.reset(boost::multiprecision::variable_precision_options::preserve_source_precision);\n   return result;\n}\n\n/*`\nAnd finally... we need to mention `preserve_component_precision`, `preserve_related_precision` and `preserve_all_precision`.\n\nThese form a hierarchy, with each inheriting the properties of those before it.\n`preserve_component_precision` is used when dealing with complex or interval numbers, for example if we have:\n\n   mpc_complex val = some_expression;\n\nAnd `some_expression` contains scalar values of type `mpfr_float`, then the precision of these is ignored unless\nwe specify at least `preserve_component_precision`.\n\n`preserve_related_precision` we'll somewhat skip over - it extends the range of types whose precision is\nconsidered within an expression to related types - for example all instantiations of `number<mpfr_float_backend<N>, ET>`\nwhen dealing with expression of type `mpfr_float`.  However, such situations are - and should be -  very rare.\n\nThe final option - `preserve_all_precision` - is used to preserve the precision of all the types in an expression, \nfor example:\n\n   // calculate 2^1000 - 1:\n   mpz_int i(1);\n   i <<= 1000;\n   i -= 1;\n\n   mp_t f = i;\n\nThe final assignment above will round the value in /i/ to the current working precision, unless `preserve_all_precision`\nis set, in which case /f/ will end up with sufficient precision to store /i/ unchanged.\n\n*/\n\n//]\n\nint main()\n{\n   mp_t::thread_default_precision(50);\n   mp_t x{6541389046624379uLL};\n   x /= 562949953421312uLL;\n   mp_t v{2};\n   mp_t err;\n   mp_t J = Bessel_J_to_precision(v, x, 50);\n\n   std::cout << std::setprecision(50) << J << std::endl;\n   std::cout << J.precision() << std::endl;\n\n   mp_t expected{\"-9.31614245636402072613249153246313221710284959883647822724e-15\"};\n   std::cout << boost::math::relative_difference(expected, J) << std::endl;\n   \n   J = Bessel_J_to_precision_2(v, x, 50);\n   std::cout << boost::math::relative_difference(expected, J) << std::endl;\n   std::cout << J.precision() << std::endl;\n   \n   std::cout << reduce_n_pi(boost::math::float_next(boost::math::float_next(5 * boost::math::constants::pi<mp_t>()))) << std::endl;\n\n   return 0;\n}\n\n", "meta": {"hexsha": "e47766e738a8b4cf273b3b613a2f9a9d3c2bcc8d", "size": 15503, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "console/src/boost_1_78_0/libs/multiprecision/example/scoped_precision_example.cpp", "max_stars_repo_name": "vany152/FilesHash", "max_stars_repo_head_hexsha": "39f282807b7f1abc56dac389e8259ee3bb557a8d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 106.0, "max_stars_repo_stars_event_min_datetime": "2015-08-07T04:23:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-27T18:25:15.000Z", "max_issues_repo_path": "console/src/boost_1_78_0/libs/multiprecision/example/scoped_precision_example.cpp", "max_issues_repo_name": "vany152/FilesHash", "max_issues_repo_head_hexsha": "39f282807b7f1abc56dac389e8259ee3bb557a8d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 130.0, "max_issues_repo_issues_event_min_datetime": "2016-06-22T22:11:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-29T20:24:09.000Z", "max_forks_repo_path": "console/src/boost_1_78_0/libs/multiprecision/example/scoped_precision_example.cpp", "max_forks_repo_name": "vany152/FilesHash", "max_forks_repo_head_hexsha": "39f282807b7f1abc56dac389e8259ee3bb557a8d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-07-08T19:18:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-14T16:39:56.000Z", "avg_line_length": 39.148989899, "max_line_length": 155, "alphanum_fraction": 0.7176675482, "num_tokens": 3607, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619959279793, "lm_q2_score": 0.8596637451167997, "lm_q1q2_score": 0.7200715111790481}}
{"text": "#include <iostream>\n#include <chrono>\n#include <random>\n#include <map>\n\n#include <opencv2/opencv.hpp>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#include \"matplotlibcpp.h\"\n\n\nusing namespace std;\nusing namespace Eigen;\nnamespace plt = matplotlibcpp;\n\ndouble g(double x, double a, double b, double c)\n{\n  // return a*x*x+b*x+c;\n  return std::exp(a * x * x + b * x + c);\n}\n\nint main(int argc, char **argv) {\n  std::cout << \"Gauss-Newton \\n\";\n\n  double aa = 1.0, bb = 2.0, cc = 1.0;\n  double a = 2.0, b = -1.0, c = 5.5;\n\n  double obs_sigma = 1.0;\n  std::default_random_engine generator;\n  std::normal_distribution<double> obs_noise_distrib(0.0, obs_sigma);\n\n\n  int N = 100;\n  std::vector<double> x_data(N), y_data(N);\n  for (int i = 0; i < N; ++i)\n  {\n    x_data[i] = static_cast<double>(i) / 100.0;\n    y_data[i] = g(x_data[i], aa, bb, cc) + obs_noise_distrib(generator);\n\n  }\n\n  chrono::steady_clock::time_point t1 = chrono::steady_clock::now();\n\n  // Optimize\n  int max_iter = 10000;\n  for (int it = 0; it < max_iter; ++it)\n  {\n    // std::cout << \"iter \" << it << \" : \";\n    // std::cout << \"abc = \" << a << \" \" << b << \" \" << c << \"\\n\";\n    Eigen::Matrix3d H = Eigen::Matrix3d::Zero();\n    Eigen::Vector3d e = Eigen::Vector3d::Zero();\n    double total_err = 0.0;\n    for (int i = 0; i < N; ++i)\n    {\n      double x = x_data[i];\n      double gx = g(x, a, b, c);\n      double err = y_data[i] - gx;\n      total_err += err * err;\n\n      // Compute derivative of f(x) (F(x) = 1/2 sum(||f(x)||^2)\n      Eigen::Vector3d J(0.0, 0.0, 0.0);\n      J[0] = -x * x * gx; // df/da\n      J[1] = -x * gx;  // df/db\n      J[2] = -gx;   // df/dc\n\n      // left part of the normal equation\n      H += J * J.transpose();\n      // right part\n      e += -J * err;\n    }\n    // std::cout << \"H = \" << H << \"\\n\";\n    // std::cout << \"total error: \" << total_err << \"\\n\";\n\n    // solve Hx = e\n    Eigen::Vector3d delta_x = H.inverse() * e;\n    // Eigen::Vector3d delta_x = H.ldlt().solve(e); // second version\n\n    // std::cout << \"delta_x = \" << delta_x.transpose() << \"\\n\";\n\n    if (delta_x.norm() < 1e-4)\n      break;\n\n    a += delta_x[0];\n    b += delta_x[1];\n    c += delta_x[2];\n  }\n  chrono::steady_clock::time_point t2 = chrono::steady_clock::now();\n  chrono::duration<double> time_used = chrono::duration_cast<chrono::duration<double>>(t2 - t1);\n  cout << \"solve time cost = \" << time_used.count() << \" seconds. \" << endl;\n  \n  std::cout << \"final = \" << a << \" \" << b << \" \" << c << \"\\n\";\n\n  vector<double> final_y_data(N);\n  for (int i = 0; i < N; ++i)\n  {\n    final_y_data[i] = g(x_data[i], a, b, c);\n  }\n\n  plt::scatter(x_data, y_data);\n  std::map<std::string, std::string> parameters;\n  parameters[\"c\"] = \"red\";\n  plt::scatter(x_data, final_y_data, 1.0, parameters);\n  plt::show();  \n\n  return 0;\n}\n", "meta": {"hexsha": "a17fcd00e1cb600e21c203332fdf86b475b17adf", "size": 2792, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch6/gauss_newton.cpp", "max_stars_repo_name": "zinsmatt/slambook2", "max_stars_repo_head_hexsha": "3648caff838241553d9f3de332068eb0d501a7dc", "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": "ch6/gauss_newton.cpp", "max_issues_repo_name": "zinsmatt/slambook2", "max_issues_repo_head_hexsha": "3648caff838241553d9f3de332068eb0d501a7dc", "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": "ch6/gauss_newton.cpp", "max_forks_repo_name": "zinsmatt/slambook2", "max_forks_repo_head_hexsha": "3648caff838241553d9f3de332068eb0d501a7dc", "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.8518518519, "max_line_length": 96, "alphanum_fraction": 0.545487106, "num_tokens": 948, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869948899666, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7200625516667523}}
{"text": "/**\n * Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/usr/include/c++/4.2.1\n * Apple LLVM version 9.1.0 (clang-902.0.39.1)\n * Target: x86_64-apple-darwin17.5.0\n * Thread model: posix\n*/\n\n#include <iostream> //std::cout\n#include <iostream> //formatting\n#include <vector> //Container\n#include <boost/rational.hpp> // Rationals\n#include <boost/multiprecision/cpp_int.hpp> //1024bit precision\n\n\ntypedef boost::rational<boost::multiprecision::int1024_t> rational; // reduce boilerplate\n\nrational bernulli(size_t n){\n\n     auto out = std::vector<rational>();\n\n     for(size_t m=0;m<=n;m++){\n         out.emplace_back(1,(m+1)); // automatically constructs object\n         for (size_t j = m;j>=1;j--){\n             out[j-1] = rational(j) * (out[j-1]-out[j]);\n         }\n     }\n     return out[0];\n }\n\nint main() {\n    for(size_t n = 0; n <= 60;n+=n>=2?2:1){\n        auto b = bernulli(n);\n        std::cout << \"B(\"<<std::right<<std::setw(2)<<n<<\") = \";\n        std::cout << std::right<<std::setw(44)<<b.numerator();\n        std::cout << \" / \" << b.denominator() <<std::endl;\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "3832f3f557de7f736f9ed5468e23fc35402d1e94", "size": 1132, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lang/C++/bernoulli-numbers.cpp", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-05T13:42:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-05T13:42:20.000Z", "max_issues_repo_path": "lang/C++/bernoulli-numbers.cpp", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "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": "lang/C++/bernoulli-numbers.cpp", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "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.3, "max_line_length": 114, "alphanum_fraction": 0.5945229682, "num_tokens": 351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966732132748, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.7200293773018274}}
{"text": "#include <iostream>\n#include <fstream>\n#include <string>\n#include <Eigen/Core>\n\n#include <g2o/core/base_vertex.h>\n#include <g2o/core/base_binary_edge.h>\n#include <g2o/core/block_solver.h>\n#include <g2o/core/optimization_algorithm_levenberg.h>\n#include <g2o/core/optimization_algorithm_gauss_newton.h>\n#include <g2o/core/optimization_algorithm_dogleg.h>\n#include <g2o/solvers/dense/linear_solver_dense.h>\n#include <g2o/solvers/cholmod/linear_solver_cholmod.h>\n\n#include <sophus/se3.h>\n#include <sophus/so3.h>\n\ntypedef Eigen::Matrix<double, 6, 6> Matrix6d;\n\n/**\n * Give an approximation( J_R^{-1} ) of the error\n */\nMatrix6d JRInv(Sophus::SE3 error)\n{\n    Matrix6d Jacobian;\n    Jacobian.block(0, 0, 3, 3) = Sophus::SO3::hat(error.so3().log());\n    Jacobian.block(0, 3, 3, 3) = Sophus::SO3::hat(error.translation()); // * Sophus::SO3::hat(error.so3().log());\n    Jacobian.block(3, 0, 3, 3) = Eigen::Matrix3d::Zero();\n    Jacobian.block(3, 3, 3, 3) = Sophus::SO3::hat(error.so3().log());\n    \n    Jacobian = Jacobian*0.5 + Matrix6d::Identity();\n    \n    return Jacobian;\n}\n\n/**\n * vertex of lie algebra\n */\ntypedef Eigen::Matrix<double, 6, 1> Vector6d;\nclass VertexSE3LieAlgebra : public g2o::BaseVertex<6, Sophus::SE3>\n{\npublic:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n\n    bool read(std::istream& is)\n    {\n        double data[7];\n        for (int i = 0; i < 7; i ++) {\n            is >> data[i];\n        }\n        \n        setEstimate(Sophus::SE3(\n            Eigen::Quaterniond(data[6], data[3], data[4], data[5]),\n            Eigen::Vector3d(data[0], data[1], data[2])\n        ));\n        \n        return true;\n    }\n    \n    bool write(std::ostream &os) const\n    {\n        os << id() << \" \";\n        Eigen::Quaterniond q = _estimate.unit_quaternion();\n        os << _estimate.translation().transpose() << \" \";\n        os << q.coeffs()[0] << \" \" << q.coeffs()[1] << \" \" << q.coeffs()[2] << \" \" <<q.coeffs()[3] << std::endl;\n        \n        return true;\n    }\n    \n    virtual void setToOriginImpl()\n    {\n        _estimate = Sophus::SE3();\n    }\n    \n    /* update */\n    virtual void oplusImpl(const double * update)\n    {\n        Sophus::SE3 up(\n            Sophus::SO3(update[3], update[4], update[5]),\n            Eigen::Vector3d(update[0], update[1], update[2])\n        );\n        _estimate = up * _estimate;\n    }\n};\n\nclass EdgeSE3LieAlgebra : public g2o::BaseBinaryEdge<6, Sophus::SE3, VertexSE3LieAlgebra, VertexSE3LieAlgebra>\n{\npublic:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n    \n    bool read(std::istream& is)\n    {\n        double data[7];\n        for (int i = 0; i < 7; i++) {\n            is >> data[i];\n        }\n        \n        Eigen::Quaterniond q(data[6], data[3], data[4], data[5]);\n        q.normalize();\n        setMeasurement(Sophus::SE3(q, Eigen::Vector3d(data[0], data[1], data[2])));\n        \n        for (int i = 0; i < information().rows() && is.good(); i ++) {\n            for (int j = i; j < information().cols() && is.good(); j ++) {\n                is >> information()(i, j);\n                if (i != j) {\n                    information()(j, i) = information()(i, j);\n                }\n            }\n        }\n        \n        return true;\n    }\n    \n    bool write(std::ostream& os) const\n    {\n        VertexSE3LieAlgebra* v1 = static_cast<VertexSE3LieAlgebra*>(_vertices[0]);\n        VertexSE3LieAlgebra* v2 = static_cast<VertexSE3LieAlgebra*>(_vertices[1]);\n        \n        os << v1->id() << \" \" << v2->id() << \" \";\n        \n        Sophus::SE3 m = _measurement;\n        Eigen::Quaterniond q = m.unit_quaternion();\n        os << m.translation().transpose() << \" \";\n        os << q.coeffs()[0] << \" \" << q.coeffs()[1] << \" \" << q.coeffs()[2] << q.coeffs()[3] << \" \";\n        \n        // information matrix\n        for (int i = 0; i < information().rows(); i++)\n            for (int j = i; j < information().cols(); j++)\n                os << information()(i, j) << \" \";\n        \n        os << std::endl;\n        \n        return true;\n    }\n    \n    // Compute Error\n    virtual void computeError()\n    {\n        Sophus::SE3 v1 = (static_cast<VertexSE3LieAlgebra*>(_vertices[0]))->estimate();\n        Sophus::SE3 v2 = (static_cast<VertexSE3LieAlgebra*>(_vertices[1]))->estimate();\n        _error = (_measurement.inverse() * v1.inverse() * v2).log();\n    }\n    \n    // compute Jacobian\n    virtual void linearizeOplus()\n    {\n        Sophus::SE3 v1 = (static_cast<VertexSE3LieAlgebra*>(_vertices[0]))->estimate();\n        Sophus::SE3 v2 = (static_cast<VertexSE3LieAlgebra*>(_vertices[1]))->estimate();\n        Matrix6d J = JRInv(Sophus::SE3::exp(_error));\n        \n        // try J ~= I ?\n        _jacobianOplusXi = - J * v2.inverse().Adj();\n        _jacobianOplusXj = J * v2.inverse().Adj();\n    }\n};\n\nint main(int argc, char** argv)\n{\n    if (argc != 2) {\n        std::cout << \"Usage: pose_graph_g2o_lie_algebra sphere.g2o\" << std::endl;\n        exit(EXIT_FAILURE);\n    }\n    \n    std::ifstream fin(argv[1]);\n    if (!fin) {\n        std::cout << \"file \" << argv[1] << \" does not exist.\" << std::endl;\n        exit(EXIT_FAILURE);\n    }\n    \n    typedef g2o::BlockSolver<g2o::BlockSolverTraits<6, 6>> Block;\n    Block::LinearSolverType* linear_solver = new g2o::LinearSolverCholmod<Block::PoseMatrixType>();\n    Block* block_solver_ptr = new Block(std::unique_ptr<Block::LinearSolverType>(linear_solver));\n    g2o::OptimizationAlgorithmLevenberg* optimization_algorithm_ptr = new g2o::OptimizationAlgorithmLevenberg(std::unique_ptr<Block>(block_solver_ptr));\n//     g2o::OptimizationAlgorithmGaussNewton* optimization_algorithm_ptr = new g2o::OptimizationAlgorithmGaussNewton(std::unique_ptr<Block>(block_solver_ptr));\n//     g2o::OptimizationAlgorithmDogleg* optimization_algorithm_ptr = new g2o::OptimizationAlgorithmDogleg(std::unique_ptr<Block>(block_solver_ptr));\n    \n    g2o::SparseOptimizer optimizer;\n    optimizer.setAlgorithm(optimization_algorithm_ptr);\n    \n    int vertexCnt = 0, edgeCnt = 0;     // the number of vertex & edge\n    std::vector<VertexSE3LieAlgebra*> vertices;\n    std::vector<EdgeSE3LieAlgebra*> edges;\n    \n    while (!fin.eof()) {\n        std::string name;\n        fin >> name;\n        if (name == \"VERTEX_SE3:QUAT\") {\n            // vertex\n            VertexSE3LieAlgebra* v = new VertexSE3LieAlgebra();\n            int index = 0;\n            fin >> index;\n            v->setId(index);\n            v->read(fin);\n            optimizer.addVertex(v);\n            vertexCnt ++;\n            vertices.push_back(v);\n            if (index == 0)\n                v->setFixed(true);\n                    \n        } else if (name == \"EDGE_SE3:QUAT\") {\n            // SE3 - SE3 dege\n            EdgeSE3LieAlgebra* e = new EdgeSE3LieAlgebra();\n            int idx1, idx2;\n            fin >> idx1 >> idx2;\n            e->setId(edgeCnt ++);\n            e->setVertex(0, optimizer.vertices()[idx1]);\n            e->setVertex(1, optimizer.vertices()[idx2]);\n            e->read(fin);\n            optimizer.addEdge(e);\n            edges.push_back(e);\n        }\n        \n        if (!fin.good()) break;\n    }\n    \n    std::cout << \"read total \" << vertexCnt << \" vertices, \" << edgeCnt << \" edges.\" << std::endl;\n    \n    std::cout << \"prepare optimizing ...\" << std::endl;\n    \n    optimizer.setVerbose(true);\n    optimizer.initializeOptimization();\n    \n    std::cout << \"calling optimizing ...\" << std::endl;\n    \n    optimizer.optimize(30);\n    \n    std::cout << \"saving optimization results ...\" << std::endl;\n    \n    /* \u56e0\u4e3a\u7528\u4e86\u81ea\u5b9a\u4e49\u9876\u70b9\u4e14\u6ca1\u6709\u5411g2o\u6ce8\u518c\uff0c\u8fd9\u91cc\u4fdd\u5b58\u81ea\u5df1\u6765\u5b9e\u73b0\u4f2a\u88c5\u6210 SE3 \u9876\u70b9\u548c\u8fb9\uff0c\u8ba9 g2o_viewer \u53ef\u4ee5\u8ba4\u51fa */\n    std::ofstream fout(\"result_lie.g2o\");\n    if (!fout.is_open()) {\n        std::cout << \"result_lie.g2o dose not exist.\" << std::endl;\n        exit(EXIT_FAILURE);\n    }\n    \n    for (auto v : vertices) {\n        fout << \"VERTEX_SE3:QUAT \";\n        v->write(fout);\n    }\n    for (auto e : edges) {\n        fout << \"EDGE_SE3:QUAT \";\n        e->write(fout);\n    }\n    \n    fout.close();\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", "meta": {"hexsha": "1da5ebbcf43cd09d3f6de9b3ff0b1761a64999e5", "size": 7958, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pose_graph/src/pose_graph_g2o_lie_algebra.cpp", "max_stars_repo_name": "LSXiang/slam_learning_journey", "max_stars_repo_head_hexsha": "1173bbab4e50a29a61d3affb23ceca32bcc0bf97", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-03-22T00:25:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-01T05:23:27.000Z", "max_issues_repo_path": "pose_graph/src/pose_graph_g2o_lie_algebra.cpp", "max_issues_repo_name": "LSXiang/slam_learning_journey", "max_issues_repo_head_hexsha": "1173bbab4e50a29a61d3affb23ceca32bcc0bf97", "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": "pose_graph/src/pose_graph_g2o_lie_algebra.cpp", "max_forks_repo_name": "LSXiang/slam_learning_journey", "max_forks_repo_head_hexsha": "1173bbab4e50a29a61d3affb23ceca32bcc0bf97", "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.6940298507, "max_line_length": 159, "alphanum_fraction": 0.5551646142, "num_tokens": 2263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037282594921, "lm_q2_score": 0.7772998508568416, "lm_q1q2_score": 0.7200157498242395}}
{"text": "// original code https://zhuanlan.zhihu.com/p/61216321\n\n#include <iostream>\n#include <opencv2/opencv.hpp>\n\n#include \"common/pixel_benchmark.h\"\n#include \"common/pixel_log.h\"\n\n#include <Eigen/Dense>\n\nusing std::cout;\nusing std::endl;\n\nint main(int argc, char **argv)\n{\n    int dim = 1000;\n    cv::Scalar s_min(-5);\n    cv::Scalar s_max(5);\n\n    cv::Mat m1(dim, dim, CV_32FC1);\n    cv::Mat m2(dim, dim, CV_32FC1);\n    cv::Mat m3 = cv::Mat::zeros(dim, dim, CV_32F);\n\n    cv::randu(m1, s_min, s_max);\n    cv::randu(m2, s_min, s_max);\n\n    const int times = 10;\n\n    // opencv multiple\n    double t_start = pixel_get_current_time();\n    for (int i = 0; i < times; i++)\n    {\n        m3 += m1 * m2;\n    }\n    double t_cost = pixel_get_current_time() - t_start;\n    printf(\"Opencv Multiple %d cost %lf ms.\\n\", times, t_cost);\n    //cout<<\"Result: \"<<endl<<m3<<endl;\n\n    // opencv add\n    m3 = cv::Mat::zeros(dim, dim, CV_32F);\n    t_start = pixel_get_current_time();\n    for (int i = 0; i < times; i++)\n    {\n        m3 += m1 + m2;\n    }\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"Opencv Add %d cost %lf ms.\\n\", times, t_cost);\n    //cout<<\"Result: \"<<endl<<m3<<endl;\n\n    // Eigen::Matrix3f eM1, eM2, eM3;\n    // eM1 << 1., 0., 3., 0., 5., 6., 7., 8., 0.;\n    // eM2 << 0., 2., 1., 4., 5., 6., 7., 1., 0.;\n    // eM3 = Eigen::Matrix3f::Zero();\n\n    Eigen::MatrixXf eM1 = Eigen::MatrixXd::Random(dim, dim);\n    Eigen::MatrixXd eM2 = Eigen::MatrixXd::Random(dim, dim);\n    Eigen::MatrixXd eM3 = Eigen::MatrixXd::Zero();\n\n    // eigen multiple\n    t_start = pixel_get_current_time();\n    for (int i = 0; i < times; i++)\n    {\n        eM3 += eM1 * eM2;\n    }\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"Eigen Multiple %d cost %lf ms.\\n\", times, t_cost);\n    //cout<<\"Result: \"<<endl<<eM3<<endl;\n\n    // eigen add\n    eM3 = Eigen::Matrix3f::Zero();\n    t_start = pixel_get_current_time();\n    for (int i = 0; i < times; i++)\n    {\n        eM3 += eM1 + eM2;\n    }\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"Eigen Add %d cost %lf ms.\\n\", times, t_cost);\n    //cout<<\"Result: \"<<endl<<eM3<<endl;\n\n    return 0;\n}", "meta": {"hexsha": "fbd8f7ef361ab49799f2e5dc995169d96eaff6e5", "size": 2151, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "matcalc/matrix_test/testbed.cpp", "max_stars_repo_name": "zchrissirhcz/pixel", "max_stars_repo_head_hexsha": "6bfe4b2f2b80de64c7de4b6d8735de8000b7dc3a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 38.0, "max_stars_repo_stars_event_min_datetime": "2020-12-23T16:37:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T13:46:04.000Z", "max_issues_repo_path": "matcalc/matrix_test/testbed.cpp", "max_issues_repo_name": "zchrissirhcz/pixel", "max_issues_repo_head_hexsha": "6bfe4b2f2b80de64c7de4b6d8735de8000b7dc3a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-01-31T16:04:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T13:58:11.000Z", "max_forks_repo_path": "matcalc/matrix_test/testbed.cpp", "max_forks_repo_name": "zchrissirhcz/pixel", "max_forks_repo_head_hexsha": "6bfe4b2f2b80de64c7de4b6d8735de8000b7dc3a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-11-23T09:33:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-15T08:13:56.000Z", "avg_line_length": 26.5555555556, "max_line_length": 63, "alphanum_fraction": 0.569502557, "num_tokens": 744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391600697869, "lm_q2_score": 0.7799929104825007, "lm_q1q2_score": 0.719964000952156}}
{"text": "#ifndef _EIGEN_QUADSOLVE_HPP_\n#define _EIGEN_QUADSOLVE_HPP_\n\n\n/*\n FILE eiquadprog.hh\n \n NOTE: this is a modified of uQuadProg++ package, working with Eigen data structures. \n       uQuadProg++ is itself a port made by Angelo Furfaro of QuadProg++ originally developed by \n       Luca Di Gaspero, working with ublas data structures. \n\n The quadprog_solve() function implements the algorithm of Goldfarb and Idnani \n for the solution of a (convex) Quadratic Programming problem\nby means of a dual method.\n\t \nThe problem is in the form:\n\nmin 0.5 * x G x + g0 x\ns.t.\n    CE^T x + ce0 = 0\n    CI^T x + ci0 >= 0\n\t \n The matrix and vectors dimensions are as follows:\n     G: n * n\n\t\tg0: n\n\t\t\t\t\n\t\tCE: n * p\n\t ce0: p\n\t\t\t\t\n\t  CI: n * m\n   ci0: m\n\n     x: n\n \n The function will return the cost of the solution written in the x vector or\n std::numeric_limits::infinity() if the problem is infeasible. In the latter case\n the value of the x vector is not correct.\n \n References: D. Goldfarb, A. Idnani. A numerically stable dual method for solving\n             strictly convex quadratic programs. Mathematical Programming 27 (1983) pp. 1-33.\n\n Notes:\n  1. pay attention in setting up the vectors ce0 and ci0. \n\t   If the constraints of your problem are specified in the form \n\t   A^T x = b and C^T x >= d, then you should set ce0 = -b and ci0 = -d.\n  2. The matrix G is modified within the function since it is used to compute\n     the G = L^T L cholesky factorization for further computations inside the function. \n     If you need the original matrix G you should make a copy of it and pass the copy\n     to the function.\n    \n \n The author will be grateful if the researchers using this software will\n acknowledge the contribution of this modified function and of Di Gaspero's\n original version in their research papers.\n\n\nLICENSE\n\nCopyright (2011) Benjamin Stephens\nCopyright (2010) Gael Guennebaud\nCopyright (2008) Angelo Furfaro\nCopyright (2006) Luca Di Gaspero\n\n\nThis file is a porting of QuadProg++ routine, originally developed\nby Luca Di Gaspero, exploiting uBlas data structures for vectors and\nmatrices instead of native C++ array.\n\nuquadprog is free software; you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation; either version 2 of the License, or\n(at your option) any later version.\n\nuquadprog is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with uquadprog; if not, write to the Free Software\nFoundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n*/\n\n#include <Eigen/Core>\n#include <Eigen/Cholesky>\n\nnamespace Eigen {\n\n// namespace internal {\n\ntemplate<typename Scalar>\ninline Scalar distance(Scalar a, Scalar b)\n{\n\tScalar a1, b1, t;\n\ta1 = std::abs(a);\n\tb1 = std::abs(b);\n\tif (a1 > b1) \n\t{\n\t\tt = (b1 / a1);\n\t\treturn a1 * std::sqrt(1.0 + t * t);\n\t}\n\telse\n\t\tif (b1 > a1)\n\t\t{\n\t\t\tt = (a1 / b1);\n\t\t\treturn b1 * std::sqrt(1.0 + t * t);\n\t\t}\n\treturn a1 * std::sqrt(2.0);\n}\n\n// }\n\ninline void compute_d(VectorXd &d, const MatrixXd& J, const VectorXd& np)\n{\n  d = J.adjoint() * np;\n}\n\ninline void update_z(VectorXd& z, const MatrixXd& J, const VectorXd& d,  int iq)\n{\n  z = J.rightCols(z.size()-iq) * d.tail(d.size()-iq);\n}\n\ninline void update_r(const MatrixXd& R, VectorXd& r, const VectorXd& d, int iq) \n{\n  r.head(iq)= R.topLeftCorner(iq,iq).triangularView<Upper>().solve(d.head(iq));\n}\n\nbool add_constraint(MatrixXd& R, MatrixXd& J, VectorXd& d, int& iq, double& R_norm);\nvoid delete_constraint(MatrixXd& R, MatrixXd& J, VectorXi& A, VectorXd& u,  int p, int& iq, int l);\n\n/* solve_quadprog2 is used when the Cholesky decomposition of the G matrix is precomputed */\ndouble solve_quadprog2(LLT<MatrixXd,Lower> &chol,  double c1, VectorXd & g0,  \n                      const MatrixXd & CE, const VectorXd & ce0,  \n                      const MatrixXd & CI, const VectorXd & ci0, \n                      VectorXd& x);\n\n/* solve_quadprog is used for on-demand QP solving */\ninline double solve_quadprog(MatrixXd & G,  VectorXd & g0,  \n                      const MatrixXd & CE, const VectorXd & ce0,  \n                      const MatrixXd & CI, const VectorXd & ci0, \n                      VectorXd& x){\n\t\t\t\t\t\t  \n  LLT<MatrixXd,Lower> chol(G.cols());\n  double c1;\n\n  /* compute the trace of the original matrix G */\n  c1 = G.trace();\n\n  /* decompose the matrix G in the form LL^T */\n  chol.compute(G);\n\n  return solve_quadprog2(chol, c1, g0, CE, ce0, CI, ci0, x);\n\n}\n\n/* solve_quadprog2 is used for when the Cholesky decomposition of G is pre-computed */\ninline double solve_quadprog2(LLT<MatrixXd,Lower> &chol,  double c1, VectorXd & g0,  \n                      const MatrixXd & CE, const VectorXd & ce0,  \n                      const MatrixXd & CI, const VectorXd & ci0, \n                      VectorXd& x)\n{\n  int i, j, k, l; /* indices */\n  int ip, me, mi;\n  int n=g0.size();   \n  int p=CE.cols(); \n  int m=CI.cols();\n  MatrixXd R(g0.size(),g0.size()), J(g0.size(),g0.size());\n  \n \n  VectorXd s(m+p), z(n), r(m + p), d(n),  np(n), u(m + p);\n  VectorXd x_old(n), u_old(m + p);\n  double f_value, psi, c2, sum, ss, R_norm;\n  const double inf = std::numeric_limits<double>::infinity();\n  double t, t1, t2; /* t is the step length, which is the minimum of the partial step length t1 \n    * and the full step length t2 */\n  VectorXi A(m + p), A_old(m + p), iai(m + p), iaexcl(m+p);\n  int q;\n  int iq, iter = 0;\n \t\n  me = p; /* number of equality constraints */\n  mi = m; /* number of inequality constraints */\n  q = 0;  /* size of the active set A (containing the indices of the active constraints) */\n  \n  /*\n   * Preprocessing phase\n   */\n\t\n\t\n \n  /* initialize the matrix R */\n  d.setZero();\n  R.setZero();\n\tR_norm = 1.0; /* this variable will hold the norm of the matrix R */\n  \n\t/* compute the inverse of the factorized matrix G^-1, this is the initial value for H */\n  // J = L^-T\n  J.setIdentity();\n  J = chol.matrixU().solve(J);\n\tc2 = J.trace();\n#ifdef TRACE_SOLVER\n print_matrix(\"J\", J, n);\n#endif\n  \n\t/* c1 * c2 is an estimate for cond(G) */\n  \n\t/* \n   * Find the unconstrained minimizer of the quadratic form 0.5 * x G x + g0 x \n   * this is a feasible point in the dual space\n\t * x = G^-1 * g0\n   */\n  x = chol.solve(g0);\n  x = -x;\n\t/* and compute the current solution value */ \n\tf_value = 0.5 * g0.dot(x);\n#ifdef TRACE_SOLVER\n  std::cerr << \"Unconstrained solution: \" << f_value << std::endl;\n  print_vector(\"x\", x, n);\n#endif\n  \n\t/* Add equality constraints to the working set A */\n  iq = 0;\n\tfor (i = 0; i < me; i++)\n\t{\n    np = CE.col(i);\n    compute_d(d, J, np);\n\t\tupdate_z(z, J, d,  iq);\n\t\tupdate_r(R, r, d,  iq);\n#ifdef TRACE_SOLVER\n\t\tprint_matrix(\"R\", R, iq);\n\t\tprint_vector(\"z\", z, n);\n\t\tprint_vector(\"r\", r, iq);\n\t\tprint_vector(\"d\", d, n);\n#endif\n    \n    /* compute full step length t2: i.e., the minimum step in primal space s.t. the contraint \n      becomes feasible */\n    t2 = 0.0;\n\tif (std::abs(z.dot(z)) > std::numeric_limits<double>::epsilon()) // i.e. z != 0\n      t2 = (-np.dot(x) - ce0(i)) / z.dot(np);\n    \n    x += t2 * z;\n\n    /* set u = u+ */\n    u(iq) = t2;\n    u.head(iq) -= t2 * r.head(iq);\n    \n    /* compute the new solution value */\n    f_value += 0.5 * (t2 * t2) * z.dot(np);\n    A(i) = -i - 1;\n    \n    if (!add_constraint(R, J, d, iq, R_norm))\n    {\n      // FIXME: it should raise an error\n      // Equality constraints are linearly dependent\n      return f_value;\n    }\n  }\n  \n\t/* set iai = K \\ A */\n\tfor (i = 0; i < mi; i++)\n\t\tiai(i) = i;\n  \nl1:\titer++;\n#ifdef TRACE_SOLVER\n  print_vector(\"x\", x, n);\n#endif\n  /* step 1: choose a violated constraint */\n\tfor (i = me; i < iq; i++)\n\t{\n\t  ip = A(i);\n\t\tiai(ip) = -1;\n\t}\n\t\n\t/* compute s(x) = ci^T * x + ci0 for all elements of K \\ A */\n\tss = 0.0;\n\tpsi = 0.0; /* this value will contain the sum of all infeasibilities */\n\tip = 0; /* ip will be the index of the chosen violated constraint */\n\tfor (i = 0; i < mi; i++)\n\t{\n\t\tiaexcl(i) = 1;\n\t\tsum = CI.col(i).dot(x) + ci0(i);\n\t\ts(i) = sum;\n\t\tpsi += std::min((double)0.0, sum);\n\t}\n#ifdef TRACE_SOLVER\n  print_vector(\"s\", s, mi);\n#endif\n\n    \n\tif (std::abs(psi) <= mi * std::numeric_limits<double>::epsilon() * c1 * c2* 100.0)\n\t{\n    /* numerically there are not infeasibilities anymore */\n    q = iq;\n\t\treturn f_value;\n  }\n    \n  /* save old values for u, x and A */\n   u_old.head(iq) = u.head(iq);\n   A_old.head(iq) = A.head(iq);\n   x_old = x;\n    \nl2: /* Step 2: check for feasibility and determine a new S-pair */\n\tfor (i = 0; i < mi; i++)\n\t{\n\t\tif (s(i) < ss && iai(i) != -1 && iaexcl(i))\n\t\t{\n\t\t\tss = s(i);\n\t\t\tip = i;\n\t\t}\n\t}\n  if (ss >= 0.0)\n  {\n    q = iq;\n    return f_value;\n  }\n    \n  /* set np = n(ip) */\n  np = CI.col(ip);\n  /* set u = (u 0)^T */\n  u(iq) = 0.0;\n  /* add ip to the active set A */\n  A(iq) = ip;\n\n#ifdef TRACE_SOLVER\n\tstd::cerr << \"Trying with constraint \" << ip << std::endl;\n\tprint_vector(\"np\", np, n);\n#endif\n    \nl2a:/* Step 2a: determine step direction */\n  /* compute z = H np: the step direction in the primal space (through J, see the paper) */\n  compute_d(d, J, np);\n  update_z(z, J, d, iq);\n  /* compute N* np (if q > 0): the negative of the step direction in the dual space */\n  update_r(R, r, d, iq);\n#ifdef TRACE_SOLVER\n  std::cerr << \"Step direction z\" << std::endl;\n\t\tprint_vector(\"z\", z, n);\n\t\tprint_vector(\"r\", r, iq + 1);\n    print_vector(\"u\", u, iq + 1);\n    print_vector(\"d\", d, n);\n    print_ivector(\"A\", A, iq + 1);\n#endif\n    \n  /* Step 2b: compute step length */\n  l = 0;\n  /* Compute t1: partial step length (maximum step in dual space without violating dual feasibility */\n  t1 = inf; /* +inf */\n  /* find the index l s.t. it reaches the minimum of u+(x) / r */\n  for (k = me; k < iq; k++)\n  {\n    double tmp;\n    if (r(k) > 0.0 && ((tmp = u(k) / r(k)) < t1) )\n    {\n      t1 = tmp;\n      l = A(k);\n    }\n  }\n  /* Compute t2: full step length (minimum step in primal space such that the constraint ip becomes feasible */\n  if (std::abs(z.dot(z))  > std::numeric_limits<double>::epsilon()) // i.e. z != 0\n    t2 = -s(ip) / z.dot(np);\n  else\n    t2 = inf; /* +inf */\n\n  /* the step is chosen as the minimum of t1 and t2 */\n  t = std::min(t1, t2);\n#ifdef TRACE_SOLVER\n  std::cerr << \"Step sizes: \" << t << \" (t1 = \" << t1 << \", t2 = \" << t2 << \") \";\n#endif\n  \n  /* Step 2c: determine new S-pair and take step: */\n  \n  /* case (i): no step in primal or dual space */\n  if (t >= inf)\n  {\n    /* QPP is infeasible */\n    // FIXME: unbounded to raise\n    q = iq;\n    return inf;\n  }\n  /* case (ii): step in dual space */\n  if (t2 >= inf)\n  {\n    /* set u = u +  t * [-r 1) and drop constraint l from the active set A */\n    u.head(iq) -= t * r.head(iq);\n    u(iq) += t;\n    iai(l) = l;\n    delete_constraint(R, J, A, u, p, iq, l);\n#ifdef TRACE_SOLVER\n    std::cerr << \" in dual space: \" \n      << f_value << std::endl;\n    print_vector(\"x\", x, n);\n    print_vector(\"z\", z, n);\n\t\tprint_ivector(\"A\", A, iq + 1);\n#endif\n    goto l2a;\n  }\n  \n  /* case (iii): step in primal and dual space */\n  \n  x += t * z;\n  /* update the solution value */\n  f_value += t * z.dot(np) * (0.5 * t + u(iq));\n  \n  u.head(iq) -= t * r.head(iq);\n  u(iq) += t;\n#ifdef TRACE_SOLVER\n  std::cerr << \" in both spaces: \" \n    << f_value << std::endl;\n\tprint_vector(\"x\", x, n);\n\tprint_vector(\"u\", u, iq + 1);\n\tprint_vector(\"r\", r, iq + 1);\n\tprint_ivector(\"A\", A, iq + 1);\n#endif\n  \n  if (t == t2)\n  {\n#ifdef TRACE_SOLVER\n    std::cerr << \"Full step has taken \" << t << std::endl;\n    print_vector(\"x\", x, n);\n#endif\n    /* full step has taken */\n    /* add constraint ip to the active set*/\n\t\tif (!add_constraint(R, J, d, iq, R_norm))\n\t\t{\n\t\t\tiaexcl(ip) = 0;\n\t\t\tdelete_constraint(R, J, A, u, p, iq, ip);\n#ifdef TRACE_SOLVER\n      print_matrix(\"R\", R, n);\n      print_ivector(\"A\", A, iq);\n#endif\n\t\t\tfor (i = 0; i < m; i++)\n\t\t\t\tiai(i) = i;\n\t\t\tfor (i = 0; i < iq; i++)\n\t\t\t{\n\t\t\t\tA(i) = A_old(i);\n\t\t\t\tiai(A(i)) = -1;\n\t\t\t\tu(i) = u_old(i);\n\t\t\t}\n\t\t\tx = x_old;\n      goto l2; /* go to step 2 */\n\t\t}    \n    else\n      iai(ip) = -1;\n#ifdef TRACE_SOLVER\n    print_matrix(\"R\", R, n);\n    print_ivector(\"A\", A, iq);\n#endif\n    goto l1;\n  }\n  \n  /* a patial step has taken */\n#ifdef TRACE_SOLVER\n  std::cerr << \"Partial step has taken \" << t << std::endl;\n  print_vector(\"x\", x, n);\n#endif\n  /* drop constraint l */\n\tiai(l) = l;\n\tdelete_constraint(R, J, A, u, p, iq, l);\n#ifdef TRACE_SOLVER\n  print_matrix(\"R\", R, n);\n  print_ivector(\"A\", A, iq);\n#endif\n  \n  s(ip) = CI.col(ip).dot(x) + ci0(ip);\n\n#ifdef TRACE_SOLVER\n  print_vector(\"s\", s, mi);\n#endif\n  goto l2a;\n}\n\n\ninline bool add_constraint(MatrixXd& R, MatrixXd& J, VectorXd& d, int& iq, double& R_norm)\n{\n int n=J.rows();\n#ifdef TRACE_SOLVER\n  std::cerr << \"Add constraint \" << iq << '/';\n#endif\n\tint i, j, k;\n\tdouble cc, ss, h, t1, t2, xny;\n\t\n  /* we have to find the Givens rotation which will reduce the element\n\t\td(j) to zero.\n\t\tif it is already zero we don't have to do anything, except of\n\t\tdecreasing j */  \n\tfor (j = n - 1; j >= iq + 1; j--)\n\t{\n    /* The Givens rotation is done with the matrix (cc cs, cs -cc).\n\t\t\t If cc is one, then element (j) of d is zero compared with element\n\t\t\t (j - 1). Hence we don't have to do anything. \n\t\t\t If cc is zero, then we just have to switch column (j) and column (j - 1) \n\t\t\t of J. Since we only switch columns in J, we have to be careful how we\n\t\t\t update d depending on the sign of gs.\n\t\t\t Otherwise we have to apply the Givens rotation to these columns.\n\t\t\t The i - 1 element of d has to be updated to h. */\n\t\tcc = d(j - 1);\n\t\tss = d(j);\n\t\th = distance(cc, ss);\n\t\tif (h == 0.0)\n\t\t\tcontinue;\n\t\td(j) = 0.0;\n\t\tss = ss / h;\n\t\tcc = cc / h;\n\t\tif (cc < 0.0)\n\t\t{\n\t\t\tcc = -cc;\n\t\t\tss = -ss;\n\t\t\td(j - 1) = -h;\n\t\t}\n\t\telse\n\t\t\td(j - 1) = h;\n\t\txny = ss / (1.0 + cc);\n\t\tfor (k = 0; k < n; k++)\n\t\t{\n\t\t\tt1 = J(k,j - 1);\n\t\t\tt2 = J(k,j);\n\t\t\tJ(k,j - 1) = t1 * cc + t2 * ss;\n\t\t\tJ(k,j) = xny * (t1 + J(k,j - 1)) - t2;\n\t\t}\n\t}\n  /* update the number of constraints added*/\n\tiq++;\n  /* To update R we have to put the iq components of the d vector\n    into column iq - 1 of R\n    */\n  R.col(iq-1).head(iq) = d.head(iq);\n#ifdef TRACE_SOLVER\n  std::cerr << iq << std::endl;\n#endif\n  \n\tif (std::abs(d(iq - 1)) <= std::numeric_limits<double>::epsilon() * R_norm)\n\t\t// problem degenerate\n\t\treturn false;\n\tR_norm = std::max<double>(R_norm, std::abs(d(iq - 1)));\n\treturn true;\n}\n\n\ninline void delete_constraint(MatrixXd& R, MatrixXd& J, VectorXi& A, VectorXd& u,  int p, int& iq, int l)\n{\n\n  int n = R.rows();\n#ifdef TRACE_SOLVER\n  std::cerr << \"Delete constraint \" << l << ' ' << iq;\n#endif\n\tint i, j, k, qq;\n\tdouble cc, ss, h, xny, t1, t2;\n  \n\t/* Find the index qq for active constraint l to be removed */\n  for (i = p; i < iq; i++)\n  if (A(i) == l)\n  {\n    qq = i;\n    break;\n  }\n      \n  /* remove the constraint from the active set and the duals */\n  for (i = qq; i < iq - 1; i++)\n  {\n    A(i) = A(i + 1);\n    u(i) = u(i + 1);\n    R.col(i) = R.col(i+1);\n  }\n      \n  A(iq - 1) = A(iq);\n  u(iq - 1) = u(iq);\n  A(iq) = 0; \n  u(iq) = 0.0;\n  for (j = 0; j < iq; j++)\n    R(j,iq - 1) = 0.0;\n  /* constraint has been fully removed */\n  iq--;\n#ifdef TRACE_SOLVER\n  std::cerr << '/' << iq << std::endl;\n#endif \n  \n  if (iq == 0)\n    return;\n  \n  for (j = qq; j < iq; j++)\n  {\n    cc = R(j,j);\n    ss = R(j + 1,j);\n    h = distance(cc, ss);\n    if (h == 0.0)\n      continue;\n    cc = cc / h;\n    ss = ss / h;\n    R(j + 1,j) = 0.0;\n    if (cc < 0.0)\n    {\n      R(j,j) = -h;\n      cc = -cc;\n      ss = -ss;\n    }\n    else\n      R(j,j) = h;\n    \n    xny = ss / (1.0 + cc);\n    for (k = j + 1; k < iq; k++)\n    {\n      t1 = R(j,k);\n      t2 = R(j + 1,k);\n      R(j,k) = t1 * cc + t2 * ss;\n      R(j + 1,k) = xny * (t1 + R(j,k)) - t2;\n    }\n    for (k = 0; k < n; k++)\n    {\n      t1 = J(k,j);\n      t2 = J(k,j + 1);\n      J(k,j) = t1 * cc + t2 * ss;\n      J(k,j + 1) = xny * (J(k,j) + t1) - t2;\n    }\n  }\n}\n\n}\n\n#endif\n", "meta": {"hexsha": "883440f579b1c854904ea7258ff9fcbe017c2589", "size": 16060, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/cilantro/3rd_party/eigen_quadprog/eiquadprog.hpp", "max_stars_repo_name": "eecn/cilantro", "max_stars_repo_head_hexsha": "467824bb7551e4537b2b7d1f697156f68f608260", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 719.0, "max_stars_repo_stars_event_min_datetime": "2017-08-07T08:30:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T07:08:52.000Z", "max_issues_repo_path": "include/cilantro/3rd_party/eigen_quadprog/eiquadprog.hpp", "max_issues_repo_name": "eecn/cilantro", "max_issues_repo_head_hexsha": "467824bb7551e4537b2b7d1f697156f68f608260", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 55.0, "max_issues_repo_issues_event_min_datetime": "2017-09-19T13:40:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-16T13:58:32.000Z", "max_forks_repo_path": "include/cilantro/3rd_party/eigen_quadprog/eiquadprog.hpp", "max_forks_repo_name": "eecn/cilantro", "max_forks_repo_head_hexsha": "467824bb7551e4537b2b7d1f697156f68f608260", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 152.0, "max_forks_repo_forks_event_min_datetime": "2017-12-13T07:28:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T07:02:48.000Z", "avg_line_length": 25.8615136876, "max_line_length": 111, "alphanum_fraction": 0.5766500623, "num_tokens": 5325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.719919295693543}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main()\n{\n  MatrixXf m(2,2);\n  MatrixXf n(2,2);\n  \n  MatrixXf result(2,2);\n\n  //initialize matrices\n  m << 1,2,\n       3,4;\n\n  n << 5,6,\n       7,8;\n  \n  // mix of array and matrix operations\n  //   first coefficient-wise addition\n  //   then the result is used with matrix multiplication\n  result = (m.array() + 4).matrix() * m;\n\n  cout << \"-- Combination 1: --\" << endl\n    << result << endl << endl;\n\n\n  // mix of array and matrix operations\n  //   first coefficient-wise multiplication\n  //   then the result is used with matrix multiplication\n  result = (m.array() * n.array()).matrix() * m;\n\n  cout << \"-- Combination 2: --\" << endl\n    << result << endl << endl;\n\n}\n", "meta": {"hexsha": "72ac5d3078b36d2fc618a74a1ccea92332d71524", "size": 765, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "t1m1/include/eigen/doc/examples/Tutorial_ArrayClass_interop.cpp", "max_stars_repo_name": "dailysoap/CSMM.104x", "max_stars_repo_head_hexsha": "4515b30ab5f60827a9011b23ef155a3063584a9d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2017-04-01T17:18:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T05:23:23.000Z", "max_issues_repo_path": "t1m1/include/eigen/doc/examples/Tutorial_ArrayClass_interop.cpp", "max_issues_repo_name": "dailysoap/CSMM.104x", "max_issues_repo_head_hexsha": "4515b30ab5f60827a9011b23ef155a3063584a9d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-05-24T13:36:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T06:44:20.000Z", "max_forks_repo_path": "t1m1/include/eigen/doc/examples/Tutorial_ArrayClass_interop.cpp", "max_forks_repo_name": "dailysoap/CSMM.104x", "max_forks_repo_head_hexsha": "4515b30ab5f60827a9011b23ef155a3063584a9d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-09-20T01:07:39.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-22T14:55:38.000Z", "avg_line_length": 19.6153846154, "max_line_length": 57, "alphanum_fraction": 0.6013071895, "num_tokens": 220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636754, "lm_q2_score": 0.8006919949619793, "lm_q1q2_score": 0.7199192849504779}}
{"text": "#include <iostream>\r\n#include <Eigen/Dense>\r\n\r\nusing namespace Eigen;\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n  Matrix3f m = Matrix3f::Random();\r\n  m = (m + Matrix3f::Constant(1.2)) * 50;\r\n  cout << \"m =\" << endl << m << endl;\r\n  Vector3f v(1,2,3);\r\n  \r\n  cout << \"m * v =\" << endl << m * v << endl;\r\n}\r\n", "meta": {"hexsha": "d2b94e797305c3c95fc1e3e143b51095975b8cfb", "size": 304, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "eigen/doc/examples/QuickStart_example2_fixed.cpp", "max_stars_repo_name": "subond/tools", "max_stars_repo_head_hexsha": "05b93e6c78eab65ef6587e684303b12c686a3480", "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": "eigen/doc/examples/QuickStart_example2_fixed.cpp", "max_issues_repo_name": "subond/tools", "max_issues_repo_head_hexsha": "05b93e6c78eab65ef6587e684303b12c686a3480", "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": "eigen/doc/examples/QuickStart_example2_fixed.cpp", "max_forks_repo_name": "subond/tools", "max_forks_repo_head_hexsha": "05b93e6c78eab65ef6587e684303b12c686a3480", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-04T15:41:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-04T15:41:53.000Z", "avg_line_length": 19.0, "max_line_length": 46, "alphanum_fraction": 0.5328947368, "num_tokens": 98, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.7879311906630568, "lm_q1q2_score": 0.7199142309742624}}
{"text": "//\n// Helper data structures and types for Tree-iLQR.\n//\n\n#pragma once\n\n#include <Eigen/Dense>\n\n#include <functional>\n#include <ostream>\n\nnamespace lqr \n{\n\n// Linearized dynamics parameters in terms of the extended-state [x, 1].\nstruct Dynamics\n{\n    // Extended linear dynamics matrix. [dim(x) + 1] x [dim(x) + 1]\n    // (extension is last row is [\\vec{0}, 1])\n    Eigen::MatrixXd A;\n\n    // Extended controls matrix. [dim(x) + 1] x [dim(u)]\n    // (extension is last row is [\\vec{0}])\n    Eigen::MatrixXd B;\n};\n\n// Quadratic cost parameters in terms of the extended-state [x, 1].\nstruct Cost \n{\n    // Extended quadratic state-cost matrix. [dim(x) + 1] x [dim(x) + 1]\n    Eigen::MatrixXd Q;\n\n    // Quadratic control-cost matrix. [dim(u)] x [dim(u)]\n    Eigen::MatrixXd R;\n};\n\n// Each plan node represents a timestep.\nclass PlanNode\n{\npublic:\n    PlanNode(int state_dim, \n             int control_dim, \n             const Eigen::MatrixXd A,\n             const Eigen::MatrixXd B,\n             const Eigen::MatrixXd Q,\n             const Eigen::MatrixXd R,\n             const double probablity);\n\n    // Throws exception if a size of an item (dynamics, cost, etc.) \n    // doesn't match expected sizes. Used for debugging. \n    void check_sizes();\n\n    // Linearized dynamics.\n    Dynamics dynamics_;\n\n    // Quadratic approximation of the cost.\n    Cost cost_;\n\n    // Feedback gain matrix on the extended-state, [dim(u)] x [dim(x) + 1]\n    Eigen::MatrixXd K_; \n\n    // Value matrix in x^T V x. [dim(x) + 1] x [dim(x) + 1]\n    Eigen::MatrixXd V_; \n\n    double probability_;\n\n    // Uses the x_ and u_ to update the linearization of the dynamics.\n    void update_dynamics();\n\n    // Uses the x_ and u_ to update the quadraticization of the cost.\n    void update_cost();\n\n    //\n    // Get and set the forward iLQR pass x and u.\n    //\n    \n    // Set the state with a [dim(x)]  (note, not extended) vector.\n    void set_x(const Eigen::VectorXd &x);\n    void set_u(const Eigen::VectorXd &u);\n    // Returns the extended-state [x, 1] for the iLQR forward pass.\n    const Eigen::VectorXd& x() const { return x_; }\n    // Returns the control [u] for the iLQR forward pass.\n    const Eigen::VectorXd& u() const { return u_; };\n\nprivate:\n    int state_dim_;\n    int control_dim_;\n\n    // State from this iLQR forward pass. [dim(x)] x [1]\n    Eigen::VectorXd x_; \n    // Control from this iLQR forward pass. [dim(u)] x [1]\n    Eigen::VectorXd u_; \n    // Combined vector [x, u], used to call numerical differentiators (e.g. Jacobian).\n    Eigen::VectorXd xu_;\n\n};\n\n// Allows the PlanNode to be printed.\nstd::ostream& operator<<(std::ostream& os, const lqr::PlanNode& node);\n\n} // namespace ilqr\n\n", "meta": {"hexsha": "67467d1f9d1df7be1e334542cf7511338161976a", "size": 2689, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/lqr/lqr_types.hh", "max_stars_repo_name": "LAIRLAB/qr_trees", "max_stars_repo_head_hexsha": "66eb7310daa1d9978158198a508d02bf2128a377", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-16T08:42:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-16T08:42:33.000Z", "max_issues_repo_path": "src/lqr/lqr_types.hh", "max_issues_repo_name": "LAIRLAB/qr_trees", "max_issues_repo_head_hexsha": "66eb7310daa1d9978158198a508d02bf2128a377", "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/lqr/lqr_types.hh", "max_forks_repo_name": "LAIRLAB/qr_trees", "max_forks_repo_head_hexsha": "66eb7310daa1d9978158198a508d02bf2128a377", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-07-10T03:25:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-22T15:58:44.000Z", "avg_line_length": 26.1067961165, "max_line_length": 86, "alphanum_fraction": 0.6266269989, "num_tokens": 714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.798186768138228, "lm_q1q2_score": 0.7199011457076274}}
{"text": "#include <geogram/basic/geometry_nd.h>\n#include <Eigen/Geometry>\n#include <cassert>\n#undef IGL_STATIC_LIBRARY\n#include <igl/point_simplex_squared_distance.h>\n\n#define sqr(x) (x) * (x)\n\ndouble inner_point_box_squared_distance(const Eigen::Vector3d& p, const Eigen::AlignedBox3d& B)\n{\n    assert(B.contains(p));\n    double result = sqr(p[0] - B.min()[0]);\n    result = std::min(result, sqr(p[0] - B.max()[0]));\n    for (int c = 1; c < 3; ++c) {\n        result = std::min(result, sqr(p[c] - B.min()[c]));\n        result = std::min(result, sqr(p[c] - B.max()[c]));\n    }\n    return result;\n}\n\ndouble point_box_signed_squared_distance(const Eigen::Vector3d& p, const Eigen::AlignedBox3d& B)\n{\n    bool inside = true;\n    double result = 0.0;\n    for (int c = 0; c < 3; c++) {\n        if (p[c] < B.min()[c]) {\n            inside = false;\n            result += sqr(p[c] - B.min()[c]);\n        }\n        else if (p[c] > B.max()[c]) {\n            inside = false;\n            result += sqr(p[c] - B.max()[c]);\n        }\n    }\n    if (inside) {\n        result = -inner_point_box_squared_distance(p, B);\n    }\n    return result;\n}\n\ndouble point_box_center_squared_distance(const Eigen::Vector3d& p, const Eigen::AlignedBox3d& B)\n{\n    double result = 0.0;\n    for (int c = 0; c < 3; ++c) {\n        double d = p[c] - 0.5 * (B.min()[c] + B.max()[c]);\n        result += sqr(d);\n    }\n    return result;\n}\n\nvoid get_point_facet_nearest_point(const Eigen::MatrixXd& V,\n                                   const Eigen::MatrixXi& F,\n                                   const Eigen::Vector3d& p,\n                                   int f,\n                                   Eigen::Vector3d& nearest_p,\n                                   double& squared_dist)\n{\n    assert(F.cols() == 3);\n#if 0\n    igl::point_simplex_squared_distance<3>(p, V, F, f, squared_dist, nearest_p);\n#else\n    GEO::vec3 query(p.data());\n    GEO::vec3 pts[3];\n    for (int lv = 0; lv < 3; ++lv) {\n        int i = F(f, lv);\n        pts[lv] = GEO::vec3(V(i, 0), V(i, 1), V(i, 2));\n    }\n    double lambda1, lambda2, lambda3;  // barycentric coords, not used.\n    GEO::vec3 x;\n    squared_dist = GEO::Geom::point_triangle_squared_distance(query, pts[0], pts[1], pts[2], x,\n                                                              lambda1, lambda2, lambda3);\n    nearest_p << x[0], x[1], x[2];\n#endif\n}\n", "meta": {"hexsha": "fed8bcd2a0c02835cf1d309a828f97cec374fecc", "size": 2355, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/distances.cpp", "max_stars_repo_name": "jdumas/aabb_benchmark", "max_stars_repo_head_hexsha": "b63e43394508b2cc53f206a46472a0d7dbf917cb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-07-18T21:48:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-04T18:15:07.000Z", "max_issues_repo_path": "src/distances.cpp", "max_issues_repo_name": "jdumas/aabb_benchmark", "max_issues_repo_head_hexsha": "b63e43394508b2cc53f206a46472a0d7dbf917cb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-11-19T20:03:12.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-16T22:55:19.000Z", "max_forks_repo_path": "src/distances.cpp", "max_forks_repo_name": "jdumas/aabb_benchmark", "max_forks_repo_head_hexsha": "b63e43394508b2cc53f206a46472a0d7dbf917cb", "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.4, "max_line_length": 96, "alphanum_fraction": 0.518895966, "num_tokens": 677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.7199008717927592}}
{"text": "#include <iostream>\n\n#include <Eigen/Dense>\n#include <Eigen/LU>\n\n#include \"AprilTags/GrayModel.h\"\n\nnamespace AprilTags {\n\nGrayModel::GrayModel() : A(), v(), b(), nobs(0), dirty(false) {\n  A.setZero();\n  v.setZero();\n  b.setZero();\n}\n\nvoid GrayModel::addObservation(float x, float y, float gray) {\n  float xy = x*y;\n\n  // update only upper-right elements. A'A is symmetric,\n  // we'll fill the other elements in later.\n  A(0,0) += x*x;\n  A(0,1) += x*y;\n  A(0,2) += x*xy;\n  A(0,3) += x;\n  A(1,1) += y*y;\n  A(1,2) += y*xy;\n  A(1,3) += y;\n  A(2,2) += xy*xy;\n  A(2,3) += xy;\n  A(3,3) += 1;\n  \n  b[0] += x*gray;\n  b[1] += y*gray;\n  b[2] += xy*gray;\n  b[3] += gray;\n\n  nobs++;\n  dirty = true;\n}\n\nfloat GrayModel::interpolate(float x, float y) {\n  if (dirty) compute();\n  return v[0]*x + v[1]*y + v[2]*x*y + v[3];\n}\n\nvoid GrayModel::compute() {\n  // we really only need 4 linearly independent observations to fit our answer, but we'll be very\n  // sensitive to noise if we don't have an over-determined system. Thus, require at least 6\n  // observations (or we'll use a constant model below).\n\n  dirty = false;\n  if (nobs >= 6) {\n    // make symmetric\n    Eigen::Matrix4d Ainv;\n    for (int i = 0; i < 4; i++)\n      for (int j = i+1; j < 4; j++)\n        A(j,i) = A(i,j);\n\n    //    try {\n    //      Ainv = A.inverse();\n    bool invertible;\n    double det_unused;\n    A.computeInverseAndDetWithCheck(Ainv, det_unused, invertible);\n    if (invertible) {\n      v = Ainv * b;\n      return;\n    }\n    std::cerr << \"AprilTags::GrayModel::compute() has underflow in matrix inverse\\n\";\n    //    }\n    //    catch (std::underflow_error&) {\n    //      std::cerr << \"AprilTags::GrayModel::compute() has underflow in matrix inverse\\n\";\n    //    }\n  }\n\n  // If we get here, either nobs < 6 or the matrix inverse generated\n  // an underflow, so use a constant model.\n  v.setZero();   // need the cast to avoid operator= ambiguity wrt. const-ness\n  v[3] = b[3] / nobs;      \n}\n\n} // namespace\n", "meta": {"hexsha": "f8728acce3d048f38c4fb7f85dd95912e9cc15a6", "size": 1974, "ext": "cc", "lang": "C++", "max_stars_repo_path": "catkin_ws/src/apriltags_ros/apriltags/src/GrayModel.cc", "max_stars_repo_name": "DiegoOrtegoP/Software", "max_stars_repo_head_hexsha": "4a07dd2dab29db910ca2e26848fa6b53b7ab00cd", "max_stars_repo_licenses": ["CC-BY-2.0"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2016-04-14T12:21:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-18T07:51:40.000Z", "max_issues_repo_path": "catkin_ws/src/apriltags_ros/apriltags/src/GrayModel.cc", "max_issues_repo_name": "DiegoOrtegoP/Software", "max_issues_repo_head_hexsha": "4a07dd2dab29db910ca2e26848fa6b53b7ab00cd", "max_issues_repo_licenses": ["CC-BY-2.0"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2017-03-03T23:33:05.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-03T18:07:53.000Z", "max_forks_repo_path": "catkin_ws/src/apriltags_ros/apriltags/src/GrayModel.cc", "max_forks_repo_name": "DiegoOrtegoP/Software", "max_forks_repo_head_hexsha": "4a07dd2dab29db910ca2e26848fa6b53b7ab00cd", "max_forks_repo_licenses": ["CC-BY-2.0"], "max_forks_count": 113.0, "max_forks_repo_forks_event_min_datetime": "2016-05-03T06:11:42.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-01T14:37:38.000Z", "avg_line_length": 24.0731707317, "max_line_length": 97, "alphanum_fraction": 0.5759878419, "num_tokens": 661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513703624558, "lm_q2_score": 0.8031738057795403, "lm_q1q2_score": 0.719845624069142}}
{"text": "//\n// OpenTissue, A toolbox for physical based simulation and animation.\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\n//\n#include <OpenTissue/configuration.h>\n\n#include <OpenTissue/core/math/big/big_types.h>\n#include <OpenTissue/core/math/optimization/optimization_bfgs.h>\n#include <OpenTissue/core/math/big/big_generate_random.h>\n#include <OpenTissue/core/math/big/big_generate_PD.h>\n#include <OpenTissue/core/math/big/io/big_matlab_write.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <OpenTissue/utility/utility_push_boost_filter.h>\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n#include <OpenTissue/utility/utility_pop_boost_filter.h>\n\ntypedef double real_type;\ntypedef ublas::compressed_matrix<real_type> matrix_type;\ntypedef ublas::vector<real_type>            vector_type;\ntypedef vector_type::size_type              size_type;\n\nclass F\n{\npublic:\n  matrix_type const & m_A;\n  vector_type const & m_b;\n\n  F(matrix_type const & A, vector_type const & b)\n    : m_A(A)\n    , m_b(b)\n  {}\n\n  real_type operator()( vector_type const & x ) const\n  {\n    return ublas::inner_prod(x, ublas::prod(m_A,x)) - inner_prod(m_b, x);\n  }\n};\n\nclass nabla_F\n{\npublic:\n  matrix_type const & m_A;\n  vector_type const & m_b;\n\n  nabla_F(matrix_type const & A, vector_type const & b)\n    : m_A(A)\n    , m_b(b)\n  {}\n\n  vector_type operator()( vector_type const & x ) const\n  {\n    return  vector_type( 2*ublas::prod(m_A,x) - m_b );\n  }\n};\n\ntemplate<typename func_functor, typename grad_functor>\nvoid do_unconstrained_minimizer_test(func_functor & f, grad_functor & nabla_f, vector_type & x, matrix_type & H, vector_type const & solution )\n{\n  using namespace OpenTissue::math::big;\n\n  size_type max_iterations       = 100;\n  real_type absolute_tolerance   = boost::numeric_cast<real_type>(1e-6);\n  real_type relative_tolerance   = boost::numeric_cast<real_type>(0.000000001);\n  real_type stagnation_tolerance = boost::numeric_cast<real_type>(0.000000001);\n  size_t status = 0;\n  size_type iteration = 0;\n  real_type accuracy = boost::numeric_cast<real_type>(0.0);\n  real_type alpha = boost::numeric_cast<real_type>(0.0001);\n  real_type beta = boost::numeric_cast<real_type>(0.5);\n\n  OpenTissue::math::optimization::bfgs(\n    f\n    , nabla_f\n    , H\n    , x \n    , max_iterations\n    , absolute_tolerance\n    , relative_tolerance\n    , stagnation_tolerance\n    , status\n    , iteration\n    , accuracy\n    , alpha\n    , beta\n    );\n\n  std::cout << \"status     = \" \n    << OpenTissue::math::optimization::get_error_message(status) \n    << std::endl;\n  std::cout << \"absolute   = \" \n    << accuracy  \n    << std::endl;\n  std::cout << \"iterations = \" \n    << iteration \n    << std::endl;\n  std::cout << \"x          = \" \n    << x \n    << std::endl;\n\n  if(status==OpenTissue::math::optimization::ABSOLUTE_CONVERGENCE)\n  {\n    BOOST_CHECK( accuracy < absolute_tolerance );\n    BOOST_CHECK( iteration <= max_iterations );\n  }\n\n  double tol = 0.001;\n  BOOST_CHECK_CLOSE( x(0), solution(0), tol);\n  BOOST_CHECK_CLOSE( x(1), solution(1), tol);\n}\n\n\n\n\n\n\nclass F_rosenbrock\n{\npublic:\n\n  F_rosenbrock(){}\n\n  real_type operator()( vector_type const & x ) const\n  {\n    real_type x_1 = x(0);\n    real_type x_2 = x(1);        \n    return (10.0*(x_2-x_1*x_1)*(x_2-x_1*x_1) + (1- x_1)*(1- x_1));\n  }\n};\n\n\n\nclass nabla_F_rosenbrock\n{\npublic:\n\n  nabla_F_rosenbrock(){}\n\n  vector_type operator()( vector_type const & x ) const\n  {\n    real_type x_1 = x(0);\n    real_type x_2 = x(1);\n    vector_type retur(2);\n    retur(0)=-40.0*(x_1*x_2 -x_1*x_1*x_1) - 2*(1-x_1);\n    retur(1)=20.0*(x_2-x_1*x_1);\n    return  retur;\n  }\n};\n\nBOOST_AUTO_TEST_SUITE(opentissue_math_big_bfgs);\n\nBOOST_AUTO_TEST_CASE(simple_test_case)\n{\n  using namespace OpenTissue::math::big;\n\n  // We are solving the problem\n  //\n  //   min_x Q(x) = x^T A x - b^T x\n  //\n  // where the gradient is given by\n  //\n  //   nabla Q(x) = 2 A x - b = 0\n  //\n  // and the exact Hessian is\n  //\n  //   H = nabla^2 Q(x) = 2 A\n  //\n  // The stationary points are given by \n  //\n  //  | 4 0| |x_1| + | -1| = 0\n  //  | 0 4| |x_2|   | -2|\n  //\n  // and has the unique solution x = [-0.25, -0.5]^T\n  //\n  size_type N = 2;\n\n  matrix_type A;\n  A.resize(N,N,false);\n\n  vector_type b;\n  b.resize(N,false);\n\n  A(0,0) = 2.0;  A(0,1) = 0.0;\n  A(1,0) = 0.0;  A(1,1) = 2.0;  \n\n  b(0) = -1.0;\n  b(1) = -2.0;\n\n  vector_type solution;\n  solution.resize(N,false);\n  solution(0) = -0.25;\n  solution(1) = -0.5;\n\n  F f(A,b);\n  nabla_F nabla_f(A,b);\n\n  vector_type x;\n  x.resize(N,false);\n  matrix_type H;\n  H.resize(N,N,false);\n\n  // use H = I/4, and x = 0\n  x.clear();\n  H(0,0) = 0.25;   H(0,1) = 0.0;\n  H(1,0) = 0.0;    H(1,1) = 0.25;   \n  do_unconstrained_minimizer_test(f,nabla_f,x,H,solution);\n\n  // use H = I, and x = 0\n  x.clear();\n  H(0,0) = 1.0;   H(0,1) = 0.0;\n  H(1,0) = 0.0;    H(1,1) = 1.0;   \n  do_unconstrained_minimizer_test(f,nabla_f,x,H,solution);\n\n  // use H = 4*I, and x = 0\n  x.clear();\n  H(0,0) = 4.0;   H(0,1) = 0.0;\n  H(1,0) = 0.0;    H(1,1) = 4.0;   \n  do_unconstrained_minimizer_test(f,nabla_f,x,H,solution);\n\n  // use H = I/4, and x = random\n  OpenTissue::math::big::generate_random( 2, x);\n  H(0,0) = 0.25;   H(0,1) = 0.0;\n  H(1,0) = 0.0;    H(1,1) = 0.25;   \n  do_unconstrained_minimizer_test(f,nabla_f,x,H,solution);\n\n  // use H = I, and x = random\n  OpenTissue::math::big::generate_random( 2, x);\n  H(0,0) = 1.0;   H(0,1) = 0.0;\n  H(1,0) = 0.0;    H(1,1) = 1.0;   \n  do_unconstrained_minimizer_test(f,nabla_f,x,H,solution);\n\n  // use H = 4*I, and x = random\n  OpenTissue::math::big::generate_random( 2, x);\n  H(0,0) = 4.0;   H(0,1) = 0.0;\n  H(1,0) = 0.0;    H(1,1) = 4.0;   \n  do_unconstrained_minimizer_test(f,nabla_f,x,H,solution);\n\n  // use H = random PD, and x = 0\n  x.clear();\n  OpenTissue::math::big::generate_PD(2, H);\n  do_unconstrained_minimizer_test(f,nabla_f,x,H,solution);\n\n  // use H = random PD, and x = random\n  OpenTissue::math::big::generate_random( 2, x);\n  OpenTissue::math::big::generate_PD(2, H);\n  do_unconstrained_minimizer_test(f,nabla_f,x,H,solution);\n\n  // H = g g^T, x = 0\n  x.clear();\n  vector_type g;\n  g.resize(N,false);\n  g = nabla_f(x);\n  H = ublas::outer_prod(g,g);\n  do_unconstrained_minimizer_test(f,nabla_f,x,H,solution);\n\n  // H = g g^T, x = random\n  OpenTissue::math::big::generate_random( 2, x);\n  g = nabla_f(x);\n  H = ublas::outer_prod(g,g);\n  do_unconstrained_minimizer_test(f,nabla_f,x,H,solution);\n\n  // H = exact Hessian, x = solution!\n  x(0) = -0.25;\n  x(1) = -0.5;\n  H(0,0) = 4.0;   H(0,1) = 0.0;\n  H(1,0) = 0.0;    H(1,1) = 4.0;   \n  do_unconstrained_minimizer_test(f,nabla_f,x,H,solution);\n\n}\n\nBOOST_AUTO_TEST_CASE(rosenbrock_test_case)\n{\n  using namespace OpenTissue::math::big;\n\n  size_type N = 2;\n\n  vector_type solution;\n  solution.resize(N,false);\n  solution(0) =  1.0;\n  solution(1) =  1.0;\n\n  F_rosenbrock f;\n  nabla_F_rosenbrock nabla_f;\n\n  vector_type x;\n  x.resize(N,false);\n  matrix_type H;\n  H.resize(N,N,false);\n\n  // use H = I/4, and x = 0\n  x.clear();\n  x(0)=2.0;\n  x(1)=2.0;\n  H(0,0) = 0.25;   H(0,1) = 0.0;\n  H(1,0) = 0.0;    H(1,1) = 0.25;   \n  do_unconstrained_minimizer_test(f,nabla_f,x,H,solution);\n\n  // use H = I, and x = 0\n  std::cout << std::endl;\n\n  x.clear();\n  x(0)=2.0;\n  x(1)=2.0;\n  std::cout << \"using H = I   x = \" << x <<  std::endl;\n  H(0,0) = 1.0;   H(0,1) = 0.0;\n  H(1,0) = 0.0;    H(1,1) = 1.0;   \n  do_unconstrained_minimizer_test(f,nabla_f,x,H,solution);\n\n  // use H = 4*I, and x = 0\n  std::cout << std::endl;\n\n  x.clear();\n  std::cout << \"using H = 4*I   x = \"<< x << std::endl;\n  H(0,0) = 4.0;   H(0,1) = 0.0;\n  H(1,0) = 0.0;    H(1,1) = 4.0;   \n  do_unconstrained_minimizer_test(f,nabla_f,x,H,solution);\n\n  // use H = I/4, and x = random\n  OpenTissue::math::big::generate_random( 2, x);\n  x *= 3.0;\n  H(0,0) = 0.25;   H(0,1) = 0.0;\n  H(1,0) = 0.0;    H(1,1) = 0.25;   \n  do_unconstrained_minimizer_test(f,nabla_f,x,H,solution);\n\n  // use H = I, and x = random\n  OpenTissue::math::big::generate_random( 2, x);\n  x *= 3.0;\n  H(0,0) = 1.0;   H(0,1) = 0.0;\n  H(1,0) = 0.0;    H(1,1) = 1.0;   \n  do_unconstrained_minimizer_test(f,nabla_f,x,H,solution);\n\n  // use H = 4*I, and x = random\n  OpenTissue::math::big::generate_random( 2, x);\n  x *= 3.0;\n  H(0,0) = 4.0;   H(0,1) = 0.0;\n  H(1,0) = 0.0;    H(1,1) = 4.0;   \n  do_unconstrained_minimizer_test(f,nabla_f,x,H,solution);\n\n  // use H = random PD, and x = 0\n  x.clear();\n  OpenTissue::math::big::generate_PD(2, H);\n  do_unconstrained_minimizer_test(f,nabla_f,x,H,solution);\n\n  // use H = random PD, and x = random\n  OpenTissue::math::big::generate_random( 2, x);\n  x *= 3.0;\n  OpenTissue::math::big::generate_PD(2, H);\n  do_unconstrained_minimizer_test(f,nabla_f,x,H,solution);\n\n  // H = exact Hessian, x = solution!\n  x(0) = 1.0;\n  x(1) = 1.0;\n  H(0,0) = 82.0;   H(0,1) = -40.0;\n  H(1,0) = -40.0;    H(1,1) = 20.0;   \n  do_unconstrained_minimizer_test(f,nabla_f,x,H,solution);\n\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "11ed28b4f9516b621cb25f5275da752f56d82f28", "size": 9025, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/core/math/optimization/bfgs/src/unit_bfgs.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:45:06.000Z", "max_issues_repo_path": "unit_tests/core/math/optimization/bfgs/src/unit_bfgs.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-20T14:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T15:26:45.000Z", "max_forks_repo_path": "unit_tests/core/math/optimization/bfgs/src/unit_bfgs.cpp", "max_forks_repo_name": "ricortiz/OpenTissue", "max_forks_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T01:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:06:49.000Z", "avg_line_length": 24.8622589532, "max_line_length": 143, "alphanum_fraction": 0.615401662, "num_tokens": 3441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735665, "lm_q2_score": 0.8056321983146848, "lm_q1q2_score": 0.7196788159981293}}
{"text": "/**\n * @file systemode_main.cc\n * @brief NPDE homework SystemODE\n * @copyright Developed at ETH Zurich\n */\n\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n#include <Eigen/SparseLU>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n\n#include \"../../../lecturecodes/helperfiles/polyfit.h\"\n#include \"systemode.h\"\n\n/* SAM_LISTING_BEGIN_0 */\nint main() {\n  // PARAMETERS\n  double T = 1;\n  int n = 5;\n\n  // INITIAL VALUE\n  Eigen::VectorXd y0(2 * n);\n  for (int i = 0; i < n; ++i) {\n    y0(i) = (i + 1.) / n;\n    y0(i + n) = -1;\n  }\n\n  // SETUP\n  double conv_rate = 0;\n  std::cout << std::setw(8) << \"M\" << std::setw(20) << \"Error\" << std::endl;\n\n  // IMPLEMENTATION OF RIGHT-HAND SIDE f\n  // Build tridiagonal C matrix\n  Eigen::SparseMatrix<double> C(n, n);\n  C.reserve(Eigen::VectorXi::Constant(n, 3));\n  C.insert(0, 0) = 2;\n  for (int i = 1; i < n; ++i) {\n    C.insert(i, i) = 2;\n    C.insert(i, i - 1) = -1;\n    C.insert(i - 1, i) = -1;\n  }\n  C.makeCompressed();\n  // Compute the right-hand side f\n  // The system of ODEs is y' = f(y) with y = [u;v],\n  // and f(y) = f([u;v]) = [v;C^{-1}r(u)]\n  auto f = [n, C](Eigen::VectorXd y) {\n    Eigen::VectorXd fy(2 * n);\n    fy.head(n) = y.tail(n);\n    Eigen::VectorXd r(n);\n    r(0) = y(0) * (y(1) + y(0));\n    r(n - 1) = y(n - 1) * (y(n - 1) + y(n - 2));\n    for (int i = 1; i < n - 1; ++i) {\n      r(i) = y(i) * (y(i - 1) + y(i + 1));\n    }\n    Eigen::SparseLU<Eigen::SparseMatrix<double>> Csolver;\n    Csolver.compute(C);\n    fy.tail(n) = Csolver.solve(r);\n    return fy;\n  };\n\n  // COMPUTE AN \"EXACT\" SOLUTION\n  // Use N=2^12 steps to calculate an approximate \"exact\" solution.\n  int N_exact = std::pow(2, 12);  // number of steps\n  double h = T / N_exact;         // step size\n  Eigen::VectorXd yT_exact = y0;  // initial value\n  Eigen::VectorXd y_next;\n  for (int step = 0; step < N_exact; step++) {\n    y_next = SystemODE::rk4step(f, h, yT_exact);\n    yT_exact = y_next;\n  }\n\n  // CONVERGENCE ANALYSIS\n  // Calculate solution using N=2,...,2^kmax steps.\n  int kmax = 10;\n  Eigen::VectorXd Error(kmax);\n  for (int k = 0; k < kmax; k++) {\n    int M = std::pow(2, k + 1);  // number of steps\n    double h = T / M;            // step size\n    Eigen::VectorXd yT = y0;     // initial value\n    // Take N RK4 steps:\n    for (int step = 0; step < M; step++) {\n      // yT is the solution at time t=h*step\n      y_next = SystemODE::rk4step(f, h, yT);\n      yT = y_next;\n    }\n    Error(k) = (yT - yT_exact).norm();\n    std::cout << std::setw(8) << M << std::setw(20) << Error(k) << std::endl;\n  }\n\n  // Estimate convergence rate\n  // Get natural logarithm of M by log(M) = log(2)*log2(N).\n  Eigen::VectorXd logM =\n      std::log(2) * Eigen::VectorXd::LinSpaced(kmax, 1, kmax);\n  Eigen::VectorXd coeffs = polyfit(logM, Error.array().log(), 1);\n  conv_rate = coeffs(0);\n\n  std::cout << \"Convergence rate: \" << std::round(std::abs(conv_rate))\n            << std::endl;\n\n  return 0;\n}\n/* SAM_LISTING_END_0 */\n", "meta": {"hexsha": "60b04609d0f9d9ee14cf237d719408102b2447cf", "size": 2953, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/SystemODE/mastersolution/systemode_main.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": "homeworks/SystemODE/mastersolution/systemode_main.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": "homeworks/SystemODE/mastersolution/systemode_main.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": 28.1238095238, "max_line_length": 77, "alphanum_fraction": 0.5580765323, "num_tokens": 1038, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543487, "lm_q2_score": 0.8056321843145405, "lm_q1q2_score": 0.7196788080682898}}
{"text": "/*\nCopyright (c) 2019, NVIDIA CORPORATION. All rights reserved.\n\nNVIDIA CORPORATION and its licensors retain all intellectual property\nand proprietary rights in and to this software, related documentation\nand any modifications thereto. Any use, reproduction, disclosure or\ndistribution of this software and related documentation without an express\nlicense agreement from NVIDIA CORPORATION is strictly prohibited.\n*/\n\n#pragma once\n\n// This header is private, do not include it directly, include pnp.hpp instead.\n\n// An implementation of the EPnP algorithm (for >=6 points) based on the following publication:\n// V. Lepetit, F. Moreno-Noguer, P. Fua, EPnP: An Accurate O(n) Solution to the PnP Problem,\n// International Journal Of Computer Vision (IJCV), 2009\n// See manuscript at http://infoscience.epfl.ch/record/160138/files/top.pdf\n// TODO: extend to 4,5 points\n\n#include <Eigen/Dense>\n\n#include \"packages/pnp/gems/generic/utils.hpp\"\n#include \"packages/pnp/gems/pnp.hpp\"  // using status codes from the public interface\n\nnamespace isaac {\nnamespace pnp {\nnamespace epnp {\n\n// Output pose and internal results from ComputeCameraPose()\n// Output pose as cam_point = rotation * world_point + translation\n// where world_point is a 3D point in world coords and cam_point in camera coords.\n// Note that cam_position = -rotation.transpose() * translation,\n// given that cam_point = rotation * (world_point - cam_position)\nstruct Result {\n  Matrix3d rotation;           // camera orientation matrix\n  Vector3d translation;        // translation vector\n  int input_dims;              // dimensionality of the input point cloud\n  Matrix3Xd ctl_points_world;  // control points in world coordinates (chosen 3D basis)\n  Matrix3Xd ctl_points_cam;    // control points in camera coordinates\n  MatrixXd bary_coeffs;        // barycentric coordinates of the input 3D points\n  MatrixXd proj_coeffs;        // coefficient matrix in the projection equations (M in Eq.7)\n  MatrixXd solution_basis;     // 4 basis vectors of the solution space of ctl_points_cam\n  VectorXd singular_values;    // all singular values of proj_coeffs in increasing order\n  VectorXd rss_repr_errors;    // RSS reprojection error for each solution space dimension\n  int solution_dims;           // optimal #dimensions of the solution space (based on repr. error)\n};\n\n// High-level function that implements the full EPnP pipeline by using the other functions below.\n// The other functions are exposed to enable detailed testing of individual parts.\n// Requires the 4 standard camera intrinsic parameters (assumes pre-calibrated camera) and\n// at least 6 2D-3D point correspondences without gross outliers for the result to be meaningful.\n// Outputs the 3D pose of the camera and some internal results in Result given:\n//  focal_u,v      relative focal lengths in horizontal / vertical pixel sizes from calibration\n//  principal_u,v  principal point coordinates in pixels from calibration\n//  points3        input 3D points as 3xN matrix (N>=6)\n//  points2        input 2D points as 2xN matrix (in corresponding order to 3D points)\npnp::Status ComputeCameraPose(double focal_u, double focal_v, double principal_u,\n                              double principal_v, const Matrix3Xd& points3,\n                              const Matrix2Xd& points2, epnp::Result* result);\n\n// Compute 3D basis aligned with a 3D point cloud: origin in the centroid and axes aligned and\n// scaled with the principal components.\n// Returns the basis as D+1 control points in columns of a 3x(D+1) matrix: the centroid, followed\n// by axis end-points along non-vanishing principal directions in decreasing order of length.\n// Possible cases:\n//   D=0: all input points coincide within tolerance or no valid input (unusable for EPnP)\n//   D=1: all input points are along a line up to tolerance (unusable for EPnP)\n//   D=2: all input points are in a plane up to tolerance (planar case, works with EPnP)\n//   D=3: input points are non-planar (works with EPnP)\n// In case of failure a 3x0 matrix is returned.\nMatrix3Xd ChooseBasis(const Matrix3Xd& points3, double tol = 1e-3);\n\n// Compute barycentric coordinates of N 3D points with respect to a basis defined by\n// 3 or 4 control points, subject to hom(points3) = hom(ctl_points) * bary_coords,\n// where hom() denotes addition of an extra row of all 1's.\n//   points3       Input 3D points as a 3xN matrix.\n//   ctl_points    3xC matrix containing C = 3 or 4 control points, see ChooseBasis() for details.\n// Returns a CxN matrix of barycentric coefficients with column sums equal to 1.\n// These barycentric coordinates can be negative or positive with no particular bound in general\n// because control points from ChooseBasis() are based on variances (PCA) and individual points\n// can be arbitrarily far from the population.\nMatrixXd ComputeBaryCoords(const Matrix3Xd& points3, const Matrix3Xd& ctl_points);\n\n// Find the solution space of the projection equations (Eqs. 4-7 in the paper above).\n// Projection can be written in the homogeneous linear form\n//                          M*x = 0    (Eq.7 in the paper),\n// where x is a vector of 9 or 12 unknown 3D camera coordinates of 3 (planar case) or 4 control\n// points and M is a 2Nx9 (planar case) or 2Nx12 matrix (non-planar case).\n// The least 1,2,3 or 4 singular values of M may all be close to 0 and any vector x lying in\n// a 1-,2-,3- or 4-D solution space will satisfy the constraints M*x ~ 0.\n// Instead of arbitrarily thresholding the singular values, EPnP considers\n// the first 1,2,3 or 4 columns of the 9x4 (planar case) or 12x4 output matrix\n// sol_basis as the basis of the solution space.\n// See SolveControlPoints() for the solution in each case (in 1,2,3,4 dimensional solution space).\n//  focal_u,v      relative focal lengths in horizontal / vertical pixel sizes\n//  principal_u,v  principal point coordinates in pixels\n//  bary_coords    3xN (planar case) or 4xN matrix, the barycentric coordinates of N>=6 3-D points\n//  points2        2D projection coordinates of the 3D points\n//  proj_coeffs    Coefficient matrix of the homogenenous form of the projections (see above)\n//  sol_basis      9x4 (planar case) or 12x4 matrix, 4 basis vectors considered for solution space.\n//  sing_values    9 or 12 singular values of M sorted in increasing order.\n//                 The first 4 singular values correspond to columns of sol_basis.\n// Returns true in case of success and outputs undefined in case of failure.\nbool SolveProjConstraints(double focal_u, double focal_v, double principal_u, double principal_v,\n                          const MatrixXd& bary_coords, const Matrix2Xd points2,\n                          MatrixXd* proj_coeffs, MatrixXd* sol_basis, VectorXd* sing_values);\n\n// Place elements of a vector of length 3*N into a 3xN matrix column-wise.\n// In EPnP, this is applied to the 3*N solution vector of 3D camera coordinates of N control points.\n// If the length of the input vector is not a multiple of 3, an empty 3x0 matrix is returned.\nMatrix3Xd ReshapeToMatrix3xN(const VectorXd& vec);\n\n// Given the solution space for the camera coordinates of the control points and given all pairwise\n// distances between control points to preserve, compute weights of the linear combination\n// of the basis vectors (Eq.8 in the EPnP paper) such that the control points can be obtained as\n//                       ReshapeToMatrix3xN(sol_basis * weights).\n// The solution space can be 1,2,3 or 4 dimensional in theory.\n//  sol_basis      Solution space basis vectors output by SolveProjConstraints().\n//  sol_dims       Number of basis vectors in sol_basis to consider for the solution.\n//                 Supported values: 1,2 for planar and 1,2,3 for non-planar case.\n//  distances      All pairwise distances between control points as returned by ComputeDistances().\n//                 3 distances for 3 points (planar case) and 6 distances for 4 points (non-planar).\n// Returns 4 weights. All weights are zero for unsupported sol_dims values and\n// only the first sol_dims weights are non-zero in supported cases (see above).\nVector4d SolveControlPoints(const MatrixXd& sol_basis, int sol_dims, const VectorXd& distances);\n\n// Compute distances between all possible pairs (i,j) of N input points.\n// Input points are in matrix columns, and i,j are column indices.\n// Every j = i+1,i+2,...,N-1 are listed first for each of i = 0,1,...,N-2\n// EPnP only applies this for the 3 or 4 control points.\n// Order for 4 points: (0,1)(0,2)(0,3)(1,2)(1,3)(2,3)\n// Order for 3 points: (0,1)(0,2)(1,2)\nVectorXd ComputeDistances(const MatrixXd& points);\n\n// Project a set of 3D points directly given in camera coordinates into the image.\n// Camera intrinsics are provided in the upper triangular 3x3 camera calibration matrix.\n// Returns the 2D projections in a 2xN matrix of pixel coordinates for a 3xN input point matrix.\n// This function serves to validate solutions to the projection equations and,\n// therefore, intentionally does not make a distinction of points behind the camera.\nMatrix2Xd ProjectPoints(const Matrix3d& calib_matrix, const Matrix3Xd& points3);\n\n}  // namespace epnp\n}  // namespace pnp\n}  // namespace isaac\n", "meta": {"hexsha": "9c72a07427834b87ec816b3cff570ba3cae8954c", "size": 9180, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sdk/packages/pnp/gems/epnp/epnp.hpp", "max_stars_repo_name": "ddr95070/RMIsaac", "max_stars_repo_head_hexsha": "ee3918f685f0a88563248ddea11d089581077973", "max_stars_repo_licenses": ["FSFAP"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sdk/packages/pnp/gems/epnp/epnp.hpp", "max_issues_repo_name": "ddr95070/RMIsaac", "max_issues_repo_head_hexsha": "ee3918f685f0a88563248ddea11d089581077973", "max_issues_repo_licenses": ["FSFAP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdk/packages/pnp/gems/epnp/epnp.hpp", "max_forks_repo_name": "ddr95070/RMIsaac", "max_forks_repo_head_hexsha": "ee3918f685f0a88563248ddea11d089581077973", "max_forks_repo_licenses": ["FSFAP"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-28T16:37:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-28T16:37:51.000Z", "avg_line_length": 62.8767123288, "max_line_length": 100, "alphanum_fraction": 0.7397603486, "num_tokens": 2249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122188543453, "lm_q2_score": 0.7931059414036511, "lm_q1q2_score": 0.7195947114815111}}
{"text": "#include <iostream>\n#include <vector>\n\n#include <Eigen/Dense>\n \nusing Eigen::MatrixXd;\n\ntypedef Eigen::Matrix<float, 3, 3> Matrix33f;\ntypedef Eigen::Matrix<float, 3, 1> Vector3f;\ntypedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> DMatrix;  // dynamic matrix\n\n\nvoid initial() {\n    Matrix33f a;\n    Vector3f v;\n    DMatrix m(10, 5);\n\n    a = Matrix33f::Identity(); \n    a << 1, 2, 3, 4, 5, 6, 7, 8, 9;  // comma-initializer syntax\n\n    // change an element of matrix directly\n    a(0, 0) = 4;\n\n    v = Vector3f::Random();\n\n    std::cout << a << std::endl;\n    std::cout << v << std::endl;\n}\n\nvoid initialByMap() {\n    int data[] = {1,2,3,4};\n    Eigen::Map<Eigen::RowVectorXi> v(data,4);\n    std::vector<float> data1 = {1,2,3,4,5,6,7,8,9};\n    Eigen::Map<Matrix33f> a(data1.data());\n\n    std::cout << v << std::endl;\n    std::cout << a << std::endl;\n}\n\nvoid calc() {\n    Matrix33f a, b;\n    a = Matrix33f::Random();\n    b = Matrix33f::Random();\n\n    std::cout << a+b << std::endl;  // eigen overload operators, like +/-/*\n    std::cout << a.array() * b.array() << std::endl;  // element-wise multiplication\n    std::cout << a*b << std::endl;   // matrix multiplication\n\n}\n\nint main()\n{\n    std::cout << \"intial: \" << std::endl;\n    initial();\n\n    std::cout << \"intial by Eigen::Map: \" << std::endl;\n    initialByMap();\n\n    std::cout << \"calculate use Eigen: \" << std::endl;\n    calc();\n\n    return 0;\n}", "meta": {"hexsha": "a6ea08475fe09dfaad62680e41b4e585486447e1", "size": 1414, "ext": "cc", "lang": "C++", "max_stars_repo_path": "basic_lib/eigenML/eigenAPI/test.cc", "max_stars_repo_name": "eleveyuan/ML_BASE", "max_stars_repo_head_hexsha": "838d25fcc56c152896cc11f02fa257d662bec206", "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": "basic_lib/eigenML/eigenAPI/test.cc", "max_issues_repo_name": "eleveyuan/ML_BASE", "max_issues_repo_head_hexsha": "838d25fcc56c152896cc11f02fa257d662bec206", "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": "basic_lib/eigenML/eigenAPI/test.cc", "max_forks_repo_name": "eleveyuan/ML_BASE", "max_forks_repo_head_hexsha": "838d25fcc56c152896cc11f02fa257d662bec206", "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": 22.4444444444, "max_line_length": 89, "alphanum_fraction": 0.572135785, "num_tokens": 464, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.8198933293122506, "lm_q1q2_score": 0.7194373594286876}}
{"text": "\r\n/*\r\n\tkstatboost\r\n\tVer. k09.00\r\n\t\r\n\tWritten by Koji Yamamoto\r\n\tCopyright (C) 2020 Koji Yamamoto\r\n\tIn using this, please read the document which states terms of use.\r\n\t\r\n\tStatistical Computations using Boost\r\n\t\r\n*/\r\n\r\n\r\n/* ********** Preprocessor Directives ********** */\r\n\r\n#ifndef kstatboost_cpp_include_guard\r\n#define kstatboost_cpp_include_guard\r\n\r\n#include <vector>\r\n\r\n#include <boost/math/tools/bivariate_statistics.hpp>\r\n\r\n\r\n/* ********** Using Directives ********** */\r\n\r\n//using namespace std;\r\n\r\n\r\n/* ********** Type Declarations: enum, class, etc. ********** */\r\n\r\n\r\n/* ********** Function Declarations ********** */\r\n\r\ndouble corrBoost( const std::vector <double> &, const std::vector <double> &); \r\n\r\n\r\n/* ********** Type Definitions: enum, class, etc. ********** */\r\n\r\n\r\n/* ********** Global Variables ********** */\r\n\r\n\r\n/* ********** Definitions of Static Member Variables ********** */\r\n\r\n\r\n/* ********** Function Definitions ********** */\r\n\r\ndouble corrBoost( const std::vector <double> &xvec, const std::vector <double> &yvec)\r\n{\r\n\r\n\tdouble ret = boost::math::tools::correlation_coefficient( xvec, yvec);\r\n\treturn ret;\r\n\r\n}\r\n\r\n\r\n/* ********** Definitions of Member Functions ********** */\r\n\r\n\r\n\r\n\r\n#endif /* kstatboost_cpp_include_guard */\r\n", "meta": {"hexsha": "73bd05352bd5481fc45cb11d4a2f5ce597e1a001", "size": 1259, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "k09/kstatboost00.cpp", "max_stars_repo_name": "kojiynet/koli", "max_stars_repo_head_hexsha": "681f9c1b1a291a36e1f0eee43c45b37567d2661e", "max_stars_repo_licenses": ["BSL-1.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": "k09/kstatboost00.cpp", "max_issues_repo_name": "kojiynet/koli", "max_issues_repo_head_hexsha": "681f9c1b1a291a36e1f0eee43c45b37567d2661e", "max_issues_repo_licenses": ["BSL-1.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": "k09/kstatboost00.cpp", "max_forks_repo_name": "kojiynet/koli", "max_forks_repo_head_hexsha": "681f9c1b1a291a36e1f0eee43c45b37567d2661e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.671875, "max_line_length": 86, "alphanum_fraction": 0.5679110405, "num_tokens": 272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096181702031, "lm_q2_score": 0.7853085708384735, "lm_q1q2_score": 0.7194287349766219}}
{"text": "#include <stan/math/prim/scal.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <gtest/gtest.h>\n#include <limits>\n#include <cmath>\n\ntemplate <typename T_N, typename T_n>\nvoid test_binom_coefficient(const T_N& N, const T_n& n) {\n  using stan::math::binomial_coefficient_log;\n  EXPECT_FLOAT_EQ(lgamma(N + 1) - lgamma(n + 1) - lgamma(N - n + 1),\n                  binomial_coefficient_log(N, n));\n}\n\nTEST(MathFunctions, binomial_coefficient_log) {\n  using stan::math::binomial_coefficient_log;\n  EXPECT_FLOAT_EQ(1.0, exp(binomial_coefficient_log(2.0, 2.0)));\n  EXPECT_FLOAT_EQ(2.0, exp(binomial_coefficient_log(2.0, 1.0)));\n  EXPECT_FLOAT_EQ(3.0, exp(binomial_coefficient_log(3.0, 1.0)));\n  EXPECT_NEAR(3.0, exp(binomial_coefficient_log(3.0, 2.0)), 0.0001);\n\n  EXPECT_FLOAT_EQ(29979.16, binomial_coefficient_log(100000, 91116));\n\n  for (int n = 0; n < 1010; ++n) {\n    test_binom_coefficient(1010, n);\n    test_binom_coefficient(1010.0, n);\n    test_binom_coefficient(1010, static_cast<double>(n));\n    test_binom_coefficient(1010.0, static_cast<double>(n));\n  }\n\n  test_binom_coefficient(1e9, 1e5);\n  test_binom_coefficient(1e50, 1e45);\n  test_binom_coefficient(1e20, 1e15);\n}\n\nTEST(MathFunctions, binomial_coefficient_log_nan) {\n  double nan = std::numeric_limits<double>::quiet_NaN();\n\n  EXPECT_PRED1(boost::math::isnan<double>,\n               stan::math::binomial_coefficient_log(2.0, nan));\n  EXPECT_PRED1(boost::math::isnan<double>,\n               stan::math::binomial_coefficient_log(nan, 2.0));\n  EXPECT_PRED1(boost::math::isnan<double>,\n               stan::math::binomial_coefficient_log(nan, nan));\n}\n", "meta": {"hexsha": "2bc50f0d4a9a2786bf6cd86edde467e73607907c", "size": 1628, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/prim/scal/fun/binomial_coefficient_log_test.cpp", "max_stars_repo_name": "peterwicksstringfield/math", "max_stars_repo_head_hexsha": "5ce0718ea64f2cca8b2f1e4eeac27a2dc2bd246e", "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": "test/unit/math/prim/scal/fun/binomial_coefficient_log_test.cpp", "max_issues_repo_name": "peterwicksstringfield/math", "max_issues_repo_head_hexsha": "5ce0718ea64f2cca8b2f1e4eeac27a2dc2bd246e", "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": "test/unit/math/prim/scal/fun/binomial_coefficient_log_test.cpp", "max_forks_repo_name": "peterwicksstringfield/math", "max_forks_repo_head_hexsha": "5ce0718ea64f2cca8b2f1e4eeac27a2dc2bd246e", "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": 36.1777777778, "max_line_length": 69, "alphanum_fraction": 0.7125307125, "num_tokens": 508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942348544447, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.7194175774858211}}
{"text": "/***********************************************************************\n* Short Title: linear algebra functions on R3\n*\n* Comments: declaration of necessary linear algebra functions for\n*     blitz::TinyVector  and  blitz::TinyMatrix\n*\n* <license text>\n***********************************************************************/\n\n#ifndef R3LINALG_HPP_INCLUDED\n#define R3LINALG_HPP_INCLUDED\n\n#include <blitz/array.h>\n\n#include \"Counter.hpp\"\n\nnamespace R3 {\n\n////////////////////////////////////////////////////////////////////////\n// Declarations\n////////////////////////////////////////////////////////////////////////\n\n// constants\n\nconst int Ndim = 3;\nusing blitz::all;\n\n// types\n\ntypedef blitz::TinyMatrix<double,Ndim,Ndim> Matrix;\ntypedef blitz::TinyVector<double,Ndim> Vector;\n\n// functions\n\ndouble determinant(const Matrix& A);\nMatrix inverse(const Matrix& A);\nMatrix transpose(const Matrix& A);\nconst Matrix& product(const Matrix&, const Matrix&);\n\ntemplate <class V> double norm(const V&);\ntemplate <class V> double distance(const V& u, const V& v);\ntemplate <class V> double dot(const V& u, const V& v);\ntemplate <class V> Vector cross(const V& u, const V& v);\nconst Vector& product(const Vector&, const Matrix&);\n\ntemplate <class M>\n    bool MatricesAlmostEqual(const M& A, const M& B, double precision=0.0);\n\ntemplate <class V>\n    bool VectorsAlmostEqual(const V& A, const V& B, double precision=0.0);\n\n\n////////////////////////////////////////////////////////////////////////\n// Definitions\n////////////////////////////////////////////////////////////////////////\n\n\ntemplate <class V>\ninline double norm(const V& u)\n{\n    static Counter* R3_norm_calls = Counter::getCounter(\"R3_norm_calls\");\n    R3_norm_calls->count();\n    return sqrt(R3::dot(u, u));\n}\n\n\ntemplate <class V>\ninline double distance(const V& u, const V& v)\n{\n    static Counter* R3_distance_calls =\n        Counter::getCounter(\"R3_distance_calls\");\n    R3_distance_calls->count();\n    static R3::Vector duv;\n    duv[0] = u[0] - v[0];\n    duv[1] = u[1] - v[1];\n    duv[2] = u[2] - v[2];\n    return R3::norm(duv);\n}\n\n\ntemplate <class V>\ninline double dot(const V& u, const V& v)\n{\n    return (u[0]*v[0] + u[1]*v[1] + u[2]*v[2]);\n}\n\n\ntemplate <class V>\ninline Vector cross(const V& u, const V& v)\n{\n    Vector res;\n    res[0] = u[1]*v[2] - u[2]*v[1];\n    res[1] = u[2]*v[0] - u[0]*v[2];\n    res[2] = u[0]*v[1] - u[1]*v[0];\n    return res;\n}\n\n\ninline const Vector& product(const Vector& u, const Matrix& M)\n{\n    static Vector res;\n    res[0] = u[0]*M(0,0) + u[1]*M(1,0)+ u[2]*M(2,0);\n    res[1] = u[0]*M(0,1) + u[1]*M(1,1)+ u[2]*M(2,1);\n    res[2] = u[0]*M(0,2) + u[1]*M(1,2)+ u[2]*M(2,2);\n    return res;\n}\n\n\ntemplate <class M>\nbool MatricesAlmostEqual(const M& A, const M& B, double precision)\n{\n    for (int i = 0; i < Ndim; ++i)\n    {\n        for (int j = 0; j < Ndim; ++j)\n        {\n            if (fabs(A(i,j) - B(i,j)) > precision)  return false;\n        }\n    }\n    return true;\n}\n\n\ntemplate <class V>\nbool VectorsAlmostEqual(const V& u, const V& v, double precision)\n{\n    for (int i = 0; i < Ndim; ++i)\n    {\n        if (fabs(u[i] - v[i]) > precision)  return false;\n    }\n    return true;\n}\n\n\n}       // End of namespace R3\n\n#endif  // R3LINALG_HPP_INCLUDED\n", "meta": {"hexsha": "b094b33c7b7a78730dae153665fe55b09f1b6615", "size": 3242, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/R3linalg.hpp", "max_stars_repo_name": "pavoljuhas/liga", "max_stars_repo_head_hexsha": "53896275e9df0a916ba6219b407ce3777ce7ba2d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-02T18:56:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-02T18:56:27.000Z", "max_issues_repo_path": "src/R3linalg.hpp", "max_issues_repo_name": "pavoljuhas/liga", "max_issues_repo_head_hexsha": "53896275e9df0a916ba6219b407ce3777ce7ba2d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-06-01T18:08:36.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-13T18:28:19.000Z", "max_forks_repo_path": "src/R3linalg.hpp", "max_forks_repo_name": "pavoljuhas/liga", "max_forks_repo_head_hexsha": "53896275e9df0a916ba6219b407ce3777ce7ba2d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-05-24T00:30:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-13T01:13:42.000Z", "avg_line_length": 23.6642335766, "max_line_length": 75, "alphanum_fraction": 0.5351634793, "num_tokens": 925, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220291, "lm_q2_score": 0.8080672158638527, "lm_q1q2_score": 0.7194175766020914}}
{"text": "#include <iostream>\n\n#include <Eigen/Dense>\n#include <Eigen/LU>\n\n#include \"AprilTags/GrayModel.h\"\n\nnamespace AprilTags {\n\nGrayModel::GrayModel() : A(), v(), b(), nobs(0), dirty(false) {\n  A.setZero();\n  v.setZero();\n  b.setZero();\n}\n\nvoid GrayModel::addObservation(float x, float y, float gray) {\n  float xy = x * y;\n\n  // update only upper-right elements. A'A is symmetric,\n  // we'll fill the other elements in later.\n  A(0, 0) += x * x;\n  A(0, 1) += x * y;\n  A(0, 2) += x * xy;\n  A(0, 3) += x;\n  A(1, 1) += y * y;\n  A(1, 2) += y * xy;\n  A(1, 3) += y;\n  A(2, 2) += xy * xy;\n  A(2, 3) += xy;\n  A(3, 3) += 1;\n\n  b[0] += x * gray;\n  b[1] += y * gray;\n  b[2] += xy * gray;\n  b[3] += gray;\n\n  nobs++;\n  dirty = true;\n}\n\nfloat GrayModel::interpolate(float x, float y) {\n  if (dirty) compute();\n  return v[0] * x + v[1] * y + v[2] * x * y + v[3];\n}\n\nvoid GrayModel::compute() {\n  // we really only need 4 linearly independent observations to fit our answer,\n  // but we'll be very\n  // sensitive to noise if we don't have an over-determined system. Thus,\n  // require at least 6\n  // observations (or we'll use a constant model below).\n\n  dirty = false;\n  if (nobs >= 6) {\n    // make symmetric\n    Eigen::Matrix4d Ainv;\n    for (int i = 0; i < 4; i++)\n      for (int j = i + 1; j < 4; j++) A(j, i) = A(i, j);\n\n    //    try {\n    //      Ainv = A.inverse();\n    bool invertible;\n    double det_unused;\n    A.computeInverseAndDetWithCheck(Ainv, det_unused, invertible);\n    if (invertible) {\n      v = Ainv * b;\n      return;\n    }\n    std::cerr\n        << \"AprilTags::GrayModel::compute() has underflow in matrix inverse\\n\";\n    //    }\n    //    catch (std::underflow_error&) {\n    //      std::cerr << \"AprilTags::GrayModel::compute() has underflow in\n    // matrix inverse\\n\";\n    //    }\n  }\n\n  // If we get here, either nobs < 6 or the matrix inverse generated\n  // an underflow, so use a constant model.\n  v.setZero();  // need the cast to avoid operator= ambiguity wrt. const-ness\n  v[3] = b[3] / nobs;\n}\n\n}  // namespace\n", "meta": {"hexsha": "e1ac79c5063cb1ae7b604109ed10fee1ec0163ef", "size": 2025, "ext": "cc", "lang": "C++", "max_stars_repo_path": "deps/src/apriltags/src/GrayModel.cc", "max_stars_repo_name": "chutsu/yac", "max_stars_repo_head_hexsha": "789c8b4116197e3a4b0232568414eec5489836da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2020-04-29T17:25:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T05:57:27.000Z", "max_issues_repo_path": "deps/src/apriltags/src/GrayModel.cc", "max_issues_repo_name": "chutsu/yac", "max_issues_repo_head_hexsha": "789c8b4116197e3a4b0232568414eec5489836da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-06-26T04:44:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-04T17:56:35.000Z", "max_forks_repo_path": "deps/src/apriltags/src/GrayModel.cc", "max_forks_repo_name": "chutsu/yac", "max_forks_repo_head_hexsha": "789c8b4116197e3a4b0232568414eec5489836da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-07-15T18:04:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-13T13:19:58.000Z", "avg_line_length": 23.8235294118, "max_line_length": 79, "alphanum_fraction": 0.5614814815, "num_tokens": 689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.7194175724869922}}
{"text": "#include <iostream>\n\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\nint main()\n{\n    MatrixXd m(2, 2);\n    m(0, 0) = 3;\n    m(1, 0) = 2.5;\n    m(0, 1) = -1;\n    m(1, 1) = m(1, 0) + m(0, 1);\n    std::cout << \"Here is the matrix m:\\n\"\n              << m << std::endl;\n    VectorXd v(2);\n    v(0) = 4;\n    v(1) = v(0) - 1;\n    std::cout << \"Here is the vector v:\\n\"\n              << v << std::endl;\n\n    MatrixXf A = MatrixXf::Random(3, 2);\n    VectorXf b = VectorXf::Random(3);\n    std::cout << \"The least squares solution to Ax=b is\\n\"\n              << A.fullPivHouseholderQr().solve(b) << '\\n';\n\n    return 0;\n}\n", "meta": {"hexsha": "cf141237146d4cd9854d7d0419ec26728a961c14", "size": 613, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/vmls.cpp", "max_stars_repo_name": "mpoullet/vmls", "max_stars_repo_head_hexsha": "dc4807a85e310195a894bfb09fcae45f6261fd37", "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/vmls.cpp", "max_issues_repo_name": "mpoullet/vmls", "max_issues_repo_head_hexsha": "dc4807a85e310195a894bfb09fcae45f6261fd37", "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/vmls.cpp", "max_forks_repo_name": "mpoullet/vmls", "max_forks_repo_head_hexsha": "dc4807a85e310195a894bfb09fcae45f6261fd37", "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.1379310345, "max_line_length": 59, "alphanum_fraction": 0.4812398042, "num_tokens": 235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299612154571, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.7191811299538229}}
{"text": "#include \"ThinPlateSpline.hpp\"\n#include <Eigen/QR>\n\nThinPlateSpline::ThinPlateSpline(const PointList &src, const PointList &dst)\n    : mSrcPoints(src), mDstPoints(dst) {}\n\nvoid ThinPlateSpline::solve() {\n\n  if (mSrcPoints.size() != mDstPoints.size())\n    return;\n\n  const int num(int(mSrcPoints.size()));\n  const int rows(num + 3 + 1);\n\n  // Create L Matrix\n  mL = Eigen::MatrixXd::Zero(rows, rows);\n\n  for (int i(0); i < num; ++i) {\n\n    int j(i + 1);\n\n    for (; j < num; ++j)\n      mL(i, j) = mL(j, i) = radialBasis(\n          (mSrcPoints[std::size_t(i)] - mSrcPoints[std::size_t(j)]).norm());\n\n    mL(j, i) = mL(i, j) = 1.0;\n    ++j;\n\n    for (int posElm(0); j < rows; ++posElm, ++j)\n      mL(j, i) = mL(i, j) = mSrcPoints[std::size_t(i)][posElm];\n  }\n\n  // Create Y Matrix\n  Eigen::MatrixXd Y = Eigen::MatrixXd::Zero(rows, 3);\n\n  for (int i(0); i < num; ++i)\n    Y.row(i) = mDstPoints[std::size_t(i)];\n\n  // Solve L W^T = Y as W^T = L^-1 Y\n  mW = mL.colPivHouseholderQr().solve(Y);\n}\n\nEigen::Vector3d ThinPlateSpline::interpolate(const Eigen::Vector3d &p) const {\n\n  Eigen::Vector3d res = Eigen::Vector3d::Zero();\n  int i(0);\n\n  for (; i < mW.rows() - (3 + 1); ++i) {\n    double rb = radialBasis((mSrcPoints[std::size_t(i)] - p).norm());\n    res += mW.row(i) * rb;\n  }\n\n  res += mW.row(i);\n  i++;\n\n  for (int j(0); j < 3; ++j, ++i)\n    res += mW.row(i) * p[j];\n\n  return res;\n}\n", "meta": {"hexsha": "8941a14b77baad90bebf1790360e4a3da7808537", "size": 1383, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ThinPlateSpline.cpp", "max_stars_repo_name": "buresu/ThinPlateSpline", "max_stars_repo_head_hexsha": "24d77d906bd1921d27a22da7120fb92e5365645f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-11-22T03:32:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-26T03:28:00.000Z", "max_issues_repo_path": "ThinPlateSpline.cpp", "max_issues_repo_name": "buresu/ThinPlateSpline", "max_issues_repo_head_hexsha": "24d77d906bd1921d27a22da7120fb92e5365645f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-07-23T07:00:13.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-25T05:52:03.000Z", "max_forks_repo_path": "ThinPlateSpline.cpp", "max_forks_repo_name": "buresu/ThinPlateSpline", "max_forks_repo_head_hexsha": "24d77d906bd1921d27a22da7120fb92e5365645f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2016-11-10T03:41:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-14T14:39:25.000Z", "avg_line_length": 22.6721311475, "max_line_length": 78, "alphanum_fraction": 0.5618221258, "num_tokens": 501, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.925229948845201, "lm_q2_score": 0.7772998611746911, "lm_q1q2_score": 0.7191811107920413}}
{"text": "#include <iostream>\n#include <Eigen\\Core>\n#include \"pca.h\"\n\nusing namespace std;\nusing Eigen::ArrayXXf;\nusing Eigen::MatrixXf;\nusing Eigen::VectorXf;\n\nusing namespace eos::pca;\n\nint main(int argc, char** argv) {\n\tVectorXf eigenvalues;\n\tMatrixXf eigenvectors;\n\n\tMatrixXf meanfree_data = MatrixXf::Random(10, 50); // rows, cols\n\tcout << \"meanfree_data: \\n\" << meanfree_data << endl;\n\n\tEigen::RowVectorXf mean_data = meanfree_data.colwise().mean();\n\tcout << \"colwise().mean(): \\n\" << mean_data << endl;\n\n\tmeanfree_data.rowwise() -= mean_data;\n\tcout << \"meanfree_data: \\n\" << meanfree_data << endl;\n\n\tCovariance covariance_type = Covariance::AtA;\n\n\tstd::tie(eigenvectors, eigenvalues) = pca(meanfree_data, covariance_type);\n\tcout << \"Eigenvectors: \\n\" << eigenvectors << endl;\n\tcout << \"Eigenvalues: \\n\" << eigenvalues << endl;\n\n\tsystem(\"pause\");\n\treturn EXIT_SUCCESS;\n}", "meta": {"hexsha": "533018eafeef22a445339ec915f164ead7f054ee", "size": 866, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/eos/eos/learn-eos/pca/main.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/eos/eos/learn-eos/pca/main.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/eos/eos/learn-eos/pca/main.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": 26.2424242424, "max_line_length": 75, "alphanum_fraction": 0.7032332564, "num_tokens": 246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088045171238, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.7191300385224559}}
{"text": "/*\n * SpectralClustering.cpp\n *\n *  Created on: 04-Mar-2009\n *      Author: sbutler\n */\n#define EIGEN2_SUPPORT\n\n#include \"SpectralClustering.h\"\n#include \"ClusterRotate.h\"\n#include \"Kmeans.h\"\n\n#include <Eigen/QR>\n\n /**\n * Performs eigenvector decomposition of an affinity matrix\n *\n * @param data \t\tthe affinity matrix\n * @param numDims\tthe number of dimensions to consider when clustering\n */\nSpectralClustering::SpectralClustering(int numDims) :\n\tmNumDims(numDims),\n\tmNumClusters(0)\n{\n\n}\n\nSpectralClustering::~SpectralClustering() {\n}\n\nEigen::MatrixXd SpectralClustering::CalcEigenVectors(Eigen::MatrixXd& affinityMatrix)\n{\n\tEigen::MatrixXd Deg = Eigen::MatrixXd::Zero(affinityMatrix.rows(), affinityMatrix.cols());\n\n\t// calc normalised laplacian \n\tfor (int i = 0; i < affinityMatrix.cols(); i++) \n\t{\n\t\tDeg(i, i) = 1 / (sqrt((affinityMatrix.row(i).sum())));\n\t}\n\tEigen::MatrixXd Lapla = Deg * affinityMatrix * Deg;\n\n\tEigen::SelfAdjointEigenSolver<Eigen::MatrixXd> s(Lapla, true);\n\tEigen::VectorXd val = s.eigenvalues();\n\tEigen::MatrixXd vec = s.eigenvectors();\n\n\t//sort eigenvalues/vectors\n\tint n = affinityMatrix.cols();\n\tfor (int i = 0; i < n - 1; ++i) \n\t{\n\t\tint k;\n\t\tval.segment(i, n - i).maxCoeff(&k);\n\t\tif (k > 0) \n\t\t{\n\t\t\tstd::swap(val[i], val[k + i]);\n\t\t\tvec.col(i).swap(vec.col(k + i));\n\t\t}\n\t}\n\n\t//choose the number of eigenvectors to consider\n\tif (mNumDims < vec.cols()) \n\t{\n\t\tmEigenVectors = vec.block(0, 0, vec.rows(), mNumDims);\n\t}\n\telse \n\t{\n\t\tmEigenVectors = vec;\n\t}\n\n\treturn mEigenVectors;\n}\n\n/**\n * Cluster by rotating the eigenvectors and evaluating the quality\n */\nstd::vector<std::vector<int> > SpectralClustering::clusterRotate(Eigen::MatrixXd& eigenVectors)\n{\n\n\tClusterRotate* clusterRotate = new ClusterRotate();\n\tstd::vector<std::vector<int> > clusters = clusterRotate->cluster(eigenVectors);\n\n\tmNumClusters = clusters.size();\n\n\treturn clusters;\n}\n\n/**\n * Cluster by kmeans\n *\n * @param numClusters\tthe number of clusters to assign\n */\nstd::vector<std::vector<int> > SpectralClustering::clusterKmeans(Eigen::MatrixXd& eigenVectors,int numClusters)\n{\n\tmNumClusters = numClusters;\n\treturn Kmeans::cluster(mEigenVectors, numClusters);\n}\n", "meta": {"hexsha": "0d7f05348abb866512857957dd5c9f622b37b45c", "size": 2155, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/SpectralClustering/SpectralClustering.cpp", "max_stars_repo_name": "gbull122/SpectralClustering", "max_stars_repo_head_hexsha": "76c1ab9e06a88a40807b5dad6f15bac9efb2da52", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-03T03:25:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-20T15:50:32.000Z", "max_issues_repo_path": "src/SpectralClustering/SpectralClustering.cpp", "max_issues_repo_name": "gbull122/SpectralClustering", "max_issues_repo_head_hexsha": "76c1ab9e06a88a40807b5dad6f15bac9efb2da52", "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/SpectralClustering/SpectralClustering.cpp", "max_forks_repo_name": "gbull122/SpectralClustering", "max_forks_repo_head_hexsha": "76c1ab9e06a88a40807b5dad6f15bac9efb2da52", "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.4479166667, "max_line_length": 111, "alphanum_fraction": 0.6969837587, "num_tokens": 601, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218305645895, "lm_q2_score": 0.7799929104825007, "lm_q1q2_score": 0.7190924918594291}}
{"text": "#include <iostream>\n#include <vector>\n#include <cmath>\n#include <random>\n#include <Eigen/Dense>\n#include <Eigen/LU>\n\nusing namespace Eigen;\n\n// \u30ac\u30a6\u30b9\u5206\u5e03\u306e\u6570\n#define K 2\n\n// \u6b21\u5143\u6570\n#define D 2\n\n// \u30c7\u30fc\u30bf\u306e\u6570\n#define N 10\n\n#define PI 4*atan(1.0)\n\n// TODO: D,1 \u306b\u3059\u308b\ntypedef Eigen::Matrix<float, 1, D> m_d;\n\n// \u591a\u6b21\u5143 (\u591a\u5909\u91cf) \u30ac\u30a6\u30b9\u5206\u5e03\nfloat gaussian(m_d& x, m_d& mu, Matrix<float,D,D>& sigma) {\n  return exp( -0.5 * (x - mu).dot( sigma.inverse() * (x - mu).transpose() ) )\n    / pow(sqrt(2 * PI), D) * sqrt(sigma.determinant());\n}\n\nfloat likelihood(\n  std::vector<float>& pi,\n  std::vector<m_d>& x,\n  std::vector<m_d>& mu,\n  std::vector<Matrix<float,D,D> >& sigma\n) {\n  float s = 0.0;\n  for(int n=0; n<N; n++) {\n    float t = 0.0;\n    for(int k=0; k<K; k++) {\n      t += pi[k] * gaussian(x[n], mu[k], sigma[k]);\n    }\n    s += log(t);\n  }\n  return s;\n}\n\nint main() {\n  // TODO: matrix<float, N, 1> \u306b\u3059\u308b\n  // TODO: \u5b9f\u969b\u306b\u4f7f\u3048\u308b\u30c7\u30fc\u30bf\u3092\u7528\u610f\u3059\u308b\n  // N \u884c D \u5217\n  std::vector<m_d> x(N, m_d::Random());\n\n  // \u5e73\u5747 mu, \u5206\u6563 sigma, \u6df7\u5408\u4fc2\u6570 pi \u3092\u521d\u671f\u5316\u3059\u308b\n  // \u5e73\u5747\n  /*\n      [\n        [mu_x, mu_y], // \u6b21\u5143\u6570 (D) \u500b\n        [mu_x, mu_y],\n        ... K \u500b\n      ]\n      \u30ac\u30a6\u30b9\u5206\u5e03 K \u306b\u5bfe\u3059\u308b, X\u8ef8\u306e\u5e73\u5747\uff0cY\u8ef8\u306e\u5e73\u5747 ...\n   */\n  std::vector<m_d> mu(K, m_d::Zero());\n\n  std::random_device rd;\n  std::mt19937 mt(rd());\n  std::uniform_real_distribution<double> distribution(0.0, 1.0);\n\n  // \u5206\u6563 (\u5206\u6563\u5171\u5206\u6563\u884c\u5217)\n  // D x D \u884c\u5217\n  Matrix<float, 1, D> v;\n  for(int i=0;i<D;i++) {\n    v(i) = distribution(mt);\n  }\n  std::vector<Matrix<float,D,D> > sigma(K, Matrix<float,D,D>(v.asDiagonal()));\n\n  // TODO: \u5236\u7d04 Sigma(k) pi_k = 1 \u3092\u6e80\u305f\u3059\u3088\u3046\u306b\u521d\u671f\u5316\u3059\u308b\n  std::vector<float> pi(K);\n  for(int i=0; i<K; i++) {\n    pi[i] = distribution(mt);\n  }\n\n  // gamma, N, K\n  std::vector<std::vector<float> > gamma(N, std::vector<float>(K));\n\n  // \u5c24\u5ea6\n  float like = likelihood(pi, x, mu, sigma);\n\n  while(true) {\n    // E-step: \u30d1\u30e9\u30e1\u30fc\u30bf (mu, sigma, pi) \u3092\u4f7f\u3063\u3066\u8ca0\u62c5\u7387 gamma \u3092\u8a08\u7b97\u3059\u308b\n    for(int n = 0; n < N; n++) {\n      float t = 0.0;\n      for(int k = 0; k < K; k++) {\n        t += pi[k] * gaussian(x[n], mu[k], sigma[k]);\n      }\n\n      for(int k = 0; k < K; k++)\n        gamma[n][k] = pi[k] * gaussian(x[n], mu[k], sigma[k]) / t;\n    }\n\n    // M-step: \u8ca0\u62c5\u7387\u3092\u4f7f\u3063\u3066\u30d1\u30e9\u30e1\u30fc\u30bf\u3092\u66f4\u65b0\u3059\u308b\n    for(int k = 0; k < K; k++) {\n      // N_k\n      float Nk = 0.0;\n      for(int n = 0; n < N; n++) {\n        Nk += gamma[n][k];\n      }\n\n      // \u5e73\u5747\n      m_d _mu = m_d::Zero();\n      for(int n = 0; n < N; n++) {\n        _mu += gamma[n][k] * x[n];\n      }\n      mu[k] = _mu / Nk;\n\n      // \u5206\u6563\n      Matrix<float, D, D> _sigma = Matrix<float,D,D>::Zero();\n      for(int n = 0; n < N; n++) {\n        _sigma += gamma[n][k] * (x[n] - mu[k]).transpose() * (x[n] - mu[k]);\n      }\n      sigma[k] = _sigma / Nk;\n\n      // \u6df7\u5408\u4fc2\u6570\n      pi[k] = Nk / N;\n\n    }\n\n    // TODO: x \u3068 mu \u306e\u5024\u304c\u540c\u3058\u306b\u306a\u308b\u554f\u984c, x \u306e\u521d\u671f\u5024\u306b Random \u3092\u4f7f\u3063\u3066\u3044\u308b\u305b\u3044 ?\n    std::cout << x[0] << \"\\n\" << mu[0] << \"\\n\" << sigma[0] << std::endl;\n\n    // \u53ce\u675f\u6027\u306e\u78ba\u8a8d\n    // \u5bfe\u6570\u5c24\u5ea6\u95a2\u6570 Sigma(n) { log ( Sigma(k) pi * N )}\n    float _like = likelihood(pi, x, mu, sigma);\n    std::cout << _like << std::endl;\n    if(_like - like < 0.01 || _like == nan)\n      break;\n    like = _like;\n\n  }\n}\n", "meta": {"hexsha": "02054558bee1aa4d23203c555374efc33f5822ee", "size": 3043, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gmm_em.cpp", "max_stars_repo_name": "mayok/was-tutorial", "max_stars_repo_head_hexsha": "c49ea554e16a2977476a8f765957615f5b0e8fbd", "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": "gmm_em.cpp", "max_issues_repo_name": "mayok/was-tutorial", "max_issues_repo_head_hexsha": "c49ea554e16a2977476a8f765957615f5b0e8fbd", "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": "gmm_em.cpp", "max_forks_repo_name": "mayok/was-tutorial", "max_forks_repo_head_hexsha": "c49ea554e16a2977476a8f765957615f5b0e8fbd", "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.5815602837, "max_line_length": 78, "alphanum_fraction": 0.4988498193, "num_tokens": 1259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172601537142, "lm_q2_score": 0.7577943822145998, "lm_q1q2_score": 0.7190841689309546}}
{"text": "/*\n * Copyright 2021 MusicScience37 (Kenta Kabashima)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/*!\n * \\file\n * \\brief Test of self_adjoint_kernel_solver class.\n */\n#include \"num_collect/interp/kernel/impl/self_adjoint_kernel_solver.h\"\n\n#include <Eigen/Cholesky>\n#include <Eigen/Core>\n#include <catch2/catch_test_macros.hpp>\n#include <catch2/matchers/catch_matchers_floating.hpp>\n\n#include \"eigen_approx.h\"\n#include \"is_finite.h\"\n#include \"num_collect/interp/kernel/calc_kernel_mat.h\"\n#include \"num_collect/interp/kernel/euclidean_distance.h\"\n#include \"num_collect/interp/kernel/gaussian_rbf.h\"\n#include \"num_collect/interp/kernel/rbf_kernel.h\"\n\nTEST_CASE(\"num_collect::interp::kernel::self_adjoint_kernel_solver\") {\n    using num_collect::interp::kernel::calc_kernel_mat;\n    using num_collect::interp::kernel::euclidean_distance;\n    using num_collect::interp::kernel::gaussian_rbf;\n    using num_collect::interp::kernel::rbf_kernel;\n    using num_collect::interp::kernel::impl::self_adjoint_kernel_solver;\n\n    const auto vars = std::vector<double>{0.0, 0.1, 0.2, 0.4, 0.6, 1.0};\n    const auto data = Eigen::VectorXd{{0.0, 0.2, 0.4, 0.7, 1.0, 2.0}};\n\n    auto kernel =\n        rbf_kernel<euclidean_distance<double>, gaussian_rbf<double>>();\n    constexpr double len_param = 0.1;\n    kernel.len_param(len_param);\n\n    const Eigen::MatrixXd kernel_mat = calc_kernel_mat(kernel, vars);\n\n    SECTION(\"compute\") {\n        auto solver =\n            self_adjoint_kernel_solver<Eigen::MatrixXd, Eigen::VectorXd>();\n        solver.compute(kernel_mat, data);\n\n        REQUIRE(solver.eigenvalues().size() == data.size());\n        for (num_collect::index_type i = 0; i < data.size(); ++i) {\n            INFO(\"i = \" << i);\n            REQUIRE(solver.eigenvalues()(i) > 0.0);\n        }\n    }\n\n    SECTION(\"solve without regularization\") {\n        auto solver =\n            self_adjoint_kernel_solver<Eigen::MatrixXd, Eigen::VectorXd>();\n        solver.compute(kernel_mat, data);\n        Eigen::VectorXd coeff;\n        solver.solve(0.0, coeff);\n\n        const Eigen::VectorXd retrieved_data = kernel_mat * coeff;\n        REQUIRE_THAT(retrieved_data, eigen_approx(data));\n    }\n\n    SECTION(\"solve with regularization\") {\n        constexpr double reg_param = 1.234;\n        auto solver =\n            self_adjoint_kernel_solver<Eigen::MatrixXd, Eigen::VectorXd>();\n        solver.compute(kernel_mat, data);\n        Eigen::VectorXd coeff;\n        solver.solve(reg_param, coeff);\n\n        const Eigen::VectorXd retrieved_data =\n            (kernel_mat +\n                Eigen::MatrixXd::Identity(data.size(), data.size()) *\n                    reg_param) *\n            coeff;\n        REQUIRE_THAT(retrieved_data, eigen_approx(data));\n    }\n\n    SECTION(\"calculate MLE objective function\") {\n        auto solver =\n            self_adjoint_kernel_solver<Eigen::MatrixXd, Eigen::VectorXd>();\n        solver.compute(kernel_mat, data);\n\n        const double mle_zero = solver.calc_mle_objective(0.0);\n        REQUIRE_THAT(mle_zero, is_finite());\n\n        constexpr double large_param = 1e+3;\n        const double mle_large = solver.calc_mle_objective(large_param);\n        REQUIRE_THAT(mle_large, is_finite());\n\n        REQUIRE(mle_large > mle_zero);\n    }\n\n    SECTION(\"calculate the coefficient of the kernel common in variables\") {\n        auto solver =\n            self_adjoint_kernel_solver<Eigen::MatrixXd, Eigen::VectorXd>();\n        solver.compute(kernel_mat, data);\n\n        REQUIRE(solver.calc_common_coeff(0.0) > 0.0);\n        constexpr double reg_param = 1e-3;\n        REQUIRE(solver.calc_common_coeff(reg_param) > 0.0);\n    }\n\n    SECTION(\"calculate the regularization term for a vector\") {\n        auto solver =\n            self_adjoint_kernel_solver<Eigen::MatrixXd, Eigen::VectorXd>();\n        solver.compute(kernel_mat, data);\n\n        constexpr double reg_param = 1e-3;\n        const auto vec = Eigen::VectorXd{{0.1, 0.2, 0.4, 0.5, 1.0, 0.7}};\n        Eigen::LLT<Eigen::MatrixXd> llt;\n        llt.compute(kernel_mat +\n            reg_param * Eigen::MatrixXd::Identity(data.size(), data.size()));\n        const Eigen::VectorXd inv_kernel_vec = llt.solve(vec);\n        const auto expected = inv_kernel_vec.dot(vec);\n        REQUIRE_THAT(solver.calc_reg_term(reg_param, vec),\n            Catch::Matchers::WithinRel(expected));\n    }\n}\n", "meta": {"hexsha": "126839339bc29a2f8f31e5413401caea4331a216", "size": 4850, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/units/interp/kernel/impl/self_adjoint_kernel_solver_test.cpp", "max_stars_repo_name": "MusicScience37/numerical-collection-cpp", "max_stars_repo_head_hexsha": "490c24aae735ba25f1060b2941cff39050a41f8f", "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": "test/units/interp/kernel/impl/self_adjoint_kernel_solver_test.cpp", "max_issues_repo_name": "MusicScience37/numerical-collection-cpp", "max_issues_repo_head_hexsha": "490c24aae735ba25f1060b2941cff39050a41f8f", "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": "test/units/interp/kernel/impl/self_adjoint_kernel_solver_test.cpp", "max_forks_repo_name": "MusicScience37/numerical-collection-cpp", "max_forks_repo_head_hexsha": "490c24aae735ba25f1060b2941cff39050a41f8f", "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": 37.0229007634, "max_line_length": 77, "alphanum_fraction": 0.666185567, "num_tokens": 1156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872046056466901, "lm_q2_score": 0.8104789063814616, "lm_q1q2_score": 0.7190606185211253}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_CONSTANT_CGOLD_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_CGOLD_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n  /*!\n    @ingroup group-constant\n    Generates a value of the chosen type which represents the conjugate Golden Ratio.\n\n    The conjugate Golden Ratio (\\f$\\bar\\phi\\f$) is defined as \\f$\\frac{1-\\sqrt5}{2}\\f$.\n\n    @par Semantic:\n\n    @code\n    T r = Cgold<T>();\n    @endcode\n\n    is equivalent to:\n\n    @code\n    T r = (1-simd::sqrt(T(5)))/2;\n    @endcode\n\n    @return A value of type @c T containing the conjugate Golden Ratio.\n\n    @see functional::cgold\n  **/\n  template<typename T> T Cgold();\n\n  namespace functional\n  {\n    /*!\n      @ingroup group-callable-constant\n      Generates a value of the chosen type which represents the conjugate Golden Ratio.\n\n      The conjugate Golden Ratio (\\f$\\bar\\phi\\f$) is defined as \\f$\\frac{1-\\sqrt5}{2}\\f$.\n\n      @par Semantic:\n\n      For any value @c x of type @c T:\n      @code\n      T r = simd::functional::cgold( boost::simd::as(x));\n      @endcode\n\n      is equivalent to:\n\n      @code\n      T r = simd::Cgold<T>();\n      @endcode\n\n      @return A value of type @c T containing the conjugate Golden Ratio.\n\n      @see Cgold\n    **/\n    Value Cgold();\n  }\n} }\n#endif\n\n#include <boost/simd/constant/definition/cgold.hpp>\n#include <boost/simd/arch/common/scalar/constant/constant_value.hpp>\n#include <boost/simd/arch/common/simd/constant/constant_value.hpp>\n\n#endif\n", "meta": {"hexsha": "0ef040a77c8e72094a68f30c48d22294285c89d6", "size": 1861, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/constant/cgold.hpp", "max_stars_repo_name": "xmar/pythran", "max_stars_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-12T13:45:09.000Z", "max_issues_repo_path": "third_party/boost/simd/constant/cgold.hpp", "max_issues_repo_name": "xmar/pythran", "max_issues_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "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": "third_party/boost/simd/constant/cgold.hpp", "max_forks_repo_name": "xmar/pythran", "max_forks_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-11-17T15:30:36.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-01T02:06:25.000Z", "avg_line_length": 24.4868421053, "max_line_length": 100, "alphanum_fraction": 0.5900053735, "num_tokens": 455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045817875224, "lm_q2_score": 0.8104789155369047, "lm_q1q2_score": 0.7190606073065242}}
{"text": "/*! \\file\n    \\brief Simple plot of 1D data of values with uncertainty.\n    \\details An example to demonstrate simple 1D plot using two vectors,\n     including showing values with uncertainty information as\n     \"plus minus\" and degrees of freedom estimates.\n*/\n\n// demo_1d_uncertainty.cpp\n\n// Copyright Paul A Bristow 2009, 2012, 2021\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// This file is written to be included from a Quickbook .qbk document.\n// It can be compiled by the C++ compiler, and run. Any output can\n// also be added here as comment or included or pasted in elsewhere.\n// Caution: this file contains Quickbook markup as well as code\n// and comments: don't change any of the special comment markups!\n\n//[demo_1d_uncertainty_1\n\n/*`First we need a few includes to use Boost.Plot:\n*/\n#include <boost/quan/unc.hpp>  // Handles information uncertainty.\n// using boost::quan::unc; // Holds value and uncertainty information.\n#include <boost/svg_plot/detail/functors.hpp>\n//  using boost::svg::detail::unc_1d_convert;\n#include <boost/svg_plot/svg_1d_plot.hpp>\n//using namespace boost::svg;\n// If list of settings required:\n#include <boost/svg_plot/show_1d_settings.hpp>\n//void boost::svg::show_1d_plot_settings(svg_1d_plot&);\n\n#include <iostream>\n// using std::cout;\n// using std::endl;\n#include <vector>\n//  using std::vector;\n#include <iterator>\n//  using std::ostream_iterator;\n#include <algorithm>\n//  using std::copy;\n//] [/demo_1d_uncertainty_1]\n\nint main()\n{\n  using namespace boost::svg;  // Convenient to avoid specifying each SVG color name separately.\n\n  using boost::quan::unc;\n  using boost::quan::uncun; // Uncertain Uncorrelated type (the normal case).\n\n//[demo_1d_uncertainty_2\n\n    /*`A STL @c std::vector is used as the container for our three data-series,\n    and values are inserted using `std::push_back`. (Since this is a 1-D plot\n    the order of data values is not important).\n    */\n    setUncDefaults(std::cout);\n    constexpr float NaN = std::numeric_limits<float>::quiet_NaN();  // NotANumber used for unknown values and unknown standard deviation.\n\n    std::vector<uncun> A_times;\n    A_times.push_back(unc<false>(3.1, 0.02F, 8));  // Not using a typedef uncun.\n    A_times.push_back(uncun(4.2, 0.01F, 14, 0U));  // Using a typedef uncun - usually easier to read.\n\n    std::vector<uncun > B_times;\n    short unsigned int t = UNC_KNOWN | UNC_EXPLICIT| DEG_FREE_EXACT | DEG_FREE_KNOWN; // An uncertain type. (But use of uncertain type t is not yet implemented.)\n\n    B_times.push_back(uncun(2.1, 0.001F, 30, t)); // Value (2.1), uncertainty (0.001F), degrees of freedom (30) and uncertain type known.\n    B_times.push_back(unc<>(5.1, 0.025F, 20, 0U)); // Value, uncertainty, and degrees of freedom known - the usual case.\n    B_times.push_back(uncun(7.8, 0.0025F, 1, 0U)); // Value and uncertainty known, but not degrees of freedom.\n    B_times.push_back(uncun(3.4, 0.03F, 1, 0U)); // Value and uncertainty known, but not degrees of freedom.\n    //B_times.push_back(uncun(6.9, 0.0F, 0, 0U)); // Only value known - no information available about uncertainty but treated as exact.\n    B_times.push_back(uncun(5.9, NaN, 1, 0U)); // Only value known - uncertainty explicit, NaN meaning no information available about uncertainty.\n    // So in both cases show all possibly significant digits (usually 15).\n    // This is ugly on a graph, so best to be explicit about uncertainty.\n\n    std::vector<unc<false> > C_times; // \n    C_times.push_back(uncun(2.6, 0.1F, 5, 0U));\n    C_times.push_back(uncun(5.4, 0.2F, 11, 0U));\n\n    /*`Echo the values (and their uncertainty information) input: */\n\n    std::cout << plusminus << addlimits << adddegfree << std::endl;\n    std::cout << \"A_times: \" << std::endl;\n    std::copy(A_times.begin(), A_times.end(), std::ostream_iterator<uncun>(std::cout, \"\\t \")); // 3.10 4.200\n    std::cout << std::endl;\n    std::cout << \"B_times: \" << std::endl;\n    std::copy(B_times.begin(), B_times.end(), std::ostream_iterator<uncun>(std::cout, \"\\t \")); // 2.1000 5.10 7.800 3.40 5.900\n    std::cout << std::endl;\n\n    std::cout << plusminus << addlimits << adddegfree << \"A_times[0] = \" << A_times[0] << std::endl;\n    // B_times[0] = 2.1000 +/-0.0010 <2.10, 2.10> (30)\n\n    /*`The constructor initializes a new 1D plot, called `my_plot`,\n    and also sets all the very many defaults for axes, width, colors, etc.\n    */\n    svg_1d_plot my_plot;\n    /*`A few (member) functions that are set (using concatenation or chaining) should be fairly self-explanatory:\n``\n    .title() provides a title at the top for the whole plot,\n    .legend_on(true) will mean that titles of data-series and their markers will display in the legend box.\n    .x_range(-1, 11) sets the axis limits from -1 to +11 (instead of the default -10 to +10).\n    .background_border_color(blue) sets just one of the very many other options.\n``\n    Also some autoscaling settings:\n    */\n    my_plot.autoscale_check_limits(false); // Default is true.\n    my_plot.autoscale_plusminus(1); //\n    //  //! Set how many std_dev or standard-deviation to allow for ellipse when autoscaling.\n    //! Default is 3 for 99% confidence.\n    // my_plot.confidence(0.01);  // Change alpha from default 0.05 == 95% to 0.01 == 99%.\n    //  my_plot.plusminus_sds(2.); // Show uncertainty as plusminus as two times standard deviation.\n    // my_plot.xy_values(false);\n\n    my_plot\n    .image_x_size(600)\n    .image_y_size(300)\n    .plot_window_on(true)\n    .background_border_color(blue)\n    .plot_border_color(yellow)\n    .plot_border_width(1)\n    //.x_ticks_on_window_or_axis(0) // now the default.\n    .legend_on(false) // or true to show a legend box.\n    .title(\"A, B and C Times\")\n    .x_range(0, 10) // but will be over-ridden by `.x_autoscale(B_times)` below:\n    .x_autoscale(B_times) // Use the data-point values in series B_times to autoscale the X-axis.\n        // Note that this might not be ideal scaling for A_times and/or C_times.\n    .x_label(\"times (sec)\")\n    .x_values_on(true)\n//   .x_values_precision(0) // Automatic number of digits of precision.\n    .x_values_precision(2) // User-chosen std::ios precision decimal digits, for example \"1.23\".\n    //.x_values_rotation(steepup) // steeper - but need more image and plot window vertical height for all data-point info.\n    .x_values_rotation(slopeup) // value description at x = 7.8 overflows both plot window and image!\n      // so might need to change `.x_range` or slope to avoid this. \n    .x_plusminus_on(true)\n    .x_plusminus_color(blue)\n    .x_addlimits_on(true) // Show plus/minus +/- confidence limits/interval for data-point value-labels.\n    .x_addlimits_color(purple)  // Show +/- in darkgreen, for example: \"+/- 0.03\".\n    .x_df_on(true) // Show degrees of freedom (usually observations -1) for data-points, for example: \"11\".\n    .x_df_color(green)  // Show degrees of freedom (usually observations -1) in green.\n    ;\n    /*`\n    Then we add our three data-series, and add optional data-series titles, \"A_times\" \"B_times\" ...\n    (very helpful if we want them to show on the legend).\n\n    All the data-points are also labeled with their value,\n    and uncertainty (+/-) and degrees of freedom if known. \n    The A_times mark data-points with a red-border circle with a green fill,\n    The B_times use a blue vertical line.\n    */\n\n    my_plot.plot(A_times, \"A\").shape(circlet).size(10).stroke_color(red).fill_color(green);\n    my_plot.plot(B_times, \"B\").shape(vertical_line).stroke_color(blue);\n\n    /*`C_times use ellipses whose width (X radius) is from the uncertainty,\n    1st standard deviation shows as ellipse in magenta, and 2nd as yellow, and 3rd as.\n\n    Or one can explicitly set some (brighter) colors for the uncertainty ellipses, or none to omit.\n    */\n    my_plot\n      .one_sd_color(pink) // Color of ellipse for one standard deviation (~68% probability).\n      .two_sd_color(magenta) // Color of ellipse for two standard deviation (~95%).\n      .three_sd_color(yellow); // Color of ellipse for two standard deviation (~99%).\n\n    my_plot.plot(C_times, \"C\").shape(unc_ellipse).fill_color(black).stroke_color(black);\n\n    /*`\n    Finally, we can write the SVG to a file of our choice.\n    */\n    std::string svg_file =  (my_plot.legend_on() == true) ?\n                            \"./demo_1d_uncertainty_legend.svg\" : \"./demo_1d_uncertainty.svg\";\n\n    my_plot.write(svg_file);\n\n    std::cout <<\"Plot written to file \" << svg_file << std::endl;\n\n    /*`Optionally we can list all the very many setting in use:*/\n    using boost::svg::show_1d_plot_settings;\n   // show_1d_plot_settings(my_plot);\n\n//] [/demo_1d_uncertainty_2]\n\n    return 0;\n} // int main()\n\n/*\n\nOutput:\n//[demo_1d_uncertainty_output\ndemo_1d_uncertainty.cpp\nLinking...\nEmbedding manifest...\nAutorun j:\\Cpp\\SVG\\debug\\demo_1d_uncertainty.exe\n3.1?0.02 (8)  4.2?0.01 (14)\n2.1?0.001 (30)  7.8?0.0025 (21)  3.4?0.03 6.9\nBuild Time 0:03\n//] [/demo_1d_uncertainty_output]\n*/\n\n/*\nData for another 1D example, also use Boost.Math?\n\nThe data is taken from J. C. Banford el al, Analyst (1983) 107, 195\nand compares the concentration of thiol of the lysate of the blood of two groups\nof volunteers as control and a second suffering from rhematoid arthritis.\n\n  map<pair<unc, unc> > control;\n  control.push_back(unc(1.921, 0.076F, 7));\n  map<pair<unc, unc> > rheumatoid;\n  control.push_back(unc(3.456, 0.44F, 6));\n\n*/\n\n/* Output Netbeans 4.7.2\n\n3.10 4.200\n2.1000 5.10 7.800 3.40 5.900\nPlot written to file ./demo_1d_uncertainty.svg\n\n\naxes_on false\nbackground_border_width 1\nbackground_border_color RGB(0,0,255)\nbackground_color RGB(255,255,255)\n...\n\n */\n", "meta": {"hexsha": "ae4cfec30a67b5ed9e25064ff37dc89881797434", "size": 9758, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/demo_1d_uncertainty.cpp", "max_stars_repo_name": "pabristow/svg_plot", "max_stars_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2016-03-09T03:23:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T14:02:07.000Z", "max_issues_repo_path": "example/demo_1d_uncertainty.cpp", "max_issues_repo_name": "pabristow/svg_plot", "max_issues_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2018-03-05T14:39:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-22T09:00:33.000Z", "max_forks_repo_path": "example/demo_1d_uncertainty.cpp", "max_forks_repo_name": "pabristow/svg_plot", "max_forks_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2016-11-04T14:36:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-17T08:12:03.000Z", "avg_line_length": 42.2424242424, "max_line_length": 161, "alphanum_fraction": 0.6950194712, "num_tokens": 2805, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677622198946, "lm_q2_score": 0.8479677660619633, "lm_q1q2_score": 0.7190493290221661}}
{"text": "/** @file 25.cpp Problem 25: 1000-digit Fibonacci number\n *\n * The Fibonacci sequence is defined by the recurrence relation:\n *\n *      F[n] = F[n-1] + F[n-2], where F[1] = 1 and F[2] = 1.\n *\n * Hence the first 12 terms will be:\n *\n *      F[1] = 1\n *      F[2] = 1\n *      F[3] = 2\n *      F[4] = 3\n *      F[5] = 5\n *      F[6] = 8\n *      F[7] = 13\n *      F[8] = 21\n *      F[9] = 34\n *      F[10] = 55\n *      F[11] = 89\n *      F[12] = 144\n *\n * The 12th term, F[12], is the first term to contain three digits.\n *\n * What is the first term in the Fibonacci sequence to contain 1000 digits?\n */\n\n#include \"int_util.hpp\"                     // pow\n\n/// @cond\n#include <boost/multiprecision/cpp_int.hpp> // cpp_int\n\n#include <cassert>                          // assert\n#include <iostream>                         // cout\n#include <utility>                          // swap\n/// @endcond\n\nusing boost::multiprecision::cpp_int;\nusing int_util::pow;\nusing std::swap;\n\nint first(int n)\n{\n    cpp_int b = 10;                 // base of digits\n    cpp_int m = pow(b, n - 1);      // lowest number having n digits\n    int r = 1;\n    for (cpp_int x = 1, y = 1; x < m; x += y, swap(x, y))\n        ++r;\n    return r;\n}\n\nint main()\n{\n    assert(first(3) == 12);\n    std::cout << first(1000) << std::endl;\n}\n", "meta": {"hexsha": "d7ab0fb35b3dbda4889acf3576838e5b847d933d", "size": 1299, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/25.cpp", "max_stars_repo_name": "jeffs/cpp-euler", "max_stars_repo_head_hexsha": "b42a8a70fad782569a699a028968bc1a60bd5c44", "max_stars_repo_licenses": ["BSL-1.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": "src/25.cpp", "max_issues_repo_name": "jeffs/cpp-euler", "max_issues_repo_head_hexsha": "b42a8a70fad782569a699a028968bc1a60bd5c44", "max_issues_repo_licenses": ["BSL-1.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": "src/25.cpp", "max_forks_repo_name": "jeffs/cpp-euler", "max_forks_repo_head_hexsha": "b42a8a70fad782569a699a028968bc1a60bd5c44", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1964285714, "max_line_length": 75, "alphanum_fraction": 0.4926866821, "num_tokens": 428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625126757597, "lm_q2_score": 0.7718435030872967, "lm_q1q2_score": 0.7189432887781538}}
{"text": "#include <vector>\r\n#include <iostream>\r\n#include <math.h>\r\n#include <Eigen/IterativeLinearSolvers>\r\n#include <iomanip>\r\n#include \"dataImport.h\"\r\n\r\n// parallel computing library: OpenOMP library\r\n// #include <omp.h>\r\n\r\n// generate increaseing sequence\r\n#include <numeric>\r\n\r\n#include <deque>\r\n\r\n\r\nusing namespace std;\r\nusing namespace Eigen;\r\n\r\n//Sigmoid function\r\ndouble sigmoid(double x){\r\n\treturn 1 / (1 + exp(x));\r\n}\r\n\r\n//Posterior probability\r\ndouble eta(vector<double>& A, vector<double>& B){\r\n\tdouble temp = 0;\r\n\tfor (int i = 0; i < A.size(); i++){\r\n\t\ttemp =temp - A[i] * B[i];\r\n\t}\r\n\treturn sigmoid(temp);\r\n}\r\n\r\n//Objective function\r\ndouble obj(vector<vector<double> >& X, vector<double>& theta, vector<double>& y, double lambda){\r\n\tdouble sum = 0;\r\n\tfor (int i = 0; i < y.size(); i++){\r\n\t\tdouble temp = 0;\r\n\t\tfor (int j = 0; j < theta.size(); j++){\r\n\t\t\ttemp += theta[j] * X[i][j];\r\n\t\t}\r\n\t\tsum += (1 - y[i])*temp + log(1 + exp(-temp));\r\n\t}\r\n\tdouble reg = 0;\r\n\tfor (int k = 0; k < theta.size(); k++){\r\n\t\treg += theta[k] * theta[k];\r\n\t}\r\n\tsum = sum + lambda*reg;\r\n\treturn sum;\r\n}\r\n\r\n//Gradient\r\nvoid grad(vector<vector<double> >& X, vector<double>& theta, vector<double>& sum, \r\n\tvector<double>& y, double lambda){\r\n\r\n\tfor (int i = 0; i < y.size(); i++){\r\n\t\tdouble temp = 0;\r\n\t\tfor (int j = 0; j < theta.size(); j++){\r\n\t\t\ttemp += theta[j] * X[i][j];\r\n\t\t}\r\n\t\tfor (int k = 0; k < theta.size(); k++){\r\n\t\t\tsum[k] += X[i][k] * (1 - y[i] - sigmoid(temp));\r\n\t\t}\r\n\t}\r\n\r\n\tfor (int i = 0; i < sum.size(); i++){\r\n\t\tsum[i] += 2 * lambda*theta[i];\r\n\t}\r\n}\r\n\r\n//Hessian\r\nvoid hess(vector<vector<double> >& X, vector<vector<double> >& sum, vector<double>& theta,\r\n\tvector<double>& y, double lambda, float startTime){\r\n\tsum.clear();\r\n\tvector<double> oneRow(theta.size(), 0);\r\n\r\n\tfor (int len = 0; len < theta.size(); len++){\r\n\t\tsum.push_back(oneRow);\r\n\t}\r\n\r\n\r\n\r\n\tdeque<int> y_ids(y.size());\r\n\r\n\tiota(y_ids.begin(), y_ids.end(), 0);\r\n\r\n\tint th_id;\r\n\tint one_y;\r\n\r\n\tint theta_size = theta.size();\r\n    {\r\n    \t// init mapper's local sum pool\r\n    \tvector<vector<double> > local_sum;\r\n\t\tvector<double> emptyRow(theta_size, 0);\r\n\r\n\t\tfor (int len = 0; len < theta_size; len++)\r\n\t\t{\r\n\t\t\tlocal_sum.push_back(emptyRow);\r\n\t\t}\r\n\r\n\t\twhile(!y_ids.empty())\r\n    \t{\r\n    \t\tvector<double> X_row_i;\r\n\r\n    \t\tone_y = -1;\r\n            // any access to shared memory should be critical\r\n            // #pragma omp critical\r\n            {\r\n                if(!y_ids.empty())\r\n                {\r\n                    one_y = y_ids.front();\r\n                    y_ids.pop_front();\r\n                    X_row_i = X[one_y];\r\n                }\r\n            }\r\n\r\n    \t\tdouble temp = 0;\r\n    \t\tif(one_y != -1)\r\n    \t\t{\r\n    \t\t\tfor (int j = 0; j < theta_size; j++)\r\n\t\t\t\t{\t \r\n\t\t\t\t\ttemp += theta[j] * X_row_i[j];\r\n\t\t\t\t}\r\n\r\n\t\t\t\tfor (int k = 0; k < theta_size; k++)\r\n\t\t\t\t{\r\n\t\t\t\t\tfor (int l = 0; l < theta_size; l++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tlocal_sum[l][k] += X_row_i[l] * X_row_i[k] * sigmoid(temp)*sigmoid(temp)*exp(temp);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n    \t\t}\r\n\t\t\t\r\n    \t}\r\n    \t\r\n\t\tfor (int k = 0; k < theta_size; k++)\r\n\t\t{\r\n\t\t\tfor (int l = 0; l < theta_size; l++)\r\n\t\t\t{\r\n\t\t\t\t// #pragma omp critical\r\n\t\t\t\t{\r\n\t\t\t\t\tsum[l][k] += local_sum[l][k];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n    \t\t\t\r\n\t\t// }\r\n    }\r\n\r\n    // #pragma omp barrier\r\n\t\r\n\r\n\r\n\tfor (int k = 0; k < theta.size(); k++){\r\n\t\tfor (int l = 0; l < theta.size(); l++){\r\n\t\t\tif (k==l){\r\n\t\t\t\tsum[k][l] += 2 * lambda;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nint main(int argc, char* argv[]){\r\n\r\n\t// prepare for parallel computing for Map reduce\r\n\r\n\tint th_id, nthreads;\r\n\r\n\t// start timing\r\n    float currentTime;\r\n    float startTime;\r\n    // shared variables;\r\n    int n, d;\r\n\r\n    vector<vector<double> > X;\r\n    vector<double> y;\r\n\r\n    //Initialization\r\n\tdouble lambda = 5;\r\n\r\n    {\r\n\t\t// #pragma omp master\r\n\t\t{\r\n\t\t\tcout << \"start running with \" << nthreads << \" cores.\" << endl;\r\n\t\t}\r\n\t}\r\n\t// Read in data\r\n\tstring dataSetFileName = argv[1]; //\"covtype_blank.data\";\r\n\tRawDataSet rawDataSet;\r\n\r\n\t// only read in the first 30000 instance\r\n\t\r\n\trawDataSet.readDataFromFile(dataSetFileName, 30000);\r\n\tcout << \"Read file done\" << endl;\r\n\trawDataSet.printDataMatrixSize();\r\n\r\n\t\r\n\t\r\n\tfor (int len = 0; len < rawDataSet.rawDataTable.size(); len++){\r\n\t\ty.push_back(rawDataSet.rawDataTable[len].back());\r\n\r\n\r\n\r\n\t\t/////////////////////\r\n\t\t//// NOTICE: code modified to fit the specific test case input: covertype\r\n\t\t////\r\n\r\n\t\t// choose covertype 2 as the flag variable\r\n\t\tif (y[len] == 2){\r\n\t\t\ty[len] = 1;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\ty[len] = 0;\r\n\t\t}\r\n\t\t///////////////////////\r\n\r\n\r\n\t\t\r\n\t\trawDataSet.rawDataTable[len].pop_back();\r\n\t\tX.push_back(rawDataSet.rawDataTable[len]);\r\n\t}\r\n\r\n\tn = y.size();\r\n\td = X[1].size();\r\n\t\r\n\r\n\tfor (int i = 0; i < n; i++){\r\n\t\tX[i].push_back(1);\r\n\t}\r\n\t\r\n\t//Tolerance\r\n\tdouble epsilon = 1.0e-5;\r\n\tint iteration = 1000;\r\n\r\n\t//Gradient descent\r\n\tvector<double> theta(d + 1, 0);\r\n\tvector<double> theta2(d + 1, 0);\r\n\r\n\tfor (int itr = 0; itr < iteration; itr++)\r\n\t{\r\n\t\tvector<double> G(d + 1, 0);\r\n\t\tgrad(X, theta, G, y, lambda);\r\n\r\n    \tcout << \"Grad of \" <<  itr << \" finished with \" << currentTime << \" seconds elapsed.\" << endl;\r\n\r\n\t\tvector<vector<double> > H;\r\n\t\thess(X, H, theta, y, lambda, startTime);\r\n\r\n    \tcout << \"Hess of \" <<  itr << \" finished with \" << currentTime << \" seconds elapsed.\" << endl;\r\n\r\n\t\tVectorXd x(d + 1), b(d + 1);\r\n\t\tMatrixXd A(d + 1, d + 1);\r\n\r\n\t\tfor (int i = 0; i < d+1; ++i) {\r\n\t\t\tA.row(i) = VectorXd::Map(&H[i][0], H[i].size());\r\n\t\t}\r\n\r\n\t\tb = VectorXd::Map(&G[0], G.size());\r\n\r\n\t\tConjugateGradient<MatrixXd> cg;\r\n\t\tcg.compute(A);\r\n\t\tx = cg.solve(b);\r\n\r\n\t\t//vector<vector<double> > H_inv;\r\n\t\t//MatrixInversion(H, d + 1, H_inv);\r\n\r\n\t\tfor (int j = 0; j < d + 1; j++){\r\n\t\t\tdouble temp = x(j);\r\n\t\t\ttheta2[j] = theta[j];\r\n\t\t\ttheta[j] = theta[j] - temp;\r\n\t\t}\r\n\r\n\t\tdouble obj1 = obj(X, theta, y, lambda);\r\n\t\tdouble obj2 = obj(X, theta2, y, lambda);\r\n\t\tdouble delta = abs(obj1 - obj2);\r\n\t\tif (delta < epsilon) break;\r\n\t}\r\n\r\n    cout << \"The program finished with \"<< currentTime << \" seconds elapsed.\" << endl;\r\n\r\n\treturn 0;\r\n}\r\n", "meta": {"hexsha": "a12979a03132079bb2cad61f792a4b6f8cb222b6", "size": 6017, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "04model/LR.cpp", "max_stars_repo_name": "robinbach/adv-loop-perf", "max_stars_repo_head_hexsha": "e97fadc9ebbe967b8d1e8d8f61cd3a423917b40c", "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": "04model/LR.cpp", "max_issues_repo_name": "robinbach/adv-loop-perf", "max_issues_repo_head_hexsha": "e97fadc9ebbe967b8d1e8d8f61cd3a423917b40c", "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": "04model/LR.cpp", "max_forks_repo_name": "robinbach/adv-loop-perf", "max_forks_repo_head_hexsha": "e97fadc9ebbe967b8d1e8d8f61cd3a423917b40c", "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.1866197183, "max_line_length": 100, "alphanum_fraction": 0.5243476816, "num_tokens": 1784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625031628428, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.7189432765471488}}
{"text": "#include \"algebra/Matrix.hpp\"\n#include \"algebra/Vector.hpp\"\n#include \"utils/GreaterThanUtils.hpp\"\n#include <NTL/ZZX.h>\n#include <cassert>\nvoid test_Matrix()\n{\n#ifdef USE_EIGEN\n    MDL::Matrix<double> mat(3, 3);\n\n    mat[0][0] = 10;\n    mat[1][1] = 3;\n    mat[2][2] = 4;\n\n    auto inv = mat.inverse();\n    auto I   = inv.dot(mat);\n    assert(I[0][0] == I[1][1] == I[2][2] == 1.0);\n    assert(I[0][1] == I[1][2] == I[0][2] == 0.0);\n    {\n        MDL::Matrix<long> mat(3, 3);\n        mat[0][0] = 10;\n        mat[1][1] = 3;\n        mat[2][2] = 4;\n        auto prod = mat.dot(mat);\n        assert(prod[0][0] == 100);\n        assert(prod[1][1] == 9);\n        assert(prod[2][2] == 16);\n        auto submat = mat.submatrix(0, 1);\n        auto matT = submat.transpose();\n        std::cout << submat << std::endl;\n        std::cout << matT << std::endl;\n        prod = matT.dot(submat);\n        std::cout << prod << std::endl;\n    }\n#endif\n}\n\nvoid test_Vector()\n{\n    MDL::Vector<NTL::ZZX> vec(3);\n\n    vec[0] = NTL::to_ZZX(1);\n    vec[1] = NTL::to_ZZX(4);\n    vec[2] = NTL::to_ZZX(3);\n    assert(std::abs(vec.L2() - std::sqrt(26.0)) < 1e-9);\n}\n\nvoid test_random_permutation()\n{\n    auto vecs  = permutated_range(10, 6);\n    auto noise = random_noise(10, 6, 10);\n}\n\nint main() {\n    test_Matrix();\n    test_Vector();\n    test_random_permutation();\n    printf(\"Passed all test!\\n\");\n    return 0;\n}\n", "meta": {"hexsha": "7154706058cbb239293ae26c811f36866e64073a", "size": 1388, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_MatrixVector.cpp", "max_stars_repo_name": "fionser/MDLHElib", "max_stars_repo_head_hexsha": "3c686ab35d7b26a893213a6e9d4249cd46c2969d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-01-16T06:20:07.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-17T12:36:34.000Z", "max_issues_repo_path": "test/test_MatrixVector.cpp", "max_issues_repo_name": "fionser/MDLHElib", "max_issues_repo_head_hexsha": "3c686ab35d7b26a893213a6e9d4249cd46c2969d", "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/test_MatrixVector.cpp", "max_forks_repo_name": "fionser/MDLHElib", "max_forks_repo_head_hexsha": "3c686ab35d7b26a893213a6e9d4249cd46c2969d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-08-26T13:16:35.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-15T02:08:20.000Z", "avg_line_length": 22.7540983607, "max_line_length": 56, "alphanum_fraction": 0.5216138329, "num_tokens": 497, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391385, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.7189369186246922}}
{"text": "#include <armadillo>\n#include <cmath>\n#include <vector>\n\ntypedef std::pair<arma::vec, arma::vec> trainingData;\n\nclass Network {\npublic:\n  explicit Network(std::vector<int> sizes) : sizes(sizes) {\n    layerNumber = sizes.size();\n\n    for (int i = 1; i < sizes.size(); ++i) {\n      biases.push_back(arma::vec(sizes[i], arma::fill::randn));\n      biasesShape.push_back(arma::vec(sizes[i], arma::fill::zeros));\n    }\n\n    for (int i = 0; i < sizes.size() - 1; ++i) {\n      weights.push_back(arma::mat(sizes[i], sizes[i + 1], arma::fill::randn));\n      weightsShape.push_back(\n          arma::mat(sizes[i], sizes[i + 1], arma::fill::zeros));\n    }\n  }\n\n  static arma::vec sigmoid(arma::vec z) {\n    z.transform([](double val) { return 1 / (1 + exp(-val)); });\n    return z;\n  }\n\n  static arma::vec sigmoidPrime(arma::vec z) {\n    arma::vec sigmoidZ = sigmoid(z);\n    arma::vec rhs = sigmoidZ;\n    rhs.transform([](double val) { return 1 - val; });\n    return sigmoidZ * arma::diagmat(rhs);\n  }\n\n  arma::vec feedforward(const arma::vec &input);\n  void sgd(std::vector<trainingData> &trainingSet, const int epochs,\n           const int miniBatchSize, const double eta);\n  void updateMiniBatch(std::vector<trainingData *> &miniBatch,\n                       const double eta);\n  void backprop(arma::vec &in, arma::vec &out, std::vector<arma::vec> &partialB,\n                std::vector<arma::mat> &partialW);\n  arma::vec costDerivative(arma::vec &out, arma::vec &y);\n\nprivate:\n  Network(){};\n\n  int layerNumber;\n  std::vector<int> sizes;\n  // biases[i] represents bias at (i+1)th layer\n  std::vector<arma::vec> biases, biasesShape;\n  // weights[i] represents weight from ith layer to (i+1)th layer\n  std::vector<arma::mat> weights, weightsShape;\n};\n", "meta": {"hexsha": "8ab9feec4c3f101049ffbb27ee1de59aa662c4f6", "size": 1740, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/network.hpp", "max_stars_repo_name": "MForever78/literate", "max_stars_repo_head_hexsha": "db6cf1a3dd95c1e5c718848731cae4346e323356", "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/network.hpp", "max_issues_repo_name": "MForever78/literate", "max_issues_repo_head_hexsha": "db6cf1a3dd95c1e5c718848731cae4346e323356", "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/network.hpp", "max_forks_repo_name": "MForever78/literate", "max_forks_repo_head_hexsha": "db6cf1a3dd95c1e5c718848731cae4346e323356", "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.6363636364, "max_line_length": 80, "alphanum_fraction": 0.6247126437, "num_tokens": 504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769413, "lm_q2_score": 0.7879311906630568, "lm_q1q2_score": 0.7189369103286244}}
{"text": "#include <gtest/gtest.h>\n#include <boost/math/constants/constants.hpp>\n#include <functional>\n#include <vector>\n#include <iostream>\n#include <iomanip>\n\n#include \"quadrature/qhermite.hpp\"\n#include \"quadrature/qhermitew.hpp\"\n#include \"quadrature/qmaxwell.hpp\"\n#include \"quadrature/qmaxwellw.hpp\"\n#include \"spectral/hermiten.hpp\"\n#include \"spectral/hermitenw.hpp\"\n\nusing namespace std;\nusing namespace boltzmann;\n\nTEST(quadrature, maxwell)\n{\n  int digits = 128;\n\n  static const double PI = boost::math::constants::pi<double>();\n  std::vector<int> Ns = {1, 5, 10, 21, 40, 60, 80};\n\n  for (auto N : Ns) {\n    QMaxwell qmaxwell(1, N, digits);\n\n    // test integration \\int \\exp{-r^2} r \\dd r = pi\n    double sum = 0;\n    for (int i = 0; i < N; ++i) {\n      sum += qmaxwell.wts(i);\n    }\n    sum *= 2 * PI;\n    EXPECT_NEAR(sum, PI, 1e-12) << boost::lexical_cast<string>(N)\n                                << \": integrate: e^{r^2} r, on [0,\\\\infty)\";\n\n    // test integration \\int r \\exp{-r^2} r \\dd r = 1/2 pi^3/2\n    sum = 0;\n    for (int i = 0; i < N; ++i) {\n      sum += qmaxwell.wts(i) * qmaxwell.pts(i);\n    }\n    sum *= 2 * PI;\n    EXPECT_NEAR(sum, 0.5 * std::pow(PI, 1.5), 1e-12)\n        << boost::lexical_cast<string>(N) << \"integrate: e^{r^2} r^2, on [0,\\\\infty)\";\n  }\n}\n\nTEST(quadrature, maxwellw)\n{\n  int digits = 128;\n\n  static const double PI = boost::math::constants::pi<double>();\n  std::vector<int> Ns = {1, 5, 10, 21, 40, 60, 80};\n\n  for (auto N : Ns) {\n    QMaxwellW qmaxwell(1, N, digits);\n\n    // test integration \\int \\exp{-r^2} r \\dd r = pi\n    double sum = 0;\n    for (int i = 0; i < N; ++i) {\n      double x = qmaxwell.pts(i);\n      sum += qmaxwell.wts(i) * std::exp(-x*x);\n    }\n    sum *= 2 * PI;\n    EXPECT_NEAR(sum, PI, 1e-12) << boost::lexical_cast<string>(N)\n                                << \": integrate: e^{r^2} r, on [0,\\\\infty)\";\n\n    // test integration \\int r \\exp{-r^2} r \\dd r = 1/2 pi^3/2\n    sum = 0;\n    for (int i = 0; i < N; ++i) {\n      double x = qmaxwell.pts(i);\n      sum += qmaxwell.wts(i) * qmaxwell.pts(i) * std::exp(-x*x);\n    }\n    sum *= 2 * PI;\n    EXPECT_NEAR(sum, 0.5 * std::pow(PI, 1.5), 1e-12)\n        << boost::lexical_cast<string>(N) << \"integrate: e^{r^2} r^2, on [0,\\\\infty)\";\n  }\n}\n\n\n\n\n\n/**\n *  @brief Test Gauss-Hermite quadrature to integrate 1, x, x^2\n *\n *  Detailed description\n *\n *  @param param\n *  @return return type\n */\nTEST(quadrature, hermite_quad_only)\n{\n  std::vector<int> Ns = {2, 5, 10, 21, 40, 60, 80, 120};\n  int digits = 128;\n  cout << \"Testing n=\" << std::for_each(Ns.begin(), Ns.end(), [](int x) { cout << x << \" \"; })\n       << \"\\n\";\n\n  static const double PI = boost::math::constants::pi<double>();\n\n  for (auto N : Ns) {\n    QHermite quad(1.0, /* alpha */\n                  N,   /*  num. quad. poins */\n                  digits);\n\n    {\n      double sum = 0;\n      for (int i = 0; i < N; ++i) {\n        sum += quad.wts(i);\n      }\n      EXPECT_NEAR(sum, std::sqrt(PI), 1e-12)\n          << boost::lexical_cast<string>(N) << \"integrate e^{-x^2} on (-\\\\infty, \\\\infty)\";\n    }\n    {\n      double sum = 0;\n      for (int i = 0; i < N; ++i) {\n        sum += quad.wts(i) * quad.pts(i);\n      }\n      EXPECT_NEAR(sum, 0, 1e-12) << boost::lexical_cast<string>(N)\n                                 << \"integrate x e^{-x^2} on (-\\\\infty, \\\\infty)\";\n    }\n    {\n      double sum = 0;\n      for (int i = 0; i < N; ++i) {\n        sum += quad.wts(i) * quad.pts(i) * quad.pts(i);\n      }\n      EXPECT_NEAR(sum, std::sqrt(PI) / 2, 1e-12)\n          << boost::lexical_cast<string>(N) << \"integrate x^2 e^{-x^2} on (-\\\\infty, \\\\infty)\";\n    }\n  }\n}\n\n/**\n *  @brief Test hermite quadrature rule by computing overlap integrals of Hermite polynomials.\n *\n *\n */\nTEST(quadrature, hermite_full)\n{\n  // hint: quadrature rule for N=1 does not exist!\n  std::vector<int> Ns = {2, 5, 10, 21, 40, 60, 80, 120};\n  cout << \"Testing n=\" << std::for_each(Ns.begin(), Ns.end(), [](int x) { cout << x << \" \"; })\n       << \"\\n\";\n  typedef double numeric_t;\n\n  for (auto N : Ns) {\n    QHermiteW quad(1.0, N);\n    auto& wts = quad.wts();\n    auto& pts = quad.pts();\n\n    HermiteNW<numeric_t> HW(N);\n    HW.compute(quad.pts());\n\n    for (unsigned i = 0; i < N; ++i) {\n      double val = 0;\n      for (unsigned int q = 0; q < quad.size(); ++q) {\n        // const double wh = exp(0.5*quad.pts(q) * quad.pts(q));\n        val += (HW.get(i)[q]) * (HW.get(i)[q]) * quad.wts(q);\n      }\n      EXPECT_NEAR(val, 1, 1e-12)\n          << \"(h_i, h_i) \"\n          << \"i=\" << boost::lexical_cast<string>(i) << \", N=\" << boost::lexical_cast<string>(N)\n          << \" (evaluatued Hermite polynomials _with_ expt weight aka Hermite functions)\";\n    }\n  }\n}\n", "meta": {"hexsha": "e818b064ec2a24c109d15aa543801e55d60ec5b6", "size": 4680, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/gtest/gtest_quadrature.cpp", "max_stars_repo_name": "simonpp/2dBoltzmann", "max_stars_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "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": "test/gtest/gtest_quadrature.cpp", "max_issues_repo_name": "simonpp/2dBoltzmann", "max_issues_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "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": "test/gtest/gtest_quadrature.cpp", "max_forks_repo_name": "simonpp/2dBoltzmann", "max_forks_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "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": 28.0239520958, "max_line_length": 95, "alphanum_fraction": 0.525, "num_tokens": 1637, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436153333645, "lm_q2_score": 0.787931190663057, "lm_q1q2_score": 0.7189369047001986}}
{"text": "/**\n * @file advectionfv2d.cc\n * @brief NPDE homework AdvectionFV2D code\n * @author Philipp Egg\n * @date 21.06.2020\n * @copyright Developed at ETH Zurich\n */\n\n#include \"advectionfv2d.h\"\n\n#include <lf/geometry/geometry.h>\n#include <lf/mesh/mesh.h>\n#include <lf/mesh/utils/utils.h>\n\n#include <Eigen/Core>\n#include <Eigen/LU>\n#include <algorithm>\n#include <array>\n#include <memory>\n#include <stdexcept>\n#include <vector>\n\nnamespace AdvectionFV2D {\n\n/* SAM_LISTING_BEGIN_1 */\nEigen::Matrix<double, 2, 3> gradbarycoordinates(\n    const Eigen::Matrix<double, 2, 3> &triangle) {\n  Eigen::Matrix3d X;\n\n  // solve for the coefficients of the barycentric coordinate functions\n  X.block<3, 1>(0, 0) = Eigen::Vector3d::Ones();\n  X.block<3, 2>(0, 1) = triangle.transpose();\n  return X.inverse().block<2, 3>(1, 0);\n}\n/* SAM_LISTING_END_1 */\n\n/* SAM_LISTING_BEGIN_2 */\nstd::shared_ptr<\n    lf::mesh::utils::CodimMeshDataSet<Eigen::Matrix<double, 2, Eigen::Dynamic>>>\ncomputeCellNormals(std::shared_ptr<const lf::mesh::Mesh> mesh_p) {\n  // Appears only in mastersolution\n\n  // Initialize datastruture for the result\n  lf::mesh::utils::CodimMeshDataSet<Eigen::Matrix<double, 2, Eigen::Dynamic>>\n      result(mesh_p, 0);\n\n  // Compute normal vectors\n  for (const lf::mesh::Entity *cell : mesh_p->Entities(0)) {\n    const lf::geometry::Geometry *geo_p = cell->Geometry();\n    const Eigen::MatrixXd corners = lf::geometry::Corners(*geo_p);\n\n    if (corners.cols() == 3) {\n      Eigen::Matrix<double, 2, Eigen::Dynamic> normal_vectors(2, 3);\n\n      // Compute normal vectors\n      Eigen::Matrix<double, 2, 3> bary_coord = gradbarycoordinates(corners);\n\n      // Reorder computed normal vectors\n      // normal_vectors[0] -> normal_vector of edge[0]\n      normal_vectors.col(0) = -(bary_coord.col(2)).normalized();\n      normal_vectors.col(1) = -(bary_coord.col(0)).normalized();\n      normal_vectors.col(2) = -(bary_coord.col(1)).normalized();\n\n      // Save the matrix in our datastructure\n      result(*cell) = normal_vectors;\n    } else {  // corners.cols() == 4\n      Eigen::Matrix<double, 2, Eigen::Dynamic> normal_vectors(2, 4);\n\n      // Split the quadrilateral into two triangles (1,2,3) and (1,3,4)\n      Eigen::Matrix<double, 2, 3> tria_1;\n      Eigen::Matrix<double, 2, 3> tria_2;\n      tria_1 << corners.col(0), corners.col(1), corners.col(2);\n      tria_2 << corners.col(0), corners.col(2), corners.col(3);\n\n      // Compute normal vectors\n      Eigen::Matrix<double, 2, 3> bary_coord_1 = gradbarycoordinates(tria_1);\n      Eigen::Matrix<double, 2, 3> bary_coord_2 = gradbarycoordinates(tria_2);\n\n      // Reorder computed normal vectors\n      // normal_vectors[0] -> normal_vector of edge[0]\n      normal_vectors.col(0) = -(bary_coord_1.col(2)).normalized();\n      normal_vectors.col(1) = -(bary_coord_1.col(0)).normalized();\n      normal_vectors.col(2) = -(bary_coord_2.col(0)).normalized();\n      normal_vectors.col(3) = -(bary_coord_2.col(1)).normalized();\n\n      // Save the matrix in our datastructure\n      result(*cell) = normal_vectors;\n    }\n  }\n  return std::make_shared<lf::mesh::utils::CodimMeshDataSet<\n      Eigen::Matrix<double, 2, Eigen::Dynamic>>>(result);\n\n}\n/* SAM_LISTING_END_2 */\n\n/* SAM_LISTING_BEGIN_3 */\nstd::shared_ptr<\n    lf::mesh::utils::CodimMeshDataSet<std::array<const lf::mesh::Entity *, 4>>>\ngetAdjacentCellPointers(std::shared_ptr<const lf::mesh::Mesh> mesh_p) {\n  // Initialize auxilary object\n  lf::mesh::utils::CodimMeshDataSet<std::array<const lf::mesh::Entity *, 2>>\n      aux_obj(mesh_p, 1, {nullptr, nullptr});\n\n  // Iterate over every cell\n  for (const lf::mesh::Entity *cell : mesh_p->Entities(0)) {\n    auto cell_edges = cell->SubEntities(1);\n\n    // Iterate over every edge of the cell\n    for (const lf::mesh::Entity *edge : cell_edges) {\n      // If aux_obj at index 0 was not set, save cell there\n      // otherwise save at the second position\n      // (The first position has to be set; the second might be set)\n      if (aux_obj(*edge)[0] == nullptr) {\n        aux_obj(*edge)[0] = cell;\n      } else if (aux_obj(*edge)[1] == nullptr) {\n        aux_obj(*edge)[1] = cell;\n      } else {\n        throw std::runtime_error(\"Error in aux_obj\");\n      }\n    }\n  }\n\n  // Initialize datastructure for result\n  lf::mesh::utils::CodimMeshDataSet<std::array<const lf::mesh::Entity *, 4>>\n      result(mesh_p, 0, {nullptr, nullptr, nullptr, nullptr});\n\n  // Collect the objects of the auxilary object\n  for (const lf::mesh::Entity *cell : mesh_p->Entities(0)) {\n    auto cell_edges = cell->SubEntities(1);\n    int counter = 0;\n    for (const lf::mesh::Entity *edge : cell_edges) {\n      if (aux_obj(*edge)[0] != cell) {\n        result(*cell)[counter] = aux_obj(*edge)[0];\n      } else {\n        result(*cell)[counter] = aux_obj(*edge)[1];\n      }\n      counter++;\n    }\n  }\n\n  return std::make_shared<lf::mesh::utils::CodimMeshDataSet<\n      std::array<const lf::mesh::Entity *, 4>>>(result);\n}\n/* SAM_LISTING_END_3 */\n\n// Function returning the barycenter of TRIA or QUAD\n/* SAM_LISTING_BEGIN_4 */\nEigen::Vector2d barycenter(const Eigen::MatrixXd corners) {\n  Eigen::Vector2d midpoint;\n  if (corners.cols() == 3) {\n    midpoint = (corners.col(0) + corners.col(1) + corners.col(2)) / 3.0;\n  } else if (corners.cols() == 4) {\n    midpoint =\n        (corners.col(0) + corners.col(1) + corners.col(2) + corners.col(3)) /\n        4.0;\n  } else {\n    throw std::runtime_error(\"Wrong geometrie in barycenter()\");\n  }\n  return midpoint;\n}\n/* SAM_LISTING_END_4 */\n\n/* SAM_LISTING_BEGIN_5 */\ndouble computeHmin(std::shared_ptr<const lf::mesh::Mesh> mesh_p) {\n  // Vector to store the distances between cells\n  std::vector<double> min_h;\n\n  // Get Adjectent Cells\n  std::shared_ptr<lf::mesh::utils::CodimMeshDataSet<\n      std::array<const lf::mesh::Entity *, 4>>>\n      adjacentCells = AdvectionFV2D::getAdjacentCellPointers(mesh_p);\n\n  // Iterate over all cells\n  for (const lf::mesh::Entity *cell : mesh_p->Entities(0)) {\n    const lf::geometry::Geometry *geo_p = cell->Geometry();\n    const Eigen::MatrixXd corners = lf::geometry::Corners(*geo_p);\n\n    // Compute the barycenter of the cell\n    Eigen::Vector2d cur_midpoint = barycenter(corners);\n\n    // Iterate over all adjecent cells\n    for (const lf::mesh::Entity *neighbour_cell : (*adjacentCells)(*cell)) {\n      // Check that the neighbor exists\n      if (neighbour_cell != nullptr) {\n        const lf::geometry::Geometry *geo_p_neighbour =\n            neighbour_cell->Geometry();\n        const Eigen::MatrixXd neighbour_corners =\n            lf::geometry::Corners(*geo_p_neighbour);\n\n        // Compute barycenter of neighbour cell\n        Eigen::Vector2d neighbour_midpoint = barycenter(neighbour_corners);\n\n        // Compute distances between cells\n        double distance = (cur_midpoint - neighbour_midpoint).norm();\n\n        // Store value in vector\n        min_h.push_back(distance);\n      }\n    }\n  }\n\n  // Find the minimum value in the vector and return it\n  return *std::min_element(std::begin(min_h), std::end(min_h));\n}\n/* SAM_LISTING_END_5 */\n\n}  // namespace AdvectionFV2D\n", "meta": {"hexsha": "29dd3e0582b8be90aa8a8d7a8f1313a9731ff090", "size": 7070, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/AdvectionFV2D/mastersolution/advectionfv2d.cc", "max_stars_repo_name": "0xBachmann/NPDECODES", "max_stars_repo_head_hexsha": "70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-22T10:59:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T10:59:19.000Z", "max_issues_repo_path": "homeworks/AdvectionFV2D/mastersolution/advectionfv2d.cc", "max_issues_repo_name": "0xBachmann/NPDECODES", "max_issues_repo_head_hexsha": "70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea", "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": "homeworks/AdvectionFV2D/mastersolution/advectionfv2d.cc", "max_forks_repo_name": "0xBachmann/NPDECODES", "max_forks_repo_head_hexsha": "70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea", "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.9903846154, "max_line_length": 80, "alphanum_fraction": 0.6551626591, "num_tokens": 2015, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953030553433, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.7187774494755174}}
{"text": "<%\ncfg['compiler_args'] = ['-std=c++11']\ncfg['include_dirs'] = ['../notebooks/eigen3']\nsetup_pybind11(cfg)\n%>\n\n#include <cmath>\n#include <pybind11/pybind11.h>\n#include <pybind11/eigen.h>\n\n#include <Eigen/LU>\n\nnamespace py = pybind11;\nusing namespace Eigen;\n\nVectorXd logistic(VectorXd xs) {\n    return 1 - 1 / (1 + exp(xs.array()));\n}\n\nMatrixXd gd(MatrixXd X, VectorXd y, VectorXd beta, double alpha, int niter) {\n    \n    int i = 0, n, p;\n    MatrixXd Xt;\n    VectorXd y_pred, epsilon, grad;\n    \n    n = X.rows();\n    p = X.cols();\n    Xt = X.transpose();\n    y_pred = VectorXd::Zero(n);\n    epsilon = VectorXd::Zero(n);\n    grad = VectorXd::Zero(p);\n    \n    for(i = 0; i < niter; i++) {\n        y_pred = logistic(X * beta);\n        epsilon = y - y_pred;\n        grad = Xt * epsilon / n;\n        beta += alpha * grad;\n    }\n    \n    return beta;\n}\n    \nPYBIND11_MODULE(logistic_gd, m) {\n    m.doc() = \"auto-compiled c++ extension\";\n    m.def(\"logistic\", &logistic);\n    m.def(\"gd\", &gd);\n}\n", "meta": {"hexsha": "127b208a4f01fc50d6a96d3eb628d6fecf99ab31", "size": 993, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "homework/logistic_gd.cpp", "max_stars_repo_name": "itachi4869/sta-663-2021", "max_stars_repo_head_hexsha": "6f7a50f4a95207a26b01afa4439d992d767a1387", "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": "homework/logistic_gd.cpp", "max_issues_repo_name": "itachi4869/sta-663-2021", "max_issues_repo_head_hexsha": "6f7a50f4a95207a26b01afa4439d992d767a1387", "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": "homework/logistic_gd.cpp", "max_forks_repo_name": "itachi4869/sta-663-2021", "max_forks_repo_head_hexsha": "6f7a50f4a95207a26b01afa4439d992d767a1387", "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": 20.6875, "max_line_length": 77, "alphanum_fraction": 0.5709969789, "num_tokens": 299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333484, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.7187774363265573}}
{"text": "//#####################################################################\n//  Copyright (c) 2011-2013 Nathan Mitchell, Eftychios Sifakis.\n//  This file is covered by the FreeBSD license. Please refer to the \n//  license.txt file for more information.\n//#####################################################################\n\n\n#include <iomanip>\n#include <iostream>\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\nnamespace{\ntemplate<class T_MATRIX>\nvoid Print_Formatted(const T_MATRIX& A,std::ostream& output)\n{\n    for(int i=0;i<A.rows();i++){\n        for(int j=0;j<A.cols();j++){\n            output<<std::setw(12)<<A(i,j);\n            if(j<A.cols()-1) output<<\" \";}\n        output<<std::endl;}\n}\n}\n\ntemplate<class T>\nvoid Singular_Value_Decomposition_Reference(const T A[9], T U[9], T Sigma[3], T V[9])\n{\n    Map<const Matrix<T,3,3>> mA=Map<const Matrix<T,3,3>>(A);\n\n    Map<Matrix<T,3,3>> mU=Map<Matrix<T,3,3>>(U);\n    Map<Matrix<T,3,1>> mSigma=Map<Matrix<T,3,1>>(Sigma);\n    Map<Matrix<T,3,3>> mV=Map<Matrix<T,3,3>>(V);\n\n    JacobiSVD<Matrix<T,3,3>> svd(mA, ComputeFullU|ComputeFullV);\n    mU=svd.matrixU();\n    mSigma=svd.singularValues();\n    mV=svd.matrixV();\n\n    if(mU.determinant() < 0.) {\n        mU.col(2) *= -1.;\n        mSigma(2) *= -1.;\n    }\n\n    if(mV.determinant() < 0.) {\n        mV.col(2) *= -1.;\n        mSigma(2) *= -1.;\n    }\n}\n\ntemplate<class T>\nbool Singular_Value_Decomposition_Compare(const T U[9], const T Sigma[3], const T V[9],\n                                          const T U_reference[9], const T Sigma_reference[3], const T V_reference[9])\n{\n\n    Map<const Matrix<T,3,3>> mU=Map<const Matrix<T,3,3>>(U);\n    Map<const Matrix<T,3,1>> mSigma=Map<const Matrix<T,3,1>>(Sigma);\n    Map<const Matrix<T,3,3>> mV=Map<const Matrix<T,3,3>>(V);\n\n    Map<const Matrix<T,3,3>> mU_reference=Map<const Matrix<T,3,3>>(U_reference);\n    Map<const Matrix<T,3,1>> mSigma_reference=Map<const Matrix<T,3,1>>(Sigma_reference);\n    Map<const Matrix<T,3,3>> mV_reference=Map<const Matrix<T,3,3>>(V_reference);\n\n    Matrix<T,3,3> mU_adjusted = mU_reference;\n    Matrix<T,3,1> mSigma_adjusted = mSigma_reference;\n    Matrix<T,3,3> mV_adjusted = mV_reference;\n\n    for (int i = 0; i < 2; i++) {\n\n      if (mU.col(i).dot(mU_adjusted.col(i)) < 0.) {\n          mU_adjusted.col(i) *= -1.;\n          mSigma_adjusted(i) *= -1.;\n          mU_adjusted.col(2) *= -1.;\n          mSigma_adjusted(2) *= -1.;\n      }\n\t\n      if (mV.col(i).dot(mV_adjusted.col(i)) < 0.) {\n          mV_adjusted.col(i) *= -1.;\n          mSigma_adjusted(i) *= -1.;\n          mV_adjusted.col(2) *= -1.;\n          mSigma_adjusted(2) *= -1.;\n      }\n\t\n    }\n    \n    std::cout<<\"Computed matrix U :\"<<std::endl;Print_Formatted(mU,std::cout);\n    std::cout<<\"Reference matrix U :\"<<std::endl;Print_Formatted(mU_reference,std::cout);\n    std::cout<<\"Adjusted matrix U :\"<<std::endl;Print_Formatted(mU_adjusted,std::cout);\n    std::cout<<\"Difference = \"<< (mU-mU_adjusted).norm()  <<std::endl;\n\n    std::cout<<std::endl;\n    std::cout<<\"Computed matrix Sigma :\"<<std::endl;Print_Formatted(mSigma,std::cout);\n    std::cout<<\"Reference matrix Sigma :\"<<std::endl;Print_Formatted(mSigma_reference,std::cout);\n    std::cout<<\"Adjusted matrix Sigma :\"<<std::endl;Print_Formatted(mSigma_adjusted,std::cout);\n    std::cout<<\"Difference = \"<<  (mSigma-mSigma_adjusted).norm()  <<std::endl;\n    \n    std::cout<<std::endl;\n    std::cout<<\"Computed matrix V :\"<<std::endl;Print_Formatted(mV,std::cout); \n    std::cout<<\"Reference matrix V :\"<<std::endl;Print_Formatted(mV_reference,std::cout);\n    std::cout<<\"Adjusted matrix V :\"<<std::endl;Print_Formatted(mV_adjusted,std::cout);\n    std::cout<<\"Difference = \"<< (mV-mV_adjusted).norm()  <<std::endl;   \n\n    Matrix<T,3,3> mA=mU*mSigma.asDiagonal()*mV.transpose();\n    Matrix<T,3,3> mA_reference=mU_reference*mSigma_reference.asDiagonal()*mV_reference.transpose();\n\n    std::cout<<std::endl;\n    std::cout<<\"Computed matrix A=U*Sigma*V^T :\"<<std::endl;Print_Formatted(mA,std::cout);\n    std::cout<<\"Reference matrix A=U*Sigma*V^T :\"<<std::endl;Print_Formatted(mA_reference,std::cout);\n    std::cout<<\"Difference = \"<< (mA-mA_reference).norm()  <<std::endl;\n\n\n    if(!((mU-mU_adjusted).norm() < 0.00001) )\n        return false;\n    \n\n    if(!((mSigma-mSigma_adjusted).norm() < 0.00001) )\n        return false;\n    \n\n    if(!((mV-mV_adjusted).norm() < 0.00001) )\n        return false;\n    \n\n    \n\n\n\n\n\n\n    return true;\n}\n\ntemplate void Singular_Value_Decomposition_Reference(const float A[9], float U[9], float Sigma[3], float V[9]);\ntemplate bool Singular_Value_Decomposition_Compare(const float U[9], const float Sigma[3], const float V[9],\n                                                   const float U_reference[9], const float Sigma_reference[3], const float V_reference[9]);\n \n", "meta": {"hexsha": "ed5b789e5c1359b2df4ba011e907dccc7fb3cc4a", "size": 4791, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "simd-numeric-kernels-new/References/Singular_Value_Decomposition/Singular_Value_Decomposition_Reference.cpp", "max_stars_repo_name": "uwgraphics/SkinFlaps", "max_stars_repo_head_hexsha": "28f66f768514347ff16a75b569aaa4274b73353a", "max_stars_repo_licenses": ["BSD-2-Clause", "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": "simd-numeric-kernels-new/References/Singular_Value_Decomposition/Singular_Value_Decomposition_Reference.cpp", "max_issues_repo_name": "uwgraphics/SkinFlaps", "max_issues_repo_head_hexsha": "28f66f768514347ff16a75b569aaa4274b73353a", "max_issues_repo_licenses": ["BSD-2-Clause", "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": "simd-numeric-kernels-new/References/Singular_Value_Decomposition/Singular_Value_Decomposition_Reference.cpp", "max_forks_repo_name": "uwgraphics/SkinFlaps", "max_forks_repo_head_hexsha": "28f66f768514347ff16a75b569aaa4274b73353a", "max_forks_repo_licenses": ["BSD-2-Clause", "Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7173913043, "max_line_length": 139, "alphanum_fraction": 0.5948653726, "num_tokens": 1441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.7187679638055317}}
{"text": "/*\n * Copyright 2015 C. Brett Witherspoon\n */\n\n#define BOOST_TEST_MODULE signum_tests\n#include <boost/test/unit_test.hpp>\n\n#include \"signum/math.hpp\"\n\nBOOST_AUTO_TEST_CASE(abs_test)\n{\n  using signum::math::abs;\n\n  BOOST_CHECK_EQUAL(abs(-5), 5);\n\n  BOOST_CHECK_EQUAL(abs(12), 12);\n\n  BOOST_CHECK_EQUAL(abs(-1.3), 1.3);\n\n  BOOST_CHECK_EQUAL(abs(5.4), 5.4);\n}\n\nBOOST_AUTO_TEST_CASE(max_test)\n{\n  using signum::math::max;\n\n  BOOST_CHECK_EQUAL(max(-7, 5), 5);\n\n  BOOST_CHECK_EQUAL(max(7, 67), 67);\n\n  BOOST_CHECK_EQUAL(max(-9.0, 5.7), 5.7);\n}\n\nBOOST_AUTO_TEST_CASE(gcd_test)\n{\n  using signum::math::gcd;\n\n  BOOST_CHECK_EQUAL(gcd(6, 15), 3);\n}\n\nBOOST_AUTO_TEST_CASE(lcm_test)\n{\n  using signum::math::lcm;\n\n  BOOST_CHECK_EQUAL(lcm(4, 10), 20);\n}\n\nBOOST_AUTO_TEST_CASE(nextpow2_test)\n{\n  using signum::math::nextpow2;\n\n  BOOST_CHECK_EQUAL(nextpow2(600000), 1048576);\n}\n\n", "meta": {"hexsha": "ba5ef264e5b5a33d5f67295249ee6818c7bb6796", "size": 862, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/math_test.cpp", "max_stars_repo_name": "spoonb/libcomm", "max_stars_repo_head_hexsha": "5638dac889bddb16420d8321067c783438a5deaf", "max_stars_repo_licenses": ["0BSD"], "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/math_test.cpp", "max_issues_repo_name": "spoonb/libcomm", "max_issues_repo_head_hexsha": "5638dac889bddb16420d8321067c783438a5deaf", "max_issues_repo_licenses": ["0BSD"], "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/math_test.cpp", "max_forks_repo_name": "spoonb/libcomm", "max_forks_repo_head_hexsha": "5638dac889bddb16420d8321067c783438a5deaf", "max_forks_repo_licenses": ["0BSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.6727272727, "max_line_length": 47, "alphanum_fraction": 0.7053364269, "num_tokens": 280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423874, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.7187679631215216}}
{"text": "\n#include \"tile/math/bignum.h\"\n\n#include <boost/math/common_factor_rt.hpp>\n\nnamespace vertexai {\nnamespace tile {\nnamespace math {\n\nInteger Floor(const Rational& x) {\n  if (x < 0) {\n    return (numerator(x) - denominator(x) + 1) / denominator(x);\n  } else {\n    return numerator(x) / denominator(x);\n  }\n}\n\nInteger Ceil(const Rational& x) { return Floor(Rational(numerator(x) - 1, denominator(x))) + 1; }\n\nRational FracPart(const Rational& x) { return x - Floor(x); }\n\nInteger Abs(const Integer& x) {\n  if (x < 0) {\n    return -x;\n  }\n  return x;\n}\n\nRational Abs(const Rational& x) {\n  if (x < 0) {\n    return -x;\n  }\n  return x;\n}\n\nRational Reduce(const Rational& v, const Rational& m) { return v - Floor(v / m) * m; }\n\nInteger XGCD(const Integer& a, const Integer& b, Integer& x, Integer& y) {  // NOLINT(runtime/references)\n  if (b == 0) {\n    x = 1;\n    y = 0;\n    return a;\n  }\n\n  Integer x1;\n  Integer gcd = XGCD(b, a % b, x1, x);\n  y = x1 - (a / b) * x;\n\n  if (gcd < 0) {\n    gcd *= -1;\n    x *= -1;\n    y *= -1;\n  }\n\n  return gcd;\n}\n\nRational XGCD(const Rational& a, const Rational& b, Integer& x, Integer& y) {  // NOLINT(runtime/references)\n  Integer m = boost::math::lcm(denominator(a), denominator(b));\n  Rational o;\n  o = Rational(XGCD(numerator(a * m), numerator(b * m), x, y), m);\n\n  if (o < 0) {\n    o *= -1;\n    x *= -1;\n    y *= -1;\n  }\n  return o;\n}\n\nRational GCD(const Rational& a, const Rational& b) {\n  Integer m = boost::math::lcm(denominator(a), denominator(b));\n  Integer g = boost::math::gcd(numerator(a * m), numerator(b * m));\n  return Rational(g, m);\n}\n\nInteger GCD(const Integer& a, const Integer& b) { return boost::math::gcd(a, b); }\n\nInteger LCM(const Integer& a, const Integer& b) { return boost::math::lcm(a, b); }\n\nInteger Min(const Integer& a, const Integer& b) {\n  if (a < b)\n    return a;\n  else\n    return b;\n}\n\nRational Min(const Rational& a, const Rational& b) {\n  if (a < b)\n    return a;\n  else\n    return b;\n}\n\nInteger Max(const Integer& a, const Integer& b) {\n  if (a < b)\n    return b;\n  else\n    return a;\n}\n\nRational Max(const Rational& a, const Rational& b) {\n  if (a < b)\n    return b;\n  else\n    return a;\n}\n\nInteger RatDiv(const Rational& a, const Rational& b, Rational& r) {  // NOLINT(runtime/references)\n  Integer q = Floor(a / b);\n  r = a - q * b;\n  return q;\n}\n\n}  // namespace math\n}  // namespace tile\n}  // namespace vertexai\n", "meta": {"hexsha": "79d72ac3da1314875853d1a5b492994c09511412", "size": 2387, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tile/math/bignum.cc", "max_stars_repo_name": "nitescuc/plaidml", "max_stars_repo_head_hexsha": "83a81af049154a2701c4fde315b5ee9bc7050a7a", "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": "tile/math/bignum.cc", "max_issues_repo_name": "nitescuc/plaidml", "max_issues_repo_head_hexsha": "83a81af049154a2701c4fde315b5ee9bc7050a7a", "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": "tile/math/bignum.cc", "max_forks_repo_name": "nitescuc/plaidml", "max_forks_repo_head_hexsha": "83a81af049154a2701c4fde315b5ee9bc7050a7a", "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": 20.2288135593, "max_line_length": 108, "alphanum_fraction": 0.5965647256, "num_tokens": 766, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7186568073831702}}
{"text": "#ifndef Interpolators__2D_BilinearInterpolator_hpp\n#define Interpolators__2D_BilinearInterpolator_hpp\n\n/** @file BilinearInterpolator.hpp\n  * @brief \n  * @author C.D. Clark III\n  * @date 12/27/16\n  */\n\n#include \"InterpolatorBase.hpp\"\n#include <boost/range/algorithm/lower_bound.hpp>\n#include <boost/range/adaptor/strided.hpp>\n\n/** @class \n  * @brief Linear interpolation for 2D functions.\n  * @author C.D. Clark III, Aaron Hoffman\n  */\n\nnamespace _2D {\n\ntemplate<class Real>\nclass BilinearInterpolator : public InterpolatorBase<BilinearInterpolator<Real>>\n{\n  public:\n    using BASE = InterpolatorBase<BilinearInterpolator<Real>>;\n    using VectorType = typename BASE::VectorType;\n    using MapType = typename BASE::MapType; \n\n    // types used to view data as 2D coordinates\n    using MatrixType    = typename BASE::MatrixType;\n    using _2DVectorView = typename BASE::_2DVectorView;\n    using _2DMatrixView = typename BASE::_2DMatrixView;\n\n    // types used for 2x2 matrix algebra\n    using Matrix22 = Eigen::Matrix<Real,2,2 >;\n    using Matrix22Array = Eigen::Array< Matrix22, Eigen::Dynamic, Eigen::Dynamic >;\n    using ColVector2 = Eigen::Matrix<Real,2,1 >;\n    using RowVector2 = Eigen::Matrix<Real,1,2 >;\n\n  protected:\n\n    using BASE::xView;\n    using BASE::yView;\n    using BASE::zView;\n    using BASE::X;\n    using BASE::Y;\n    using BASE::Z;\n    \n    Matrix22Array Q; // naming convention used by wikipedia article (see Wikipedia https://en.wikipedia.org/wiki/Bilinear_interpolation)\n\n\n  public:\n\n    template<typename I>\n    BilinearInterpolator( I n, Real *x, Real *y, Real *z ) {this->setData(n,x,y,z);}\n\n    template<typename X, typename Y, typename Z>\n    BilinearInterpolator( X &x, Y &y, Z &z ) {this->setData(x,y,z);}\n\n    BilinearInterpolator():BASE(){}\n    BilinearInterpolator(const BilinearInterpolator& rhs)\n    :BASE(rhs)\n    ,Q(rhs.Q)\n    {}\n\n    // copy-swap idiom\n    friend void swap( BilinearInterpolator& lhs, BilinearInterpolator& rhs)\n    {\n      lhs.Q.swap(rhs.Q);\n      swap( static_cast<BASE&>(lhs), static_cast<BASE&>(rhs) );\n    }\n\n    BilinearInterpolator& operator=(BilinearInterpolator rhs)\n    {\n      swap(*this,rhs);\n      return *this;\n    }\n\n    Real operator()( Real x, Real y ) const;\n\n\n  private:\n\n    void setupInterpolator();\n    friend BASE;\n\n};\n\ntemplate<class Real>\nvoid\nBilinearInterpolator<Real>::setupInterpolator()\n{\n\n  // Interpolation will be done by multiplying the coordinates by coefficients.\n\n  Q = Matrix22Array( X->size()-1, Y->size()-1 );\n\n  // We are going to pre-compute the interpolation coefficients so\n  // that we can interpolate quickly\n  for(int i = 0; i < X->size() - 1; i++)\n  {\n    for( int j = 0; j < Y->size() - 1; j++)\n    {\n      Real tmp = ( ((*X)(i+1) - (*X)(i) )*( (*Y)(j+1) - (*Y)(j) ) );\n      Q(i,j) = Z->block(i,j,2,2)/tmp;\n    }\n  }\n}\n\ntemplate<class Real>\nReal\nBilinearInterpolator<Real>::operator()( Real x, Real y ) const\n{\n  BASE::checkData();\n  \n  // no extrapolation...\n  if( x < (*X)(0)\n   || x > (*X)(X->size()-1)\n   || y < (*Y)(0)\n   || y > (*Y)(Y->size()-1) )\n  {\n    return 0;\n  }\n  // find the x index that is just to the LEFT of x\n  //int i  = Utils::index__last_lt( x, *X, X->size() );\n  // NOTE: X data is strided.\n  auto xrng = std::make_pair( X->data(), X->data()+X->size()*X->innerStride() ) | boost::adaptors::strided(X->innerStride());\n  int i = boost::lower_bound( xrng, x) - boost::begin(xrng) - 1;\n  if(i < 0)\n    i = 0;\n\n  // find the y index that is just BELOW y\n  //int j  = Utils::index__last_lt( y, *Y, Y->size() );\n  // NOTE: Y data is NOT strided\n  auto yrng = std::make_pair( Y->data(), Y->data()+Y->size() );\n  int j = boost::lower_bound( yrng, y) - boost::begin(yrng) - 1;\n  if(j < 0)\n    j = 0;\n  \n\n\n  // now, create the coordinate vectors (see Wikipedia https://en.wikipedia.org/wiki/Bilinear_interpolation)\n  RowVector2 vx;\n  ColVector2 vy;\n  vx << ((*X)(i+1) - x), (x - (*X)(i));\n  vy << ((*Y)(j+1) - y), (y - (*Y)(j));\n\n  // interpolation is just x*Q*y\n\n  return vx*Q(i,j)*vy;\n}\n\n\n\n}\n\n#endif // include protector\n", "meta": {"hexsha": "1f4577dc8fcc47e485a2a37f05d103ea597a3b1f", "size": 4041, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libraries/libInterpolate/src/Interpolators/_2D/BilinearInterpolator.hpp", "max_stars_repo_name": "bindungszustandsamplitude/dysonutils", "max_stars_repo_head_hexsha": "0875307a1a4d4183a650b796caa0111713006210", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-07-17T09:41:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-17T09:41:17.000Z", "max_issues_repo_path": "src/Interpolators/_2D/BilinearInterpolator.hpp", "max_issues_repo_name": "XiaoLeiziGitHub/libInterpolate", "max_issues_repo_head_hexsha": "19a399d1a4fae6c4390adbbd2b1ef7fc8d3278b0", "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/Interpolators/_2D/BilinearInterpolator.hpp", "max_forks_repo_name": "XiaoLeiziGitHub/libInterpolate", "max_forks_repo_head_hexsha": "19a399d1a4fae6c4390adbbd2b1ef7fc8d3278b0", "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.5759493671, "max_line_length": 136, "alphanum_fraction": 0.6307844593, "num_tokens": 1205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898102301019, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.7185459102056581}}
{"text": "#include <Eigen/Core>\n#include <Eigen/QR>\n\n#include \"tools.hpp\"\n\nusing namespace std;\n\n// For converting back and forth between radians and degrees.\nconstexpr double pi() {\n  return M_PI;\n}\n\ndouble deg2rad(double x) {\n  return x * pi() / 180;\n}\n\ndouble rad2deg(double x) {\n  return x * 180 / pi();\n}\n\n// Checks if the SocketIO event has JSON data.\n// If there is data the JSON object in string format will be returned,\n// else the empty string \"\" will be returned.\nstring hasData(string s) {\n  auto found_null = s.find(\"null\");\n  auto b1 = s.find_first_of(\"[\");\n  auto b2 = s.rfind(\"}]\");\n  if (found_null != string::npos) {\n    return \"\";\n  } else if (b1 != string::npos && b2 != string::npos) {\n    return s.substr(b1, b2 - b1 + 2);\n  }\n  return \"\";\n}\n\n// Evaluate a polynomial.\ndouble polyeval(Eigen::VectorXd coeffs, double x) {\n  double result = 0.0;\n  for (int i = 0; i < coeffs.size(); i++) {\n    result += coeffs[i] * pow(x, i);\n  }\n  return result;\n}\n\n// Fit a polynomial.\n// Adapted from\n// https://github.com/JuliaMath/Polynomials.jl/blob/master/src/Polynomials.jl#L676-L716\nEigen::VectorXd polyfit(Eigen::VectorXd xvals, Eigen::VectorXd yvals, int order) {\n  assert(xvals.size() == yvals.size());\n  assert(order >= 1 && order <= xvals.size() - 1);\n  Eigen::MatrixXd A(xvals.size(), order + 1);\n\n  for (int i = 0; i < xvals.size(); i++) {\n    A(i, 0) = 1.0;\n  }\n\n  for (int j = 0; j < xvals.size(); j++) {\n    for (int i = 0; i < order; i++) {\n      A(j, i + 1) = A(j, i) * xvals(j);\n    }\n  }\n\n  auto Q = A.householderQr();\n  auto result = Q.solve(yvals);\n  return result;\n}\n\n\n// 2D affine transformation for a list of points \nvoid Tranform2d(std::vector<double>       &dst_x,\n                std::vector<double>       &dst_y,\n                const std::vector<double> &src_x,\n                const std::vector<double> &src_y,\n                double translation_x, double translation_y, double psi) {\n\n  // make sure destination vectors have same length as source vectors\n  dst_x.resize(src_x.size());\n  dst_y.resize(src_y.size());\n\n  for (int idx = 0; idx < (int) src_x.size(); idx++) {\n    double dx = src_x[idx] - translation_x;\n    double dy = src_y[idx] - translation_y;\n    dst_x[idx] = dx*cos(psi) - dy*sin(psi);\n    dst_y[idx] = dx*sin(psi) + dy*cos(psi);\n  }\n}\n", "meta": {"hexsha": "3904a8f8bf0155ea2368e027e6039adc8bef0816", "size": 2282, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tools.cpp", "max_stars_repo_name": "da-phil/SDC-Model-Predictive-Control", "max_stars_repo_head_hexsha": "563e8f16f61713096170728cda576b86dba4d3cb", "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/tools.cpp", "max_issues_repo_name": "da-phil/SDC-Model-Predictive-Control", "max_issues_repo_head_hexsha": "563e8f16f61713096170728cda576b86dba4d3cb", "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/tools.cpp", "max_forks_repo_name": "da-phil/SDC-Model-Predictive-Control", "max_forks_repo_head_hexsha": "563e8f16f61713096170728cda576b86dba4d3cb", "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.2298850575, "max_line_length": 87, "alphanum_fraction": 0.6069237511, "num_tokens": 675, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182187, "lm_q2_score": 0.8376199714402812, "lm_q1q2_score": 0.7184836895131187}}
{"text": "//  (C) Copyright Jeremy Murphy 2015.\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#include <boost/config.hpp>\r\n#define BOOST_TEST_MAIN\r\n#include <boost/array.hpp>\r\n#include <boost/math/common_factor_rt.hpp>\r\n#include <boost/mpl/list.hpp>\r\n#include <boost/test/test_case_template.hpp>\r\n#include <boost/test/unit_test.hpp>\r\n#include <boost/multiprecision/cpp_int.hpp>\r\n#include <utility>\r\n#include <boost/random.hpp>\r\n\r\n//\r\n// Naive implmentation, any fancy versions we create should always agree with this:\r\n//\r\ntemplate <class T>\r\ntypename boost::enable_if_c<std::numeric_limits<T>::is_signed, T>::type unsigned_abs(T v) { return v < 0 ? -v : v; }\r\ntemplate <class T>\r\ntypename boost::disable_if_c<std::numeric_limits<T>::is_signed, T>::type unsigned_abs(T v) { return v; }\r\n\r\ntemplate <class T>\r\nT euclid_textbook(T a, T b)\r\n{\r\n   using std::swap;\r\n   if(a < b)\r\n      swap(a, b);\r\n   while(b)\r\n   {\r\n      T t = b;\r\n      b = a % b;\r\n      a = t;\r\n   }\r\n   return unsigned_abs(a);\r\n}\r\n\r\ntypedef boost::mpl::list<boost::int32_t\r\n#if !BOOST_WORKAROUND(BOOST_MSVC, <= 1500)\r\n   , boost::int64_t, boost::multiprecision::cpp_int\r\n#endif\r\n> signed_integral_test_types;\r\n\r\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_zero, T, signed_integral_test_types)\r\n{\r\n    T a = boost::math::gcd(static_cast<T>(2), static_cast<T>(0));\r\n    BOOST_CHECK_EQUAL(a, static_cast<T>(2));\r\n    a = boost::math::gcd(static_cast<T>(0), static_cast<T>(2));\r\n    BOOST_CHECK_EQUAL(a, static_cast<T>(2));\r\n}\r\n\r\n\r\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_signed, T, signed_integral_test_types)\r\n{\r\n    T a = boost::math::gcd(static_cast<T>(-40902), static_cast<T>(-24140));\r\n    BOOST_CHECK_EQUAL(a, static_cast<T>(34));\r\n    a = boost::math::gcd(static_cast<T>(40902), static_cast<T>(24140));\r\n    BOOST_CHECK_EQUAL(a, static_cast<T>(34));\r\n}\r\n\r\ntypedef boost::mpl::list<boost::uint32_t\r\n#if !BOOST_WORKAROUND(BOOST_MSVC, <= 1500)\r\n   , boost::uint64_t, boost::multiprecision::uint256_t\r\n#endif\r\n> unsigned_integral_test_types;\r\n\r\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_unsigned, T, unsigned_integral_test_types)\r\n{\r\n    T a = boost::math::gcd(static_cast<T>(40902), static_cast<T>(24140));\r\n    BOOST_CHECK_EQUAL(a, static_cast<T>(34));\r\n    a = boost::math::gcd(static_cast<T>(1836311903), static_cast<T>(2971215073)); // 46th and 47th Fibonacci numbers. 47th is prime.\r\n    BOOST_CHECK_EQUAL(a, static_cast<T>(1));\r\n}\r\n\r\ntypedef boost::mpl::list<boost::int32_t, boost::int64_t> short_signed_integral_test_types;\r\ntypedef boost::mpl::list<boost::uint32_t, boost::uint64_t> short_unsigned_integral_test_types;\r\n\r\nBOOST_AUTO_TEST_CASE_TEMPLATE(signed_random_test, T, short_signed_integral_test_types)\r\n{\r\n   boost::random::mt19937 gen;\r\n   boost::uniform_int<T> dist((std::numeric_limits<T>::min)(), (std::numeric_limits<T>::max)());\r\n   for(unsigned i = 0; i < 100000; ++i)\r\n   {\r\n      T u = dist(gen);\r\n      T v = dist(gen);\r\n      BOOST_CHECK_EQUAL(boost::math::gcd(u, v), euclid_textbook(u, v));\r\n   }\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_random_unsigned, T, short_unsigned_integral_test_types)\r\n{\r\n   boost::random::mt19937 gen;\r\n   boost::uniform_int<T> dist((std::numeric_limits<T>::min)(), (std::numeric_limits<T>::max)());\r\n   for(unsigned i = 0; i < 100000; ++i)\r\n   {\r\n      T u = dist(gen);\r\n      T v = dist(gen);\r\n      BOOST_CHECK_EQUAL(boost::math::gcd(u, v), euclid_textbook(u, v));\r\n   }\r\n}\r\n\r\n\r\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_gcd_range, T, unsigned_integral_test_types)\r\n{\r\n    std::vector<T> a;\r\n    typedef typename std::vector<T>::iterator I;\r\n    std::pair<T, I> d;\r\n    a.push_back(40902);\r\n    d = boost::math::gcd_range(a.begin(), a.end());\r\n    BOOST_CHECK(d == std::make_pair(T(40902), a.end()));\r\n    a.push_back(24140);\r\n    d = boost::math::gcd_range(a.begin(), a.end());\r\n    BOOST_CHECK(d == std::make_pair(T(34), a.end()));\r\n    a.push_back(85);\r\n    d = boost::math::gcd_range(a.begin(), a.end());\r\n    BOOST_CHECK(d == std::make_pair(T(17), a.end()));\r\n    a.push_back(23893);\r\n    d = boost::math::gcd_range(a.begin(), a.end());\r\n    BOOST_CHECK(d == std::make_pair(T(1), a.end()));\r\n    a.push_back(1024);\r\n    d = boost::math::gcd_range(a.begin(), a.end());\r\n    BOOST_CHECK(d == std::make_pair(T(1), a.end() - 1));\r\n}\r\n", "meta": {"hexsha": "e9bf4d5e4116035e0c7ddc4905a937bd691c4fd3", "size": 4374, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/test/test_gcd.cpp", "max_stars_repo_name": "lijgame/boost", "max_stars_repo_head_hexsha": "ec2214a19cdddd1048058321a8105dd0231dac47", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-15T19:57:24.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-15T19:57:24.000Z", "max_issues_repo_path": "thirdparty-cpp/boost_1_62_0/libs/math/test/test_gcd.cpp", "max_issues_repo_name": "nxplatform/nx-mobile", "max_issues_repo_head_hexsha": "0dc174c893f2667377cb2ef7e5ffeb212fa8b3e5", "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": "thirdparty-cpp/boost_1_62_0/libs/math/test/test_gcd.cpp", "max_forks_repo_name": "nxplatform/nx-mobile", "max_forks_repo_head_hexsha": "0dc174c893f2667377cb2ef7e5ffeb212fa8b3e5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-03-08T11:06:22.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-08T11:06:22.000Z", "avg_line_length": 34.7142857143, "max_line_length": 133, "alphanum_fraction": 0.6643804298, "num_tokens": 1200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.7184716893269317}}
{"text": "/*****************************************************************************\n * array.cpp        Blitz++ Array stencilling example\n *****************************************************************************/\n\n#include <blitz/array.h>   \n\nBZ_USING_NAMESPACE(blitz)\n\nint main()\n{\n    int N = 64;\n\n    // Create three-dimensional arrays of float\n    Array<float,3> A(N,N,N), B(N,N,N);\n\n    // Set up initial conditions: +30 C over an interior block,\n    // and +22 C elsewhere\n    A = 22.0;\n\n    Range interior(N/4,3*N/4);\n    A(interior,interior,interior) = 30.0;\n\n    int numIters = 301;\n\n    Range I(1,N-2), J(1,N-2), K(1,N-2);\n\n#ifdef BZ_HAVE_STD\n#ifdef BZ_ARRAY_SPACE_FILLING_TRAVERSAL\n    generateFastTraversalOrder(TinyVector<int,2>(N-2,N-2));\n#endif\n#endif\n\n    for (int i=0; i < numIters; ++i)\n    {\n        double c = 1/6.5;\n \n        B(I,J,K) = c * (.5 * A(I,J,K) + A(I+1,J,K) + A(I-1,J,K)\n            + A(I,J+1,K) + A(I,J-1,K) + A(I,J,K+1) + A(I,J,K-1));\n\n        A(I,J,K) = c * (.5 * B(I,J,K) + B(I+1,J,K) + B(I-1,J,K)\n            + B(I,J+1,K) + B(I,J-1,K) + B(I,J,K+1) + B(I,J,K-1));\n\n        // Output the result along a line through the centre\n        for (int j=0; j < 8; ++j)\n            cout << setprecision(2) << A(N/2,N/2,j*N/8) << \" \";\n\n        cout << endl;\n        cout.flush();\n    }\n\n    return 0;\n}\n\n", "meta": {"hexsha": "72563f685787b12fd32c44273fa6f1ffce217831", "size": 1329, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/examples/array.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/array.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/array.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": 24.6111111111, "max_line_length": 79, "alphanum_fraction": 0.4514672686, "num_tokens": 431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.7184716826129072}}
{"text": "#ifndef CTCD_DISTANCE_HPP\n#define CTCD_DISTANCE_HPP 1\n\n#include <Eigen/Geometry>\n#include <algorithm>\n\n// Source: Etienne Vouga\n// https://github.com/evouga/collisiondetection\n\nnamespace mcl {\nnamespace ctcd\n{\n\n  // Efficiently calculates whether or not a point p is closer to than eta distance to the plane spanned by vertices q0, q1, and q2.\n  // This method does not require any floating point divisions and so is significantly faster than computing the distance itself.\n  static inline bool vertexPlaneDistanceLessThan(const Eigen::Vector3d &p, \n\t\t\t\t\t    const Eigen::Vector3d &q0, const Eigen::Vector3d &q1, const Eigen::Vector3d &q2, double eta)\n  {\n    Eigen::Vector3d c = (q1-q0).cross(q2-q0);\n    return c.dot(p-q0)*c.dot(p-q0) < eta*eta*c.dot(c);\n  }\n\n  // Efficiently calculates whether or not the line spanned by vertices (p0, p1) is closer than eta distance to the line spanned by vertices (q0, q1).\n  // This method does not require any floating point divisions and so is significantly faster than computing the distance itself.\n  static inline bool lineLineDistanceLessThan(const Eigen::Vector3d &p0, const Eigen::Vector3d &p1,\n\t\t\t\t\t  const Eigen::Vector3d &q0, const Eigen::Vector3d &q1, double eta)\n  {\n\tEigen::Vector3d c = (p1-p0).cross(q1-q0);\n\treturn c.dot(q0-p0)*c.dot(q0-p0) < eta*eta*c.dot(c);\n  }\n\n  // Computes the vector between a point p and the closest point to p on the triangle (q0, q1, q2). Also returns the barycentric coordinates of this closest point on the triangle;\n  // q0bary is the barycentric coordinate of q0, etc. (The distance from p to the triangle is the norm of this vector.)\n  static inline Eigen::Vector3d vertexFaceDistance(const Eigen::Vector3d &p, \n\t\t\t\t\t    const Eigen::Vector3d &q0, const Eigen::Vector3d &q1, const Eigen::Vector3d &q2, \n\t\t\t\t\t    double &q0bary, double &q1bary, double &q2bary, bool clamp_barys = true)\n  {\n  Eigen::Vector3d ab = q1-q0;\n  Eigen::Vector3d ac = q2-q0;\n  Eigen::Vector3d ap = p-q0;\n\n  double d1 = ab.dot(ap);\n  double d2 = ac.dot(ap);\n\n  // corner and edge cases\n\n  if(d1 <= 0 && d2 <= 0)\n    {\n      q0bary = 1.0;\n      q1bary = 0.0;\n      q2bary = 0.0;\n      return q0-p;\n    }\n\n  Eigen::Vector3d bp = p-q1;\n  double d3 = ab.dot(bp);\n  double d4 = ac.dot(bp);\n  if(d3 >= 0 && d4 <= d3)\n    {\n      q0bary = 0.0;\n      q1bary = 1.0;\n      q2bary = 0.0;\n      return q1-p;\n    }\n\n  double vc = d1*d4 - d3*d2;\n  if((vc <= 0) && (d1 >= 0) && (d3 <= 0))\n    {\n      double v = d1 / (d1-d3);\n      q0bary = 1.0 - v;\n      q1bary = v;\n      q2bary = 0;\n      return (q0 + v*ab)-p;\n    }\n  \n  Eigen::Vector3d cp = p-q2;\n  double d5 = ab.dot(cp);\n  double d6 = ac.dot(cp);\n  if(d6 >= 0 && d5 <= d6)\n    {\n      q0bary = 0;\n      q1bary = 0;\n      q2bary = 1.0;\n      return q2-p;\n    }\n\n  double vb = d5*d2 - d1*d6;\n  if((vb <= 0) && (d2 >= 0) && (d6 <= 0))\n    {\n      double w = d2/(d2-d6);\n      q0bary = 1-w;\n      q1bary = 0;\n      q2bary = w;\n      return (q0 + w*ac)-p;\n    }\n\n  double va = d3*d6 - d5*d4;\n  if((va <= 0) && (d4-d3 >= 0) && (d5-d6 >= 0))\n    {\n      double w = (d4 - d3) / ((d4 - d3) + (d5 - d6));\n      q0bary = 0;\n      q1bary = 1.0 - w;\n      q2bary = w;\n      \n      return (q1 + w*(q2-q1))-p;\n    }\n\n  // face case\n  double denom = 1.0 / (va + vb + vc);\n  double v = vb * denom;\n  double w = vc * denom;\n  double u = 1.0 - v - w;\n  q0bary = u;\n  q1bary = v;\n  q2bary = w;\n\n  if (clamp_barys)\n  {\n    q0bary = std::clamp(q0bary, 0.0, 1.0);\n    q1bary = std::clamp(q1bary, 0.0, 1.0);\n    q2bary = std::clamp(q2bary, 0.0, 1.0);\n  }\n\n  return (u*q0 + v*q1 + w*q2)-p;\n  }\n\n  // Computes the shotest vector between a segment (p0, p1) and segment (q0, q1). Also returns the barycentric coordinates of the closest points on both segments; p0bary is the barycentric\n  // coordinate of p0, etc. (The distance between the segments is the norm of this vector).\n  static inline Eigen::Vector3d edgeEdgeDistance(const Eigen::Vector3d &p0, const Eigen::Vector3d &p1,\n\t\t\t\t\t  const Eigen::Vector3d &q0, const Eigen::Vector3d &q1,\n\t\t\t\t\t  double &p0bary, double &p1bary,\n\t\t\t\t\t  double &q0bary, double &q1bary,\n\t\t\t\t\t\tbool clamp_barys = true )\n  {  \n  Eigen::Vector3d d1 = p1-p0;\n  Eigen::Vector3d d2 = q1-q0;\n  Eigen::Vector3d r = p0-q0;\n  double a = d1.squaredNorm();\n  double e = d2.squaredNorm();\n  double f = d2.dot(r);\n\n  auto myclamp = [&clamp_barys](double x)\n  {\n    if (!clamp_barys) { return x; }\n    return std::clamp(x, 0.0, 1.0);\n  };\n\n  double s,t;\n\n  double c = d1.dot(r);\n  double b = d1.dot(d2);\n  double denom = a*e-b*b;\n  if(denom != 0.0) \n    {\n      s = myclamp( (b*f-c*e)/denom );\n    }\n  else \n    {\n      //parallel edges and/or degenerate edges; values of s doesn't matter\n      s = 0;\n    }\n  double tnom = b*s + f;\n  if(tnom < 0 || e == 0)\n    {\n      t = 0;\n      if(a == 0)\n\ts = 0;\n      else\n\ts = myclamp(-c/a);  \n    }\n  else if(tnom > e)\n    {\n      t = 1.0;\n      if(a == 0)\n\ts = 0;\n      else\n\ts = myclamp( (b-c)/a );\n    }\n  else\n    t = tnom/e;\t    \n\n  Eigen::Vector3d c1 = p0 + s*d1;\n  Eigen::Vector3d c2 = q0 + t*d2;\n\n  p0bary = 1.0-s;\n  p1bary = s;\n  q0bary = 1.0-t;\n  q1bary = t;\n\n  if (clamp_barys)\n  {\n    p0bary = std::clamp(p0bary, 0.0, 1.0);\n    p1bary = std::clamp(p1bary, 0.0, 1.0);\n    q0bary = std::clamp(q0bary, 0.0, 1.0);\n    q1bary = std::clamp(q1bary, 0.0, 1.0);\n  }\n\n  return c2-c1;\n  }\n\n} // ns ctcd\n} // ns mcl\n\n#endif\n", "meta": {"hexsha": "76533571a16e18317878a6ae6022b6212dd4bcea", "size": 5360, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/MCL/ccd_internal/Distance.hpp", "max_stars_repo_name": "mattoverby/mclccd", "max_stars_repo_head_hexsha": "2137e4edee822c62c4aa5485cb83d7f8191c950c", "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/MCL/ccd_internal/Distance.hpp", "max_issues_repo_name": "mattoverby/mclccd", "max_issues_repo_head_hexsha": "2137e4edee822c62c4aa5485cb83d7f8191c950c", "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": "include/MCL/ccd_internal/Distance.hpp", "max_forks_repo_name": "mattoverby/mclccd", "max_forks_repo_head_hexsha": "2137e4edee822c62c4aa5485cb83d7f8191c950c", "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.1463414634, "max_line_length": 188, "alphanum_fraction": 0.5837686567, "num_tokens": 2012, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418262465169, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.7183353180147212}}
{"text": "#include <iostream>\nusing namespace std;\n\n#include <ctime>\n#include <Eigen/Core>\n#include <Eigen/Dense>\nusing namespace Eigen;\n\n#define MATRIX_SIZE 50\n\nint main(int argc, char **argv)\n{\n    Matrix<float, 2, 3> matrix_23;\n    Vector3d v_3d;\n    Matrix<float, 3, 1> vd_3d;\n    Matrix3d matrix_33 = Matrix3d::Zero();\n    Matrix<double, Dynamic, Dynamic> matrix_dynamic;\n\n    MatrixXd matrix_x;\n\n    matrix_23 << 1, 2, 3, 4, 5, 6;\n    cout<< \"matrix 2x3 from 1 to 6: \\n\" << matrix_23 << endl;\n\n    // visit element via ()\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    v_3d << 3, 2, 1;\n    vd_3d << 4, 5, 6;\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    return 0;\n}", "meta": {"hexsha": "84e3fcb5182ce8bd86629a1c0beda6ba3408a0eb", "size": 883, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "slam/ch3/eigenMatrix.cpp", "max_stars_repo_name": "iwentao/learn_slam", "max_stars_repo_head_hexsha": "971bc19d36eca710cf77879764002cf4e95bdb76", "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": "slam/ch3/eigenMatrix.cpp", "max_issues_repo_name": "iwentao/learn_slam", "max_issues_repo_head_hexsha": "971bc19d36eca710cf77879764002cf4e95bdb76", "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": "slam/ch3/eigenMatrix.cpp", "max_forks_repo_name": "iwentao/learn_slam", "max_forks_repo_head_hexsha": "971bc19d36eca710cf77879764002cf4e95bdb76", "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.8648648649, "max_line_length": 67, "alphanum_fraction": 0.570781427, "num_tokens": 325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632916317103, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.7183202064336747}}
{"text": "#include \"eigen_ext.hpp\"\n#include \"integrate_func.hpp\"\n#include \"parameters.hpp\"\n#include <cassert>\n#include <iostream>\n\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n\nnamespace pear {\ndouble triangle_area(Vec &xp, Vec &yp) {\n  double area;\n  area = xp(1) * yp(2) + xp(0) * yp(1) + xp(2) * yp(0) - xp(1) * yp(0) -\n         xp(0) * yp(2) - xp(2) * yp(1);\n  return area;\n}\n\nMat int_func_block(Vec &xp, Vec &yp) {\n  double area = triangle_area(xp, yp);\n  Mat int_func_block(3, 3);\n\n  double b11 = 6 * xp(0) + 2 * xp(1) + 2 * xp(2);\n  double b12 = 2 * xp(0) + 2 * xp(1) + xp(2);\n  double b13 = 2 * xp(0) + xp(1) + 2 * xp(2);\n\n  double b21 = 2 * xp(0) + 2 * xp(1) + xp(2);\n  double b22 = 2 * xp(0) + 6 * xp(1) + 2 * xp(2);\n  double b23 = xp(0) + 2 * xp(1) + 2 * xp(2);\n\n  double b31 = 2 * xp(0) + xp(1) + 2 * xp(2);\n  double b32 = xp(0) + 2 * xp(1) + 2 * xp(2);\n  double b33 = 2 * xp(0) + 2 * xp(1) + 6 * xp(2);\n\n  int_func_block << b11, b12, b13, b21, b22, b23, b31, b32, b33;\n  int_func_block = int_func_block * area / 60;\n\n  return int_func_block;\n}\n\nMat int_func(Vec &xp, Vec &yp, MatI &t) {\n\n  int np = xp.rows();\n  int nt = t.rows();\n\n  Mat int_F(np, np);\n  Mat int_F_block(3, 3);\n\n  VecI t_loc(3);\n  Vec xp_loc(3);\n  Vec yp_loc(3);\n\n  for (int idxm = 0; idxm < nt; idxm++) {\n    t_loc = t.row(idxm);\n    xp_loc = pear::extract<Vec>(xp, t_loc);\n    yp_loc = pear::extract<Vec>(yp, t_loc);\n\n    int_F_block = int_func_block(xp_loc, yp_loc);\n    for (int idx1 = 0; idx1 < 3; idx1++) {\n      for (int idx2 = 0; idx2 < 3; idx2++) {\n        int_F(t_loc(idx1), t_loc(idx2)) += int_F_block(idx1, idx2);\n      }\n    }\n  }\n  return int_F;\n}\n\n} // namespace pear\n", "meta": {"hexsha": "363197fbb7af62707f036e624aeac630bc2ef9fe", "size": 1658, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/integrate_func.cpp", "max_stars_repo_name": "hdeplaen/the_winning_pear", "max_stars_repo_head_hexsha": "e3eb2f553fdcbdc7d5e5357dbb07fd60e41b8d35", "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/integrate_func.cpp", "max_issues_repo_name": "hdeplaen/the_winning_pear", "max_issues_repo_head_hexsha": "e3eb2f553fdcbdc7d5e5357dbb07fd60e41b8d35", "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/integrate_func.cpp", "max_forks_repo_name": "hdeplaen/the_winning_pear", "max_forks_repo_head_hexsha": "e3eb2f553fdcbdc7d5e5357dbb07fd60e41b8d35", "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.3823529412, "max_line_length": 72, "alphanum_fraction": 0.5542822678, "num_tokens": 671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632896242073, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.7183202048786963}}
{"text": "#include <Eigen/Core>\n#include <cstdlib>\n#include <ctime>\n#include <iostream>\n#include <mathtoolbox/numerical-optimization.hpp>\n#include <optimization-test-functions.hpp>\n\nint main()\n{\n    constexpr otf::FunctionType type       = otf::FunctionType::Rosenbrock;\n    constexpr int               dimensions = 100;\n\n    std::srand(static_cast<unsigned>(std::time(nullptr)));\n\n    mathtoolbox::optimization::Setting setting;\n    setting.algorithm          = mathtoolbox::optimization::Algorithm::Bfgs;\n    setting.x_init             = Eigen::VectorXd::Random(dimensions);\n    setting.f                  = [](const Eigen::VectorXd& x) { return otf::GetValue(x, type); };\n    setting.g                  = [](const Eigen::VectorXd& x) { return otf::GetGrad(x, type); };\n    setting.type               = mathtoolbox::optimization::Type::Min;\n    setting.max_num_iterations = 1000;\n\n    const mathtoolbox::optimization::Result result = mathtoolbox::optimization::RunOptimization(setting);\n\n    const Eigen::VectorXd expected_solution = otf::GetSolution(dimensions, type);\n    const double          expected_value    = otf::GetValue(expected_solution, type);\n    const double          initial_value     = otf::GetValue(setting.x_init, type);\n    const double          found_value       = otf::GetValue(result.x_star, type);\n\n    std::cout << \"#iterations: \" << result.num_iterations << std::endl;\n    std::cout << \"Initial solution: \" << setting.x_init.transpose() << \" (\" << initial_value << \")\" << std::endl;\n    std::cout << \"Found solution: \" << result.x_star.transpose() << \" (\" << found_value << \")\" << std::endl;\n    std::cout << \"Expected solution: \" << expected_solution.transpose() << \" (\" << expected_value << \")\" << std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "814f96a67e19cb347ca4eb61b19a48aad2ebfa59", "size": 1745, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/bfgs/main.cpp", "max_stars_repo_name": "yuki-koyama/mathtoolbox", "max_stars_repo_head_hexsha": "eb7449c3c489f465849a74405e72aff016a296f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 195.0, "max_stars_repo_stars_event_min_datetime": "2018-04-28T16:12:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:52:56.000Z", "max_issues_repo_path": "examples/bfgs/main.cpp", "max_issues_repo_name": "amazing89/mathtoolbox", "max_issues_repo_head_hexsha": "8904bb06ced2ac501594f9574ef1ba3454b8e38e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 52.0, "max_issues_repo_issues_event_min_datetime": "2018-04-15T01:24:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-02T09:14:23.000Z", "max_forks_repo_path": "examples/bfgs/main.cpp", "max_forks_repo_name": "amazing89/mathtoolbox", "max_forks_repo_head_hexsha": "8904bb06ced2ac501594f9574ef1ba3454b8e38e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 21.0, "max_forks_repo_forks_event_min_datetime": "2018-06-05T04:11:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T13:28:12.000Z", "avg_line_length": 47.1621621622, "max_line_length": 118, "alphanum_fraction": 0.6349570201, "num_tokens": 415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632896242073, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.7183201952274344}}
{"text": "/*\n * find_crossing.cpp\n *\n * Finds the energy threshold crossing for a damped oscillator.\n * The algorithm uses a dense out stepper with find_if to first find an\n * interval containing the threshold crossing and the utilizes the dense out\n * functionality with a bisection to further refine the interval until some\n * desired precision is reached.\n *\n * Copyright 2015 Mario Mulansky\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\n\n\n#include <iostream>\n#include <utility>\n#include <algorithm>\n#include <array>\n\n#include <boost/numeric/odeint/stepper/runge_kutta_dopri5.hpp>\n#include <boost/numeric/odeint/stepper/generation.hpp>\n#include <boost/numeric/odeint/iterator/adaptive_iterator.hpp>\n\nnamespace odeint = boost::numeric::odeint;\n\ntypedef std::array<double, 2> state_type;\n\nconst double gam = 1.0;  // damping strength\n\nvoid damped_osc(const state_type &x, state_type &dxdt, const double /*t*/)\n{\n    dxdt[0] = x[1];\n    dxdt[1] = -x[0] - gam * x[1];\n}\n\n\nstruct energy_condition {\n\n    // defines the threshold crossing in terms of a boolean functor\n\n    double m_min_energy;\n\n    energy_condition(const double min_energy)\n        : m_min_energy(min_energy) { }\n\n    double energy(const state_type &x) {\n        return 0.5 * x[1] * x[1] + 0.5 * x[0] * x[0];\n    }\n\n    bool operator()(const state_type &x) {\n        // becomes true if the energy becomes smaller than the threshold\n        return energy(x) <= m_min_energy;\n    }\n};\n\n\ntemplate<class System, class Condition>\nstd::pair<double, state_type>\nfind_condition(state_type &x0, System sys, Condition cond,\n               const double t_start, const double t_end, const double dt,\n               const double precision = 1E-6) {\n\n    // integrates an ODE until some threshold is crossed\n    // returns time and state at the point of the threshold crossing\n    // if no threshold crossing is found, some time > t_end is returned\n\n    auto stepper = odeint::make_dense_output(1.0e-6, 1.0e-6,\n                                             odeint::runge_kutta_dopri5<state_type>());\n\n    auto ode_range = odeint::make_adaptive_range(std::ref(stepper), sys, x0,\n                                                 t_start, t_end, dt);\n\n    // find the step where the condition changes\n    auto found_iter = std::find_if(ode_range.first, ode_range.second, cond);\n\n    if(found_iter == ode_range.second)\n    {\n        // no threshold crossing -> return time after t_end and ic\n        return std::make_pair(t_end + dt, x0);\n    }\n\n    // the dense out stepper now covers the interval where the condition changes\n    // improve the solution by bisection\n    double t0 = stepper.previous_time();\n    double t1 = stepper.current_time();\n    double t_m;\n    state_type x_m;\n    // use odeint's resizing functionality to allocate memory for x_m\n    odeint::adjust_size_by_resizeability(x_m, x0,\n                                         typename odeint::is_resizeable<state_type>::type());\n    while(std::abs(t1 - t0) > precision) {\n        t_m = 0.5 * (t0 + t1);  // get the mid point time\n        stepper.calc_state(t_m, x_m); // obtain the corresponding state\n        if (cond(x_m))\n            t1 = t_m;  // condition changer lies before midpoint\n        else\n            t0 = t_m;  // condition changer lies after midpoint\n    }\n    // we found the interval of size eps, take it's midpoint as final guess\n    t_m = 0.5 * (t0 + t1);\n    stepper.calc_state(t_m, x_m);\n    return std::make_pair(t_m, x_m);\n}\n\n\nint main(int argc, char **argv)\n{\n    state_type x0 = {{10.0, 0.0}};\n    const double t_start = 0.0;\n    const double t_end = 10.0;\n    const double dt = 0.1;\n    const double threshold = 0.1;\n\n    energy_condition cond(threshold);\n    state_type x_cond;\n    double t_cond;\n    std::tie(t_cond, x_cond) = find_condition(x0, damped_osc, cond,\n                                              t_start, t_end, dt, 1E-6);\n    if(t_cond > t_end)\n    {\n        // time after t_end -> no threshold crossing within [t_start, t_end]\n        std::cout << \"No threshold crossing found.\" << std::endl;\n    } else\n    {\n        std::cout.precision(16);\n        std::cout << \"Time of energy threshold crossing: \" << t_cond << std::endl;\n        std::cout << \"State: [\" << x_cond[0] << \" , \" << x_cond[1] << \"]\" << std::endl;\n        std::cout << \"Energy: \" << cond.energy(x_cond) << std::endl;\n    }\n}\n", "meta": {"hexsha": "a17ef4f970576d0883518767b2c2b6c06615754a", "size": 4460, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/odeint/examples/find_crossing.cpp", "max_stars_repo_name": "cpp-pm/boost", "max_stars_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_stars_repo_licenses": ["BSL-1.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": "libs/numeric/odeint/examples/find_crossing.cpp", "max_issues_repo_name": "cpp-pm/boost", "max_issues_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_issues_repo_licenses": ["BSL-1.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": "libs/numeric/odeint/examples/find_crossing.cpp", "max_forks_repo_name": "cpp-pm/boost", "max_forks_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 33.037037037, "max_line_length": 93, "alphanum_fraction": 0.6349775785, "num_tokens": 1159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637397236824, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.7182349037446535}}
{"text": "///////////////////////////////////////////////////////////////////\n//  Copyright Eduardo Quintana 2021\n//  Copyright Janek Kozicki 2021\n//  Copyright Christopher Kormanyos 2021\n//  Distributed under the Boost Software License,\n//  Version 1.0. (See accompanying file LICENSE_1_0.txt\n//  or copy at http://www.boost.org/LICENSE_1_0.txt)\n/*\n    boost::math::fft example 06\n    \n    Fast Polynomial Multiplication with quadmath\n*/\n\n#include <boost/math/fft/bsl_backend.hpp>\n#include <boost/multiprecision/complex128.hpp>\n#include <iostream>\n#include <vector>\n#include <exception>\n\ntemplate<class Real, class Complex>\nstd::vector<Real> multiply_complex(\n    const std::vector<Real>& A, \n    const std::vector<Real>& B)\n{\n  const std::size_t N = A.size();\n  std::vector< Complex > TA(N),TB(N);\n  boost::math::fft::bsl_rdft<Real> P(N); \n  P.real_to_complex(A.begin(),A.end(),TA.begin());\n  P.real_to_complex(B.begin(),B.end(),TB.begin());\n  \n  std::vector<Real> C(N);\n  \n  for(unsigned int i=0;i<N;++i)\n  {\n    TA[i]*=TB[i];\n  }\n  \n  P.complex_to_real(TA.begin(),TA.end(),C.begin());\n  std::transform(C.begin(), C.end(), C.begin(),\n                 [N](Real x) { return x / N; });\n  \n  return C;\n}\n\ntemplate<class Real>\nReal difference(const std::vector<Real>& A, const std::vector<Real>& B)\n{\n  using std::abs;\n  Real diff{};\n  if(A.size()!=B.size()) return -1;\n  for(unsigned int i=0;i<A.size();++i)\n  {\n    diff += abs(A[i]-B[i]);\n  }\n  return diff;\n}\n\ntemplate<typename Real, typename Complex>\nvoid multiply() {\n  using std::abs;\n  std::vector<Real> A{1.,4.,-5.,1.,0.,0.,0.,0.};\n  std::vector<Real> B{-1.,1.,2.,3.,0.,0.,0.,0.};\n  std::vector<Real> C{-1,-3,11,5,3,-13,3,0};\n  \n  std::vector<Real> result;\n  Real diff;\n  \n  result = multiply_complex<Real,Complex>(A,B);\n  diff = difference(result,C);\n  if(abs(diff)>1e-3) \n    throw std::runtime_error(\"wrong result\");\n}\n\nint main()\n{\n  multiply<\n    ::boost::multiprecision::float128,\n    ::boost::multiprecision::complex128>();\n  return 0;\n}\n\n\n", "meta": {"hexsha": "408ca9595eb6aa367a3f27c3538da9652a89ce2a", "size": 1993, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/fft_ex06_float128.cpp", "max_stars_repo_name": "BoostGSoC21/math", "max_stars_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_stars_repo_licenses": ["BSL-1.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": "example/fft_ex06_float128.cpp", "max_issues_repo_name": "BoostGSoC21/math", "max_issues_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 30.0, "max_issues_repo_issues_event_min_datetime": "2021-06-22T12:59:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-02T09:27:49.000Z", "max_forks_repo_path": "example/fft_ex06_float128.cpp", "max_forks_repo_name": "BoostGSoC21/math", "max_forks_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-07T21:15:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-07T21:15:02.000Z", "avg_line_length": 24.0120481928, "max_line_length": 71, "alphanum_fraction": 0.6101354742, "num_tokens": 584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.920789673717312, "lm_q2_score": 0.7799928900257126, "lm_q1q2_score": 0.7182093987085991}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include <vector>\n#include <cmath>\n\nEigen::MatrixXd sigmoid(Eigen::MatrixXd mat){\n    int r = mat.rows() ; int c = mat.cols();\n    for (int i=0; i<r; i++){\n        for (int j=0; j<c; j++){\n            mat(i,j) = 1/(1+exp(-mat(i,j)));\n        }\n    }\n    return mat;\n};\n\n\nclass NeuralNetwork{\n    public:\n    std::vector <Eigen::MatrixXd> biases;\n    std::vector <Eigen::MatrixXd> weights;\n    int num_layers;\n    std::vector <int> sizes;\n\n    NeuralNetwork(std::vector <int> Sizes){\n        num_layers = Sizes.size();\n        sizes = Sizes;\n\n        // Initializing random biases\n        // std::cout<< \"Initializing bases\"<< std::endl;\n        for (int i=1; i<sizes.size(); i++){\n            int y = sizes[i];\n            auto m = Eigen::MatrixXd::Random(y,1);\n            biases.push_back(m);\n            // std::cout<< \"Shape : \"<<y << \" \"<< 1 << std::endl;\n        }\n\n        // Initializing random weights\n        // std::cout<< \"Initializing weights\"<< std::endl;\n        for (int i=0; i<sizes.size()-1; i++){\n            int x = sizes[i] ; int y = sizes[i+1];\n            auto m = Eigen::MatrixXd::Random(y,x);\n            weights.push_back(m);\n            // std::cout<< \"Shape : \"<<y<< \" \"<<x<< std::endl;\n        }\n    };\n\n    Eigen::MatrixXd predict(Eigen::MatrixXd input){\n        for (int i=0; i<biases.size(); i++){\n            input = sigmoid((weights[i]*input) + biases[i]);\n        }\n\n        return input;\n    };\n\n};\n", "meta": {"hexsha": "3fbf471a6afc8dfaf400b16fdb97346424c8e5d7", "size": 1478, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "NeuralNetworks/nn.cpp", "max_stars_repo_name": "adityapande-1995/CPP_Projects", "max_stars_repo_head_hexsha": "4546c504fbbdb2ea25c6a8d7073448b565538701", "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": "NeuralNetworks/nn.cpp", "max_issues_repo_name": "adityapande-1995/CPP_Projects", "max_issues_repo_head_hexsha": "4546c504fbbdb2ea25c6a8d7073448b565538701", "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": "NeuralNetworks/nn.cpp", "max_forks_repo_name": "adityapande-1995/CPP_Projects", "max_forks_repo_head_hexsha": "4546c504fbbdb2ea25c6a8d7073448b565538701", "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.3928571429, "max_line_length": 65, "alphanum_fraction": 0.50202977, "num_tokens": 389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.944176852582231, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.7181887340365021}}
{"text": "#pragma once\n\n#include <vector>\n#include <Eigen/Dense>\n#include <string>\n\nnamespace cvgl {\n\ninline double clip(double v, double min, double max)\n{\n    return (v < min ? min : (v > max ? max : v));\n}\n\ninline Eigen::ArrayXd clip(const Eigen::ArrayXd& v, double min, double max)\n{\n    return v.unaryExpr([&](double x){return clip(x, min, max); });\n}\n\ninline double wrap(double x, double x_min, double x_max)\n{\n    return fmod( fmod((x - x_min), (x_max - x_min)) + (x_max - x_min), (x_max - x_min)) + x_min;\n}\n\ninline double scale(double v, double in_min, double in_max, double out_min, double out_max)\n{\n    const double in_range = in_max - in_min;\n    return (( (v - in_min) / (in_range == 0 ? 1 : in_range) ) * (out_max - out_min)) + out_min;\n}\n\ninline Eigen::ArrayXd scale(const Eigen::ArrayXd& v, double in_min, double in_max, double out_min, double out_max)\n{\n    return v.unaryExpr([&](double x){ return scale(x, in_min, in_max, out_min, out_max); });\n}\n\ntemplate <typename T>\ninline std::vector<T> scale(const std::vector<T>& v, const T in_min, const T in_max, const T out_min, const T out_max)\n{\n    T in_range = in_max - in_min;\n    T out_range = out_max - out_min;\n    std::vector<T> ret( v.size() );\n    for( auto& q : v )\n    {\n        ret.emplace_back( ( ((q - in_min) / in_range) * out_range) + out_min );\n    }\n    return ret;\n}\n\ninline double scale_clip(double v, double in_min, double in_max, double out_min, double out_max)\n{\n    double clip_min = out_min > out_max ? out_max : out_min;\n    double clip_max = out_max < out_min ? out_min : out_max;\n\n    return clip( scale( v, in_min, in_max, out_min, out_max), clip_min, clip_max);\n}\n\ninline Eigen::ArrayXd scale_clip(const Eigen::ArrayXd& v, double in_min, double in_max, double out_min, double out_max)\n{\n    double clip_min = out_min > out_max ? out_max : out_min;\n    double clip_max = out_max < out_min ? out_min : out_max;\n\n    return clip( scale( v, in_min, in_max, out_min, out_max), clip_min, clip_max);\n}\n\n\ntemplate <typename T>\ninline std::vector<T> scale_clip(const std::vector<T>& v, const T in_min, const T in_max, const T out_min, const T out_max)\n{\n    double clip_min = out_min > out_max ? out_max : out_min;\n    double clip_max = out_max < out_min ? out_min : out_max;\n\n    T in_range = in_max - in_min;\n    T out_range = out_max - out_min;\n    std::vector<T> ret( v.size() );\n    for( auto& q : v )\n    {\n        T val = ( ((q - in_min) / in_range) * out_range) + out_min;\n        val = (val < clip_min ? clip_min : (val > clip_max ? clip_max : val));\n        ret.emplace_back(val);\n    }\n    return ret;\n}\n\n\n\ninline double sum( std::vector<double> &vec )\n{\n    double _sum = 0;\n    for (auto& n : vec){\n        _sum += n;\n    }\n    return _sum;\n}\n\n\ninline int32_t round(double x)\n{\n    return int32_t(x + 0.5);\n}\n\ninline std::vector<double> dur2x( std::vector<double> & vec)\n{\n    std::vector<double> seq_x{0};\n    for( size_t i = 0; i < vec.size()-1; ++i)\n    {\n        seq_x.emplace_back( seq_x.back() + vec[i] );\n    }\n    return seq_x;\n}\n\ninline Eigen::ArrayXd dur2x( Eigen::ArrayXd & vec)\n{\n    Eigen::ArrayXd seq_x( vec.size()+1 );\n    seq_x(0) = 0;\n    \n    for( size_t i = 1; i < vec.size()+1; i++)\n    {\n        seq_x(i) = seq_x(i-1) + vec[i-1];\n    }\n    \n    return seq_x;\n}\n\ninline Eigen::ArrayXd mtof( const Eigen::ArrayXd & v, double a4 = 440.)\n{\n    return a4 * pow(2., (v - 69.) / 12.) ;\n}\n\ninline double mtof( double v, double a4 = 440.)\n{\n    return a4 * pow(2., (v - 69.) / 12.) ;\n}\n\ninline double ftom( double v, double a4 = 440. )\n{\n    return 69.0 + (12.0 * log2( v / a4 ));\n}\n\n/*\ninline Eigen::ArrayXd ftom( const Eigen::ArrayXd & v, double a4 = 440. )\n{\n    return 69 + (12 * log2( v / a4 ));\n}*/\n\n\ninline double erb( double center_hz, double ratio)\n{\n    const double half_bandwidth = (24.7 * ((0.00437 * center_hz) + 1)) * 0.5;\n    return center_hz + (half_bandwidth * ratio);\n}\n\ninline double tanhScale( double x, double in_min, double in_max, double curveScalar = 1 )\n{\n    const double curveTanh = tanh(curveScalar);\n    const double scaled_x = scale( x, in_min, in_max, -1., 1.);\n    return scale( tanh( scaled_x * curveTanh ), -curveTanh, curveTanh, 0., 1. );\n}\n\ninline double scaleInterval( long step, std::vector<double> scale )\n{\n    if( step < 0 ) {\n        return scale[ long( step % scale.size() ) ] + ( long( ((step+1) / (long)scale.size() ) - 1 ) * 12 );\n    }\n    else\n        return scale[ long( step % scale.size() ) ] + long( (step / scale.size() ) * 12 );\n}\n\n\ninline double dbtoa(double db){ return pow(10., (db / 20.)); }\n\n\ndouble ntom( const std::string & note );\n\ndouble lineLookup( double t, std::vector<double> x, std::vector<double> y );\n\nEigen::ArrayXd lineLookup( const Eigen::ArrayXd& t, const std::vector<double>& x, const std::vector<double>& y );\n\ntemplate <typename T>\nstd::vector<T> aseq(T from, T to, T step = 1)\n{\n    std::vector<T> ret;\n    T incr = from;\n    while( incr <= to )\n    {\n        ret.emplace_back(incr);\n        incr += step;\n    }\n    \n    return ret;\n}\n\ninline double easeInOutQuad(double x)\n{\n    return x < 0.5 ? 2 * x * x : 1 - pow(-2 * x + 2, 2) / 2;\n}\n\ninline double easeInOutSine(double x)\n{\n    return -(cos(M_PI * x) - 1) * 0.5;\n}\n\ninline double easeInSine(double x)\n{\n     return 1 - cos((x * M_PI) * 0.5);\n}\n\ninline double easeOutSine(double x)\n{\n     return sin((x * M_PI) * 0.5);\n}\n\ninline double easeInExpo(double x)\n{\n    return x == 0 ? 0 : pow(2, 10 * x - 10);\n}\n\ninline double easeOutExpo(double x)\n{\n    return x == 1 ? 1 : 1 - pow(2, -10 * x);\n\n}\n\n}\n", "meta": {"hexsha": "acdb07053d2610315d601c1c3f57a99261906b2d", "size": 5531, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/cvglHelperFunctions.hpp", "max_stars_repo_name": "HfMT-ZM4/cvgl-osc", "max_stars_repo_head_hexsha": "97b4259aac6757a68959cfa625c59c97bd7a62d1", "max_stars_repo_licenses": ["CC0-1.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": "include/cvglHelperFunctions.hpp", "max_issues_repo_name": "HfMT-ZM4/cvgl-osc", "max_issues_repo_head_hexsha": "97b4259aac6757a68959cfa625c59c97bd7a62d1", "max_issues_repo_licenses": ["CC0-1.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": "include/cvglHelperFunctions.hpp", "max_forks_repo_name": "HfMT-ZM4/cvgl-osc", "max_forks_repo_head_hexsha": "97b4259aac6757a68959cfa625c59c97bd7a62d1", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.802690583, "max_line_length": 123, "alphanum_fraction": 0.611462665, "num_tokens": 1744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587934924569, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.7181768479399686}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <cstddef>\n\nnamespace icarus\n{\n    template<typename T, size_t N>\n    struct VarianceEstimator\n    {\n        VarianceEstimator(size_t sampleSize) :\n            mSampleSize(sampleSize),\n            mSampleNumber(0)\n        {\n            mMean.setZero();\n            mMoment.setZero();\n        }\n\n        void addSample(Eigen::Matrix<T, N, 1> const & sample)\n        {\n            ++mSampleNumber;\n            auto oldMean = mMean;\n            mMean += (sample - mMean) / T(mSampleNumber);\n            mMoment += (sample - oldMean).cwiseProduct(sample - mMean);\n        }\n\n        Eigen::Matrix<T, N, 1> mean() const\n        {\n            return mMean;\n        }\n\n        Eigen::Matrix<T, N, 1> variance() const\n        {\n            return mMoment / mSampleSize;\n        }\n    private:\n        size_t mSampleSize;\n        size_t mSampleNumber;\n        Eigen::Matrix<T, N, 1> mMean;\n        Eigen::Matrix<T, N, 1> mMoment;\n    };\n}\n", "meta": {"hexsha": "8230a1bc15f5de08c142bc5529bb9f8dbf9d6e90", "size": 975, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "icarus/include/icarus/sensor/VarianceEstimator.hpp", "max_stars_repo_name": "Icarus-Quadro/Icarus", "max_stars_repo_head_hexsha": "10c4f1e804432d8cd11541f3e7342a12acec79f4", "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": "icarus/include/icarus/sensor/VarianceEstimator.hpp", "max_issues_repo_name": "Icarus-Quadro/Icarus", "max_issues_repo_head_hexsha": "10c4f1e804432d8cd11541f3e7342a12acec79f4", "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": "icarus/include/icarus/sensor/VarianceEstimator.hpp", "max_forks_repo_name": "Icarus-Quadro/Icarus", "max_forks_repo_head_hexsha": "10c4f1e804432d8cd11541f3e7342a12acec79f4", "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.6744186047, "max_line_length": 71, "alphanum_fraction": 0.5179487179, "num_tokens": 249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587817066392, "lm_q2_score": 0.8080672204860317, "lm_q1q2_score": 0.7181768384162358}}
{"text": "#include <iostream>\r\n#include <string>\r\n#include <vector>\r\n#include <iomanip>\r\n#include <boost/algorithm/string/erase.hpp>\r\n#include <boost/algorithm/string/case_conv.hpp>\r\n\r\ninline void ignoreExtraInputs() {\r\n\tstd::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\\n');\r\n}\r\n\r\ninline std::string decimalToBinary(int decInput) {\r\n\t\r\n\tint exponent = 0;\r\n\tint previousExponent = 0;\r\n\tstd::string binaryNum = \"\";\r\n\t\r\n\twhile (pow(2, exponent) <= decInput) {\r\n\t\tpreviousExponent = exponent;\r\n\t\texponent++;\r\n\t}\r\n\twhile (previousExponent >= 0) {\r\n\t\tif (decInput - pow(2, previousExponent) >= 0) {\r\n\t\t\tdecInput -= (int) pow(2, previousExponent);\r\n\t\t\tbinaryNum.push_back('1');\r\n\t\t}\r\n\t\telse {\r\n\t\t\tbinaryNum.push_back('0');\r\n\t\t}\r\n\t\tpreviousExponent--;\r\n\t}\r\n\treturn binaryNum;\r\n}\r\n\r\n/*inline std::vector<std::string> decimalToBinaryReturningArray(int decInput) {\r\n\r\n\tint exponent = 0;\r\n\tint previousExponent = 0;\r\n\tstd::vector<std::string> binaryNum = {};\r\n\r\n\twhile (pow(2, exponent) <= decInput) {\r\n\t\tpreviousExponent = exponent;\r\n\t\texponent++;\r\n\t}\r\n\twhile (previousExponent >= 0) {\r\n\t\tif (decInput - pow(2, previousExponent) >= 0) {\r\n\t\t\tdecInput -= (int)pow(2, previousExponent);\r\n\t\t\tbinaryNum.push_back(\"1\");\r\n\t\t}\r\n\t\telse {\r\n\t\t\tbinaryNum.push_back(\"0\");\r\n\t\t}\r\n\t\tpreviousExponent--;\r\n\t}\r\n\treturn binaryNum;\r\n}*/\r\n\r\ninline std::string nibbleGuaranteeer(std::string sub_h_binInput)\r\n{\r\n\tint binaryLength = sub_h_binInput.length();\r\n\tstd::string newBinarySequ = \"\";\r\n\r\n\tif (binaryLength % 4 != 0) {\r\n\t\tfor (unsigned int i = 0; i < (unsigned)(4 - (binaryLength % 4)); i++) {\r\n\t\t\tnewBinarySequ.push_back('0');\r\n\t\t}\r\n\t\tbinaryLength += (4 - (binaryLength % 4));\r\n\t\tnewBinarySequ += sub_h_binInput;\r\n\t}\r\n\telse {\r\n\t\tnewBinarySequ = sub_h_binInput;\r\n\t}\r\n\treturn newBinarySequ;\r\n}\r\n\r\n/*inline std::vector<std::string> nibbleGuaranteeer(std::vector<std::string> sub_h_binInput, int requiredSize)\r\n{\r\n\tint binaryLength = requiredSize;\r\n\tstd::vector<std::string> newBinarySequ = {};\r\n\r\n\tif (binaryLength % 4 != 0) {\r\n\t\tfor (unsigned int i = 0; i < (unsigned)(4 - (binaryLength % 4)); i++) {\r\n\t\t\tnewBinarySequ.push_back(\"0\");\r\n\t\t}\r\n\t\tbinaryLength += (4 - (binaryLength % 4));\r\n\t\t//newBinarySequ += sub_h_binInput;\r\n\t\tfor (unsigned int i = 0; i < sub_h_binInput.size(); i++) {\r\n\t\t\tnewBinarySequ.push_back(sub_h_binInput[i]);\r\n\t\t}\r\n\t}\r\n\telse {\r\n\t\tnewBinarySequ = sub_h_binInput;\r\n\t}\r\n\treturn newBinarySequ;\r\n}*/\r\n\r\ninline std::string nibbleSpaceAparter(std::string sub_binInput) {\r\n\r\n\tint indexModifier = 4;\r\n\tint whiteSpaceAddedModifier = 0;\r\n\r\n\tfor (unsigned int i = 0; i < (unsigned)((sub_binInput.length() / 4) - 1); i++) {\r\n\t\tsub_binInput.insert(indexModifier + whiteSpaceAddedModifier, \" \");\r\n\t\tindexModifier += 4;\r\n\t\twhiteSpaceAddedModifier++;\r\n\t}\r\n\treturn sub_binInput;\r\n}\r\n\r\ninline std::string binaryToHexa(std::string h_binInput) {\r\n\r\n\tint binaryLength = 0;\r\n\tint nibbleIndexBeginModifier = 0;\r\n\tint nibbleIndexEndModifier = 4;\r\n\tint nibbleCalculatedDecimalValue = 0;\r\n\tint nibbleHighestExponentValue = 8;\r\n\tstd::string hexaValue = \"\";\r\n\tstd::vector<std::string> nibbles;\r\n\r\n\th_binInput = nibbleGuaranteeer(h_binInput);\r\n\tbinaryLength = h_binInput.length() / 4;\r\n\t\r\n\tfor (unsigned int i = 0; i < (unsigned) binaryLength; i++) {\r\n\t\tnibbles.push_back(h_binInput.substr(nibbleIndexBeginModifier, nibbleIndexEndModifier));\r\n\t\tnibbleIndexBeginModifier += 4;\r\n\t\tnibbleIndexEndModifier += 4;\r\n\t}\r\n\r\n\tfor (std::string &nibbleValue : nibbles) {\r\n\t\tnibbleCalculatedDecimalValue = 0;\r\n\t\tnibbleHighestExponentValue = 8;\r\n\t\tfor (unsigned int i = 0; i < 4; i++) {\r\n\t\t\tif (nibbleValue[i] == '1') {\r\n\t\t\t\tnibbleCalculatedDecimalValue += nibbleHighestExponentValue;\r\n\t\t\t}\r\n\t\t\tnibbleHighestExponentValue = (int) ((nibbleHighestExponentValue / 2) + 0.5);\r\n\t\t}\r\n\t\tif (nibbleCalculatedDecimalValue >= 0 && nibbleCalculatedDecimalValue <= 9) {\r\n\t\t\thexaValue.push_back(nibbleCalculatedDecimalValue + 48);\r\n\t\t}\r\n\t\telse if (nibbleCalculatedDecimalValue >= 10 && nibbleCalculatedDecimalValue <= 15) {\r\n\t\t\thexaValue.push_back(nibbleCalculatedDecimalValue + 55);\r\n\t\t}\r\n\t}\r\n\treturn hexaValue;\r\n}\r\n\r\ninline int binaryToDecimal(std::string d_binInput) {\r\n\r\n\tint nibbleHighestExponentValue = (int) pow(2, d_binInput.length() - 1);\r\n\tint nibbleCalculatedDecimalValue = 0;\r\n\t\r\n\tfor (char &indexValue : d_binInput) {\r\n\t\tif (indexValue == '1') {\r\n\t\t\tnibbleCalculatedDecimalValue += nibbleHighestExponentValue;\r\n\t\t}\r\n\t\tnibbleHighestExponentValue = (int) ((nibbleHighestExponentValue / 2) + 0.5);\r\n\t}\r\n\treturn nibbleCalculatedDecimalValue;\r\n}\r\n\r\ninline int hexaToDecimal(std::string hexaInput) {\r\n\r\n\tint hexaHighestExponentValue = (int) pow(16, hexaInput.length() - 1);\r\n\tint hexaToDecimalValue = 0;\r\n\r\n\tfor (char &indexValue : hexaInput) {\r\n\t\tif (indexValue >= '0' && indexValue <= '9') {\r\n\t\t\thexaToDecimalValue += (indexValue - 48) * hexaHighestExponentValue;\r\n\t\t}\r\n\t\telse if (indexValue >= 'A' && indexValue <= 'F') {\r\n\t\t\thexaToDecimalValue += (indexValue - 55) * hexaHighestExponentValue;\r\n\t\t}\r\n\t\telse {\r\n\t\t\tstd::cout << \"\\nSomething went wrong in the 'hexaToDecimal' function\\n\";\r\n\t\t}\r\n\t\thexaHighestExponentValue = hexaHighestExponentValue / 16;\r\n\t}\r\n\treturn hexaToDecimalValue;\r\n}\r\n\r\n/*inline std::string addition(std::string binaryInputOne, std::string binaryInputTwo) {\r\n\r\n\tstd::vector<std::string> indexedBinaryInput_One = {}, indexedBinaryInput_Two = {};\r\n\tstd::string resultantBinaryValue = \"\", remainder = \"0\";\r\n\tint binaryLength = -1;\r\n\r\n\tindexedBinaryInput_One = decimalToBinaryReturningArray(binaryToDecimal(binaryInputOne));\r\n\tindexedBinaryInput_Two = decimalToBinaryReturningArray(binaryToDecimal(binaryInputTwo));\r\n\r\n\tif (indexedBinaryInput_One.size() > indexedBinaryInput_Two.size()) {\r\n\t\tbinaryLength = indexedBinaryInput_One.size();\r\n\t}\r\n\telse {\r\n\t\tbinaryLength = indexedBinaryInput_Two.size();\r\n\t}\r\n\tindexedBinaryInput_One = nibbleGuaranteeer(indexedBinaryInput_One, binaryLength);\r\n\tindexedBinaryInput_Two = nibbleGuaranteeer(indexedBinaryInput_Two, binaryLength);\r\n\r\n\tfor (int i = (binaryLength-1); i >= 0; i--) {\r\n\t\tif (indexedBinaryInput_One[i] == \"0\" && indexedBinaryInput_Two[i] == \"0\" && remainder == \"0\") {\r\n\t\t\tresultantBinaryValue.push_back('0');\r\n\t\t\tremainder = \"0\";\r\n\t\t}\r\n\t\telse if ((indexedBinaryInput_One[i] == \"1\" && indexedBinaryInput_Two[i] == \"0\" && remainder == \"0\") ||\r\n\t\t\t\t (indexedBinaryInput_One[i] == \"0\" && indexedBinaryInput_Two[i] == \"1\" && remainder == \"0\") ||\r\n\t\t\t\t (indexedBinaryInput_One[i] == \"0\" && indexedBinaryInput_Two[i] == \"0\" && remainder == \"1\")) {\r\n\t\t\tresultantBinaryValue.push_back('1');\r\n\t\t\tremainder = \"0\";\r\n\t\t}\r\n\t\telse if ((indexedBinaryInput_One[i] == \"1\" && indexedBinaryInput_Two[i] == \"1\" && remainder == \"0\") ||\r\n\t\t\t\t (indexedBinaryInput_One[i] == \"1\" && indexedBinaryInput_Two[i] == \"0\" && remainder == \"1\") ||\r\n\t\t\t\t (indexedBinaryInput_One[i] == \"0\" && indexedBinaryInput_Two[i] == \"1\" && remainder == \"1\")) {\r\n\t\t\tresultantBinaryValue.push_back('0');\r\n\t\t\tremainder = \"1\";\r\n\t\t}\r\n\t\telse if (indexedBinaryInput_One[i] == \"1\" && indexedBinaryInput_Two[i] == \"1\" && remainder == \"1\") {\r\n\t\t\tresultantBinaryValue.push_back('1');\r\n\t\t\tremainder = \"1\";\r\n\t\t}\r\n\t\telse {\r\n\t\t\tstd::cout << \"\\nThere happens to be something else occurring in the forloop in 'binaryAddition'\\n\";\r\n\t\t}\r\n\t}\r\n\r\n\treturn resultantBinaryValue;\r\n}*/", "meta": {"hexsha": "8095f14bf14f672dd57d9d46a20e99bcab4bfa43", "size": 7232, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "BC_Functions.cpp", "max_stars_repo_name": "Qesto/Byte-Conversion-Program", "max_stars_repo_head_hexsha": "87dc38935306e2ddcbe31f25edd52f4db09e8c81", "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": "BC_Functions.cpp", "max_issues_repo_name": "Qesto/Byte-Conversion-Program", "max_issues_repo_head_hexsha": "87dc38935306e2ddcbe31f25edd52f4db09e8c81", "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": "BC_Functions.cpp", "max_forks_repo_name": "Qesto/Byte-Conversion-Program", "max_forks_repo_head_hexsha": "87dc38935306e2ddcbe31f25edd52f4db09e8c81", "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.859030837, "max_line_length": 111, "alphanum_fraction": 0.6711836283, "num_tokens": 2092, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111796979521253, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.7179469133904767}}
{"text": "/*\n-------------------------------------------------------------------------\n   This file is part of BayesOpt, an efficient C++ library for \n   Bayesian optimization.\n\n   Copyright (C) 2011-2015 Ruben Martinez-Cantin <rmcantin@unizar.es>\n \n   BayesOpt is free software: you can redistribute it and/or modify it \n   under the terms of the GNU Affero General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   BayesOpt is distributed in the hope that it will be useful, but \n   WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU Affero General Public License for more details.\n\n   You should have received a copy of the GNU Affero General Public License\n   along with BayesOpt.  If not, see <http://www.gnu.org/licenses/>.\n------------------------------------------------------------------------\n*/\n\n#ifndef __TEST_FUNCTIONS_HPP__\n#define __TEST_FUNCTIONS_HPP__\n\n#define _USE_MATH_DEFINES\n#include <cmath>\n#include <algorithm>\n#include <boost/math/constants/constants.hpp>\n#include <boost/numeric/ublas/assignment.hpp>\n#include \"bayesopt/bayesopt.hpp\"\n#include \"specialtypes.hpp\"\n\n\n\nclass ExampleOneD: public bayesopt::ContinuousModel\n{\npublic:\n  ExampleOneD(bayesopt::Parameters par):\n    ContinuousModel(1,par) {}\n\n  double evaluateSample(const vectord& xin)\n  {\n    if (xin.size() != 1)\n      {\n\tstd::cout << \"WARNING: This only works for 1D inputs.\" << std::endl\n\t\t  << \"WARNING: Using only first component.\" << std::endl;\n      }\n\n    double x = xin(0);\n    return (x-0.3)*(x-0.3) + sin(20*x)*0.2;\n  };\n\n  bool checkReachability(const vectord &query)\n  {return true;};\n\n  void printOptimal()\n  {\n    std::cout << \"Optimal:\" << 0.23719 << std::endl;\n  }\n\n};\n\n\nclass BraninNormalized: public bayesopt::ContinuousModel\n{\npublic:\n  BraninNormalized(bayesopt::Parameters par):\n    ContinuousModel(2,par) {}\n\n  double evaluateSample( const vectord& xin)\n  {\n     if (xin.size() != 2)\n      {\n\tstd::cout << \"WARNING: This only works for 2D inputs.\" << std::endl\n\t\t  << \"WARNING: Using only first two components.\" << std::endl;\n      }\n\n    double x = xin(0) * 15 - 5;\n    double y = xin(1) * 15;\n    \n    return branin(x,y);\n  }\n\n  double branin(double x, double y)\n  {\n    const double pi = boost::math::constants::pi<double>();\n    const double rpi = pi*pi;\n    return sqr(y-(5.1/(4*rpi))*sqr(x)\n\t       +5*x/pi-6)+10*(1-1/(8*pi))*cos(x)+10;\n  };\n\n  bool checkReachability(const vectord &query)\n  {return true;};\n\n  inline double sqr( double x ){ return x*x; };\n\n  void printOptimal()\n  {\n    vectord sv(2);  \n    sv(0) = 0.1238938; sv(1) = 0.818333;\n    std::cout << \"Solutions: \" << sv << \"->\" \n\t      << evaluateSample(sv) << std::endl;\n    sv(0) = 0.5427728; sv(1) = 0.151667;\n    std::cout << \"Solutions: \" << sv << \"->\" \n\t      << evaluateSample(sv) << std::endl;\n    sv(0) = 0.961652; sv(1) = 0.1650;\n    std::cout << \"Solutions: \" << sv << \"->\" \n\t      << evaluateSample(sv) << std::endl;\n  }\n\n};\n\n\nclass ExampleCamelback: public bayesopt::ContinuousModel\n{\npublic:\n  ExampleCamelback(bayesopt::Parameters par):\n    ContinuousModel(2,par) {}\n\n  double evaluateSample( const vectord& x)\n  {\n     if (x.size() != 2)\n      {\n\tstd::cout << \"WARNING: This only works for 2D inputs.\" << std::endl\n\t\t  << \"WARNING: Using only first two components.\" << std::endl;\n      }\n     double x1_2 = x(0)*x(0);\n     double x2_2 = x(1)*x(1);\n\n     double tmp1 = (4 - 2.1 * x1_2 + (x1_2*x1_2)/3) * x1_2;\n     double tmp2 = x(0)*x(1);\n     double tmp3 = (-4 + 4 * x2_2) * x2_2;\n     return tmp1 + tmp2 + tmp3;\n  }\n\n  bool checkReachability(const vectord &query)\n  {return true;};\n\n  inline double sqr( double x ){ return x*x; };\n\n  void printOptimal()\n  {\n    vectord sv(2);  \n    sv(0) = 0.0898; sv(1) = -0.7126;\n    std::cout << \"Solutions: \" << sv << \"->\" \n\t      << evaluateSample(sv) << std::endl;\n    sv(0) = -0.0898; sv(1) = 0.7126;\n    std::cout << \"Solutions: \" << sv << \"->\" \n\t      << evaluateSample(sv) << std::endl;\n  }\n\n};\n\n\n\nclass ExampleHartmann6: public bayesopt::ContinuousModel\n{\npublic:\n  ExampleHartmann6(bayesopt::Parameters par):\n    ContinuousModel(6,par), mA(4,6), mC(4), mP(4,6)\n  {\n    mA <<= 10.0,   3.0, 17.0,   3.5,  1.7,  8.0,\n      0.05, 10.0, 17.0,   0.1,  8.0, 14.0,\n      3.0,   3.5,  1.7,  10.0, 17.0,  8.0,\n      17.0,   8.0,  0.05, 10.0,  0.1, 14.0;\n    \n    mC <<= 1.0, 1.2, 3.0, 3.2;\n\n    mP <<= 0.1312, 0.1696, 0.5569, 0.0124, 0.8283, 0.5886,\n      0.2329, 0.4135, 0.8307, 0.3736, 0.1004, 0.9991,\n      0.2348, 0.1451, 0.3522, 0.2883, 0.3047, 0.6650,\n      0.4047, 0.8828, 0.8732, 0.5743, 0.1091, 0.0381;\n  }\n\n  double evaluateSample( const vectord& xin)\n  {\n    double y = 0.0;\n    for(size_t i=0; i<4; ++i)\n      {\n\tdouble sum = 0.0;\n\tfor(size_t j=0;j<6; ++j)\n\t  {\n\t    double val = xin(j)-mP(i,j);\n\t    sum -= mA(i,j)*val*val;\n\t  }\n\ty -= mC(i)*std::exp(sum);\n      }\n    return y;\n  };\n\n  bool checkReachability(const vectord &query)\n  {return true;};\n\n  inline double sqr( double x ){ return x*x; };\n\n  void printOptimal()\n  {\n    vectord sv(6);\n    sv <<= 0.20169, 0.150011, 0.476874, 0.275332, 0.311652, 0.6573;\n\n    std::cout << \"Solution: \" << sv << \"->\" \n\t      << evaluateSample(sv) << std::endl;\n  }\n\nprivate:\n  matrixd mA;\n  vectord mC;\n  matrixd mP;\n};\n\n\n#endif\n", "meta": {"hexsha": "eaa54597a733fdec5b634bbb7d5f0a6ac2e3469b", "size": 5374, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external/bayesopt/utils/testfunctions.hpp", "max_stars_repo_name": "pchrapka/brain-modelling", "max_stars_repo_head_hexsha": "f232b5a858e45f10b0b0735269010454129ab017", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-10-13T19:37:52.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-13T19:37:52.000Z", "max_issues_repo_path": "external/bayesopt/utils/testfunctions.hpp", "max_issues_repo_name": "pchrapka/brain-modelling", "max_issues_repo_head_hexsha": "f232b5a858e45f10b0b0735269010454129ab017", "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": "external/bayesopt/utils/testfunctions.hpp", "max_forks_repo_name": "pchrapka/brain-modelling", "max_forks_repo_head_hexsha": "f232b5a858e45f10b0b0735269010454129ab017", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-25T12:22:05.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-25T12:22:05.000Z", "avg_line_length": 25.1121495327, "max_line_length": 75, "alphanum_fraction": 0.5818756978, "num_tokens": 1850, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237605, "lm_q2_score": 0.7879311856832191, "lm_q1q2_score": 0.7179469111805482}}
{"text": "#include <iostream>\n#include <g2o/core/base_vertex.h>\n#include <g2o/core/base_unary_edge.h>\n#include <g2o/core/block_solver.h>\n#include <g2o/core/optimization_algorithm_levenberg.h>\n#include <g2o/core/optimization_algorithm_gauss_newton.h>\n#include <g2o/core/optimization_algorithm_dogleg.h>\n#include <g2o/solvers/dense/linear_solver_dense.h>\n#include <Eigen/Core>\n#include <opencv2/core/core.hpp>\n#include <cmath>\n#include <chrono>\n#include <boost/program_options.hpp>\n#include <filesystem>\n#include \"CommonCurve.h\" //std::left std::setw std::setfill\n\nnamespace fs = std::filesystem;\nusing namespace boost;\nnamespace po = boost::program_options;\n// The vertex of the curve model, template parameters: optimization of variable dimensions and data types\nclass CurveFittingVertex: public g2o::BaseVertex<3, Eigen::Vector3d>\n{\npublic:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    virtual void setToOriginImpl() // Reset\n    {\n        _estimate << 0,0,0;\n    }\n    \n    virtual void oplusImpl( const double* update ) // Update\n    {\n        _estimate += Eigen::Vector3d(update);\n    }\n    // Save and read: leave blank\n    virtual bool read( std::istream& in ) {}\n    virtual bool write( std::ostream& out ) const {}\n};\n\n// Error model template parameters: observation dimension, type, connection vertex type\nclass CurveFittingEdge: public g2o::BaseUnaryEdge<1,double,CurveFittingVertex>\n{\npublic:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    CurveFittingEdge( double x ): BaseUnaryEdge(), _x(x) {}\n    // Calculate curve model error\n    void computeError()\n    {\n        const CurveFittingVertex* v = static_cast<const CurveFittingVertex*> (_vertices[0]);\n        const Eigen::Vector3d abc = v->estimate();\n        _error(0,0) = _measurement - std::exp( abc(0,0)*_x*_x + abc(1,0)*_x + abc(2,0) ) ;\n    }\n    virtual bool read( std::istream& in ) {}\n    virtual bool write( std::ostream& out ) const {}\npublic:\n    double _x;  //x value, y value _measurement\n};\n\nint main( int argc, char** argv )\n{\n\n    std::string dataFile = \"readDataG2O.txt\";\n    std::string parameter = \"parametersG2O.txt\";\n    std::string path = \"./result/\";\n    // create directory if not exist\n    struct stat info;\n    if( stat( path.c_str(), &info ) != 0 )fs::create_directories(path);\n    std::string pathRealData = path + za::getCurrentTime() + dataFile;\n    std::string pathParameter = path + za::getCurrentTime() + parameter;\n  \n    // True parameter value to be estimated \n    double a, b, c;  \n\n    // Total number of data point       \n    int N, iterate ;   \n\n    // Noise Sigma value                       \n    double w_sigma; \n    // Cammand line parser \n\ttry \n\t\t{\n\t\t\tpo::options_description desc(\"Allowed options\");\n\t\t\tdesc.add_options()\n\t\t\t\t(\"help,h\", \"produce help message\")\n\t\t\t\t(\"first,a\", po::value<double>(),\n\t\t\t\t\t\"first parameter\")\t\t\t\n                (\"second,b\", po::value<double>(),\n\t\t\t\t\t\"second parameter\")\n\t\t\t\t(\"third,c\", po::value<double>(),\n\t\t\t\t\t\"third parameter\")\t\t\t\t\n                (\"number,n\", po::value<int>(&N)->default_value(100)->implicit_value(500),\n\t\t\t\t\t\"number of data\")                \n                (\"iteration,i\", po::value<int>(&iterate)->default_value(100)->implicit_value(200),\n\t\t\t\t\t\"number of iterations\")\n\t\t\t\t(\"noise,s\", po::value<double>(&w_sigma)->default_value(1)->implicit_value(5),\n\t\t\t\t\t\"noise added\");\t\t\n                    \n\t\n\t\t\t/* Point out that all unknown values \u200b\u200bshould be converted to the value of the \"input-file\" option.\n\t\t\t\t\t* Also use the command_line_parser class instead of parse_command_line */\n\t\t\tpo::variables_map vm;        \n\t\t\tpo::store(po::parse_command_line(argc, argv, desc), vm);\n\t\t\tpo::notify(vm);  \n\n\t\t\tif (vm.count(\"help\")) \n\t\t\t{\n\t\t\t\tstd::cout << \"Usage: options_description [options]\\n\";\n\t\t\t\tstd::cout << desc;\n\t\t\t\treturn 0;\n\t\t\t}\n \t\t\tif (vm.count(\"first\") ) \n        \t{\n\n                a =  vm[\"first\"].as<double>();\n        \t} \n        \telse \n       \t\t{\n            \tstd::cout << \"First parameter not set.\\n\";\n\t\t\t\treturn -1;\n        \t}\t\t\t\n \t\t\tif (vm.count(\"second\") ) \n        \t{\n\n                b =  vm[\"second\"].as<double>();\n        \t} \n        \telse \n       \t\t{\n            \tstd::cout << \"Second parameter not set.\\n\";\n\t\t\t\treturn -1;\n        \t}\t\t\t\n \t\t\tif (vm.count(\"third\") ) \n        \t{\n\n                a =  vm[\"third\"].as<double>();\n        \t} \n        \telse \n       \t\t{\n            \tstd::cout << \"Third parameter not set.\\n\";\n\t\t\t\treturn -1;\n        \t}\t\t\t\n        }// end of try\n\t\t\t\n        catch(std::exception& e)\n\t\t{\n\t\t\tstd::cout << e.what() << \"\\n\";\n\t\t\treturn 1;\n\t\t}\n\n\n\n\n\n\n\n      // OpenCV random number generator               \n    cv::RNG rng;       \n\n    // abc Estimated value of the parameter                 \n    double abc[3] = {0,0,0};            \n\n   // set of x and y data \n    std::vector<double> x_data, y_data;      \n    std::ofstream myfile;\n    const int nameWidth     = 6;\n    const int numWidth      = 8;\n    myfile.open (&pathRealData[0]);\n    for(int i = 0; i < 25; i++) za::printElement(\"-\", 1, myfile);\n    myfile <<\"\\n\";\n    za::printElement(\"|\", 1, myfile);\n    za::printElement(\"N\", nameWidth, myfile);\n    za::printElement(\"|\", 1, myfile);\n    za::printElement(\"X\", nameWidth, myfile);\n    za::printElement(\"|\", 1, myfile);\n    za::printElement(\"Y\", 10, myfile);\n    za::printElement(\"|\", 1, myfile);\n    myfile <<\"\\n\";\n    for(int i = 0; i < 25; i++) za::printElement(\"-\", 1, myfile);\n    myfile <<\"\\n\";\n    std::cout<<\"Generating data: \\n\";\n    \n    for ( int i=0; i<N; i++ )\n    {\n        double x = i/100.0;\n        x_data.push_back ( x );\n        y_data.push_back (\n            exp ( a*x*x + b*x + c ) + rng.gaussian ( w_sigma )\n        );\n        za::printElement(\"|\", 1, myfile);\n        za::printElement(i+1, nameWidth, myfile);\n        za::printElement(\"|\", 1, myfile);\n        za::printElement(x_data[i], nameWidth, myfile);\n        za::printElement(\"|\", 1, myfile);\n        za::printElement(y_data[i], 10, myfile);\n        za::printElement(\"|\", 1, myfile);\n        myfile <<\"\\n\";\n        for(int i = 0; i < 25; i++) za::printElement(\"-\", 1, myfile);\n        myfile <<\"\\n\";\n    }\n     myfile.close();   \n    // Build graph optimization, first set g2o\n    // The dimension of the optimized variable for each error term is 3, and the dimension of the error value is 1\n    typedef g2o::BlockSolver< g2o::BlockSolverTraits<3,1> > Block;  \n    //zouma\n    // Linear equation solver\n    std::unique_ptr<Block::LinearSolverType> linearSolver \n\t\t\t\t(new g2o::LinearSolverDense<Block::PoseMatrixType>());\n\n    // Matrix block solver\n    std::unique_ptr<Block> solver_ptr (new Block(std::move(linearSolver)));\n\t\n    // Gradient descent method, choose from GN, LM, DogLeg\n    g2o::OptimizationAlgorithmGaussNewton * solver = new g2o::OptimizationAlgorithmGaussNewton(std::move(solver_ptr));\n    //zouma\n    \n    g2o::SparseOptimizer optimizer;     // Graph model\n    optimizer.setAlgorithm( solver );   // Set up the solver\n    optimizer.setVerbose( true );       // Turn on debug output\n    \n    // Add vertices to the graph\n    CurveFittingVertex* v = new CurveFittingVertex();\n    v->setEstimate( Eigen::Vector3d(0,0,0) );\n    v->setId(0);\n    optimizer.addVertex( v );\n    \n    // Add edges to the graph\n    for ( int i=0; i<N; i++ )\n    {\n        CurveFittingEdge* edge = new CurveFittingEdge( x_data[i] );\n        edge->setId(i);\n        edge->setVertex( 0, v );                // Set the connected vertices\n        edge->setMeasurement( y_data[i] );      // Observed value\n        edge->setInformation( Eigen::Matrix<double,1,1>::Identity()*1/(w_sigma*w_sigma) ); // Information matrix: the inverse of the covariance matrix\n        optimizer.addEdge( edge );\n    }\n    \n    //Perform optimization\n    std::cout<<\"start optimization\\n\";\n    std::chrono::steady_clock::time_point t1 = std::chrono::steady_clock::now();\n    optimizer.initializeOptimization();\n    optimizer.optimize(iterate);\n    std::chrono::steady_clock::time_point t2 = std::chrono::steady_clock::now();\n    std::chrono::duration<double> time_used = std::chrono::duration_cast<std::chrono::duration<double>>( t2-t1 );\n    std::cout<<\"solve time cost = \"<<time_used.count()<<\" seconds. \\n\";\n    \n    // Output optimized value\n    Eigen::Vector3d abc_estimate = v->estimate();\n    std::ofstream mySol;\n    mySol.open (&pathParameter[0]);\n    mySol<<\"estimated model a, b, c: \"<<abc_estimate.transpose()<<\"\\n\";\n    mySol.close();    \n    return 0;\n}", "meta": {"hexsha": "f4764575e4bad6c84c35ee3edcece1308f6b60be", "size": 8394, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/g2o/demoG2O.cpp", "max_stars_repo_name": "zoumson/CurveFitting", "max_stars_repo_head_hexsha": "bf115ce0e98478a8a1e6962e8a124582e0a7be4b", "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/g2o/demoG2O.cpp", "max_issues_repo_name": "zoumson/CurveFitting", "max_issues_repo_head_hexsha": "bf115ce0e98478a8a1e6962e8a124582e0a7be4b", "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/g2o/demoG2O.cpp", "max_forks_repo_name": "zoumson/CurveFitting", "max_forks_repo_head_hexsha": "bf115ce0e98478a8a1e6962e8a124582e0a7be4b", "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": 33.4422310757, "max_line_length": 150, "alphanum_fraction": 0.5963783655, "num_tokens": 2254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026595857203, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.7179383781516862}}
{"text": "//\n//  strassen.cpp\n//  Jacobian\n//\n//  Created by David Freifeld\n//  Copyright \u00a9 2020 David Freifeld. All rights reserved.\n//\n//  Description:\n//  Experimental benchmarking of Strassen's Algorithm vs plain Eigen matrix multiply.\n//  While naive multiplication is O(n^3), Strassen's Algorithm for matrix multiply is O(n^2.8074)\n//  which means significant differences will begin to manifest for large matrices. All faster algorithms are galactic.\n//\n\n#include <Eigen/Dense>\n#include <ctime>\n#include <iostream>\n\n// Not remotely extensible, just initial test.\nEigen::MatrixXf strassen_mul(Eigen::MatrixXf x, Eigen::MatrixXf y)\n{\n  int power = 0;\n  int largest;\n  if (x.rows() >= x.cols() || x.rows() >= y.cols() || x.rows() >= y.rows()) largest = x.rows();\n  else if (x.cols() >= x.rows() || x.cols() >= y.cols() || x.cols() >= y.rows()) largest = x.cols();\n  else if (y.cols() >= x.rows() || y.cols() >= x.cols() || y.cols() >= y.rows()) largest = y.cols();\n  else if (y.rows() >= x.rows() || y.rows() >= x.cols() || y.rows() >= y.cols()) largest = y.rows();\n  for (; pow(2, power) < largest; power++) {\n    std::cout << pow(2, power) << \" \" << power <<\"\\n\";\n  }\n  std::cout << \"POWER: \" << power << \" LARGEST: \" << largest << \"\\n\";\n  Eigen::MatrixXf a ((int)pow(2,power), (int)pow(2,power));\n  Eigen::MatrixXf b ((int)pow(2,power), (int)pow(2,power));\n  a.block(0,0,x.rows(), x.cols()) = x;\n  b.block(0,0,y.rows(), y.cols()) = y;\n  std::cout << \"\\nINIT\\n\" << a << \"\\n\\n\" << b << \"\\n\\n\\n\";\n  std::cout << \"\\nEIGEN_VER\\n\" << a*b << \"\\n\\n\\n\";\n  //Eigen::MatrixXf a ()\n  int block_len = largest/2;\n  Eigen::MatrixXf result ((int)pow(2,power), (int)pow(2,power));\n\n  Eigen::MatrixXf m1 = ((a.block(0,0, block_len, block_len)) + a.block(a.rows()-block_len,a.cols()-block_len, block_len, block_len)) * (b.block(0,0, block_len, block_len) + b.block(b.rows()-block_len,b.cols()-block_len, block_len, block_len));\n  Eigen::MatrixXf m2 = (a.block(a.rows()-block_len, 0, block_len, block_len) + a.block(a.rows()-block_len,a.cols()-block_len, block_len, block_len)) * (b.block(0,0, block_len, block_len));\n  Eigen::MatrixXf m3 = a.block(0,0, block_len, block_len) * (b.block(0,b.cols()-block_len, block_len, block_len) - b.block(b.rows()-block_len,b.cols()-block_len, block_len, block_len));\n  Eigen::MatrixXf m4 = a.block(a.rows()-block_len,a.cols()-block_len, block_len, block_len) * (b.block(b.rows()-block_len,0, block_len, block_len) - b.block(0,0, block_len, block_len));\n  Eigen::MatrixXf m5 = (a.block(0, 0, block_len, block_len) + a.block(0,a.cols()-block_len, block_len, block_len)) * (b.block(b.rows()-block_len,b.cols()-block_len, block_len, block_len));\n  Eigen::MatrixXf m6 = (a.block(a.rows()-block_len,0, block_len, block_len) - a.block(0,0, block_len, block_len)) * (b.block(0,0, block_len, block_len) + b.block(0,b.cols()-block_len, block_len, block_len));\n  Eigen::MatrixXf m7 = (a.block(0,a.cols()-block_len, block_len, block_len) - a.block(a.rows()-block_len,a.cols()-block_len, block_len, block_len)) * (b.block(a.rows()-block_len,0, block_len, block_len) + b.block(b.rows()-block_len,b.cols()-block_len, block_len, block_len));\n\n  //  std::cout << m1 + m4 - m5 + m7 << \"\\n\\n\" << m3+m5 << \"\\n\\n\" << m2+m4 << \"\\n\\n\" << m1-m2+m3+m6;\n  \n  result.block(0,0, block_len, block_len) =  m1 + m4 - m5 + m7;\n  result.block(0,result.cols()-block_len, block_len, block_len) =  m3 + m5;\n  result.block(result.rows()-block_len,0, block_len, block_len) =  m2 + m4;\n  result.block(result.rows()-block_len,result.cols()-block_len, block_len, block_len) =  m1 -m2 + m3 + m6;\n  std::cout << \"\\nSTRASSEN_VER\\n\" << result << \"\\n\\n\\n\";\n  return result;\n}\n\nint main()\n{\n  srand((unsigned int) time(0));\n  int sz;\n  std::cin >> sz;\n  Eigen::MatrixXf a = Eigen::MatrixXf::Random(sz, 3);\n  Eigen::MatrixXf b = Eigen::MatrixXf::Random(3, sz);\n  \n  auto eigen_begin = std::chrono::high_resolution_clock::now();\n  Eigen::MatrixXf product = a * b;\n  auto eigen_end = std::chrono::high_resolution_clock::now();\n  \n  auto strassen_begin = std::chrono::high_resolution_clock::now();\n  Eigen::MatrixXf sproduct = strassen_mul(a, b);\n  auto strassen_end = std::chrono::high_resolution_clock::now();\n  \n  /* std::cout << \"EIGEN: \" << std::chrono::duration_cast<std::chrono::nanoseconds>(eigen_end - eigen_begin).count() / pow(10,9) << \" STRASSEN: \" << std::chrono::duration_cast<std::chrono::nanoseconds>(strassen_end - strassen_begin).count() / pow(10,9) << \"\\n\"; */\n  /* std::cout << \"A:\\n\" << a << \"\\nB:\\n\" << b << \"\\nEigen:\\n\" << product << \"\\nStrassen:\\n\" << sproduct << \"\\n\"; */\n}\n", "meta": {"hexsha": "3751048e8e7ea2f453712a11f3f06758bc5b20f1", "size": 4561, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/experimental/strassen.cpp", "max_stars_repo_name": "richardfeynmanrocks/ml-in-parallel", "max_stars_repo_head_hexsha": "6fd978b1f4a97ae789a13e0c2f20638672848aa5", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-10-01T23:28:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T02:21:20.000Z", "max_issues_repo_path": "src/experimental/strassen.cpp", "max_issues_repo_name": "quantumish/Jacobian", "max_issues_repo_head_hexsha": "6fd978b1f4a97ae789a13e0c2f20638672848aa5", "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": "src/experimental/strassen.cpp", "max_forks_repo_name": "quantumish/Jacobian", "max_forks_repo_head_hexsha": "6fd978b1f4a97ae789a13e0c2f20638672848aa5", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-14T16:06:20.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-14T16:06:20.000Z", "avg_line_length": 58.4743589744, "max_line_length": 275, "alphanum_fraction": 0.6382372287, "num_tokens": 1488, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026618464796, "lm_q2_score": 0.7826624688140726, "lm_q1q2_score": 0.7179383659704861}}
{"text": "#pragma once\n\n#include <Eigen/Core>\nusing namespace Eigen;\n\n#include <autodiff/forward.hpp>\n#include <autodiff/forward/eigen.hpp>\nusing namespace autodiff;\n\nnamespace samson::so3\n{\n    auto so3(const Vector3dual &v) -> Matrix3dual\n    {\n        Matrix3dual X;\n        X << 0.0, -v(2), v(1), v(2), 0.0, -v(0), -v(1), v(0), 0.0;\n        return X;\n    }\n\n    auto so3(const Matrix3dual &X) -> Vector3dual\n    {\n        Vector3dual v;\n        v << X(2, 1), X(0, 2), X(1, 0);\n        return v;\n    }\n\n    auto to_axis_angle(const Vector3dual &v) -> std::pair<Vector3dual, dual>\n    {\n        dual theta = v.norm();\n        Vector3dual k = v.normalized();\n        return std::make_pair(k, theta);\n    }\n\n    auto exp(const Vector3dual &v) -> Matrix3dual\n    {\n        auto [k, th] = to_axis_angle(v);\n        // std::cout << (th) << std::endl;; \n        Matrix3dual K = so3(k);\n        return Matrix3dual::Identity() + sin(th) * K + (1.0 - cos(th)) * K * K;\n    }\n\n    auto exp(const Matrix3dual &X) -> Matrix3dual\n    {\n        Vector3dual v = so3(X);\n        return exp(v);\n    }\n\n    auto from_axis_angle(const Vector3dual &axis, dual angle)\n    {\n        Vector3dual x = axis * angle;\n        Matrix3dual X = so3(x);\n        return exp(X);\n    }\n\n} // namespace samson::so3", "meta": {"hexsha": "747b5f97836358317f569c9f7e3b402f787b61cc", "size": 1271, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/samson/so3.hpp", "max_stars_repo_name": "tingelst/samson", "max_stars_repo_head_hexsha": "a34717d40d61868cb87560b94f422859d59d8bde", "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/samson/so3.hpp", "max_issues_repo_name": "tingelst/samson", "max_issues_repo_head_hexsha": "a34717d40d61868cb87560b94f422859d59d8bde", "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": "include/samson/so3.hpp", "max_forks_repo_name": "tingelst/samson", "max_forks_repo_head_hexsha": "a34717d40d61868cb87560b94f422859d59d8bde", "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.537037037, "max_line_length": 79, "alphanum_fraction": 0.5476003147, "num_tokens": 417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810496235896, "lm_q2_score": 0.7577943822145998, "lm_q1q2_score": 0.7179200372213272}}
{"text": "#include \"SlamShuffler.h\"\n\n#include <AdventOfCodeCommon/DisableLibraryWarningsMacros.h>\n\n__BEGIN_LIBRARIES_DISABLE_WARNINGS\n#include <boost/integer/mod_inverse.hpp>\n__END_LIBRARIES_DISABLE_WARNINGS\n\nnamespace AdventOfCode\n{\nnamespace Year2019\n{\nnamespace Day22\n{\n\nSlamShuffler::SlamShuffler(std::vector<ShuffleInstruction> instructions, BigNumber deckSize, BigNumber numIterations)\n    : m_instructions{std::move(instructions)}\n    , m_deckSize{deckSize}\n    , m_numIterations{numIterations}\n{\n\n}\n\nBigNumber SlamShuffler::getCardAtPosition(BigNumber position)\n{\n    BigNumber iterOneResult = getWhereCardComesFrom(position);\n    BigNumber iterTwoResult = getWhereCardComesFrom(iterOneResult);\n\n    // Subtract the following equations:\n    // slope * position + offset = iterOneResult\n    // slope * iterOneResult + offset = iterTwoResult\n    // -> slope = (iterOneResult - iterTwoResult) / (position - iterOneResult)\n    BigNumber slope = (iterOneResult - iterTwoResult) * boost::integer::mod_inverse(position - iterOneResult + m_deckSize, m_deckSize) % m_deckSize;\n    BigNumber offset = (iterOneResult - slope * position + m_deckSize * position * slope) % m_deckSize;\n\n    // For 2 iterations:\n    // result = slope * (slope * position + offset) + offset\n    // For m_numIterations iterations:\n    // (slope^m_numIterations) * position + (slope^(m_numIterations - 1))) * offset + (slope^(m_numIterations - 2))) * offset + ... + offset\n    // (slope^m_numIterations) * position + (slope^m_numIterations - 1) / (slope - 1) * B\n    BigNumber slopeToTheNumberOfIterations = boost::multiprecision::powm(slope, m_numIterations, m_deckSize);\n    BigNumber firstTerm = slopeToTheNumberOfIterations * position;\n    BigNumber secondTerm = (slopeToTheNumberOfIterations - 1) * boost::integer::mod_inverse(slope - 1 + m_deckSize, m_deckSize) * offset;\n\n    return (firstTerm + secondTerm) % m_deckSize;\n}\n\nstd::vector<unsigned> SlamShuffler::getAllCardsAfterSingleIteration()\n{\n    std::vector<unsigned> allCards;\n\n    for (int i = 0; i < m_deckSize; ++i)\n    {\n        auto cardAtPosition = getWhereCardComesFrom(i);\n        allCards.push_back(unsigned{cardAtPosition});\n    }\n\n    return allCards;\n}\n\nBigNumber SlamShuffler::getWhereCardComesFrom(BigNumber position) const\n{\n    for (auto instructionIter = m_instructions.crbegin(); instructionIter != m_instructions.crend(); ++instructionIter)\n    {\n        position = executeInReverse(*instructionIter, position);\n    }\n\n    return position;\n}\n\nBigNumber SlamShuffler::executeInReverse(const ShuffleInstruction& instruction, BigNumber position) const\n{\n    if (instruction.type == DEAL_INTO_NEW_STACK)\n    {\n        return m_deckSize - 1 - position;\n    }\n    else if (instruction.type == CUT)\n    {\n        return (position + instruction.arg + m_deckSize) % m_deckSize;\n    }\n    else\n    {\n        BigNumber inverse = boost::integer::mod_inverse(BigNumber{instruction.arg}, m_deckSize);\n        return inverse * position % m_deckSize;\n    }\n}\n\n}\n}\n}\n", "meta": {"hexsha": "8dd575ead707e2a93143c542e80aacf8f7666824", "size": 2996, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/AdventOfCode2019/Day22-SlamShuffle/SlamShuffler.cpp", "max_stars_repo_name": "dbartok/advent-of-code-cpp", "max_stars_repo_head_hexsha": "c8c2df7a21980f8f3e42128f7bc5df8288f18490", "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/AdventOfCode2019/Day22-SlamShuffle/SlamShuffler.cpp", "max_issues_repo_name": "dbartok/advent-of-code-cpp", "max_issues_repo_head_hexsha": "c8c2df7a21980f8f3e42128f7bc5df8288f18490", "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/AdventOfCode2019/Day22-SlamShuffle/SlamShuffler.cpp", "max_forks_repo_name": "dbartok/advent-of-code-cpp", "max_forks_repo_head_hexsha": "c8c2df7a21980f8f3e42128f7bc5df8288f18490", "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.9230769231, "max_line_length": 148, "alphanum_fraction": 0.720293725, "num_tokens": 757, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474155747541, "lm_q2_score": 0.752012562644147, "lm_q1q2_score": 0.7179068494079828}}
{"text": "//Link to Boost\n #define BOOST_TEST_DYN_LINK\n\n//VERY IMPORTANT - include this last\n#include <boost/test/unit_test.hpp>\n\n#include <cmath>\n#include \"test.h\"\n#include \"../common.h\"\n#include \"../gegenbauer_polynomial.hpp\"\n\nBOOST_DATA_TEST_CASE(GegenbauerDAlphaAt0_test, bdata::xrange(0, 20) ^ bdata::random(-10.0, 10.0), n, x)\n{\n    float_type actual = GegenbauerDAlphaAt0(n, x);\n\n    float_type arr[1] = {x};\n    float_type *v1 = gegenbauer_polynomial_value(n, 1, -inc, arr);\n    float_type *v2 = gegenbauer_polynomial_value(n, 1, inc, arr);\n    float_type ret1 = v1[n + 0 * (n + 1)];\n    float_type ret2 = v2[n + 0 * (n + 1)];\n    delete v1;\n    delete v2;\n    \n    float_type expect = (ret2 - ret1) / (2 * inc);\n    MY_FLOAT_EQUAL(actual, expect, tol);\n}\n\n", "meta": {"hexsha": "6596e0bf84f3e9cef6ca086a7a39d499635b0ac8", "size": 755, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/commonTests.cpp", "max_stars_repo_name": "gaolichen/cftbtsp", "max_stars_repo_head_hexsha": "e764b6ca339d6d68a5c6b6acd9f58ef64c628d47", "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/test/commonTests.cpp", "max_issues_repo_name": "gaolichen/cftbtsp", "max_issues_repo_head_hexsha": "e764b6ca339d6d68a5c6b6acd9f58ef64c628d47", "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/test/commonTests.cpp", "max_forks_repo_name": "gaolichen/cftbtsp", "max_forks_repo_head_hexsha": "e764b6ca339d6d68a5c6b6acd9f58ef64c628d47", "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.9642857143, "max_line_length": 103, "alphanum_fraction": 0.6582781457, "num_tokens": 249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213745668094, "lm_q2_score": 0.7981867825403177, "lm_q1q2_score": 0.7176667970787095}}
{"text": "#include <stan/math/prim/scal.hpp>\n#include <stan/math/prim/arr/fun/log_sum_exp.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <gtest/gtest.h>\n#include <limits>\n#include <vector>\n\nvoid test_log_sum_exp(double a, double b) {\n  using stan::math::log_sum_exp;\n  using std::exp;\n  using std::log;\n  EXPECT_FLOAT_EQ(log(exp(a) + exp(b)), log_sum_exp(a, b));\n}\n\nvoid test_log_sum_exp(const std::vector<double>& as) {\n  using stan::math::log_sum_exp;\n  using std::exp;\n  using std::log;\n  double sum_exp = 0.0;\n  for (size_t n = 0; n < as.size(); ++n)\n    sum_exp += exp(as[n]);\n  EXPECT_FLOAT_EQ(log(sum_exp), log_sum_exp(as));\n}\n\nTEST(MathFunctions, log_sum_exp) {\n  using stan::math::log_sum_exp;\n  std::vector<double> as;\n  test_log_sum_exp(as);\n  as.push_back(0.0);\n  test_log_sum_exp(as);\n  as.push_back(1.0);\n  test_log_sum_exp(as);\n  as.push_back(-1.0);\n  test_log_sum_exp(as);\n  as.push_back(-10000.0);\n  test_log_sum_exp(as);\n\n  as.push_back(10000.0);\n  EXPECT_FLOAT_EQ(10000.0, log_sum_exp(as));\n}\n\nTEST(MathFunctions, log_sum_exp_2) {\n  using stan::math::log_sum_exp;\n  test_log_sum_exp(1.0, 2.0);\n  test_log_sum_exp(1.0, 1.0);\n  test_log_sum_exp(3.0, 2.0);\n  test_log_sum_exp(-20.0, 12);\n  test_log_sum_exp(-20.0, 12);\n\n  // exp(10000.0) overflows\n  EXPECT_FLOAT_EQ(10000.0, log_sum_exp(10000.0, 0.0));\n  EXPECT_FLOAT_EQ(0.0, log_sum_exp(-10000.0, 0.0));\n}\n\nTEST(MathFunctions, log_sum_exp_2_inf) {\n  using stan::math::log_sum_exp;\n  double inf = std::numeric_limits<double>::infinity();\n  test_log_sum_exp(1.0, -inf);\n  test_log_sum_exp(-inf, 3.0);\n  test_log_sum_exp(-inf, -inf);\n  EXPECT_FLOAT_EQ(inf, log_sum_exp(inf, 3.0));\n  EXPECT_FLOAT_EQ(inf, log_sum_exp(inf, inf));\n}\n\nTEST(MathFunctions, log_sum_exp_nan) {\n  double nan = std::numeric_limits<double>::quiet_NaN();\n\n  EXPECT_PRED1(boost::math::isnan<double>, stan::math::log_sum_exp(1.0, nan));\n\n  EXPECT_PRED1(boost::math::isnan<double>, stan::math::log_sum_exp(nan, 1.0));\n\n  EXPECT_PRED1(boost::math::isnan<double>, stan::math::log_sum_exp(nan, nan));\n}\n", "meta": {"hexsha": "439c77e1a9bccf6522ed498b93a5897dade1c228", "size": 2045, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/prim/scal/fun/log_sum_exp_test.cpp", "max_stars_repo_name": "peterwicksstringfield/math", "max_stars_repo_head_hexsha": "5ce0718ea64f2cca8b2f1e4eeac27a2dc2bd246e", "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": "test/unit/math/prim/scal/fun/log_sum_exp_test.cpp", "max_issues_repo_name": "peterwicksstringfield/math", "max_issues_repo_head_hexsha": "5ce0718ea64f2cca8b2f1e4eeac27a2dc2bd246e", "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": "test/unit/math/prim/scal/fun/log_sum_exp_test.cpp", "max_forks_repo_name": "peterwicksstringfield/math", "max_forks_repo_head_hexsha": "5ce0718ea64f2cca8b2f1e4eeac27a2dc2bd246e", "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": 27.6351351351, "max_line_length": 78, "alphanum_fraction": 0.702200489, "num_tokens": 672, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094032139576, "lm_q2_score": 0.8031738010682209, "lm_q1q2_score": 0.7174827089093383}}
{"text": "#include \"gtest/gtest.h\"\n\n#include <math.h>\n\n#include <Eigen/Core>\n\n#include \"pICP/utils.h\"\n\nnamespace\n{\n\nTEST(utils, translate_2d)\n{\n    Eigen::Matrix< float, 2, 5 > coordinates;\n    coordinates << 1., 2., 3., 4., 5.,\n                   1., 2., 3., 4., 5.;\n\n    Eigen::Matrix< float, 2, 2 > rotation;\n    rotation.setIdentity();\n\n    Eigen::Matrix< float, 2, 1 > translation;\n    translation << 10., 10;\n\n    Eigen::Matrix< float, 2, 5 > translatedCoordinates = pICP::transformCoordinatesMatrix( coordinates, rotation, translation );\n\n    Eigen::Matrix< float, 2, 5 > expectedCoordinates;\n    expectedCoordinates << 11., 12., 13., 14., 15.,\n                           11., 12., 13., 14., 15.;\n\n    EXPECT_TRUE( translatedCoordinates == expectedCoordinates );\n}\n\nTEST(utils, rotate_2d)\n{\n    Eigen::Matrix< float, 2, 5 > coordinates;\n    coordinates <<  1.,  2.,  3.,  4.,  5.,\n                   11., 22., 33., 44., 55.;\n\n    Eigen::Matrix< float, 2, 2 > rotation;\n    rotation << std::cos( M_PI/2. ), -std::sin( M_PI/2. ),\n                std::sin( M_PI/2.),   std::cos( M_PI/2. );\n\n    Eigen::Matrix< float, 2, 1 > translation;\n    translation << 0., 0;\n\n    Eigen::Matrix< float, 2, 5 > translatedCoordinates = pICP::transformCoordinatesMatrix( coordinates, rotation, translation );\n\n    Eigen::Matrix< float, 2, 5 > expectedCoordinates;\n    expectedCoordinates << -11., -22., -33., -44., -55.,\n                             1.,   2.,   3.,   4.,   5.;\n\n    EXPECT_TRUE( translatedCoordinates == expectedCoordinates );\n}\n\nTEST(utils, transform_3d)\n{\n    Eigen::Matrix< float, 3, 5 > coordinates;\n    coordinates << 1., 2., 3., 4., 5.,\n                   1., 2., 3., 4., 5.,\n                   1., 2., 3., 4., 5.;\n\n    Eigen::Matrix< float, 3, 3 > rotation;\n    rotation << 1.,                  0.,                   0.,               \n                0., std::cos( M_PI/2. ), -std::sin( M_PI/2. ),\n                0.,  std::sin( M_PI/2.),  std::cos( M_PI/2. );\n\n    Eigen::Matrix< float, 3, 1 > translation;\n    translation << 1., 2., 3;\n\n    Eigen::Matrix< float, 3, 5 > translatedCoordinates = pICP::transformCoordinatesMatrix( coordinates, rotation, translation );\n\n    Eigen::Matrix< float, 3, 5 > expectedCoordinates;\n    expectedCoordinates <<  2., 3.,  4.,  5.,  6.,\n                            1., 0., -1., -2., -3.,\n                            4., 5.,  6.,  7.,  8.;\n\n    EXPECT_TRUE( translatedCoordinates == expectedCoordinates );\n}\n\nTEST(utils, coordinatesDifferenceNorm_equality)\n{\n    Eigen::Matrix< float, 3, 5 > coordinates;\n    coordinates << 1., 2., 3., 4., 5.,\n                   1., 2., 3., 4., 5.,\n                   1., 2., 3., 4., 5.;\n\n    Eigen::Matrix< float, 3, 5 > sameCoordinates = coordinates;\n\n    EXPECT_EQ(pICP::coordinatesDifferenceNorm( coordinates, sameCoordinates ), 0. );\n}\n\nTEST(utils, coordinatesDifferenceNorm_inequality)\n{\n    Eigen::Matrix< float, 3, 5 > coordinates;\n    coordinates << 1., 2., 3., 4., 5.,\n                   1., 2., 3., 4., 5.,\n                   1., 2., 3., 4., 5.;\n\n    Eigen::Matrix< float, 3, 5 > differentCoordinates = coordinates;\n    //differentCoordinates( 1, 3 ) += 2.;\n    differentCoordinates( 2, 4 ) += 3.;\n\n    EXPECT_EQ(pICP::coordinatesDifferenceNorm( coordinates, differentCoordinates ), 3. );\n}\n\n}  // namespace\n", "meta": {"hexsha": "3cad14861ee0a24981292a26e32e9578e52b5a4b", "size": 3292, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/pICP/utils.cpp", "max_stars_repo_name": "BlademasterQAQ/pICP", "max_stars_repo_head_hexsha": "18f091a9e70216bc12e910db6fe243eb913b6614", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 26.0, "max_stars_repo_stars_event_min_datetime": "2018-06-06T06:19:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T07:51:12.000Z", "max_issues_repo_path": "test/pICP/utils.cpp", "max_issues_repo_name": "BlademasterQAQ/pICP", "max_issues_repo_head_hexsha": "18f091a9e70216bc12e910db6fe243eb913b6614", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-10-04T18:10:12.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-22T18:28:16.000Z", "max_forks_repo_path": "test/pICP/utils.cpp", "max_forks_repo_name": "BlademasterQAQ/pICP", "max_forks_repo_head_hexsha": "18f091a9e70216bc12e910db6fe243eb913b6614", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-05-16T17:33:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-01T12:34:12.000Z", "avg_line_length": 30.7663551402, "max_line_length": 128, "alphanum_fraction": 0.5394896719, "num_tokens": 1032, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094088947399, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.7174827050546618}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\nusing namespace Eigen;\nusing namespace std;\n\nMatrixXcd bl_bicggr(const MatrixXcd& A, const MatrixXcd& B, const double& tol, const int& itermax)\n{\n// Block BiCGGR [Tadano etal 2009 JSIAM letters]\n  double Bnorm= B.norm();\n  MatrixXcd X= MatrixXcd::Zero(B.rows(),B.cols()); // Initial guess of X (zeros)\n  MatrixXcd R= B-A*X;\n  MatrixXcd P= R;\n  MatrixXcd V= A*R;\n  MatrixXcd W= V;\n  MatrixXcd R0til= R; //MatrixXcd::Random(n,L);\n  MatrixXcd R0til_H= R0til.adjoint();\n  for(int k= 0; k < itermax; ++k){\n    MatrixXcd alfa= (R0til_H*V).fullPivLu().solve(R0til_H*R);\n    complex<double> qsi= (W.adjoint()*R).trace()/(W.adjoint()*W).trace();\n    MatrixXcd S= P-qsi*V;\n    MatrixXcd U= S*alfa;\n    MatrixXcd Y= A*U;\n    X= X+qsi*R+U;\n    MatrixXcd Rnew= R-qsi*W-Y;\n    double err= Rnew.norm()/Bnorm;\n    cout << \"bl_bicggr: \" << \"iter= \" << k << \" relative err= \" << err << endl;\n    if(err < tol) break;\n    W= A*Rnew;\n    MatrixXcd gamma = (R0til_H*R).fullPivLu().solve(R0til_H*Rnew/qsi);\n    R=Rnew;\n    P= R+U*gamma;\n    V= W+Y*gamma;\n\n  }\n  if((A*X-B).norm()/Bnorm > 10*tol){\n      cerr << \"bl_bicggr did not converge to solution within error tolerance !\" << endl;\n     // exit(EXIT_FAILURE);\n  }\n\n  return X;\n}\n", "meta": {"hexsha": "ebce8e05ce6467508282edb8b2bb4ec426c277f3", "size": 1254, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bl_bicggr.cpp", "max_stars_repo_name": "nmoteki/block-Krylov-linear-solvers", "max_stars_repo_head_hexsha": "0c123f474296219c1b944ad83f8e3c7abbf0c2b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-27T08:44:06.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-27T08:44:06.000Z", "max_issues_repo_path": "bl_bicggr.cpp", "max_issues_repo_name": "nmoteki/block-Krylov-linear-solvers", "max_issues_repo_head_hexsha": "0c123f474296219c1b944ad83f8e3c7abbf0c2b0", "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": "bl_bicggr.cpp", "max_forks_repo_name": "nmoteki/block-Krylov-linear-solvers", "max_forks_repo_head_hexsha": "0c123f474296219c1b944ad83f8e3c7abbf0c2b0", "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.8571428571, "max_line_length": 98, "alphanum_fraction": 0.6228070175, "num_tokens": 456, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.7173146463579211}}
{"text": "#include \"rmsd_align.hpp\"\n#include <Eigen/Dense>\n\n#include <iostream> // delete me\n\nnamespace timemachine {\n\n/*\nOptimally align x2 onto x1. In particular, x2 is shifted so that its centroid is placed\nat the same position as the of x1's centroid. x2 is also rotated so that the RMSD\nis minimized.\n*/\nvoid rmsd_align_cpu(const int N, const double *x1_raw, const double *x2_raw, double *x2_aligned_raw) {\n\n    Eigen::MatrixXd x1(N, 3);\n    Eigen::MatrixXd x2(N, 3);\n\n    for (int i = 0; i < N; i++) {\n        x1(i, 0) = x1_raw[i * 3 + 0];\n        x1(i, 1) = x1_raw[i * 3 + 1];\n        x1(i, 2) = x1_raw[i * 3 + 2];\n\n        x2(i, 0) = x2_raw[i * 3 + 0];\n        x2(i, 1) = x2_raw[i * 3 + 1];\n        x2(i, 2) = x2_raw[i * 3 + 2];\n    }\n\n    Eigen::Vector3d x1_centroid = x1.colwise().mean();\n    Eigen::Vector3d x2_centroid = x2.colwise().mean();\n    Eigen::Vector3d translation = x2_centroid - x1_centroid;\n\n    // shift to the center\n    Eigen::MatrixXd x1_centered = x1.rowwise() - x1_centroid.transpose();\n    Eigen::MatrixXd x2_centered = x2.rowwise() - x2_centroid.transpose();\n\n    // compute correlations\n    Eigen::MatrixXd c = x2_centered.transpose() * x1_centered;\n    Eigen::JacobiSVD<Eigen::MatrixXd> svd(c, Eigen::ComputeFullU | Eigen::ComputeFullV);\n    auto s = svd.singularValues();\n\n    Eigen::MatrixXd u = svd.matrixU();\n    Eigen::MatrixXd v = svd.matrixV();\n    Eigen::MatrixXd v_t = v.transpose();\n\n    bool is_reflection = u.determinant() * v_t.determinant() < 0.0;\n    if (is_reflection) {\n        for (int i = 0; i < 3; i++) {\n            u(i, 2) = -u(i, 2);\n        }\n    }\n\n    Eigen::MatrixXd rotation = u * v_t;\n\n    // x2 is centered\n    Eigen::MatrixXd x2_rot = x2_centered * rotation;\n    Eigen::MatrixXd x2_aligned = x2_rot.rowwise() - (translation.transpose() - x2_centroid.transpose());\n\n    for (int i = 0; i < N; i++) {\n        x2_aligned_raw[i * 3 + 0] = x2_aligned(i, 0);\n        x2_aligned_raw[i * 3 + 1] = x2_aligned(i, 1);\n        x2_aligned_raw[i * 3 + 2] = x2_aligned(i, 2);\n    }\n}\n\n} // namespace timemachine\n", "meta": {"hexsha": "1b1825436230e1869a2fa2067ddf33b3c4404784", "size": 2052, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "timemachine/cpp/src/rmsd_align.cpp", "max_stars_repo_name": "proteneer/timemachine", "max_stars_repo_head_hexsha": "feee9f24adcb533ab9e1c15a3f4fa4dcc9d9a701", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 91.0, "max_stars_repo_stars_event_min_datetime": "2019-01-05T17:03:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T09:08:46.000Z", "max_issues_repo_path": "timemachine/cpp/src/rmsd_align.cpp", "max_issues_repo_name": "proteneer/timemachine", "max_issues_repo_head_hexsha": "feee9f24adcb533ab9e1c15a3f4fa4dcc9d9a701", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 474.0, "max_issues_repo_issues_event_min_datetime": "2019-01-07T14:33:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T19:15:12.000Z", "max_forks_repo_path": "timemachine/cpp/src/rmsd_align.cpp", "max_forks_repo_name": "proteneer/timemachine", "max_forks_repo_head_hexsha": "feee9f24adcb533ab9e1c15a3f4fa4dcc9d9a701", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2019-01-13T00:40:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T10:23:54.000Z", "avg_line_length": 31.0909090909, "max_line_length": 104, "alphanum_fraction": 0.6047758285, "num_tokens": 682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425289753969, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.7173146386693082}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include \"../simple_lib/include/simple_layer.h\"\n\nusing namespace Eigen;\n\nint main(){\n    using std::cout;\n    using std::endl;\n    using namespace MyDL;\n\n    int batch_size = 2;\n    int num_category = 3;\n    MatrixXd X = MatrixXd::Zero(batch_size, num_category);\n    MatrixXd t = MatrixXd::Zero(batch_size, num_category);\n    double loss;\n    MatrixXd dX;\n\n    // X << 0.2, 0.3, 0.5,\n    //      0.1, 0.7, 0.2;\n    X << 1, 2, 3,\n         1, 0, 0;\n    t << 0, 0, 1,\n         1, 0, 0;\n\n    SoftmaxWithLoss loss_layer;\n\n    loss = loss_layer.forward(X, t);\n    cout << \"loss: \" << loss << endl; \n\n    dX = loss_layer.backward();\n    cout << \"gradient: \" << endl;\n    cout << dX << endl;\n\n    return 0;\n}", "meta": {"hexsha": "b0eb53bcf00ce032ae6c8b6f4d8ee493a4e2884e", "size": 743, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch5/softmax_with_loss.cpp", "max_stars_repo_name": "potedo/zeroDL_cpp", "max_stars_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-22T15:26:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-22T15:26:20.000Z", "max_issues_repo_path": "ch5/softmax_with_loss.cpp", "max_issues_repo_name": "potedo/zeroDL_cpp", "max_issues_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "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": "ch5/softmax_with_loss.cpp", "max_forks_repo_name": "potedo/zeroDL_cpp", "max_forks_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "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": 20.6388888889, "max_line_length": 58, "alphanum_fraction": 0.5612382234, "num_tokens": 244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.7173146369514549}}
{"text": "//EuropeanOption.cpp\n\n//Modification date: 6/17/15\n\n#include \"EuropeanOption.hpp\"\n#include \"GlobalFunctions.hpp\"\n#include <cmath>\n#include <iostream>\n#include <boost/math/distributions/normal.hpp>\nusing namespace std;\n\n\n\n//Operator Overloads\nEuropeanOption& EuropeanOption::operator = (const EuropeanOption& source)\n{\n\tif (this == &source)\t\t\t\t\t\t\t//check if current object and argument object are same object\n\t\treturn *this;\n\n\tOption::operator =(source);\n\n\tT = source.T;\n\t\n\treturn *this;\n}\n\nEuropeanOption& EuropeanCallOption::operator = (const EuropeanOption& source)\n{\n\tif (this == &source)\t\t\t\t\t\t\t//check if current object and argument object are same object\n\t\treturn *this;\n\n\tEuropeanOption::operator=(source);\n\treturn *this;\n}\n\nEuropeanOption& EuropeanPutOption::operator = (const EuropeanOption& source)\n{\n\tif (this == &source)\t\t\t\t\t\t\t//check if current object and argument object are same object\n\t\treturn *this;\n\n\tEuropeanOption::operator=(source);\n\treturn *this;\n}\n\nvoid EuropeanCallOption::Print() const{\n\tcout << \"Call Option data: T=\" << T << \", K=\" << K << \", sig=\" << sig << \", r=\" <<r << \", S=\" << S << \"\\n\";\n\tdouble C = CallPrice(S, K, T, r, sig, b); double P = PutPrice(S, K, T, r, sig, b);\n\tcout << \"Black Scholes Formulae: C=\" << C << \", P=\" << P << \"\\n\";\n\tcout << \"Put Call Parity: C=\" << CallPricePCP(P, S, K, T, r, b) << \", P=\" << PutPricePCP(C, S, K, T, r, b) << \"\\n\";\n\tcout << \"Delta(Call)=\" << CallDelta(S, K, T, r, sig, b) << \"\\n\";\n\tcout << \"Gamma=\" << GammaGF(S, K, T, r, sig, b) << \", Vega=\" << VegaGF(S, K, T, r, sig, b) << \"\\n\";\t\t//Gamma and Vega are the same for call and put option, given the parameters are.\n\tcout << \"Theta(Call)=\" << CallTheta(S, K, T, r, sig, b) << \"\\n\";\n\tcout << \"Rho(Call)=\" << CallRho(S, K, T, r, sig, b) << endl;\n\n\tif (PutCallParity(C, P))\t\t\t\t\t\t//calling on either type of option, as long as Option Data is the same.\n\t\tcout << \"Put Call Parity is Satisfied\\n\";\n\telse\n\t\tcout << \"Arbitrage oportunity is detected!!!!\\n\";\n\n}\n\nvoid EuropeanPutOption::Print()const {\n\tcout << \"Put Option data: T=\" << T << \", K=\" << K << \", sig=\" << sig << \", r=\" << r << \", S=\" << S << \"\\n\";\n\tdouble C = CallPrice(S, K, T, r, sig, b); double P = PutPrice(S, K, T, r, sig, b);\n\tcout << \"Black Scholes Formulae: C=\" << C << \", P=\" << P << \"\\n\";\n\tcout << \"Put Call Parity: C=\" << CallPricePCP(P, S, K, T, r, b) << \", P=\" << PutPricePCP(C, S, K, T, r, b) << \"\\n\";\n\tcout << \"Delta(Put)=\" << PutDelta(S, K, T, r, sig, b) << \"\\n\";\n\tcout << \"Gamma=\" << GammaGF(S, K, T, r, sig, b) << \", Vega=\" << VegaGF(S, K, T, r, sig, b) << \"\\n\";\t\t//Gamma and Vega are the same for call and put option, given the parameters are.\n\tcout << \"Theta(Put)=\" << PutTheta(S, K, T, r, sig, b) << \"\\n\";\n\tcout << \"Rho(Put)=\" << CallRho(S, K, T, r, sig, b) << endl;\n\n\tif (PutCallParity(C, P))\t\t\t\t\t\t//calling on either type of option, as long as Option Data is the same.\n\t\tcout << \"Put Call Parity is Satisfied\\n\";\n\telse\n\t\tcout << \"Arbitrage oportunity is detected!!!!\\n\";\n\n}\n\n\n//Pricing option functions\n\nstd::vector<double> EuropeanCallOption::Price(double LowerLimit, double UpperLimit, int Num, FunctionPointer Ptr)\n{\n\tvector<double> mesh = MeshArray(LowerLimit, UpperLimit, Num);\n\t\n\tvector<double> result;\n\tresult.reserve(mesh.size());\n\t\n\tfor (vector<double>::iterator it = mesh.begin(); it != mesh.end(); ++it)\n\t{\n\t\tresult.push_back((this->*Ptr)(*it));\t\t//Calculate result using function pointer. Current value of vector element is taken as an argument.\n\t}\n\treturn result;\n}\n\nstd::vector<double> EuropeanPutOption::Price(double LowerLimit, double UpperLimit, int Num, FunctionPointer Ptr)\n{\n\tvector<double> mesh = MeshArray(LowerLimit, UpperLimit, Num);\n\n\tvector<double> result;\n\tresult.reserve(mesh.size());\n\n\tfor (vector<double>::iterator it = mesh.begin(); it != mesh.end(); ++it)\n\t{\n\t\tresult.push_back((this->*Ptr)(*it));\n\t}\n\treturn result;\n}\n\nbool EuropeanOption::PutCallParity(double C, double P)const\n{\n\tstatic const double epsilon = 0.00001;\n\n\tif ((C + K*exp(-r*T) - P - S*exp((b - r)*T)) > epsilon)\n\t{\t\t\n\t\treturn false;\n\t}\n\telse\n\t{\n\t\treturn true;\n\t}\n}\n", "meta": {"hexsha": "44f20287d9beb9e7e2675b2152d6f9e4c37ea1d6", "size": 4063, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "EuropeanOption.cpp", "max_stars_repo_name": "IlyaKul/OptionPricers", "max_stars_repo_head_hexsha": "4907e77994e75697ba7673673536c0312cd1e063", "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": "EuropeanOption.cpp", "max_issues_repo_name": "IlyaKul/OptionPricers", "max_issues_repo_head_hexsha": "4907e77994e75697ba7673673536c0312cd1e063", "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": "EuropeanOption.cpp", "max_forks_repo_name": "IlyaKul/OptionPricers", "max_forks_repo_head_hexsha": "4907e77994e75697ba7673673536c0312cd1e063", "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.0325203252, "max_line_length": 182, "alphanum_fraction": 0.6192468619, "num_tokens": 1226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711756575749, "lm_q2_score": 0.8438950966654772, "lm_q1q2_score": 0.7172865074444185}}
{"text": "#define BOOST_TEST_MODULE \"JosephusModule\"\n#include <boost/test/unit_test.hpp>\n#include <boost/test/unit_test_parameters.hpp>\n\n#include \"Josephus.h\"\n#include <list>\n#include <vector>\n\n\nBOOST_AUTO_TEST_CASE(ERASE_VECTOR_AT_INDEX)\n{\n\tboost::unit_test::unit_test_log.set_threshold_level(boost::unit_test::log_all_errors);\n\tBOOST_TEST_MESSAGE(\"Test the erasing vector at index of\");\n\n\tstd::vector<int> vec1{ 1,2,3,4,5,6 };\n\teraseVectorAtIndex(vec1, 2); // removes the 3 at index 2\n\n\tBOOST_CHECK(vec1.at(0) == 1);\n\tBOOST_CHECK(vec1.at(1) == 2);\n\tBOOST_CHECK(vec1.at(2) == 4);\n\tBOOST_CHECK(vec1.at(3) == 5);\n\tBOOST_CHECK(vec1.at(4) == 6);\n}\n\n\nBOOST_AUTO_TEST_CASE( JOSEPHUS_TEST_N5K2 )\n{\n\tboost::unit_test::unit_test_log.set_threshold_level(boost::unit_test::log_all_errors);\n\tint N = 5;\n\tint K = 2;\n\tBOOST_TEST_MESSAGE(\"Test the Josephus Algorithm with N=\" << N << \" and K= \" << K << \" !!!\");\n\n\tstd::vector<int> evadedVectorList;\n\tint remainder = Josephus(N, K, evadedVectorList);\n\t/// 1 2 3 4 5 => 1 3 4 5 => 1 3 5 (1. durchlauf vorbei) => 3 5 => 3\n\t// sol : 2 4 1 5 , rem=3\n\t// math.sol: remainder = 1001 => 00011 = 3\n\n\tBOOST_CHECK(evadedVectorList.at(0) == 2);\n\tBOOST_CHECK(evadedVectorList.at(1) == 4);\n\tBOOST_CHECK(evadedVectorList.at(2) == 1);\n\tBOOST_CHECK(evadedVectorList.at(3) == 5);\n\n\tBOOST_CHECK(remainder == 3);\n} \n\n\n\nBOOST_AUTO_TEST_CASE(JOSEPHUS_TEST_N5K11)\n{\n\tboost::unit_test::unit_test_log.set_threshold_level(boost::unit_test::log_all_errors);\n\tint N = 5;\n\tint K = 11;\n\tBOOST_TEST_MESSAGE(\"Test the Josephus Algorithm with N=\" << N << \" and K= \"<< K <<\" !!!\");\n\n\tstd::vector<int> evadedVectorList;\n\tint remainder = Josephus(N, K, evadedVectorList);\n\t// sol : 1  4 2 3  rem 5\n\t// math.sol: remainder = 5^1 + 5^0 = 5 rem = 5\n\n\tBOOST_CHECK(evadedVectorList.at(0) == 1);\n\tBOOST_CHECK(evadedVectorList.at(1) == 4);\n\tBOOST_CHECK(evadedVectorList.at(2) == 2);\n\tBOOST_CHECK(evadedVectorList.at(3) == 3);\n\n\tBOOST_CHECK(remainder == 5);\n}\n\n\nBOOST_AUTO_TEST_CASE(JOSEPHUS_TEST_N13K2)\n{\n\tboost::unit_test::unit_test_log.set_threshold_level(boost::unit_test::log_all_errors);\n\tint N = 13;\n\tint K = 2;\n\tBOOST_TEST_MESSAGE(\"Test the Josephus Algorithm with N=\" << N << \" and K= \" << K << \" !!!\");\n\n\tstd::vector<int> evadedVectorList;\n\tint remainder = Josephus(N, K, evadedVectorList);\n\t/// 11\n\t// sol : 2 4 6 8 10 12 (all even positions done) 1 5 9 13 7 3 rem 11\n\t// math.sol: remainder = 1101 => 1011 = 11 \n\n\tBOOST_CHECK(evadedVectorList.at(0) == 2);\n\tBOOST_CHECK(evadedVectorList.at(1) == 4);\n\tBOOST_CHECK(evadedVectorList.at(2) == 6);\n\tBOOST_CHECK(evadedVectorList.at(3) == 8);\n\tBOOST_CHECK(evadedVectorList.at(4) == 10);\n\tBOOST_CHECK(evadedVectorList.at(5) == 12);\n\tBOOST_CHECK(evadedVectorList.at(6) == 1);\n\tBOOST_CHECK(evadedVectorList.at(7) == 5);\n\tBOOST_CHECK(evadedVectorList.at(8) == 9);\n\tBOOST_CHECK(evadedVectorList.at(9) == 13);\n\tBOOST_CHECK(evadedVectorList.at(10) == 7);\n\tBOOST_CHECK(evadedVectorList.at(11) == 3);\n\n\tBOOST_CHECK(remainder == 11);\n}\n\n\n\nBOOST_AUTO_TEST_CASE(JOSEPHUS_TEST_N13K3)\n{\n\tboost::unit_test::unit_test_log.set_threshold_level(boost::unit_test::log_all_errors);\n\tint N = 13;\n\tint K = 3;\n\tBOOST_TEST_MESSAGE(\"Test the Josephus Algorithm with N=\" << N << \" and K= \" << K << \" !!!\");\n\n\tstd::vector<int> evadedVectorList;\n\tint remainder = Josephus(N, K, evadedVectorList);\n\t///  \n\t// sol: 3 6 9 12 2  7  11  4 10 5  1  8 rem 13\n\n\t// math.sol: remainder = 3^2 + 3^1 + 3^0 = 13 so rem is 13\n\n\n\tBOOST_CHECK(evadedVectorList.at(0) == 3);\n\tBOOST_CHECK(evadedVectorList.at(1) == 6);\n\tBOOST_CHECK(evadedVectorList.at(2) == 9);\n\tBOOST_CHECK(evadedVectorList.at(3) == 12);\n\tBOOST_CHECK(evadedVectorList.at(4) == 2);\n\tBOOST_CHECK(evadedVectorList.at(5) == 7);\n\tBOOST_CHECK(evadedVectorList.at(6) == 11);\n\tBOOST_CHECK(evadedVectorList.at(7) == 4);\n\tBOOST_CHECK(evadedVectorList.at(8) == 10);\n\tBOOST_CHECK(evadedVectorList.at(9) == 5);\n\tBOOST_CHECK(evadedVectorList.at(10) == 1);\n\tBOOST_CHECK(evadedVectorList.at(11) == 8);\n\n\tBOOST_CHECK(remainder == 13);\n}\n", "meta": {"hexsha": "f56faa3698f25d5297ba33f2c8db943a7166b682", "size": 3977, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tests/JosephusTest.cc", "max_stars_repo_name": "RobertHue/JosephusProblem", "max_stars_repo_head_hexsha": "f4dcf95f21fb11c460832b2eab94da86d6048959", "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/JosephusTest.cc", "max_issues_repo_name": "RobertHue/JosephusProblem", "max_issues_repo_head_hexsha": "f4dcf95f21fb11c460832b2eab94da86d6048959", "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/JosephusTest.cc", "max_forks_repo_name": "RobertHue/JosephusProblem", "max_forks_repo_head_hexsha": "f4dcf95f21fb11c460832b2eab94da86d6048959", "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.358778626, "max_line_length": 93, "alphanum_fraction": 0.6924817702, "num_tokens": 1312, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711642563823, "lm_q2_score": 0.8438950947024555, "lm_q1q2_score": 0.7172864961544961}}
{"text": "/*    This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.\n *    See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.\n *    Author(s):       Vincent Rouvreau\n *\n *    Copyright (C) 2017 Inria\n *\n *    Modification(s):\n *      - YYYY/MM Author: Description of the modification\n */\n\n#include <gudhi/Alpha_complex.h>\n#include <gudhi/Rips_complex.h>\n#include <gudhi/distance_functions.h>\n#include <gudhi/Simplex_tree.h>\n#include <gudhi/Persistent_cohomology.h>\n#include <gudhi/Points_off_io.h>\n#include <gudhi/Bottleneck.h>\n\n#include <CGAL/Epick_d.h>\n\n#include <boost/program_options.hpp>\n\n#include <string>\n#include <vector>\n#include <limits>  // infinity\n#include <utility>  // for pair\n#include <algorithm>  // for transform\n\n\n// Types definition\nusing Simplex_tree = Gudhi::Simplex_tree<Gudhi::Simplex_tree_options_fast_persistence>;\nusing Filtration_value = Simplex_tree::Filtration_value;\nusing Rips_complex = Gudhi::rips_complex::Rips_complex<Filtration_value>;\nusing Field_Zp = Gudhi::persistent_cohomology::Field_Zp;\nusing Persistent_cohomology = Gudhi::persistent_cohomology::Persistent_cohomology<Simplex_tree, Field_Zp >;\nusing Kernel = CGAL::Epick_d< CGAL::Dynamic_dimension_tag >;\nusing Point_d = Kernel::Point_d;\nusing Points_off_reader = Gudhi::Points_off_reader<Point_d>;\n\nvoid program_options(int argc, char * argv[]\n                     , std::string & off_file_points\n                     , Filtration_value & threshold\n                     , int & dim_max\n                     , int & p\n                     , Filtration_value & min_persistence);\n\nstatic inline std::pair<double, double> compute_root_square(std::pair<double, double> input) {\n  return std::make_pair(std::sqrt(input.first), std::sqrt(input.second));\n}\n\nint main(int argc, char * argv[]) {\n  std::string off_file_points;\n  Filtration_value threshold;\n  int dim_max;\n  int p;\n  Filtration_value min_persistence;\n\n  program_options(argc, argv, off_file_points, threshold, dim_max, p, min_persistence);\n\n  Points_off_reader off_reader(off_file_points);\n\n  // --------------------------------------------\n  // Rips persistence\n  // --------------------------------------------\n  Rips_complex rips_complex(off_reader.get_point_cloud(), threshold, Gudhi::Euclidean_distance());\n\n  // Construct the Rips complex in a Simplex Tree\n  Simplex_tree rips_stree;\n\n  rips_complex.create_complex(rips_stree, dim_max);\n  std::cout << \"The Rips complex contains \" << rips_stree.num_simplices() << \" simplices and has dimension \"\n            << rips_stree.dimension() << \" \\n\";\n\n  // Sort the simplices in the order of the filtration\n  rips_stree.initialize_filtration();\n\n  // Compute the persistence diagram of the complex\n  Persistent_cohomology rips_pcoh(rips_stree);\n  // initializes the coefficient field for homology\n  rips_pcoh.init_coefficients(p);\n  rips_pcoh.compute_persistent_cohomology(min_persistence);\n\n  // rips_pcoh.output_diagram();\n\n  // --------------------------------------------\n  // Alpha persistence\n  // --------------------------------------------\n  Gudhi::alpha_complex::Alpha_complex<Kernel> alpha_complex(off_reader.get_point_cloud());\n\n  Simplex_tree alpha_stree;\n  alpha_complex.create_complex(alpha_stree, threshold * threshold);\n  std::cout << \"The Alpha complex contains \" << alpha_stree.num_simplices() << \" simplices and has dimension \"\n            << alpha_stree.dimension() << \" \\n\";\n\n  // Sort the simplices in the order of the filtration\n  alpha_stree.initialize_filtration();\n\n  // Compute the persistence diagram of the complex\n  Persistent_cohomology alpha_pcoh(alpha_stree);\n  // initializes the coefficient field for homology\n  alpha_pcoh.init_coefficients(p);\n  alpha_pcoh.compute_persistent_cohomology(min_persistence * min_persistence);\n\n  // alpha_pcoh.output_diagram();\n\n  // --------------------------------------------\n  // Bottleneck distance between both persistence\n  // --------------------------------------------\n  double max_b_distance {};\n  for (int dim = 0; dim < dim_max; dim ++) {\n    std::vector< std::pair< Filtration_value , Filtration_value > > rips_intervals;\n    std::vector< std::pair< Filtration_value , Filtration_value > > alpha_intervals;\n    rips_intervals = rips_pcoh.intervals_in_dimension(dim);\n    alpha_intervals = alpha_pcoh.intervals_in_dimension(dim);\n    std::transform(alpha_intervals.begin(), alpha_intervals.end(), alpha_intervals.begin(), compute_root_square);\n\n    double bottleneck_distance = Gudhi::persistence_diagram::bottleneck_distance(rips_intervals, alpha_intervals);\n    std::cout << \"In dimension \" << dim << \", bottleneck distance = \" << bottleneck_distance << std::endl;\n    if (bottleneck_distance > max_b_distance)\n      max_b_distance = bottleneck_distance;\n  }\n  std::cout << \"================================================================================\" << std::endl;\n  std::cout << \"Bottleneck distance is \" << max_b_distance << std::endl;\n\n  return 0;\n}\n\nvoid program_options(int argc, char * argv[]\n                     , std::string & off_file_points\n                     , Filtration_value & threshold\n                     , int & dim_max\n                     , int & p\n                     , Filtration_value & min_persistence) {\n  namespace po = boost::program_options;\n  po::options_description hidden(\"Hidden options\");\n  hidden.add_options()\n      (\"input-file\", po::value<std::string>(&off_file_points),\n       \"Name of an OFF file containing a point set.\\n\");\n\n  po::options_description visible(\"Allowed options\", 100);\n  visible.add_options()\n      (\"help,h\", \"produce help message\")\n      (\"max-edge-length,r\",\n       po::value<Filtration_value>(&threshold)->default_value(std::numeric_limits<Filtration_value>::infinity()),\n       \"Maximal length of an edge for the Rips complex construction.\")\n      (\"cpx-dimension,d\", po::value<int>(&dim_max)->default_value(1),\n       \"Maximal dimension of the Rips complex we want to compute.\")\n      (\"field-charac,p\", po::value<int>(&p)->default_value(11),\n       \"Characteristic p of the coefficient field Z/pZ for computing homology.\")\n      (\"min-persistence,m\", po::value<Filtration_value>(&min_persistence),\n       \"Minimal lifetime of homology feature to be recorded. Default is 0. Enter a negative value to see zero length intervals\");\n\n  po::positional_options_description pos;\n  pos.add(\"input-file\", 1);\n\n  po::options_description all;\n  all.add(visible).add(hidden);\n\n  po::variables_map vm;\n  po::store(po::command_line_parser(argc, argv).\n            options(all).positional(pos).run(), vm);\n  po::notify(vm);\n\n  if (vm.count(\"help\") || !vm.count(\"input-file\")) {\n    std::cout << std::endl;\n    std::cout << \"Compute the persistent homology with coefficient field Z/pZ \\n\";\n    std::cout << \"of a Rips complex defined on a set of input points.\\n \\n\";\n    std::cout << \"The output diagram contains one bar per line, written with the convention: \\n\";\n    std::cout << \"   p   dim b d \\n\";\n    std::cout << \"where dim is the dimension of the homological feature,\\n\";\n    std::cout << \"b and d are respectively the birth and death of the feature and \\n\";\n    std::cout << \"p is the characteristic of the field Z/pZ used for homology coefficients.\" << std::endl << std::endl;\n\n    std::cout << \"Usage: \" << argv[0] << \" [options] input-file\" << std::endl << std::endl;\n    std::cout << visible << std::endl;\n    exit(-1);\n  }\n}\n", "meta": {"hexsha": "6c0dc9bf3145c2813d50c0aafac35a1b7fcd2b67", "size": 7445, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Bottleneck_distance/example/alpha_rips_persistence_bottleneck_distance.cpp", "max_stars_repo_name": "jmarino/gudhi-devel", "max_stars_repo_head_hexsha": "b1824e4de6fd1d037af3c1341c3065731472ffc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-27T03:32:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-14T21:14:14.000Z", "max_issues_repo_path": "src/Bottleneck_distance/example/alpha_rips_persistence_bottleneck_distance.cpp", "max_issues_repo_name": "jmarino/gudhi-devel", "max_issues_repo_head_hexsha": "b1824e4de6fd1d037af3c1341c3065731472ffc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-08-25T16:03:23.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-28T07:36:21.000Z", "max_forks_repo_path": "src/Bottleneck_distance/example/alpha_rips_persistence_bottleneck_distance.cpp", "max_forks_repo_name": "jmarino/gudhi-devel", "max_forks_repo_head_hexsha": "b1824e4de6fd1d037af3c1341c3065731472ffc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-11-06T12:36:23.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-25T14:53:13.000Z", "avg_line_length": 41.5921787709, "max_line_length": 129, "alphanum_fraction": 0.6632639355, "num_tokens": 1792, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122288794595, "lm_q2_score": 0.7905303211371898, "lm_q1q2_score": 0.7172578276677786}}
{"text": "/*! \\file demo_Hoaglin.cpp\n  \\brief Demonstration of Boxplot quartile options. Boxplots appear different depending the choice of definition for the quartile.\n\n  \\details\n    \"Some Implementations of the Boxplot\"\n    Michael Frigge, David C. Hoaglin and Boris Iglewicz\n    The American Statistician, Vol. 43, No. 1 (Feb., 1989), pp. 50-54\n    discusses the design of the boxplot.\n\n    However the plot of their example data shown below shows the considerable variation in the appearance of the same data,\n    using different definitions of quartiles used in various popular statistics packages.\n\n    One obvious conclusion is that you should not expect boxplots to look the same when using more than one program.\n\n    Boost.Plot provides 5 popular definitions for the quartiles.\n    This should allow the user to produce plots that look similar to boxplots from most statistics plotting program.\n    To confuse matter further, most have their own default definition *and* options to chose other definitions:\n    these options are shown below as type, method, PCTLDEF.\n\n    The interquartile range is calculated using the 1st \\& 3rd sample quartiles,\n    but there are various ways to calculate those quartiles, summarised in\n    Rob J. Hyndman and Yanan Fan, 1996, \"Sample Quantiles in Statistical Packages\",\n    The American Statistician 50(4):361-365, (1996).\n\n    The interquartile range, often called IQR is quartile 3 (p = 3/4) - quartile 1 (1/4).\n    The median is the 2nd quartile (p = 2/4 = 1/2).\n\n    Five of Hyndman and Fan's sample quantile definitions have a particularly simple common form\n    selected according to which definition of m is chosen in function quantiles.\n    This is implemented in function quantiles by parameter `HF_definition`:\n\n      double quantile(vector<double>& data, double p, int HF_definition = 8);\n\n    The default definition is that recommended by Hyndman and Fan, or\n    users can select which definition is used for all boxplots, or individual data series as shown in the example below.\n\n       my_boxplot.quartile_definition(5); // All plots\n\n       my_boxplot.plot.quartile_definition(7); // Just this data series plot.\n\n    Hyndman and Fan definitions 4 to 8 are used by the following packages:\n\n    * #4 SAS (PCTLDEF=1), R (type=4), Maple (method=3)\n    * #5 R (type=5), Maple (method=4), Wolfram Mathematica quartiles.\n    * #6 Minitab, SPSS, BMDP, JMP, SAS (PCTLDEF=4), R(type=6), Maple (method=5).\n    * #7 Excel, S-Plus, R (type=7[default]), Maxima, Maple (method=6).\n    * #8 H&F 8: R (type=8), Maple (method=7[default]).\n\n    Some observations on the various options are:\n\n    * #4 Often a moderate interquartile range.\n\n    * #5 Symmetric linear interpolation: a common choice when the data represent a sample\n    from a continuous distribution and you want an unbiased estimate of the quartiles of that distribution.\n\n    * #6 This \"half\" sample excludes the sample median (k observations) for odd n (=2*k+1).\n    This will tend to be a better estimate for the population quartiles,\n    but will tend to give quartile estimates that are a bit too far\n    from the center of the whole sample (too wide an interquartile range).\n\n    * #7 Smallest interquartile range, so flags most outliers.\n    For a continuous distribution,\n    this will tend to give too narrow an interquartile range,\n    since there will tend to be a small fraction of the population beyond the extreme\n    sample observations. In particular, for odd n (=2*k+1), Excel calculates the\n    1st (3rd) quartile as the median of the lower (upper) \"half\" of the sample\n    including the sample median (k+1 observations).\n\n    * #8 recommended by H&F because it is\n    approximately median-unbaised estimate regardless of distribution\n    and thus suitable for continuous and discrete distributions.\n    which gives quartiles between those reported by Minitab and Excel.\n    This approach is approximately median unbiased for continuous distributions.\n    Slightly higher interquartile range than definition 7.\n\n    The 'fences' beyond which points are regarded as outliers, or extreme outliers,\n    are a multiplying factor, usually called k, and usually 1.5 * interquartile range,\n    and 3 * interquartile range as recommended by Hoaglin et al.\n\n  \\author Paul A Bristow\n*/\n\n// Copyright Jacob Voytko 2007\n// Copyright Paul A. Bristow 2008\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// An example to demonstrate the implementation of boxplot.\n\n// This file is written to be included from a Quickbook .qbk document.\n// It can be compiled by the C++ compiler, and run. Any output can\n// also be added here as comment or included or pasted in elsewhere.\n\n// Caution: this file contains Quickbook markup as well as code\n// and comments: don't change any of the special comment markups!\n\n//[demo_Hoaglin_1\n\n/*`\n\n\"Some Implementations of the Boxplot\"\nMichael Frigge, David C. Hoaglin and Boris Iglewicz\nThe American Statistician, Vol. 43, No. 1 (Feb., 1989), pp. 50-54\ndiscusses the design of the boxplot.\n\nHowever the plot of their example data shown below shows the considerable variation in the appearance of the same data,\nusing different definitions of quartiles used in various popular statistics packages.\n\nOne obvious conclusion is that you should not expect boxplots to look the same when using more than one program.\n\nBoost.Plot provides 5 popular definitions for the quartiles.\nThis should allow the user to produce plots that look similar to boxplots from most statistics plotting program.\nTo confuse matter further, most have their own default definition *and* options to chose other definitions:\nthese options are shown below as type, method, PCTLDEF.\n\nThe interquartile range is calculated using the 1st & 3rd sample quartiles,\nbut there are various ways to calculate those quartiles, summarised in\nRob J. Hyndman and Yanan Fan, 1996, \"Sample Quantiles in Statistical Packages\",\nThe American Statistician 50(4):361-365, (1996).\n\nThe interquartile range, often called IQR is quartile 3 (p = 3/4) - quartile 1 (1/4).\nThe median is the 2nd quartile (p = 2/4 = 1/2).\n\nFive of Hyndman and Fan's sample quantile definitions have a particularly simple common form\nselected according to which definition of m is chosen in function quantiles.\nThis is implemented in function quantiles by parameter `HF_definition`:\n\n  double quantile(vector<double>& data, double p, int HF_definition = 8);\n\nThe default definition is that recommended by Hyndman and Fan, or\nusers can select which definition is used for all boxplots, or individual data series as shown in the example below.\n\n   my_boxplot.quartile_definition(5); // All plots\n\n   my_boxplot.plot.quartile_definition(7); // Just this data series plot.\n\nHyndman and Fan definitions 4 to 8 are used by the following packages:\n\n* #4 SAS (PCTLDEF=1), R (type=4), Maple (method=3)\n* #5 R (type=5), Maple (method=4), Wolfram Mathematica quartiles.\n* #6 Minitab, SPSS, BMDP, JMP, SAS (PCTLDEF=4), R(type=6), Maple (method=5).\n* #7 Excel, S-Plus, R (type=7[default]), Maxima, Maple (method=6).\n* #8 H&F 8: R (type=8), Maple (method=7[default]).\n\nSome observations on the various options are:\n\n* #4 Often a moderate interquartile range.\n\n* #5 Symmetric linear interpolation: a common choice when the data represent a sample\nfrom a continuous distribution and you want an unbiased estimate of the quartiles of that distribution.\n\n* #6 This \"half\" sample excludes the sample median (k observations) for odd n (=2*k+1).\nThis will tend to be a better estimate for the population quartiles,\nbut will tend to give quartile estimates that are a bit too far\nfrom the center of the whole sample (too wide an interquartile range).\n\n* #7 Smallest interquartile range, so flags most outliers.\nFor a continuous distribution,\nthis will tend to give too narrow an interquartile range,\nsince there will tend to be a small fraction of the population beyond the extreme\nsample observations. In particular, for odd n (=2*k+1), Excel calculates the\n1st (3rd) quartile as the median of the lower (upper) \"half\" of the sample\nincluding the sample median (k+1 observations).\n\n* #8 recommended by H&F because it is\napproximately median-unbaised estimate regardless of distribution\nand thus suitable for continuous and discrete distributions.\nwhich gives quartiles between those reported by Minitab and Excel.\nThis approach is approximately median unbiased for continuous distributions.\nSlightly higher interquartile range than definition 7.\n\nThe 'fences' beyond which points are regarded as outliers, or extreme outliers,\nare a multiplying factor, usually called k, and usually 1.5 * interquartile range,\nand 3 * interquartile range as recommended by Hoaglin et al.\n\n*/\n\n#include <vector>\nusing std::vector;\n#include <cmath>\nusing ::sin;\n//#include <boost/assert.hpp> // for BOOST_ASSERT\n#include <boost/svg_plot/svg_boxplot.hpp>\n\n#include <boost/svg_plot/quantile.hpp>\nusing boost::svg::quantile;\n\n// double boost::svg::quantile(vector<double>& data, double p, int HF_definition);\n// Estimate pth quantile of data using one of 5 definitions.\n// Default HF_definition is the recommendation of Hyndman and Fan, definition #8.\n\n#include <boost/array.hpp>\n  using boost::array;\n\n#include <iostream>\nusing std::cout;\nusing std::endl;\n//] [demo_Hoaglin_1]\n\nint main()\n{\n  using namespace boost::svg;\n  try\n  {\n//[demo_Hoaglin_2]\n  // 11 values from Hoaglin et al page 50.\n  const boost::array<double, 11> Hoaglin_data = {53., 56., 75., 81., 82., 85., 87., 89., 95., 99., 100.};\n  //                                                       q1           median           q3\n\n  vector<double> Hoaglin(Hoaglin_data.begin(), Hoaglin_data.end());\n  for (int def = 4; def <= 8; def++)\n  { // All the F&Y definitions of quartiles.\n    double q1 = quantile(Hoaglin, 0.25, def); // 75\n    double q2 = quantile(Hoaglin, 0.5, def); // 85\n    double q3 = quantile(Hoaglin, 0.75, def); // 95\n    cout << \"Hoaglin definition #\" << def << \", q1 \" << q1\n      << \", q2 \" << q2 << \", q3 \" << q3 << \", IQR \" << q3 - q1 << endl;\n  } // for\n\n  // Same data copied for different data series.\n  vector<double> Hoaglin4(Hoaglin_data.begin(), Hoaglin_data.end());\n  vector<double> Hoaglin5(Hoaglin_data.begin(), Hoaglin_data.end());\n  vector<double> Hoaglin6(Hoaglin_data.begin(), Hoaglin_data.end());\n  vector<double> Hoaglin7(Hoaglin_data.begin(), Hoaglin_data.end());\n  vector<double> Hoaglin8(Hoaglin_data.begin(), Hoaglin_data.end());\n\n  svg_boxplot H_boxplot;\n\n  /*`Show the quartile definition default.\n*/\n    cout << \"Default boxplot.quartile_definition() = \" << H_boxplot.quartile_definition() << endl; // 8\n\n/*` Add title, labels, range etc to the whole boxplot:\n*/\n  H_boxplot  // Title and axes labels.\n    .title(\"Hoaglin Example Data\")\n    .x_label(\"Boxplot\")\n    .y_label(\"Value\")\n    .y_range(45, 115)  // Y-Axis range.\n    .y_minor_tick_length(2)\n    .y_major_interval(10);\n\n/*`Add a few setting to the plot including setting quartile definition (though is actually same as the default 8),\nand show that the value is stored.\n*/\n    svg_boxplot& b = H_boxplot.median_values_on(true)\n    .outlier_values_on(true)\n    .extreme_outlier_values_on(true)\n    .quartile_definition(8);\n/*`Show the quartile definition just assigned:\n*/\n    cout << \"boxplot.quartile_definition() = \" << b.quartile_definition() << endl; // 8\n\n/*`Add a data series container, and labels, to the plot using the whole boxplot quartile definition set.\n*/\n    H_boxplot.plot(Hoaglin_data, \"default_8\");\n\n/*`Add another data series container, and the labels, to the plot, and select a *different* quartile definition.\n*/\n\n    svg_boxplot_series& d4 =\n    H_boxplot.plot(Hoaglin4, \"def #4\")\n    .whisker_length(4.)\n    .quartile_definition(4);\n\n/*`Show the quartile definition just assigned to the this data series.\n*/\n  cout << \"boxplot_series.quartile_definition() = \" << d4.quartile_definition() << endl; // 4\n\n/*`Add yet more data series container, and the labels, to the plot, and select a *different* quartile definition for each.\n*/    H_boxplot.plot(Hoaglin5, \"def #5\")\n    .whisker_length(5.)\n    .quartile_definition(5);\n\n    H_boxplot.plot(Hoaglin6, \"def #6\")\n    .whisker_length(6.)\n    .quartile_definition(6);\n\n    H_boxplot.plot(Hoaglin6, \"def #7\")\n    .whisker_length(7.)\n    .quartile_definition(7);\n\n    H_boxplot.plot(Hoaglin6, \"def #8\")\n    .whisker_length(8.)\n    .quartile_definition(8);\n\n/*`Write the entire SVG plot to a file.\n*/\n  H_boxplot.write(\"demo_Hoaglin.svg\");\n//] [demo_Hoaglin_2]\n  }\n  catch(const std::exception& e)\n  {\n    std::cout <<\n      \"\\n\"\"Message from thrown exception was:\\n  \" << e.what() << std::endl;\n  }\n  return 0;\n} // int main()\n\n/*\n\nOutput:\n\n//[demo_Hoaglin_output\n\n``Autorun \"j:\\Cpp\\SVG\\debug\\demo_Hoaglin.exe\"\nHoaglin definition #4, q1 70.25, q2 83.5, q3 90.5, IQR 20.25\nHoaglin definition #5, q1 76.5, q2 85, q3 93.5, IQR 17\nHoaglin definition #6, q1 75, q2 85, q3 95, IQR 20\nHoaglin definition #7, q1 78, q2 85, q3 92, IQR 14\nHoaglin definition #8, q1 76, q2 85, q3 94, IQR 18\nDefault boxplot.quartile_definition() = 8\nboxplot.quartile_definition() = 8\nboxplot_series.quartile_definition() = 4\n``\n//] [demo_Hoaglin_output]\n\n\n*/\n\n", "meta": {"hexsha": "12325d62b531729eabd91850dd162f42eb8c9f32", "size": 13324, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/demo_Hoaglin.cpp", "max_stars_repo_name": "pabristow/svg_plot", "max_stars_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2016-03-09T03:23:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T14:02:07.000Z", "max_issues_repo_path": "example/demo_Hoaglin.cpp", "max_issues_repo_name": "pabristow/svg_plot", "max_issues_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2018-03-05T14:39:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-22T09:00:33.000Z", "max_forks_repo_path": "example/demo_Hoaglin.cpp", "max_forks_repo_name": "pabristow/svg_plot", "max_forks_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2016-11-04T14:36:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-17T08:12:03.000Z", "avg_line_length": 41.1234567901, "max_line_length": 130, "alphanum_fraction": 0.7266586611, "num_tokens": 3622, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527869325345, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.7171957029064242}}
{"text": "#include <cassert>\n#include <boost/numeric/ublas/lu.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n#include \"geometry/matrix.h\"\n\nnamespace gca {\n\n  int determinant_sign(const ublas::permutation_matrix<std ::size_t>& pm) {\n    int pm_sign=1;\n    std::size_t size = pm.size();\n    for (std::size_t i = 0; i < size; ++i)\n      if (i != pm(i))\n\tpm_sign *= -1.0; // swap_rows would swap a pair of rows here, so we change sign\n    return pm_sign;\n  }\n\n  double determinant(matrix& m) {\n    ublas::permutation_matrix<size_t> pm(m.size1());\n    double det = 1.0;\n    if( lu_factorize(m,pm) ) {\n      det = 0.0;\n    } else {\n      for(int i = 0; i < m.size1(); i++)\n\tdet *= m(i,i); // multiply by elements on diagonal\n      det = det * determinant_sign( pm );\n    }\n    return det;\n  }\n\n  double determinant(const matrix& m) {\n    matrix l = m;\n    return determinant(l);\n  }\n\n  matrix inverse(matrix& a) {\n    matrix a_inv = ublas::identity_matrix<double>(a.size1());\n    ublas::permutation_matrix<size_t> pm(a.size1());\n    int res = lu_factorize(a, pm);\n    if (!res) {\n      lu_substitute(a, pm, a_inv);\n    } else {\n      std::cout << a << std::endl;\n      std::cout << \"Singular matrix!\" << std::endl;\n      assert(false);\n    }\n    return a_inv;\n  }\n\n  matrix inverse(const matrix& a) {\n    matrix b = a;\n    return inverse(b);\n  }\n\n  using namespace gca;\n\n  matrix\n  plane_basis_rotation(const point at, const point bt, const point ct,\n\t\t       const point apt, const point bpt, const point cpt) {\n    matrix a(3, 3);\n    a(0, 0) = at.x;\n    a(1, 0) = at.y;\n    a(2, 0) = at.z;\n\n    a(0, 1) = bt.x;\n    a(1, 1) = bt.y;\n    a(2, 1) = bt.z;\n\n    a(0, 2) = ct.x;\n    a(1, 2) = ct.y;\n    a(2, 2) = ct.z;\n  \n    matrix b(3, 3);\n    b(0, 0) = apt.x;\n    b(1, 0) = apt.y;\n    b(2, 0) = apt.z;\n\n    b(0, 1) = bpt.x;\n    b(1, 1) = bpt.y;\n    b(2, 1) = bpt.z;\n\n    b(0, 2) = cpt.x;\n    b(1, 2) = cpt.y;\n    b(2, 2) = cpt.z;\n\n    auto a_inv = inverse(a);\n    return prod(b, a_inv);\n  }\n\n  vec\n  to_vector(const point p) {\n    vec v(3);\n    v(0) = p.x;\n    v(1) = p.y;\n    v(2) = p.z;\n    return v;\n  }\n\n  point from_vector(ublas::vector<double> v) {\n    return point(v(0), v(1), v(2));\n  }\n\n  vec\n  plane_basis_displacement(const matrix& r,\n\t\t\t   const point u1, const point u2, const point u3,\n\t\t\t   const point q1, const point q2, const point q3,\n\t\t\t   const point p1, const point p2, const point p3) {\n    vec uv1 = to_vector(u1);\n    vec uv2 = to_vector(u2);\n    vec uv3 = to_vector(u3);\n\n    vec qv1 = to_vector(q1);\n    vec qv2 = to_vector(q2);\n    vec qv3 = to_vector(q3);\n\n    vec pv1 = to_vector(p1);\n    vec pv2 = to_vector(p2);\n    vec pv3 = to_vector(p3);\n\n    vec s(3);\n    s(0) = inner_prod(qv1, uv1) - inner_prod(prod(r, pv1), uv1);\n    s(1) = inner_prod(qv2, uv2) - inner_prod(prod(r, pv2), uv2);\n    s(2) = inner_prod(qv3, uv3) - inner_prod(prod(r, pv3), uv3);\n\n    matrix u(3, 3);\n    u(0, 0) = uv1(0);\n    u(0, 1) = uv1(1);\n    u(0, 2) = uv1(2);\n\n    u(1, 0) = uv2(0);\n    u(1, 1) = uv2(1);\n    u(1, 2) = uv2(2);\n\n    u(2, 0) = uv3(0);\n    u(2, 1) = uv3(1);\n    u(2, 2) = uv3(2);\n\n    auto u_inv = inverse(u);\n\n    return prod(u_inv, s);\n  }\n\n  point times_3(const matrix m, const point p) {\n    auto v = to_vector(p);\n    return from_vector(prod(m, v));\n  }\n}\n", "meta": {"hexsha": "d71ddf2e45fbb3f0f3ecfab9aa696cd8f0e719a5", "size": 3265, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/geometry/matrix.cpp", "max_stars_repo_name": "dillonhuff/scg", "max_stars_repo_head_hexsha": "21d004ce37c0e0e3650e373726d7e8bac51fffa4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2018-05-10T16:40:38.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-09T06:36:09.000Z", "max_issues_repo_path": "src/geometry/matrix.cpp", "max_issues_repo_name": "dillonhuff/scg", "max_issues_repo_head_hexsha": "21d004ce37c0e0e3650e373726d7e8bac51fffa4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-10-26T13:08:56.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-26T13:08:56.000Z", "max_forks_repo_path": "src/geometry/matrix.cpp", "max_forks_repo_name": "dillonhuff/scg", "max_forks_repo_head_hexsha": "21d004ce37c0e0e3650e373726d7e8bac51fffa4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-11-28T17:36:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-30T14:32:05.000Z", "avg_line_length": 22.0608108108, "max_line_length": 80, "alphanum_fraction": 0.5427258806, "num_tokens": 1196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096181702031, "lm_q2_score": 0.7826624688140728, "lm_q1q2_score": 0.7170046154614087}}
{"text": "// This file contains portions of the implementation of class ExpressionMatrix\n// that deal with Locality Sensitive Hashing (LSH).\n// LSH is used for efficiently finding pairs of similar cells.\n// See Chapter 3 of Leskovec, Rajaraman, Ullman, Mining of Massive Datasets,\n// Cambridge University Press, 2014, also freely downloadable here:\n// http://www.mmds.org/#ver21\n// and in particular sections 3.4 through 3.7.\n\n// The similarity between two cells can be written as the cosine of the vector\n// between expression counts for the two cells, linearly scaled to zero mean\n// and unit variance. As described in section 3.7.2 of the book referenced above,\n// we use random unit vectors in gene space to generate LSH functions\n// for the cosine similarity.\n// These are vectors of dimension equal to the number of genes,\n// and with unit L2-norm (the sum of the square if the components is 1).\n// These vectors are organized by band and row (see section 3.4.1 of the\n// book referenced above). There are lshBandCount bands and lshRowCount\n// rows per band, for a total lshBandCount*lshRowCount random vectors.\n// Each of these vectors defines an hyperplane orthogonal to it.\n// As described in section 3.7.2 of the book referenced above,\n// each hyperplane provides a function of a locality-sensitive function.\n\n\n#include \"ExpressionMatrix.hpp\"\n#include \"BitSet.hpp\"\n#include \"charikar.hpp\"\n#include \"ExpressionMatrixSubset.hpp\"\n#include \"heap.hpp\"\n#include \"iterator.hpp\"\n#include \"Lsh.hpp\"\n#include \"multipleSetUnion.hpp\"\n#include \"nextPowerOfTwo.hpp\"\n#include \"orderPairs.hpp\"\n#include \"SimilarPairs.hpp\"\n#include \"timestamp.hpp\"\nusing namespace ChanZuckerberg;\nusing namespace ExpressionMatrix2;\n\n#include <boost/math/constants/constants.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n\n#include \"algorithm.hpp\"\n#include <cmath>\n#include \"fstream.hpp\"\n#include <chrono>\n#include <numeric>\n#include <queue>\n#include <random>\n\n\n\n// Analyze the quality of a set of similar pairs.\nvoid ExpressionMatrix::analyzeSimilarPairs(\n    const string& similarPairsName,\n    double csvDownsample) const\n{\n    // Open the SimilarPairs object we want to analyze.\n    const SimilarPairs similarPairs(directoryName + \"/SimilarPairs-\" + similarPairsName, true);\n    const GeneSet& geneSet = similarPairs.getGeneSet();\n    const CellSet& cellSet = similarPairs.getCellSet();\n    const CellId cellCount = CellId(cellSet.size());\n\n    // Create the expression matrix subset to be used\n    // for exact similarity computations.\n    const string expressionMatrixSubsetName = directoryName + \"/tmp-ExpressionMatrixSubset-\" + similarPairsName;\n    ExpressionMatrixSubset expressionMatrixSubset(\n        expressionMatrixSubsetName, geneSet, cellSet, cellExpressionCounts);\n\n    // Open the output csv file.\n    ofstream csvOut(similarPairsName + \"-analysis.csv\");\n    csvOut << \"GlobalCellId0,GlobalCellId1,ExactSimilarity,StoredSimilarity\\n\";\n\n    // Statistics for bins of exact similarity values.\n    const size_t binCount = 200;\n    const double binWidth = 2. / binCount;\n    vector<size_t> sum0(binCount, 0);\n    vector<double> sum1(binCount, 0.);\n    vector<double> sum2(binCount, 0.);\n\n\n    // Random number generator used for downsampling\n    using RandomSource = boost::mt19937;\n    using UniformDistribution = boost::uniform_01<>;\n    const int seed = 231;\n    RandomSource randomSource(seed);\n    UniformDistribution uniformDistribution;\n    boost::variate_generator<RandomSource, UniformDistribution>\n        uniformGenerator(randomSource, uniformDistribution);\n\n    // Loop over all values stored in the SimilarPairs object.\n    size_t pairCount = 0;\n    size_t csvPairCount = 0;\n    for(CellId localCellId0=0; localCellId0<cellCount; localCellId0++) {\n        if((localCellId0 % 100)==0) {\n            cout << timestamp << \"Working on cell \" << localCellId0 << \" of \" << cellCount << endl;\n        }\n        const CellId globalCellId0 = cellSet[localCellId0];\n        for(const auto& p: similarPairs[localCellId0]) {\n            ++pairCount;\n            const CellId localCellId1 = p.first;\n            const CellId globalCellId1 = cellSet[localCellId1];\n            const float& storedSimilarity = p.second;\n            const double exactSimilarity = expressionMatrixSubset.\n                computeCellSimilarity(localCellId0, localCellId1);\n\n            // Update statistics.\n            const double delta = storedSimilarity - exactSimilarity;\n            const size_t bin = size_t(floor((exactSimilarity+1.) / binWidth));\n            CZI_ASSERT(bin < binCount);\n            ++(sum0[bin]);\n            sum1[bin] += delta;\n            sum2[bin] += delta*delta;\n\n            // Write to csv output (with downsampling).\n            if(uniformGenerator() < csvDownsample) {\n                ++csvPairCount;\n                csvOut << globalCellId0 << \",\";\n                csvOut << globalCellId1 << \",\";\n                csvOut << exactSimilarity << \",\";\n                csvOut << storedSimilarity << \"\\n\";\n            }\n        }\n    }\n\n   cout << \"Total number of ordered cell pairs: \" << size_t(cellCount) * size_t(cellCount-1) << endl;\n   cout << \"Number of cell pairs with a stored similarity value: \"<< pairCount << endl;\n   cout << \"Number of cell pairs written to csv file: \" << csvPairCount << endl;\n\n\n   // Compute average and standard deviation of the error for each bin.\n   ofstream statsOut(similarPairsName + \"-analysis-statistics.csv\");\n   statsOut << \"Similarity,Bias,Rms\\n\";\n   for(size_t bin=0; bin<binCount; bin++) {\n       if(sum0[bin] < 2) {\n           continue;\n       }\n       const double similarity = (double(bin) + 0.5) * binWidth - 1.;\n       const double s0 = double(sum0[bin]);\n       const double s1 = sum1[bin];\n       const double s2 = sum2[bin];\n       const double average = s1 / s0;\n       const double sigma = sqrt(s2 / s0); // Sigma around 0.\n       statsOut << similarity << \",\";\n       statsOut << average << \",\";\n       statsOut << sigma << \"\\n\";\n   }\n\n}\n\n\n\n// Used to test improvements to findSimilarPairs3.\nvoid ExpressionMatrix::findSimilarPairs4(\n    ostream& out,\n    const string& geneSetName,      // The name of the gene set to be used.\n    const string& cellSetName,      // The name of the cell set to be used.\n    const string& similarPairsName, // The name of the SimilarPairs object to be created.\n    size_t k,                       // The maximum number of similar pairs to be stored for each cell.\n    double similarityThreshold,     // The minimum similarity for a pair to be stored.\n    size_t lshCount,                // The number of LSH vectors to use.\n    unsigned int seed               // The seed used to generate the LSH vectors.\n    )\n{\n    out << timestamp << \"ExpressionMatrix::findSimilarPairs4 begins.\" << endl;\n\n    // Locate the gene set and verify that it is not empty.\n    const auto itGeneSet = geneSets.find(geneSetName);\n    if(itGeneSet == geneSets.end()) {\n        throw runtime_error(\"Gene set \" + geneSetName + \" does not exist.\");\n    }\n    const GeneSet& geneSet = itGeneSet->second;\n    if(geneSet.size() == 0) {\n        throw runtime_error(\"Gene set \" + geneSetName + \" is empty.\");\n    }\n\n    // Locate the cell set and verify that it is not empty.\n    const auto& it = cellSets.cellSets.find(cellSetName);\n    if(it == cellSets.cellSets.end()) {\n        throw runtime_error(\"Cell set \" + cellSetName + \" does not exist.\");\n    }\n    const MemoryMapped::Vector<CellId>& cellSet = *(it->second);\n    const CellId cellCount = CellId(cellSet.size());\n    if(cellCount == 0) {\n        throw runtime_error(\"Cell set \" + cellSetName + \" is empty.\");\n    }\n\n    // Create the expression matrix subset for this gene set and cell set.\n    out << timestamp << \"Creating expression matrix subset.\" << endl;\n    const string expressionMatrixSubsetName =\n        directoryName + \"/tmp-ExpressionMatrixSubset-\" + similarPairsName;\n    ExpressionMatrixSubset expressionMatrixSubset(\n        expressionMatrixSubsetName, geneSet, cellSet, cellExpressionCounts);\n\n    // Create the Lsh object that will do the computation.\n    Lsh lsh(directoryName + \"/tmp-Lsh\", expressionMatrixSubset, lshCount, seed);\n\n    // Temporary storage of pairs for each cell.\n    vector< vector< pair<CellId, float> > > tmp(cellCount);\n    const size_t tmpStore = 2 * k;\n    for(auto& v: tmp) {\n        v.reserve(tmpStore);\n    }\n\n    // Current similarity threshold for each cell.\n    vector<float> cellThreshold(cellCount, float(similarityThreshold));\n\n\n\n    // Loop over all pairs. This is much faster than findSimilarPairs0\n    // (around 15 ns per pair when using LSH vectors of 1024 bits), but\n    // still scales like the square of the number of cells in the cell set.\n    // This loops in blocks of cells for better memory locality than a simple\n    // loop over cell pairs.\n    out << timestamp << \"Begin computing similarities for all cell pairs.\" << endl;\n    const auto t0 = std::chrono::steady_clock::now();\n    const CellId blockSize = 64;\n    size_t pairCount = 0;\n    size_t totalPairCount = size_t(cellCount)*(size_t(cellCount-1))/2;\n    size_t blockCount = 0;\n    for(CellId begin0=0; begin0<cellCount; begin0+=blockSize) {\n        const CellId end0 = min(begin0+blockSize, cellCount);\n        for(CellId begin1=0; begin1<=begin0; begin1+=blockSize) {\n            if(blockCount>0 && ((blockCount%1000000)==0)) {\n                out << timestamp << \"Pair computation \";\n                out << 100.*double(pairCount)/double(totalPairCount);\n                out << \"% complete.\" << endl;\n            }\n            ++blockCount;\n            const CellId end1 = min(begin1+blockSize, end0);\n            for(CellId cell0=begin0; cell0!=end0; ++cell0) {\n                auto& tmp0 = tmp[cell0];\n                for(CellId cell1=begin1; cell1!=end1 && cell1<cell0; ++cell1) {\n                    auto& tmp1 = tmp[cell1];\n                    ++pairCount;\n\n                    // Compute the LSH similarity between these two cells.\n                    const double similarity = lsh.computeCellSimilarity(cell0, cell1);\n\n                    // If the similarity is sufficient, pass it to the SimilarPairs container,\n                    // which will make the decision whether to store it, depending on the\n                    // number of pairs already stored for cellId0 and cellId1.\n                    if(similarity > similarityThreshold) {\n                        if(similarity > cellThreshold[cell0]) {\n                            tmp0.push_back(make_pair(cell1, similarity));\n                            if(tmp0.size() == tmpStore) {\n                                keepBest(tmp0, k, OrderPairsBySecondGreater< pair<CellId, float> >());\n                                cellThreshold[cell0] = tmp0.back().second;\n                            }\n                        }\n                        if(similarity > cellThreshold[cell1]) {\n                            tmp1.push_back(make_pair(cell0, similarity));\n                            if(tmp1.size() == tmpStore) {\n                                keepBest(tmp1, k, OrderPairsBySecondGreater< pair<CellId, float> >());\n                                cellThreshold[cell1] = tmp1.back().second;\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n    // Keep at most k of each.\n    for(auto& tmp0: tmp) {\n        if(tmp0.size() > k) {\n            keepBest(tmp0, k, OrderPairsBySecondGreater< pair<CellId, float> >());\n        }\n    }\n    const auto t1 = std::chrono::steady_clock::now();\n    const double t01 = 1.e-9 * double((std::chrono::duration_cast<std::chrono::nanoseconds>(t1 - t0)).count());\n    CZI_ASSERT(pairCount == totalPairCount);\n    out << \"Time for all pairs: \" << t01 << \" s.\" << endl;\n    out << \"Time per pair: \" << t01/(0.5*double(cellCount)*double(cellCount-1)) << \" s.\" << endl;\n\n    // Store the pairs in a SimilarPairs object.\n    out << timestamp << \"Initializing SimilarPairs object.\" << endl;\n    SimilarPairs similarPairs(directoryName + \"/SimilarPairs-\" + similarPairsName, k, geneSet, cellSet);\n    out << timestamp << \"Copying similar pairs.\" << endl;\n    similarPairs.copy(tmp);\n\n\n    // Sort the similar pairs for each cell by decreasing similarity.\n    out << timestamp << \"Sorting similar pairs.\" << endl;\n    similarPairs.sort();\n    out << timestamp << \"ExpressionMatrix::findSimilarPairs4 ends.\" << endl;\n\n    lsh.remove();\n\n}\nvoid ExpressionMatrix::findSimilarPairs4(\n    const string& geneSetName,      // The name of the gene set to be used.\n    const string& cellSetName,      // The name of the cell set to be used.\n    const string& similarPairsName, // The name of the SimilarPairs object to be created.\n    size_t k,                       // The maximum number of similar pairs to be stored for each cell.\n    double similarityThreshold,     // The minimum similarity for a pair to be stored.\n    size_t lshCount,                // The number of LSH vectors to use.\n    unsigned int seed               // The seed used to generate the LSH vectors.\n    )\n{\n    findSimilarPairs4(cout, geneSetName, cellSetName, similarPairsName,\n        k, similarityThreshold, lshCount, seed);\n}\n\n\n// Find similar cell pairs using LSH, without looping over all pairs.\n// This uses slices of each LSH signature.\n// The number of bits in each slice is lshSliceLength.\n// If lshSliceLength is 0, it is set to the base 2 log of the number of cells\n// (rounded up).\n// For each slice we store the cells with each possible value of the signature slice.\nvoid ExpressionMatrix::findSimilarPairs5(\n    const string& geneSetName,      // The name of the gene set to be used.\n    const string& cellSetName,      // The name of the cell set to be used.\n    const string& lshName,          // The name of the Lsh object to be used.\n    const string& similarPairsName, // The name of the SimilarPairs object to be created.\n    size_t k,                       // The maximum number of similar pairs to be stored for each cell.\n    double similarityThreshold,     // The minimum similarity for a pair to be stored.\n    size_t lshSliceLength,          // The number of bits in each LSH signature slice, or 0 for automatic selection.\n    size_t bucketOverflow           // If not zero, ignore buckets larger than this.\n    )\n{\n    cout << timestamp << \"ExpressionMatrix::findSimilarPairs5 begins.\" << endl;\n    const auto t0 = std::chrono::steady_clock::now();\n\n    // Locate the gene set and verify that it is not empty.\n    const auto itGeneSet = geneSets.find(geneSetName);\n    if(itGeneSet == geneSets.end()) {\n        throw runtime_error(\"Gene set \" + geneSetName + \" does not exist.\");\n    }\n    const GeneSet& geneSet = itGeneSet->second;\n    if(geneSet.size() == 0) {\n        throw runtime_error(\"Gene set \" + geneSetName + \" is empty.\");\n    }\n\n    // Locate the cell set and verify that it is not empty.\n    const auto& it = cellSets.cellSets.find(cellSetName);\n    if(it == cellSets.cellSets.end()) {\n        throw runtime_error(\"Cell set \" + cellSetName + \" does not exist.\");\n    }\n    const MemoryMapped::Vector<CellId>& cellSet = *(it->second);\n    const CellId cellCount = CellId(cellSet.size());\n    if(cellCount == 0) {\n        throw runtime_error(\"Cell set \" + cellSetName + \" is empty.\");\n    }\n\n    // Access the Lsh object that will do the computation.\n    Lsh lsh(directoryName + \"/Lsh-\" + lshName);\n    if(lsh.cellCount() != cellSet.size()) {\n        throw runtime_error(\"LSH object \" + lshName + \" has a number of cells inconsistent with cell set \" + cellSetName);\n    }\n\n\n    // Find the signature bits corresponding to each slice.\n    const size_t sliceCount = lsh.lshCount() / lshSliceLength;\n    vector< vector<size_t> > allSlicesBits(sliceCount);\n    for(size_t sliceId=0; sliceId<sliceCount; sliceId++) {\n        vector<size_t>& sliceBits = allSlicesBits[sliceId];\n        const size_t sliceBegin = sliceId * lshSliceLength;\n        const size_t sliceEnd = sliceBegin + lshSliceLength;\n        for(size_t bit=sliceBegin; bit!=sliceEnd; bit++) {\n            sliceBits.push_back(bit);\n        }\n    }\n\n\n    // Table to contain, for each signature slice,\n    // the cells with each of possible value of the slice.\n    // Indexed by [sliceId][sliceValue].\n    // All cell ids are local to the cell set we are using.\n    vector< vector < vector<CellId> > > tables(sliceCount);\n\n\n\n    // Loop over the signature slices.\n    // Each generates a new table of cells.\n    for(size_t sliceId=0; sliceId<sliceCount; sliceId++) {\n        cout << timestamp << \"Computing cell table for signature slice \" << sliceId << \" of \" << sliceCount << endl;\n        vector < vector<CellId> >& table = tables[sliceId];\n        table.resize(1ULL << lshSliceLength);\n        const vector<size_t>& sliceBits = allSlicesBits[sliceId];\n\n        // Store each cell id based on the value of this signature slice.\n        for(CellId cellId=0; cellId<cellCount; cellId++) {\n            const uint64_t signatureSlice = lsh.getSignature(cellId).getBits(sliceBits);\n            CZI_ASSERT(signatureSlice < table.size());\n            table[signatureSlice].push_back(cellId);\n        }\n    }\n    cout << timestamp << \"Computation of cell table completed.\" << endl;\n\n    // Temporary storage of pairs for each cell.\n    vector< vector< pair<CellId, float> > > tmp(cellCount);\n\n\n    // Loop over cells.\n    // For each cell, compute the union of all the table vectors\n    // this cell belongs to. This is the set of candidate neighbors\n    // for this cell.\n    size_t fullCellCount = 0;\n    vector<CellId> candidates;\n    vector< const vector<CellId>* > setsToUnion;\n    vector< pair<CellId, float> > cellNeighbors;    // The neighbors of a single cell.\n    size_t totalCandidateCount = 0;\n    for(CellId cellId0=0; cellId0<cellCount; cellId0++) {\n        if((cellId0 % 10000)==0) {\n            cout << timestamp << \"Find neighbors for cell \" << cellId0 << \" begins.\" << endl;\n        }\n        // const auto t0 = std::chrono::steady_clock::now();\n\n        // Find the candidates.\n        // This can be made faster using a heap\n        // to compute the union.\n        candidates.clear();\n        setsToUnion.clear();\n        // size_t totalCountToUnion = 0;\n        for(size_t sliceId=0; sliceId<sliceCount; sliceId++) {\n            const uint64_t signatureSlice = lsh.getSignature(cellId0).getBits(allSlicesBits[sliceId]);\n            const auto& bucket = tables[sliceId][signatureSlice];\n            if(bucketOverflow==0 || bucket.size()<=bucketOverflow) {\n                setsToUnion.push_back(&tables[sliceId][signatureSlice]);\n                // totalCountToUnion += tables[sliceId][signatureSlice].size();\n            }\n#if 0\n            cout << \"Bucket for cell \" << cellId0 << \" slice \" << sliceId << \": \";\n            copy(tables[sliceId][signatureSlice].begin(), tables[sliceId][signatureSlice].end(),\n                ostream_iterator<CellId>(cout, \" \"));\n            cout << endl;\n#endif\n        }\n        multipleSetUnion(setsToUnion, candidates);\n        totalCandidateCount += candidates.size();\n        // const auto t1 = std::chrono::steady_clock::now();\n\n        // Check each of the candidates.\n        cellNeighbors.clear();\n        for(const CellId cellId1: candidates) {\n            if(cellId1 == cellId0) {\n                continue;\n            }\n            const double similarity = lsh.computeCellSimilarity(cellId0, cellId1);\n            if(similarity > similarityThreshold) {\n                cellNeighbors.push_back(make_pair(cellId1, float(similarity)));\n            }\n        }\n        // const auto t2 = std::chrono::steady_clock::now();\n\n#if 0\n        cout << \"cellNeighbors before keepBest \" << cellId0 << endl;\n        for(const auto& p: cellNeighbors) {\n            cout << p.first << \" \" << p.second << \"\\n\";\n        }\n#endif\n\n        // Store the pairs we found, keeping only the k best.\n        // const size_t goodCandidatesCount = cellNeighbors.size();\n        keepBest(cellNeighbors, k, OrderPairsBySecondGreater< pair<CellId, float> >());\n        // const auto t3 = std::chrono::steady_clock::now();\n#if 0\n        cout << \"cellNeighbors after keepBest\" << cellId0  << endl;\n        for(const auto& p: cellNeighbors) {\n            cout << p.first << \" \" << p.second << \"\\n\";\n        }\n#endif\n        tmp[cellId0] = cellNeighbors;\n        // const auto t4 = std::chrono::steady_clock::now();\n\n        if(cellNeighbors.size() == k) {\n            ++fullCellCount;\n        }\n\n#if 0\n        if(cellId0 > 10000) {\n            cout << cellId0 << \" \";\n            cout << 1.e-9 * double((std::chrono::duration_cast<std::chrono::nanoseconds>(t1 - t0)).count()) << \" \";\n            cout << 1.e-9 * double((std::chrono::duration_cast<std::chrono::nanoseconds>(t2 - t1)).count()) << \" \";\n            cout << 1.e-9 * double((std::chrono::duration_cast<std::chrono::nanoseconds>(t3 - t2)).count()) << \" \";\n            cout << 1.e-9 * double((std::chrono::duration_cast<std::chrono::nanoseconds>(t4 - t3)).count()) << \" \";\n            cout << setsToUnion.size() << \" \" << totalCountToUnion << \" \";\n            cout << candidates.size() << \" \" << goodCandidatesCount << \" \" << cellNeighbors.size() << \"\\n\";\n        }\n#endif\n    }\n    cout << \"Average number of candidates per cell is \" << double(totalCandidateCount)/cellCount << endl;\n    cout << \"Number of cells with \" << k << \" neighbors  is \" << fullCellCount << endl;\n\n    // Store the pairs in a SimilarPairs object.\n    cout << timestamp << \"Initializing SimilarPairs object.\" << endl;\n    SimilarPairs similarPairs(directoryName + \"/SimilarPairs-\" + similarPairsName, k, geneSet, cellSet);\n    cout << timestamp << \"Copying similar pairs.\" << endl;\n    similarPairs.copy(tmp);\n\n\n    // Sort the similar pairs for each cell by decreasing similarity.\n    cout << timestamp << \"Sorting similar pairs.\" << endl;\n    similarPairs.sort();\n    const auto t1 = std::chrono::steady_clock::now();\n    const double t01 = 1.e-9 * double((std::chrono::duration_cast<std::chrono::nanoseconds>(t1 - t0)).count());\n    cout << timestamp << \"ExpressionMatrix::findSimilarPairs5 ends. Took \" << t01 << \" s.\" << endl;\n\n}\n\n\n\n// Find similar cell pairs using LSH, without looping over all pairs.\n// Like findSimilarPairs5, but using variable lsh slice length.\nvoid ExpressionMatrix::findSimilarPairs7(\n    const string& geneSetName,      // The name of the gene set to be used.\n    const string& cellSetName,      // The name of the cell set to be used.\n    const string& lshName,          // The name of the Lsh object to be used.\n    const string& similarPairsName, // The name of the SimilarPairs object to be created.\n    size_t k,                       // The maximum number of similar pairs to be stored for each cell.\n    double similarityThreshold,     // The minimum similarity for a pair to be stored.\n    const vector<int>& lshSliceLengths, // The number of bits in each LSH signature slice, in decreasing order.\n    CellId maxCheck,                // Maximum number of cells to consider for each cell.\n    size_t log2BucketCount\n    )\n{\n    cout << timestamp << \"ExpressionMatrix::findSimilarPairs7 begins.\" << endl;\n    const auto t0 = std::chrono::steady_clock::now();\n\n    // Locate the gene set and verify that it is not empty.\n    const auto itGeneSet = geneSets.find(geneSetName);\n    if(itGeneSet == geneSets.end()) {\n        throw runtime_error(\"Gene set \" + geneSetName + \" does not exist.\");\n    }\n    const GeneSet& geneSet = itGeneSet->second;\n    if(geneSet.size() == 0) {\n        throw runtime_error(\"Gene set \" + geneSetName + \" is empty.\");\n    }\n\n    // Locate the cell set and verify that it is not empty.\n    const auto& it = cellSets.cellSets.find(cellSetName);\n    if(it == cellSets.cellSets.end()) {\n        throw runtime_error(\"Cell set \" + cellSetName + \" does not exist.\");\n    }\n    const MemoryMapped::Vector<CellId>& cellSet = *(it->second);\n    const CellId cellCount = CellId(cellSet.size());\n    if(cellCount == 0) {\n        throw runtime_error(\"Cell set \" + cellSetName + \" is empty.\");\n    }\n\n    // Access the Lsh object that will do the computation.\n    Lsh lsh(directoryName + \"/Lsh-\" + lshName);\n    if(lsh.cellCount() != cellCount) {\n        throw runtime_error(\"LSH object \" + lshName + \" has a number of cells inconsistent with cell set \" + cellSetName);\n    }\n    const size_t lshBitCount = lsh.lshCount();\n    cout << \"Number of LSH signature bits is \" << lshBitCount << endl;\n\n    // Check that the slice lengths are in decreasing order.\n    const size_t sliceLengthCount = lshSliceLengths.size();\n    for(size_t i=1; i<sliceLengthCount; i++) {\n        if(lshSliceLengths[i] >= lshSliceLengths[i-1]) {\n            throw runtime_error(\"The slice lengths are not in decreasing order.\");\n        }\n    }\n\n    // Check that the slice lengths are no more than 64.\n    for(size_t i=0; i<sliceLengthCount; i++) {\n        if(lshSliceLengths[i] > 64) {\n            throw runtime_error(\"Each slice length can be at most 64 bits.\");\n        }\n    }\n\n    // Create SimilarPairs object that will store the results.\n    SimilarPairs similarPairs(directoryName + \"/SimilarPairs-\" + similarPairsName, k, geneSet, cellSet);\n\n\n\n    // For each slice length and signature slice of that length,\n    // each cell is assigned to a bucket\n    // based on the value of its signature slice.\n    // The cells in each bucket will be stored in\n    // tables4[sliceLengthId][sliceId][bucketId],\n    // where:\n    // - sliceLengthId corresponds to the slice lengths to be used,\n    //   stored in lshSliceLengths in decreasing order.\n    // - sliceId identifies the particular slice of that length\n    //   (we have a total lshBitCount bits, which can be used\n    //   to form lshBitCount/lshSliceLength possible signature\n    //   slices each lshSliceLength bits in length).\n    // - bucketId identifies the bucket.\n    vector< vector< vector< vector<CellId> > > > table4;\n\n    // Vector to contain the signature bits of each signature slice.\n    // Indexed by [sliceLengthId][sliceId].\n    vector< vector< vector< size_t > > > sliceBits3;\n\n    // Assign cells to buckets.\n    findSimilarPairs7AssignCellsToBuckets(lsh, lshSliceLengths, sliceBits3, table4, log2BucketCount);\n\n\n\n    // Bit set to keep track which cellId1 cells we have already\n    // looked at, for a given cellId0.\n    BitSet cellMap(cellCount);\n\n    // Other vectors used over and over again for each cell.\n    vector<CellId> candidateNeighbors;\n    vector< pair<uint32_t, CellId> > neighbors; // pair(mismatchCount, cellId1)\n\n    const size_t mismatchCountThreshold =\n        lsh.computeMismatchCountThresholdFromSimilarityThreshold(similarityThreshold);\n    cout << \"Mismatch count threshold is \" << mismatchCountThreshold << endl;\n\n\n\n    // For each cell, look at cells in the same bucket.\n    // Stop when we found enough similar cells.\n    cout << timestamp << \"Finding similar cell pairs.\" << endl;\n    const uint64_t bucketCount = (1ULL << log2BucketCount);\n    const uint64_t bucketMask = bucketCount - 1ULL;\n    for(CellId cellId0=0; cellId0<cellCount; cellId0++) {\n        if(cellId0!=0 && (cellId0 % 1000)==0) {\n            cout << timestamp << \"Working on cell \" << cellId0 << \" of \" << cellCount << endl;\n        }\n        const BitSetPointer signature = lsh.getSignature(cellId0);\n\n        // Loop over slice lengths.\n        for(size_t sliceLengthId=0; sliceLengthId<sliceLengthCount; sliceLengthId++) {\n            const auto& table3 = table4[sliceLengthId];\n            const auto& sliceBits2 = sliceBits3[sliceLengthId];\n\n            // Extract the slice length.\n            const size_t sliceLength = lshSliceLengths[sliceLengthId];\n\n            // Compute the number of possible slices for this length.\n            const size_t sliceCount = lshBitCount / sliceLength;\n\n            // Loop over all possible signature slices of this length.\n            for(size_t sliceId=0; sliceId<sliceCount; sliceId++) {\n                const auto& table2 = table3[sliceId];\n                const auto& sliceBits1 = sliceBits2[sliceId];\n\n                // Extract this signature slice for this cell.\n                const uint64_t signatureSlice = signature.getBits(sliceBits1);\n\n                // Find the bucket that corresponds to this signature slice.\n                const uint64_t bucketId =\n                    (sliceLength<log2BucketCount) ?\n                    signatureSlice :\n                    (MurmurHash64A(&signatureSlice, 8, 231) & bucketMask);\n                CZI_ASSERT(bucketId < table2.size());\n                const auto& table1 = table2[bucketId];\n\n                // Loop over cells in the same bucket.\n                for(const CellId cellId1: table1) {\n                    if(cellId1 == cellId0){\n                        continue;\n                    }\n                    if(cellMap.get(cellId1)) {\n                        continue;   // We already looked at this one.\n                    }\n                    cellMap.set(cellId1);\n                    candidateNeighbors.push_back(cellId1);\n                    const uint32_t mismatchCount = uint32_t(lsh.computeMismatchCount(cellId0, cellId1));\n                    if(mismatchCount < mismatchCountThreshold) {\n                        neighbors.push_back(make_pair(mismatchCount, cellId1));\n                    }\n                    if(candidateNeighbors.size() == maxCheck) {\n                        break;\n                    }\n                }\n                if(candidateNeighbors.size() == maxCheck) {\n                    break;\n                }\n            }\n            if(candidateNeighbors.size() == maxCheck) {\n                break;\n            }\n        }\n\n        // Only keep the k best neighbors, then sort them.\n        // This is faster than sorting, then keeping the k best,\n        // because it avoids doing a complete sorting of all of the neighbors.\n        // Instead, keepBest uses std::nth_element, which does a partial sorting.\n        keepBest(neighbors, k, std::less< pair<uint32_t, CellId> >());\n        sort(neighbors.begin(), neighbors.end());\n\n        // Store.\n        for(const auto& neighbor: neighbors) {\n            const CellId cellId1 = neighbor.second;\n            const uint32_t mismatchCount = neighbor.first;\n            const double similarity = lsh.getSimilarity(mismatchCount);\n            similarPairs.addUnsymmetricNoCheck(cellId0, cellId1, similarity);\n        }\n\n        // Clean up our data structures so we can reuse them for the next cell.\n        for(const CellId cellId1: candidateNeighbors) {\n            cellMap.clear(cellId1);\n        }\n        candidateNeighbors.clear();\n        neighbors.clear();\n\n    }\n\n\n    const auto t1 = std::chrono::steady_clock::now();\n    const double t01 = 1.e-9 * double((std::chrono::duration_cast<std::chrono::nanoseconds>(t1 - t0)).count());\n    cout << timestamp << \"ExpressionMatrix::findSimilarPairs7 ends. Took \" << t01 << \" s.\" << endl;\n}\n\n\n\n// In the initial phase of findSimilarPairs7, we assign cells to buckets.\n// For each slice length and signature slice of that length,\n// each cell is assigned to a bucket\n// based on the value of its signature slice.\n\n// The cells in each bucket are stored in\n// tables4[sliceLengthId][sliceId][bucketId],\n// where:\n// - sliceLengthId corresponds to the slice lengths to be used,\n//   stored in lshSliceLengths in decreasing order.\n// - sliceId identifies the particular slice of that length\n//   (we have a total lshBitCount bits, which can be used\n//   to form lshBitCount/lshSliceLength possible signature\n//   slices each lshSliceLength bits in length).\n// - bucketId identifies the bucket.\n\n// Vector sliceBits3 is used to store the signature bits of each signature slice.\n// Indexed by [sliceLengthId][sliceId].\n\nvoid ExpressionMatrix::findSimilarPairs7AssignCellsToBuckets(\n    Lsh& lsh,\n    const vector<int>& lshSliceLengths,                     // The number of signature slice bits, in decreasing order.\n    vector< vector< vector< size_t > > >& sliceBits3,       // The bits of each slice. See comments above.\n    vector< vector< vector< vector<CellId> > > >& table4,   // The cells in each bucket. See comments above.\n    size_t log2BucketCount\n    )\n{\n    // Check that the slice lengths are in decreasing order.\n    const size_t sliceLengthCount = lshSliceLengths.size();\n    for(size_t i=1; i<sliceLengthCount; i++) {\n        if(lshSliceLengths[i] >= lshSliceLengths[i-1]) {\n            throw runtime_error(\"The slice lengths are not in decreasing order.\");\n        }\n    }\n\n    // Check that the slice lengths are no more than 64.\n    for(size_t i=0; i<sliceLengthCount; i++) {\n        if(lshSliceLengths[i] > 64) {\n            throw runtime_error(\"Each slice length can be at most 64 bits.\");\n        }\n    }\n\n\n    // Initialize the table4 and sliceBits3 data structures.\n    cout << timestamp << \"Initializing data structures for findSimilarPairs7.\" << endl;\n    table4.resize(sliceLengthCount);\n    sliceBits3.resize(sliceLengthCount);\n    const uint64_t bucketCount = (1ULL << log2BucketCount);\n    const uint64_t bucketMask = bucketCount - 1ULL;\n    const size_t lshBitCount = lsh.lshCount();\n    for(size_t sliceLengthId=0; sliceLengthId<sliceLengthCount; sliceLengthId++) {\n        auto& table3 = table4[sliceLengthId];\n        auto& sliceBits2 = sliceBits3[sliceLengthId];\n\n        // Extract the slice length.\n        const size_t sliceLength = lshSliceLengths[sliceLengthId];\n\n        // Compute the number of possible slices for this length.\n        const size_t sliceCount = lshBitCount / sliceLength;\n        table3.resize(sliceCount);\n        sliceBits2.resize(sliceCount);\n        const uint64_t tableSize = std::min(uint64_t(1ULL<<sliceLength), bucketCount);\n        cout << \"Number of slices of length \" << sliceLength << \" is \" << sliceCount;\n        cout << \". Table size is \" << tableSize << endl;\n\n        // Loop over all possible signature slices of this length.\n        for(size_t sliceId=0; sliceId<sliceCount; sliceId++) {\n            auto& table2 = table3[sliceId];\n            table2.resize(tableSize);\n\n            // Gather the signature bits.\n            auto& sliceBits1 = sliceBits2[sliceId];\n            sliceBits1.resize(sliceLength);\n            size_t bitPosition = sliceId * sliceLength;\n            for(size_t bitId=0; bitId<sliceLength; bitId++, ++bitPosition) {\n                sliceBits1[bitId] = bitPosition;\n            }\n        }\n    }\n\n\n\n    // Assign cells to buckets.\n    cout << timestamp << \"Assigning cells to buckets.\" << endl;\n    const CellId cellCount = lsh.cellCount();\n    for(CellId cellId=0; cellId<cellCount; cellId++) {\n        if(cellId!=0 && (cellId % 100000)==0) {\n            cout << timestamp << \"Working on cell \" << cellId << \" of \" << cellCount << endl;\n        }\n        const BitSetPointer signature = lsh.getSignature(cellId);\n\n        // Loop over slice lengths.\n        for(size_t sliceLengthId=0; sliceLengthId<sliceLengthCount; sliceLengthId++) {\n            auto& table3 = table4[sliceLengthId];\n            const auto& sliceBits2 = sliceBits3[sliceLengthId];\n\n            // Extract the slice length.\n            const size_t sliceLength = lshSliceLengths[sliceLengthId];\n\n            // Compute the number of possible slices for this length.\n            const size_t sliceCount = lshBitCount / sliceLength;\n\n            // Loop over all possible signature slices of this length.\n            for(size_t sliceId=0; sliceId<sliceCount; sliceId++) {\n                auto& table2 = table3[sliceId];\n                const auto& sliceBits1 = sliceBits2[sliceId];\n\n                // Extract this signature slice for this cell.\n                const uint64_t signatureSlice = signature.getBits(sliceBits1);\n\n                // Add this cell to the bucket that corresponds to this signature slice.\n                const uint64_t bucketId =\n                    (sliceLength<log2BucketCount) ?\n                    signatureSlice :\n                    (MurmurHash64A(&signatureSlice, 8, 231) & bucketMask);\n                CZI_ASSERT(bucketId < table2.size());\n                table2[bucketId].push_back(cellId);\n            }\n        }\n\n    }\n}\n\n\n\n// Find similar cell pairs using LSH and the Charikar algorithm.\n// See M. Charikar, \"Similarity Estimation Techniques from Rounding Algorithms\", 2002,\n// section \"5. Approximate Nearest neighbor Search in Hamming Space.\".\n// The Charikar algorithm is for approximate nearest neighbor, but with appropriate\n// choices of the algorithm parameters permutationCount and searchCount\n// can be used for approximate k nearest neighbors.\n// In the Charikar paper, permutationCount is N and searchCount is 2N.\n// To reduce memory requirements, we don't store all bits all bits of\n// the permuted signatures - only the most significant permutedBitCount.\n// In practice it is best to set this to 64, so the permuted signatured\n// use only one 64-bit word each.\nvoid ExpressionMatrix::findSimilarPairs6(\n    const string& geneSetName,      // The name of the gene set to be used.\n    const string& cellSetName,      // The name of the cell set to be used.\n    const string& lshName,          // The name of the Lsh object to be used.\n    const string& similarPairsName, // The name of the SimilarPairs object to be created.\n    size_t k,                       // The maximum number of similar pairs to be stored for each cell.\n    double similarityThreshold,     // The minimum similarity for a pair to be stored.\n    size_t permutationCount,        // The number of bit permutations for the Charikar algorithm.\n    size_t searchCount,             // The number of cells checked for each cell, in the Charikar algorithm.\n    size_t permutedBitCount,        // The number of most significant bits stored for each permuted signature.\n    int seed                        // The seed used to randomly generate the bit permutations.\n    )\n{\n    cout << timestamp << \"ExpressionMatrix::findSimilarPairs6 begins.\" << endl;\n    bool debug = false;\n    const auto t0 = std::chrono::steady_clock::now();\n\n    // Locate the gene set and verify that it is not empty.\n    const auto itGeneSet = geneSets.find(geneSetName);\n    if(itGeneSet == geneSets.end()) {\n        throw runtime_error(\"Gene set \" + geneSetName + \" does not exist.\");\n    }\n    const GeneSet& geneSet = itGeneSet->second;\n    if(geneSet.size() == 0) {\n        throw runtime_error(\"Gene set \" + geneSetName + \" is empty.\");\n    }\n\n    // Locate the cell set and verify that it is not empty.\n    const auto& it = cellSets.cellSets.find(cellSetName);\n    if(it == cellSets.cellSets.end()) {\n        throw runtime_error(\"Cell set \" + cellSetName + \" does not exist.\");\n    }\n    const MemoryMapped::Vector<CellId>& cellSet = *(it->second);\n    const CellId cellCount = CellId(cellSet.size());\n    if(cellCount == 0) {\n        throw runtime_error(\"Cell set \" + cellSetName + \" is empty.\");\n    }\n\n    // Access the Lsh object that will do the computation.\n    Lsh lsh(directoryName + \"/Lsh-\" + lshName);\n    if(lsh.cellCount() != cellSet.size()) {\n        throw runtime_error(\"LSH object \" + lshName + \" has a number of cells inconsistent with cell set \" + cellSetName);\n    }\n    const size_t lshCount = lsh.lshCount();\n\n    // Sanity check on the number of most significant bits stored for\n    // each permuted signature.\n    if(permutedBitCount > lshCount) {\n        throw runtime_error(\n            \"Argument permutationStoreBitCount \" +\n            to_string(permutedBitCount) +\n            \" exceeds number of signature bits \" +\n            to_string(lshCount));\n    }\n\n\n    // Write out the signatures.\n    if(debug) {\n        cout << \"Cell signatures:\\n\";\n        for(size_t i=0; i<lshCount; i++) {\n            cout << (i%10);\n        }\n        cout << \"\\n\";\n        for(CellId cellId=0; cellId<cellCount; cellId++) {\n            cout << lsh.getSignature(cellId).getString(lshCount) << \" \" << cellId << \"\\n\";\n        }\n    }\n\n\n\n    // Create the random number generator that will be used to generate\n    // the random permutations of the signature bits.\n    std::mt19937 randomGenerator(seed);\n\n\n    // For each of the permutations, we will store:\n    // - The permuted signatures, in sorted order (first permutationStoreBitCount bits only).\n    // - The corresponding cell ids, in order consistent with the permuted signatures.\n    const size_t permutedWordCount = ((permutedBitCount-1) >> 6) + 1;\n    cout << \"Allocating \" << ((8*permutationCount*size_t(lsh.cellCount())*permutedWordCount) >> 30) << \" GB for permutation data.\" << endl;\n    vector<Charikar::PermutationData> permutationData(\n        permutationCount,\n        Charikar::PermutationData(lsh.cellCount(), permutedWordCount));\n\n\n\n    // For each of the permutations, compute permuted/sorted signatures.\n    // We only compute and store the first permutedBitCount bits of each permuted signature.\n    cout << timestamp << \"Phase 1 of Charikar algorithm begins.\" << endl;\n    const auto t1 = std::chrono::steady_clock::now();\n    for(size_t permutationId=0; permutationId<permutationCount; permutationId++) {\n        cout << timestamp << \"Working on permutation \" << permutationId << \" of \" << permutationCount << endl;\n\n        // Generate a random permutation of the signature bits.\n        vector<uint64_t> bitPermutation(lshCount);\n        std::iota(bitPermutation.begin(), bitPermutation.end(), 0ULL);\n        std::shuffle(bitPermutation.begin(), bitPermutation.end(), randomGenerator);\n        bitPermutation.resize(permutedBitCount);    // Only keep the permutedBitCount most significant bits.\n\n        if(debug) {\n            cout << \"Creating permutation data for permutation \" << permutationId << \".\\n\";\n            cout << \"Bit permutation:\\n\";\n            for(size_t i=0; i<lshCount; i++) {\n                cout << i << \" \" << bitPermutation[i] << \"\\n\";\n            }\n        }\n\n        // Compute the permuted signatures for this permutation.\n        BitSets permutedSignatures(cellCount, permutedWordCount);\n        for(CellId cellId=0; cellId<cellCount; cellId++) {\n            BitSetPointer signature = lsh.getSignature(cellId);\n            BitSetPointer permutedSignature = permutedSignatures[cellId];\n            permutedSignature.fillUsingPermutation(bitPermutation, signature);\n        }\n\n        // Write the permuted signatures.\n        if(debug) {\n            for(CellId cellId=0; cellId<cellCount; cellId++) {\n                cout << permutedSignatures[cellId].getString(lshCount) << \" \" << cellId << \"\\n\";\n            }\n        }\n\n        // Sort the permuted signatures lexicographically,\n        // Keeping track of the cell ids as they get reordered.\n        vector< pair<BitSetPointer, CellId> > table(cellCount);\n        for(CellId cellId=0; cellId<cellCount; cellId++) {\n            pair<BitSetPointer, CellId>& p = table[cellId];\n            p.first = permutedSignatures[cellId];\n            p.second = cellId;\n        }\n        if(debug) {\n            cout << \"Table before sorting:\" << endl;\n            for(CellId cellId=0; cellId<cellCount; cellId++) {\n                pair<BitSetPointer, CellId>& p = table[cellId];\n                cout << p.first.getString(lshCount) << \" \" << p.second << \"\\n\";\n            }\n        }\n        sort(table.begin(), table.end());\n        if(debug) {\n            cout << \"Table after sorting:\" << endl;\n            for(CellId i=0; i<cellCount; i++) {\n                pair<BitSetPointer, CellId>& p = table[i];\n                cout << p.first.getString(lshCount) << \" \" << p.second << \"\\n\";\n            }\n        }\n\n        // Store the sorted signatures and corresponding cell ids for this permutation.\n        BitSets& thisPermutationBitSets = permutationData[permutationId].signatures;\n        vector<CellId>& thisPermutationCellIds = permutationData[permutationId].cellIds;\n        CZI_ASSERT(thisPermutationBitSets.bitSetCount == cellCount);\n        CZI_ASSERT(thisPermutationBitSets.wordCount == permutedWordCount);\n        CZI_ASSERT(thisPermutationCellIds.size() == cellCount);\n        for(CellId i=0; i<cellCount; i++) {\n            pair<BitSetPointer, CellId>& p = table[i];\n            thisPermutationBitSets.set(i, p.first);\n            thisPermutationCellIds[i] = p.second;\n        }\n        permutationData[permutationId].computeCellPositions();\n\n        if(debug) {\n            cout << \"Permutation data for permutation \" << permutationId << \":\" << endl;\n            for(CellId i=0; i<cellCount; i++) {\n                cout << thisPermutationBitSets[i].getString(lshCount) << \" \" << thisPermutationCellIds[i] << \"\\n\";\n            }\n        }\n    }\n    const auto t2 = std::chrono::steady_clock::now();\n    cout << timestamp << \"Phase 1 of Charikar algorithm took \";\n    cout << 1.e-9 * double((std::chrono::duration_cast<std::chrono::nanoseconds>(t2 - t1)).count()) << \" s.\" << endl;\n\n    // Temporary storage of pairs for each cell.\n    vector< vector< pair<CellId, float> > > pairs(cellCount);\n    vector< pair<CellId, float> > cellNeighbors;\n\n\n    // At this point the necessary data structures are in place and we can use the Charikar algorithm\n    // to find the neighbors of each cell.\n    debug = false;\n    cout << timestamp << \"Phase 2 of Charikar algorithm begins.\" << endl;\n    const auto t3 = std::chrono::steady_clock::now();\n    for(CellId cellId0=0; cellId0<cellCount; cellId0++) {\n        if(cellId0!=0 && (cellId0%100000)==0) {\n            cout << timestamp << \"Working on cell \" << cellId0 << \" of \" << cellCount << endl;\n        }\n\n        // Extract the permuted signatures for this cell.\n        vector<BitSetPointer> signatures0(permutationCount);\n        for(size_t permutationId=0; permutationId<permutationCount; permutationId++) {\n           Charikar::PermutationData& p = permutationData[permutationId];\n           const size_t i = p.cellPositions[cellId0];\n           CZI_ASSERT(p.cellIds[i] == cellId0);\n           signatures0[permutationId] = p.signatures[i];\n        }\n\n\n        // Create the priority queue of Charikar pointers.\n        std::priority_queue<Charikar::Pointer> priorityQueue;\n        for(size_t permutationId=0; permutationId<permutationCount; permutationId++) {\n            Charikar::PermutationData& pd = permutationData[permutationId];\n            const size_t i = pd.cellPositions[cellId0];\n            CZI_ASSERT(pd.cellIds[i] == cellId0);\n\n            // Add the forward moving pointer.\n            if(i < cellCount-1) {\n                Charikar::Pointer pointer;\n                pointer.permutationId = permutationId;\n                pointer.index = i+1;\n                pointer.movesForward = true;\n                pointer.prefixLength = commonPrefixLength(\n                    signatures0[permutationId], pd.signatures[i+1]);\n                priorityQueue.push(pointer);\n            }\n\n            // Add the backward moving pointer.\n            if(i > 1) {\n                Charikar::Pointer pointer;\n                pointer.permutationId = permutationId;\n                pointer.index = i-1;\n                pointer.movesForward = false;\n                pointer.prefixLength = commonPrefixLength(\n                    signatures0[permutationId], pd.signatures[i-1]);\n                priorityQueue.push(pointer);\n            }\n\n        }\n\n\n\n        // The heart of the Charikar algorithm begins here.\n        // At each iteration we get the pointer with the best prefix.\n        cellNeighbors.clear();\n        for(size_t iteration=0; iteration<searchCount; iteration++) {\n\n            // Get the pointer with the best prefix.\n            if(priorityQueue.empty()) {\n                break;\n            }\n            Charikar::Pointer pointer = priorityQueue.top();\n            priorityQueue.pop();\n\n            // Compute the number of mismatches.\n            Charikar::PermutationData& pd = permutationData[pointer.permutationId];\n            const CellId cellId1 = pd.cellIds[pointer.index];\n            CZI_ASSERT(cellId1 != cellId0); // By construction.\n            const double similarity = lsh.computeCellSimilarity(cellId0, cellId1);\n            if(similarity > similarityThreshold) {\n                cellNeighbors.push_back(make_pair(cellId1, similarity));\n                if(false) {\n                    cout << cellId0 << \" \" << cellId1 << \" \" << pointer.prefixLength << \" \" << similarity << endl;\n                }\n            }\n\n            // Update the pointer and requeue it.\n            if(pointer.movesForward) {\n                if(pointer.index < cellCount-1) {\n                    ++pointer.index;\n                    pointer.prefixLength = commonPrefixLength(\n                        signatures0[pointer.permutationId], pd.signatures[pointer.index]);\n                    priorityQueue.push(pointer);\n                }\n            } else {\n                if(pointer.index > 0) {\n                    --pointer.index;\n                    pointer.prefixLength = commonPrefixLength(\n                        signatures0[pointer.permutationId], pd.signatures[pointer.index]);\n                    priorityQueue.push(pointer);\n                }\n            }\n\n        }\n\n        // Sort, deduplicate, keep the best k.\n        sort(cellNeighbors.begin(), cellNeighbors.end(),\n            OrderPairsBySecondGreaterThenByFirstLess< pair<CellId, float> >());\n        cellNeighbors.resize(unique(cellNeighbors.begin(), cellNeighbors.end()) - cellNeighbors.begin());\n        if(cellNeighbors.size() > k) {\n            cellNeighbors.resize(k);\n        }\n\n        // Store.\n        pairs[cellId0] = cellNeighbors;\n    }\n    const auto t4 = std::chrono::steady_clock::now();\n    cout << timestamp << \"Phase 2 of Charikar algorithm took \";\n    cout << 1.e-9 * double((std::chrono::duration_cast<std::chrono::nanoseconds>(t4 - t3)).count()) << \" s.\" << endl;\n\n\n\n    // Store the pairs in a SimilarPairs object.\n    cout << timestamp << \"Initializing SimilarPairs object.\" << endl;\n    SimilarPairs similarPairs(directoryName + \"/SimilarPairs-\" + similarPairsName, k, geneSet, cellSet);\n    cout << timestamp << \"Copying similar pairs.\" << endl;\n    similarPairs.copy(pairs);\n\n\n    // Sort the similar pairs for each cell by decreasing similarity.\n    // (This should not be necessary - consider removing).\n    cout << timestamp << \"Sorting similar pairs.\" << endl;\n    similarPairs.sort();\n\n    const auto t5 = std::chrono::steady_clock::now();\n    const double t05 = 1.e-9 * double((std::chrono::duration_cast<std::chrono::nanoseconds>(t5 - t0)).count());\n    cout << timestamp << \"ExpressionMatrix::findSimilarPairs6 ends. Took \" << t05 << \" s.\" << endl;\n}\n\n\n\n// Compute cell LSH signatures and store them.\nvoid ExpressionMatrix::computeLshSignatures(\n    const string& geneSetName,      // The name of the gene set to be used.\n    const string& cellSetName,      // The name of the cell set to be used.\n    const string& lshName,          // The name of the Lsh object to be created.\n    size_t lshCount,                // The number of LSH vectors to use.\n    unsigned int seed               // The seed used to generate the LSH vectors.\n    )\n{\n    cout << timestamp << \"ExpressionMatrix::computeLshSignatures begins.\" << endl;\n\n    // Locate the gene set and verify that it is not empty.\n    const auto itGeneSet = geneSets.find(geneSetName);\n    if(itGeneSet == geneSets.end()) {\n        throw runtime_error(\"Gene set \" + geneSetName + \" does not exist.\");\n    }\n    const GeneSet& geneSet = itGeneSet->second;\n    if(geneSet.size() == 0) {\n        throw runtime_error(\"Gene set \" + geneSetName + \" is empty.\");\n    }\n\n    // Locate the cell set and verify that it is not empty.\n    const auto& it = cellSets.cellSets.find(cellSetName);\n    if(it == cellSets.cellSets.end()) {\n        throw runtime_error(\"Cell set \" + cellSetName + \" does not exist.\");\n    }\n    const MemoryMapped::Vector<CellId>& cellSet = *(it->second);\n    const CellId cellCount = CellId(cellSet.size());\n    if(cellCount == 0) {\n        throw runtime_error(\"Cell set \" + cellSetName + \" is empty.\");\n    }\n\n    // Create the expression matrix subset for this gene set and cell set.\n    cout << timestamp << \"Creating expression matrix subset.\" << endl;\n    const string expressionMatrixSubsetName =\n        directoryName + \"/tmp-ExpressionMatrixSubset-\" + lshName;\n    ExpressionMatrixSubset expressionMatrixSubset(\n        expressionMatrixSubsetName, geneSet, cellSet, cellExpressionCounts);\n\n    // Create the Lsh object that will do the computation.\n    Lsh lsh(directoryName + \"/Lsh-\" + lshName, expressionMatrixSubset, lshCount, seed);\n\n    cout << timestamp << \"ExpressionMatrix::computeLshSignatures ends.\" << endl;\n}\n\n\n\n// Compare two SimilarPairs objects computed using LSH,\n// assuming that the first one was computed using a complete\n// loop on all pairs (findSimilarPairs4).\nvoid ExpressionMatrix::compareSimilarPairs(\n    const string& similarPairsName0,\n    const string& similarPairsName1)\n{\n    // Access the SimilarPairs objects.\n    const SimilarPairs similarPairs0(directoryName + \"/SimilarPairs-\" + similarPairsName0, true);\n    const SimilarPairs similarPairs1(directoryName + \"/SimilarPairs-\" + similarPairsName1, true);\n\n    // Sanity check that the two use the same gene sets and cell sets.\n    CZI_ASSERT(similarPairs0.getGeneSet() == similarPairs1.getGeneSet());\n    CZI_ASSERT(similarPairs0.getCellSet() == similarPairs1.getCellSet());\n\n    // Loop over cells.\n    ofstream csvOut(\"CompareSimilarPairs.csv\");\n    csvOut << \"CellId,Stored0,Stored1,Lowest0,Lowest1,\\n\";\n    const CellId cellCount = CellId(similarPairs0.getCellSet().size());\n    for(CellId cellId=0; cellId<cellCount; cellId++) {\n        const auto n0 = similarPairs0.size(cellId);\n        const auto n1 = similarPairs1.size(cellId);\n        const auto lowest0 = n0 ? ((similarPairs0.end(cellId)-1)->second) : 1.;\n        const auto lowest1 = n1 ? ((similarPairs1.end(cellId)-1)->second) : 1.;\n        if(n0==n1 && lowest0==lowest1) {\n            continue;\n        }\n        csvOut << cellId << \",\";\n        csvOut << n0 << \",\";\n        csvOut << n1 << \",\";\n        if(n0) {\n            csvOut << lowest0;\n        }\n        csvOut << \",\";\n        if(n1) {\n            csvOut << lowest1;\n        }\n        csvOut << \",\";\n        csvOut << \"\\n\";\n\n\n    }\n\n\n}\n\n\n// Analyze the quality of the LSH computation of cell similarity.\nvoid ExpressionMatrix::analyzeLsh(\n    const string& geneSetName,      // The name of the gene set to be used.\n    const string& cellSetName,      // The name of the cell set to be used.\n    size_t lshCount,                // The number of LSH vectors to use.\n    unsigned int seed,              // The seed used to generate the LSH vectors and to downsample.\n    double csvDownsample            // The fraction of pairs that will be included in the output spreadsheet.\n    )\n{\n\n    // Locate the gene set and verify that it is not empty.\n    const auto itGeneSet = geneSets.find(geneSetName);\n    if(itGeneSet == geneSets.end()) {\n        throw runtime_error(\"Gene set \" + geneSetName + \" does not exist.\");\n    }\n    const GeneSet& geneSet = itGeneSet->second;\n    if(geneSet.size() == 0) {\n        throw runtime_error(\"Gene set \" + geneSetName + \" is empty.\");\n    }\n\n    // Locate the cell set and verify that it is not empty.\n    const auto& it = cellSets.cellSets.find(cellSetName);\n    if(it == cellSets.cellSets.end()) {\n        throw runtime_error(\"Cell set \" + cellSetName + \" does not exist.\");\n    }\n    const MemoryMapped::Vector<CellId>& cellSet = *(it->second);\n    const CellId cellCount = CellId(cellSet.size());\n    if(cellCount == 0) {\n        throw runtime_error(\"Cell set \" + cellSetName + \" is empty.\");\n    }\n\n    // Create the expression matrix subset for this gene set and cell set.\n    cout << timestamp << \"Creating expression matrix subset.\" << endl;\n    const string expressionMatrixSubsetName =\n        directoryName + \"/tmp-ExpressionMatrixSubset\";\n    ExpressionMatrixSubset expressionMatrixSubset(\n        expressionMatrixSubsetName, geneSet, cellSet, cellExpressionCounts);\n\n\n    // Create the Lsh object that will do the computation.\n    Lsh lsh(directoryName + \"/tmp-Lsh\", expressionMatrixSubset, lshCount, seed);\n\n    // Random number generator used for downsampling\n    using RandomSource = boost::mt19937;\n    using UniformDistribution = boost::uniform_01<>;\n    RandomSource randomSource(seed);\n    UniformDistribution uniformDistribution;\n    boost::variate_generator<RandomSource, UniformDistribution>\n        uniformGenerator(randomSource, uniformDistribution);\n\n    // Statistics for bins of exact similarity values.\n    const size_t binCount = 200;\n    const double binWidth = 2. / binCount;\n    vector<size_t> sum0(binCount, 0);\n    vector<double> sum1(binCount, 0.);\n    vector<double> sum2(binCount, 0.);\n\n    // Open the output csv file.\n    ofstream csvOut( \"Lsh-analysis.csv\");\n    csvOut << \"LocalCellId0,LocalCellId1,GlobalCellId0,GlobalCellId1,ExactSimilarity,LshSimilarity\\n\";\n\n\n    // Loop over pairs of cells.\n    for(CellId localCellId0=0; localCellId0<cellCount-1; localCellId0++) {\n        if((localCellId0%1000) == 0 ) {\n            cout << timestamp << \"Working on cell \" << localCellId0 << \" of \" << cellCount << endl;\n        }\n        for(CellId localCellId1=localCellId0+1; localCellId1<cellCount; localCellId1++) {\n\n            // Compute exact similarity for this pair.\n            const double exactSimilarity = expressionMatrixSubset.\n                computeCellSimilarity(localCellId0, localCellId1);\n\n            // Compute LSH similarity for this pair.\n            const double lshSimilarity = lsh.computeCellSimilarity(localCellId0, localCellId1);\n\n            // Update statistics.\n            const double delta = lshSimilarity - exactSimilarity;\n            const size_t bin = size_t(floor((exactSimilarity+1.) / binWidth));\n            CZI_ASSERT(bin < binCount);\n            ++(sum0[bin]);\n            sum1[bin] += delta;\n            sum2[bin] += delta*delta;\n\n            // Write to the output csv file, subject to downsampling.\n            if(uniformGenerator() < csvDownsample) {\n                csvOut << localCellId0 << \",\";\n                csvOut << localCellId1 << \",\";\n                csvOut << cellSet[localCellId0] << \",\";\n                csvOut << cellSet[localCellId1] << \",\";\n                csvOut << exactSimilarity << \",\";\n                csvOut << lshSimilarity << \",\\n\";\n            }\n        }\n\n    }\n\n\n\n    // Compute average and standard deviation of the error for each bin.\n    ofstream statsOut(\"LSH-analysis-statistics.csv\");\n    statsOut << \"Similarity,Bias,Rms,RmsTheory\\n\";\n    for(size_t bin=0; bin<binCount; bin++) {\n        if(sum0[bin] < 2) {\n            continue;\n        }\n        using boost::math::double_constants::pi;\n        const double similarity = (double(bin) + 0.5) * binWidth - 1.;\n        const double sinTheta = sqrt(1.-similarity*similarity);\n        const double theta = std::acos(similarity);\n        const double p = 1.- theta / pi;\n        const double theoreticalSigma = pi * sinTheta * sqrt(p*(1.-p)/double(lshCount));\n        const double s0 = double(sum0[bin]);\n        const double s1 = sum1[bin];\n        const double s2 = sum2[bin];\n        const double average = s1 / s0;\n        const double sigma = sqrt(s2 / s0); // Sigma around 0.\n        statsOut << similarity << \",\";\n        statsOut << average << \",\";\n        statsOut << sigma << \",\";\n        statsOut << theoreticalSigma << \"\\n\";\n    }\n\n    lsh.remove();\n}\n\n\n\n// Analyze LSH signatures.\nvoid ExpressionMatrix::analyzeLshSignatures(\n    const string& geneSetName,      // The name of the gene set to be used.\n    const string& cellSetName,      // The name of the cell set to be used.\n    size_t lshCount,                // The number of LSH vectors to use.\n    unsigned int seed              // The seed used to generate the LSH vectors and to downsample.\n    )\n{\n    // Locate the gene set and verify that it is not empty.\n    const auto itGeneSet = geneSets.find(geneSetName);\n    if(itGeneSet == geneSets.end()) {\n        throw runtime_error(\"Gene set \" + geneSetName + \" does not exist.\");\n    }\n    const GeneSet& geneSet = itGeneSet->second;\n    if(geneSet.size() == 0) {\n        throw runtime_error(\"Gene set \" + geneSetName + \" is empty.\");\n    }\n\n    // Locate the cell set and verify that it is not empty.\n    const auto& it = cellSets.cellSets.find(cellSetName);\n    if(it == cellSets.cellSets.end()) {\n        throw runtime_error(\"Cell set \" + cellSetName + \" does not exist.\");\n    }\n    const MemoryMapped::Vector<CellId>& cellSet = *(it->second);\n    const CellId cellCount = CellId(cellSet.size());\n    if(cellCount == 0) {\n        throw runtime_error(\"Cell set \" + cellSetName + \" is empty.\");\n    }\n\n    // Create the expression matrix subset for this gene set and cell set.\n    cout << timestamp << \"Creating expression matrix subset.\" << endl;\n    const string expressionMatrixSubsetName =\n        directoryName + \"/tmp-ExpressionMatrixSubset\";\n    ExpressionMatrixSubset expressionMatrixSubset(\n        expressionMatrixSubsetName, geneSet, cellSet, cellExpressionCounts);\n\n\n    // Create the Lsh object that will do the computation.\n    Lsh lsh(directoryName + \"/tmp-Lsh\", expressionMatrixSubset, lshCount, seed);\n\n    // Gather cells with the same signature.\n#if 0\n    vector< pair<BitSetPointer, CellId> > table;\n    table.reserve(cellCount);\n    for(CellId cellId=0; cellId<cellCount; cellId++) {\n        table.push_back(make_pair(lsh.getSignature(cellId), cellId));\n    }\n    cout << timestamp << \"Sorting by signature.\" << endl;\n    sort(table.begin(), table.end());\n#endif\n    map<BitSetPointer, vector<CellId> > signatureMap;\n    for(CellId cellId=0; cellId<cellCount; cellId++) {\n        signatureMap[lsh.getSignature(cellId)].push_back(cellId);\n    }\n\n\n    // Create a table of signatures ordered by decreasing number of cells.\n    vector< pair<BitSetPointer, size_t> > signatureTable;\n    for(const auto& p: signatureMap) {\n        const BitSetPointer signature = p.first;\n        const size_t size = p.second.size();\n        signatureTable.push_back(make_pair(signature, size));\n    }\n    sort(signatureTable.begin(), signatureTable.end(),\n        OrderPairsBySecondGreater< pair<BitSet, size_t> >());\n\n\n\n    // Write a csv file with one line for each distinct signature.\n    {\n        ofstream csvOut(\"Signatures.csv\");\n        for(const auto& p: signatureTable) {\n            const BitSetPointer signature = p.first;\n            const size_t size = p.second;\n            csvOut << signature.getString(lshCount) << \",\" << size << \"\\n\";\n        }\n    }\n\n\n\n    vector<size_t> histogram;\n    for(const auto& p: signatureMap) {\n        const size_t size = p.second.size();\n        if(size >= histogram.size()) {\n            histogram.resize(size+1, 0);\n        }\n        ++(histogram[size]);\n    }\n    ofstream csvOut(\"Histogram.csv\");\n    size_t sum = 0;\n    for(size_t i=0; i<histogram.size(); i++) {\n        const size_t frequency = histogram[i];\n        if(frequency) {\n            sum += frequency*i;\n            csvOut << i << \",\" << frequency << \",\" << frequency*i  << \",\" << sum << \"\\n\";\n        }\n    }\n    cout << flush;\n\n\n    lsh.writeSignatureStatistics(\"LshSignatureStatistics.csv\");\n    lsh.remove();\n\n}\n", "meta": {"hexsha": "6d6999cb1ebaf1c30c689e8d515c9f3348ff99f9", "size": 63376, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ExpressionMatrixLsh.cpp", "max_stars_repo_name": "iosonofabio/ExpressionMatrix2", "max_stars_repo_head_hexsha": "a6fc6938fe857fe1bd6a9200071957691295ba3c", "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/ExpressionMatrixLsh.cpp", "max_issues_repo_name": "iosonofabio/ExpressionMatrix2", "max_issues_repo_head_hexsha": "a6fc6938fe857fe1bd6a9200071957691295ba3c", "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/ExpressionMatrixLsh.cpp", "max_forks_repo_name": "iosonofabio/ExpressionMatrix2", "max_forks_repo_head_hexsha": "a6fc6938fe857fe1bd6a9200071957691295ba3c", "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.966779661, "max_line_length": 139, "alphanum_fraction": 0.6268461247, "num_tokens": 14974, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086368, "lm_q2_score": 0.7826624738835051, "lm_q1q2_score": 0.7170046129351503}}
{"text": "/**\n *@file main.cpp\n */\n\n#include <fstream>\n#include <armadillo>\n#include \"Poly.h\"\n#include \"Basis.h\"\n#include \"Density.h\"\n#include \"time.h\"\n\n/**\n * @mainpage Calcul et trac\u00e9 de la densit\u00e9 d'un syst\u00e8me nucl\u00e9aire\n *# Densit\u00e9 nucl\u00e9aire locale\n *\\f[\\rho(\\mathbf{r})\\equiv \\sum_a \\sum_b \\rho_{ab}\\psi_a(\\mathbf{r})\\psi^*_b(\\mathbf{r})\\f]\n *avec \\f[\\rho_{ab}\\f] une matrice donn\u00e9e\n *et \\f[\\psi_a(\\mathbf{r})\\f] la fonction d'onde solution de l'\u00e9quation de Schr\u00f6dinger 3D\n\\f[\n\\psi_{m,n,n_z}(r_\\perp, \\theta, z)\n        \\equiv\n    Z(z, n_z)\n    .\n    R(r_\\perp, m, n)\n    .\n         e^{im\\theta}\n\\f]\n * # Equation de Schr\u00f6dinger\n * \\f[\\hat{H}_{(z)}\\psi_n(z) = E_n\\psi_n(z)\\f]\n */\n\n/**\n *La fonction principale\n *\n *Cette fonction a pour but de calculer les donn\u00e9es n\u00e9cessaires pour tracer les grraphes\n *\n *@return la fonction cr\u00e9er des fichier .txt et retourne 0\n */\n\nint main()\n{\n    clock_t start, finish;\n    double duration;\n\n    Basis basis(1.935801664793151,      2.829683956491218,     14,     1.3);\n\n    Density density(basis);\n\n    std::cout<< \"===Calcul de la fonction d'onde===\" << std::endl;\n    //Calcul de la densit\u00e9 2D\n    arma::vec rVals_psi = arma::linspace(-10,10,100);\n    arma::vec zVals_psi = arma::linspace(-10,10,100);\n    arma::mat psi = basis.basisFunc(0, 0, 0, zVals_psi, rVals_psi);\n    Utils::matToFile(rVals_psi, \"rVals_psi000.txt\");\n    Utils::matToFile(zVals_psi, \"zVals_psi000.txt\");\n    Utils::matToFile(psi%psi, \"Psi000.txt\");\n\n    psi = basis.basisFunc(0, 0, 1, zVals_psi, rVals_psi);\n    Utils::matToFile(rVals_psi, \"rVals_psi001.txt\");\n    Utils::matToFile(zVals_psi, \"zVals_psi001.txt\");\n    Utils::matToFile(psi%psi, \"Psi001.txt\");\n\n    psi = basis.basisFunc(0, 1, 1, zVals_psi, rVals_psi);\n    Utils::matToFile(rVals_psi, \"rVals_psi011.txt\");\n    Utils::matToFile(zVals_psi, \"zVals_psi011.txt\");\n    Utils::matToFile(psi%psi, \"Psi011.txt\");\n\n    psi = basis.basisFunc(1, 0, 1, zVals_psi, rVals_psi);\n    Utils::matToFile(rVals_psi, \"rVals_psi101.txt\");\n    Utils::matToFile(zVals_psi, \"zVals_psi101.txt\");\n    Utils::matToFile(psi%psi, \"Psi101.txt\");\n    std::cout<< \"Psi.py pour le plot Psi\" << std::endl;\n\n    std::cout<< \"===Calcul de la densit\u00e9 2D===\" << std::endl;\n    //Calcul de la densit\u00e9 2D\n    arma::vec rVals_2D = arma::linspace(-10,10,100);\n    arma::vec zVals_2D = arma::linspace(-10,10,100);\n    arma::mat R = density.calcDensity1(rVals_2D, zVals_2D);\n    Utils::matToFile(rVals_2D, \"rVals.txt\");\n    Utils::matToFile(zVals_2D, \"zVals.txt\");\n    Utils::matToFile(R, \"plot2d.txt\");\n    std::cout<< \"Density.py pour le plot 2D\" << std::endl;\n\n\n\n    std::cout<< \"===Calcul de la densit\u00e9 3D===\" << std::endl;\n    //Calcul de la densit\u00e9 3D\n    arma::vec zVals = arma::linspace(-20,20,64);\n\n    arma::mat rVals;\n\n\n    if (!rVals.load(\"rVals3d.txt\"))\n    {\n        std::cout<< \"=================================\" << std::endl;\n        std::cout<< \"ERREUR: ex\u00e9cuter python rVals3d.py\" << std::endl;\n        std::cout<< \"=================================\" << std::endl;\n    }\n\n    start = clock();\n    arma::cube results = arma::zeros(rVals.n_rows,rVals.n_cols,zVals.n_rows);\n    arma::mat result = arma::zeros(rVals.n_rows,zVals.n_rows);\n\n    for (uint i =0; i<rVals.n_cols; i++)\n    {\n        density.calcDensity1(rVals.col(i), zVals);\n        for (uint k=0; k<results.n_slices; k++)\n            results.slice(k).col(i) = result.col(k);\n        finish = clock();\n        duration = (double)(finish - start) / CLOCKS_PER_SEC;\n        std::cout<< i <<\" :\" << duration << \"s\" << std::endl;\n    }\n\n    finish = clock();\n    duration = (double)(finish - start) / CLOCKS_PER_SEC;\n    std::cout<< duration << \"s Temps de calcul de la densit\u00e9 3D\" << std::endl;\n\n    //Enregistrement des donn\u00e9es dans un fichier\n    std::ofstream out(\"plot3d.raw\");\n    if (out.is_open())\n    {\n        out << Utils::cubeToRaw(results) << std::endl;\n        out.close();\n    }\n    std::cout << \"La matrice est stock\u00e9e dans \" << \"plot3d.raw\" << std::endl;\n\n    //Analyse des performances des calculs\n    std::cout<< \"====Performances des calculs===\" << std::endl;\n\n    rVals = arma::linspace(-10,10,10);\n    zVals = arma::linspace(-10,10,10);\n\n    start = clock();\n\n    arma::mat resOp = density.calcDensityOp(rVals, zVals);\n    finish = clock();\n    duration = (double)(finish - start) / CLOCKS_PER_SEC;\n    std::cout<< duration << \"s apr\u00e8s l'optimisation 1\" << std::endl;\n\n    start = clock();\n    arma::mat res2 = density.calcDensity1(rVals, zVals);\n    finish = clock();\n    duration = (double)(finish - start) / CLOCKS_PER_SEC;\n    std::cout<< duration << \"s apr\u00e8s l'optimisation 2\" << std::endl;\n\n    start = clock();\n    arma::mat res1 = density.calcDensity(rVals, zVals);\n    finish = clock();\n    duration = (double)(finish - start) / CLOCKS_PER_SEC;\n    std::cout<< duration << \"s sans Optimization\" << std::endl;\n\n    std::cout << \"Diff\u00e9rence Op 1: \" << arma::norm(res1 - resOp) << std::endl;\n    std::cout << \"Diff\u00e9rence Op 2: \" << arma::norm(res1 - res2) << std::endl;\n\n    return 0;\n}\n\n\n", "meta": {"hexsha": "5c5d6060acc892b5180dde0c44e132a8265a6470", "size": 5016, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "DinghaoLI/Nuclear_Local_Density", "max_stars_repo_head_hexsha": "d85e01fe121c5064c8a43cca2bf2a8a1902b5013", "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/main.cpp", "max_issues_repo_name": "DinghaoLI/Nuclear_Local_Density", "max_issues_repo_head_hexsha": "d85e01fe121c5064c8a43cca2bf2a8a1902b5013", "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/main.cpp", "max_forks_repo_name": "DinghaoLI/Nuclear_Local_Density", "max_forks_repo_head_hexsha": "d85e01fe121c5064c8a43cca2bf2a8a1902b5013", "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.746835443, "max_line_length": 92, "alphanum_fraction": 0.605661882, "num_tokens": 1631, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070035949657, "lm_q2_score": 0.7879311956428946, "lm_q1q2_score": 0.7169441132664249}}
{"text": "/*\n * PolynomialSpline.hpp\n *\n *  Created on: Mar 7, 2017\n *      Author: Dario Bellicoso\n */\n\n#pragma once\n\n// eigen\n#include <Eigen/Core>\n\n// curves\n#include \"curves/polynomial_splines_traits.hpp\"\n\nnamespace curves {\n\n/*\n * This class is the implementation of a scalar polinomial spline s(t) function of a scalar t.\n * The spline is define as\n *    s(t) = an*t^n + ... + a1*t + a0 = sum(ai*t^i)\n *\n *  The spline coefficients are stored in a standard container as\n *    alpha = [an ... a1 a0]\n */\ntemplate <int splineOrder_>\nclass PolynomialSpline {\n public:\n\n  static constexpr unsigned int splineOrder = splineOrder_;\n  static constexpr unsigned int coefficientCount = splineOrder + 1;\n\n  using SplineImplementation = spline_traits::spline_rep<double, splineOrder>;\n  using SplineCoefficients = typename SplineImplementation::SplineCoefficients;\n  using EigenTimeVectorType = Eigen::Matrix<double, 1, coefficientCount>;\n  using EigenCoefficientVectorType = Eigen::Matrix<double, coefficientCount, 1>;\n\n  PolynomialSpline() :\n    duration_(0.0),\n    didEvaluateCoeffs_(false),\n    coefficients_()\n  {\n\n  }\n\n  PolynomialSpline(const SplineCoefficients& coefficients, double duration) :\n    duration_(duration),\n    didEvaluateCoeffs_(true),\n    coefficients_(coefficients)\n  {\n\n  }\n\n  PolynomialSpline(SplineCoefficients&& coefficients, double duration) :\n    duration_(duration),\n    didEvaluateCoeffs_(true),\n    coefficients_(std::forward<SplineCoefficients>(coefficients))\n  {\n\n  }\n\n  virtual ~PolynomialSpline() {\n\n  }\n\n  PolynomialSpline(PolynomialSpline &&) = default;\n  PolynomialSpline& operator=(PolynomialSpline &&) = default;\n\n  PolynomialSpline(const PolynomialSpline&) = default;\n  PolynomialSpline& operator=(const PolynomialSpline&) = default;\n\n  //! Get the coefficients of the spline.\n  const SplineCoefficients& getCoefficients() const {\n    return coefficients_;\n  }\n\n  //! Compute the coefficients of the spline.\n  bool computeCoefficients(const SplineOptions& options) {\n    SplineImplementation::compute(options, coefficients_);\n    duration_ = options.tf_;\n    return true;\n  }\n\n  //! Set the coefficients and the duration of the spline.\n  void setCoefficientsAndDuration(const SplineCoefficients& coefficients, double duration) {\n    coefficients_ = coefficients;\n    duration_ = duration;\n  }\n\n  //! Set the coefficients and the duration of the spline.\n  void setCoefficientsAndDuration(const EigenCoefficientVectorType& coefficients, double duration) {\n    for (unsigned int k=0; k<coefficientCount; k++) {\n      coefficients_[k] = coefficients(k);\n    }\n    duration_ = duration;\n  }\n\n  //! Get the spline evaluated at time tk.\n  constexpr double getPositionAtTime(double tk) const {\n    return std::inner_product(coefficients_.begin(), coefficients_.end(),\n                              SplineImplementation::tau(std::max(0.0, std::min(tk, duration_))).begin(), 0.0);\n  }\n\n  //! Get the first derivative of the spline evaluated at time tk.\n  constexpr double getVelocityAtTime(double tk) const {\n    return std::inner_product(coefficients_.begin(), coefficients_.end(),\n                              SplineImplementation::dtau(std::max(0.0, std::min(tk, duration_))).begin(), 0.0);\n  }\n\n  //! Get the second derivative of the spline evaluated at time tk.\n  constexpr double getAccelerationAtTime(double tk) const {\n    return std::inner_product(coefficients_.begin(), coefficients_.end(),\n                              SplineImplementation::ddtau(std::max(0.0, std::min(tk, duration_))).begin(), 0.0);\n  }\n\n  //! Get the time vector tau evaluated at time tk.\n  static inline void getTimeVector(Eigen::Ref<EigenTimeVectorType> timeVec, double tk) {\n    timeVec = Eigen::Map<EigenTimeVectorType>(SplineImplementation::tau(tk).data());\n  }\n\n  //! Get the first derivative of the time vector tau evaluated at time tk.\n  static inline void getdTimeVector(Eigen::Ref<EigenTimeVectorType> dtimeVec, double tk) {\n    dtimeVec = Eigen::Map<EigenTimeVectorType>(SplineImplementation::dtau(tk).data());\n  }\n\n  //! Get the second derivative of the time vector tau evaluated at time tk.\n  static inline void getddTimeVector(Eigen::Ref<EigenTimeVectorType> ddtimeVec, double tk) {\n    ddtimeVec = Eigen::Map<EigenTimeVectorType>(SplineImplementation::ddtau(tk).data());\n  }\n\n  //! Get the time vector tau evaluated at zero.\n  static inline void getTimeVectorAtZero(Eigen::Ref<EigenTimeVectorType> timeVec) {\n    timeVec = Eigen::Map<const EigenTimeVectorType>((SplineImplementation::tauZero).data());\n  }\n\n  //! Get the first derivative of the time vector tau evaluated at zero.\n  static inline void getdTimeVectorAtZero(Eigen::Ref<EigenTimeVectorType> dtimeVec) {\n    dtimeVec = Eigen::Map<const EigenTimeVectorType>((SplineImplementation::dtauZero).data());\n  }\n\n  //! Get the second derivative of the time vector tau evaluated at zero.\n  static inline void getddTimeVectorAtZero(Eigen::Ref<EigenTimeVectorType> ddtimeVec) {\n    ddtimeVec = Eigen::Map<const EigenTimeVectorType>((SplineImplementation::ddtauZero).data());\n  }\n\n  //! Get the duration of the spline in seconds.\n  double getSplineDuration() const {\n    return duration_;\n  }\n\n protected:\n  //! The duration of the spline in seconds.\n  double duration_;\n\n  //! True if the coefficents were computed at least once.\n  bool didEvaluateCoeffs_;\n\n  /*\n   * s(t) = an*t^n + ... + a1*t + a0\n   * splineCoeff_ = [an ... a1 a0]\n   */\n  SplineCoefficients coefficients_;\n};\n\n} /* namespace */\n", "meta": {"hexsha": "be681f64759abda2e355779e706c46b956c4c916", "size": 5465, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "curves/include/curves/PolynomialSpline.hpp", "max_stars_repo_name": "frontw/curves", "max_stars_repo_head_hexsha": "b442b753922ec270c46096d169a8042e0ef9a5f3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-08-21T08:58:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-02T16:17:52.000Z", "max_issues_repo_path": "curves/include/curves/PolynomialSpline.hpp", "max_issues_repo_name": "copark86/curves", "max_issues_repo_head_hexsha": "b442b753922ec270c46096d169a8042e0ef9a5f3", "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": "curves/include/curves/PolynomialSpline.hpp", "max_forks_repo_name": "copark86/curves", "max_forks_repo_head_hexsha": "b442b753922ec270c46096d169a8042e0ef9a5f3", "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.921686747, "max_line_length": 112, "alphanum_fraction": 0.714547118, "num_tokens": 1326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070011518829, "lm_q2_score": 0.787931190663057, "lm_q1q2_score": 0.7169441068102547}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// QuickBook Example\n\n// Copyright (c) 2020 Digvijay Janartha, Hamirpur, India.\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//[disjoint\n//` Checks if two geometries are disjoint\n\n#include <iostream>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n\nnamespace bg = boost::geometry; /*< Convenient namespace alias >*/\n\nint main()\n{\n    // Checks if two geometries are disjoint, which means that two geometries have zero intersection.\n    bg::model::polygon<bg::model::d2::point_xy<double> > poly1;\n    bg::read_wkt(\"POLYGON((0 2,-2 0,-4 2,-2 4,0 2))\", poly1);\n    bg::model::polygon<bg::model::d2::point_xy<double> > poly2;\n    bg::read_wkt(\"POLYGON((2 2,4 4,6 2,4 0,2 2))\", poly2);\n    bool check_disjoint = bg::disjoint(poly1, poly2);\n    if (check_disjoint) {\n         std::cout << \"Disjoint: Yes\" << std::endl;\n    } else {\n        std::cout << \"Disjoint: No\" << std::endl;\n    }\n\n    bg::model::polygon<bg::model::d2::point_xy<double> > poly3;\n    bg::read_wkt(\"POLYGON((0 2,2 4,4 2,2 0,0 2))\", poly3);\n    check_disjoint = bg::disjoint(poly1, poly3);\n    if (check_disjoint) {\n         std::cout << \"Disjoint: Yes\" << std::endl;\n    } else {\n        std::cout << \"Disjoint: No\" << std::endl;\n    }\n\n    return 0;\n}\n\n//]\n\n\n//[disjoint_output\n/*`\nOutput:\n[pre\nDisjoint: Yes\nDisjoint: No\n\n[$img/algorithms/disjoint.png]\n\n]\n*/\n//]\n", "meta": {"hexsha": "6beffc27aaae34260db5d3a39afe3533db7339f9", "size": 1611, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/src/examples/algorithms/disjoint.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/algorithms/disjoint.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": "doc/src/examples/algorithms/disjoint.cpp", "max_forks_repo_name": "jkerkela/geometry", "max_forks_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_forks_repo_licenses": ["BSL-1.0"], "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": 25.9838709677, "max_line_length": 101, "alphanum_fraction": 0.6480446927, "num_tokens": 508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511579973932, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7168780103767454}}
{"text": "/**\n * @file taylorode.cc\n * @brief NPDE homework TaylorODE\n * @author ?, Philippe Peter\n * @date 24.03.2021\n * @copyright Developed at ETH Zurich\n */\n\n#include \"taylorode.h\"\n\n#include <Eigen/Core>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\nnamespace TaylorODE {\n\n/* SAM_LISTING_BEGIN_1 */\nEigen::Vector2d PredPreyModel::f(const Eigen::Vector2d& y) const {\n  return {(alpha1_ - beta1_ * y(1)) * y(0), (beta2_ * y(0) - alpha2_) * y(1)};\n}\n\nEigen::Vector2d PredPreyModel::df(const Eigen::Vector2d& y,\n                                  const Eigen::Vector2d& z) const {\n  Eigen::Matrix2d Df;\n  Df << alpha1_ - beta1_ * y(1), -beta1_ * y(0), beta2_ * y(1),\n      -alpha2_ + beta2_ * y(0);\n  return Df * z;\n}\n\nEigen::Vector2d PredPreyModel::d2f(const Eigen::Vector2d& y,\n                                   const Eigen::Vector2d& z) const {\n  Eigen::Matrix2d H1, H2;\n  H1 << 0, -beta1_, -beta1_, 0;\n  H2 << 0, beta2_, beta2_, 0;\n  return {z.transpose() * H1 * z, z.transpose() * H2 * z};\n}\n\nstd::vector<Eigen::Vector2d> SolvePredPreyTaylor(const PredPreyModel& model,\n                                                 double T,\n                                                 const Eigen::Vector2d& y0,\n                                                 unsigned int M) {\n  std::vector<Eigen::Vector2d> res;\n  res.reserve(M + 1);\n\n  Eigen::Vector2d y = y0;\n  double h = T / M;\n  res.push_back(y);\n\n  for (unsigned int k = 0; k < M; ++k) {\n    // evaluate terms for taylor step.\n    auto fy = model.f(y);\n    auto dfyfy = model.df(y, fy);\n    auto df2yfy = model.df(y, dfyfy);\n    auto d2fyfy = model.d2f(y, fy);\n\n    // evaluate taylor expansion to compute update\n    y = y + h * fy + 0.5 * h * h * dfyfy +\n        1.0 / 6.0 * h * h * h * (df2yfy + d2fyfy);\n\n    // save new state:\n    res.push_back(y);\n  }\n  return res;\n}\n/* SAM_LISTING_END_1 */\n\n/* SAM_LISTING_BEGIN_2 */\ndouble TestCvgTaylorMethod() {\n  // initialize parameters for the model:\n  double T = 10;               // final time\n  Eigen::Vector2d y0(100, 5);  // initial condition\n  Eigen::Vector2d yex(0.319465882659820,\n                      9.730809352326228);  // reference solution\n  double alpha1 = 3.0;\n  double alpha2 = 2.0;\n  double beta1 = 0.1;\n  double beta2 = 0.1;\n  PredPreyModel model(alpha1, alpha2, beta1, beta2);\n\n  // Initialize parameters for the convergence study\n  unsigned int M0 = 128;    // Minimum number of timesteps\n  unsigned int numRef = 8;  // Number of refinements\n\n  // Convergence study\n  Eigen::ArrayXd error(numRef);\n  Eigen::ArrayXd M(numRef);\n  for (unsigned int i = 0; i < numRef; ++i) {\n    M(i) = std::pow(2, i) * M0;\n    auto res = SolvePredPreyTaylor(model, T, y0, M(i));\n    error(i) = (res.back() - yex).norm();\n  }\n\n  PrintErrorTable(M, error);\n\n  // calculate linear regression line: log(error) ~ c0 + c1*log(M)\n  Eigen::MatrixXd A(numRef, 2);\n  A.col(0) = Eigen::VectorXd::Ones(numRef);\n  A.col(1) = M.log();\n  Eigen::VectorXd logError = error.log();\n  Eigen::Vector2d coeffs = A.householderQr().solve(logError);\n\n  // estimated convergence rate: -c1\n  return -coeffs(1);\n}\n/* SAM_LISTING_END_2 */\n\nvoid PrintErrorTable(const Eigen::ArrayXd& M, const Eigen::ArrayXd& error) {\n  std::cout << std::setw(15) << \"M\" << std::setw(15) << \"error\" << std::setw(15)\n            << \"rate\" << std::endl;\n\n  for (unsigned int i = 0; i < M.size(); ++i) {\n    std::cout << std::setw(15) << M(i) << std::setw(15) << error(i);\n    if (i > 0) {\n      std::cout << std::setw(15) << std::log2(error(i - 1) / error(i));\n    }\n    std::cout << std::endl;\n  }\n}\n\n}  // namespace TaylorODE\n", "meta": {"hexsha": "d6c641e699282435b103eecc889cd3136db4f9de", "size": 3602, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/TaylorODE/mastersolution/taylorode.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": "homeworks/TaylorODE/mastersolution/taylorode.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": "homeworks/TaylorODE/mastersolution/taylorode.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": 29.2845528455, "max_line_length": 80, "alphanum_fraction": 0.5780122154, "num_tokens": 1165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.8558511396138366, "lm_q1q2_score": 0.7168780001820956}}
{"text": "/**\n * @file semimprk.cc\n * @brief NPDE homework SemImpRK code\n * @author Unknown, Oliver Rietmann\n * @date 04.04.2021\n * @copyright Developed at ETH Zurich\n */\n\n#include \"semimprk.h\"\n\n#include <Eigen/Core>\n#include <algorithm>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\n#include \"polyfit.h\"\n\nnamespace SemImpRK {\n\n/* SAM_LISTING_BEGIN_0 */\ndouble cvgRosenbrock() {\n  double cvgRate = 0.0;\n  // TO DO: (13-2.d) Use polyfit() to estimate the rate of convergence\n  // for solveRosenbrock().\n  // Final time\n  const double T = 10.0;\n  // Mesh sizes h=2^{-k} for k in K.\n  const Eigen::ArrayXd K = Eigen::ArrayXd::LinSpaced(7, 4, 10);\n\n  // Initial data\n  Eigen::Vector2d y0(1., 1.);\n  // Parameter and useful matrix for f\n  const double lambda = 1;\n  Eigen::Matrix2d R;\n  R << 0.0, -1.0, 1.0, 0.0;\n\n  // Function and its Jacobian\n  auto f = [&R, &lambda](Eigen::Vector2d y) {\n    return R * y + lambda * (1.0 - y.squaredNorm()) * y;\n  };\n  auto df = [&lambda](Eigen::Vector2d y) {\n    double x = 1 - y.squaredNorm();\n    Eigen::Matrix2d J;\n    J << lambda * x - 2 * lambda * y(0) * y(0), -1 - 2 * lambda * y(1) * y(0),\n        1 - 2 * lambda * y(1) * y(0), lambda * x - 2 * lambda * y(1) * y(1);\n    return J;\n  };\n\n  // Reference mesh size\n  const int N_ref = 10 * std::pow(2, 12);\n  // Reference solution\n  std::vector<Eigen::VectorXd> solref = solveRosenbrock(f, df, y0, N_ref, T);\n\n  Eigen::ArrayXd Error(K.size());\n  std::cout << std::setw(15) << \"N\" << std::setw(16) << \"maxerr\\n\";\n  // Main loop: loop over all meshes\n  for (unsigned int i = 0; i < K.size(); ++i) {\n    // h = 2^{-k} => N = T*h = T*2^k\n    int N = T * std::pow(2, K[i]);\n    // Get solution\n    std::vector<Eigen::VectorXd> sol = solveRosenbrock(f, df, y0, N, T);\n    // Compute error\n    double maxerr = 0;\n    for (unsigned int j = 0; j < sol.size(); ++j) {\n      maxerr =\n          std::max(maxerr, (sol.at(j) - solref.at((j * N_ref) / N)).norm());\n    }\n\n    Error[i] = maxerr;\n    std::cout << std::setw(15) << N << std::setw(16) << maxerr << std::endl;\n  }\n  // Use log(N)=log(T*2^k)=log(T)+log(2)*k to get natural logarithm of N.\n  cvgRate = -polyfit(std::log(2.0) * K, Error.log(), 1)(0);\n  return cvgRate;\n}\n/* SAM_LISTING_END_0 */\n\n}  // namespace SemImpRK\n", "meta": {"hexsha": "17f860130fcba6bf9a0b8bca4eb031a2b80686e0", "size": 2270, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/SemImpRK/mastersolution/semimprk.cc", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "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": "homeworks/SemImpRK/mastersolution/semimprk.cc", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "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": "homeworks/SemImpRK/mastersolution/semimprk.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "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.024691358, "max_line_length": 78, "alphanum_fraction": 0.5806167401, "num_tokens": 814, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511359371249, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7168779918986244}}
{"text": "\n#pragma once\n\n#include \"perceive/foundation.hpp\"\n#include \"perceive/geometry/vector.hpp\"\n#include <Eigen/Dense>\n\nnamespace perceive\n{\n// ------------------------------------------------------------------- is-finite\n\nbool is_finite(const Vector2r& M);\nbool is_finite(const Vector3r& M);\nbool is_finite(const Vector4r& M);\nbool is_finite(const Matrix3r& M);\nbool is_finite(const Matrix34r& M);\nbool is_finite(const MatrixXr& M);\n\n// ------------------------------------------------------------------- normalize\n\ninline Vector3r& normalize(Vector3r& X)\n{\n   auto norm_inv = 1.0 / X.norm();\n   X *= norm_inv;\n   return X;\n}\n\ninline Vector3r normalized(const Vector3r& X)\n{\n   auto Y(X);\n   normalize(Y);\n   return Y;\n}\n\n// ------------------------------------------------------------------------- str\n\nstd::string str(const Vector2r& M);\nstd::string str(const Vector3r& M);\nstd::string str(const Vector4r& M);\nstd::string str(const Matrix3r& M);\nstd::string str(const Matrix34r& M);\nstd::string str(const MatrixXr& M);\n\nstd::string str(std::string name, const Matrix3r& M);\nstd::string str(std::string name, const Matrix34r& M);\nstd::string str(std::string name, const MatrixXr& M);\n\n// ------------------------------------------------------------------------- SVD\n\nreal svd_thin(const MatrixXr& M, VectorXr& out);\nreal svd_thin(const Matrix3r& M, Vector3r& out);\n// real svd_thin(const Matrix3d& M, Vector3d& out);\n// real svd_thin(const MatrixXd& M, VectorXd& out);\nreal svd_thin(const MatrixXr& M, Vector6r& out);\nvoid svd_UV(const MatrixXr& M, MatrixXr& U, MatrixXr& V);\nvoid svd_UV(const Matrix3r& M, Matrix3r& U, Matrix3r& V);\n// void svd_UV(const MatrixXd& M, MatrixXd& U, MatrixXd& V);\nvoid svd_UDV(const MatrixXr& M, MatrixXr& U, VectorXr& D, MatrixXr& V);\nvoid svd_UDV(const Matrix3r& M, Matrix3r& U, Vector3r& D, Matrix3r& V);\nvoid svd_UDV(const Matrix3r& M, Matrix3r& U, Matrix3r& D, Matrix3r& V);\n// void svd_UDV(const MatrixXd& M, MatrixXd& U, VectorXd& D, MatrixXd& V);\n\nvoid svd_UDV(const Eigen::Matrix<std::complex<long double>, 3, 3>& M,\n             Eigen::Matrix<std::complex<long double>, 3, 3>& U,\n             Eigen::Matrix<std::complex<long double>, 3, 1>& D,\n             Eigen::Matrix<std::complex<long double>, 3, 3>& V);\nvoid svd_UDV(const Eigen::Matrix<std::complex<double>, 3, 3>& M,\n             Eigen::Matrix<std::complex<double>, 3, 3>& U,\n             Eigen::Matrix<std::complex<double>, 3, 1>& D,\n             Eigen::Matrix<std::complex<double>, 3, 3>& V);\nvoid svd_UDV(const Eigen::Matrix<std::complex<float>, 3, 3>& M,\n             Eigen::Matrix<std::complex<float>, 3, 3>& U,\n             Eigen::Matrix<std::complex<float>, 3, 1>& D,\n             Eigen::Matrix<std::complex<float>, 3, 3>& V);\n\nvoid svd_UDV(\n    const Eigen::\n        Matrix<std::complex<long double>, Eigen::Dynamic, Eigen::Dynamic>& M,\n    Eigen::Matrix<std::complex<long double>, Eigen::Dynamic, Eigen::Dynamic>& U,\n    Eigen::Matrix<std::complex<long double>, Eigen::Dynamic, 1>& D,\n    Eigen::Matrix<std::complex<long double>, Eigen::Dynamic, Eigen::Dynamic>&\n        V);\n\nvoid svd_UDV(\n    const Eigen::Matrix<std::complex<double>, Eigen::Dynamic, Eigen::Dynamic>&\n        M,\n    Eigen::Matrix<std::complex<double>, Eigen::Dynamic, Eigen::Dynamic>& U,\n    Eigen::Matrix<std::complex<double>, Eigen::Dynamic, 1>& D,\n    Eigen::Matrix<std::complex<double>, Eigen::Dynamic, Eigen::Dynamic>& V);\n\nvoid svd_UDV(\n    const Eigen::Matrix<std::complex<float>, Eigen::Dynamic, Eigen::Dynamic>& M,\n    Eigen::Matrix<std::complex<float>, Eigen::Dynamic, Eigen::Dynamic>& U,\n    Eigen::Matrix<std::complex<float>, Eigen::Dynamic, 1>& D,\n    Eigen::Matrix<std::complex<float>, Eigen::Dynamic, Eigen::Dynamic>& V);\n\n// double bdcsvd_thin(const MatrixXd& M, VectorXd& out);\nreal bdcsvd_thin(const MatrixXr& M, VectorXr& out);\n\ntemplate<typename T> struct CentreEigenVectorResult\n{\n   T C;                           // centre\n   vector<std::pair<T, real>> Es; // {eigenvectors, eigenvalues}\n};\n\ntemplate<typename InputIt>\nauto calc_centre_and_eigenvectors(InputIt begin, InputIt end)\n    -> CentreEigenVectorResult<\n        typename std::iterator_traits<InputIt>::value_type>;\n\n// For best results, centre and scale the data before performing svd-3d-UDV\nstruct SVD3DRet\n{\n   Matrix3r U, V;\n   Vector3r D;\n   Matrix3r Dm() const noexcept; // `D` as a Diagonal Matrix\n   string to_string() const noexcept;\n   friend string str(const SVD3DRet& o) noexcept { return o.to_string(); }\n   Vector3r eigen_vector(int ind) const noexcept;\n   Quaternion rot_vec() const noexcept;\n};\n\ntemplate<typename InputIt> SVD3DRet svd_3d_UDV(InputIt start, InputIt finish);\n\n// ------------------------------------------------------------ condition-number\n\nreal condition_number(const MatrixXr& M);\nreal condition_number(const Matrix3r& M);\n\n// ----------------------------------------------------------------- matrix rank\n\ntemplate<typename T> inline unsigned matrix_rank(const T& M)\n{\n   Eigen::FullPivLU<T> lu(M);\n   return lu.rank();\n}\n\n// ------------------------------------------------------------------ null space\ntemplate<typename T> inline T matrix_kernel(const T& M)\n{\n   Eigen::FullPivLU<T> lu(M);\n   T out = lu.kernel();\n   return out;\n}\n\n// -------------------------------------------------------- Cross-product Matrix\n\nvoid to_cross_product_matrix(const Vector3& X, Matrix3r& M);\nvoid to_cross_product_matrix(const Vector3r& X, Matrix3r& M);\nMatrix3r make_cross_product_matrix(const Vector3& X);\nMatrix3r make_cross_product_matrix(const Vector3r& X);\n\n// --------------------------------------------------- Quadratic with Constraint\n\n// Minimize xGtGx such that Hx = h\n//  * G must have more rows than columns.\n//  * G.cols() == H.cols()\nMatrixXr minimize_with_constraint(const MatrixXr& G, const MatrixXr& H, real h);\n\n//\n//\n//\n//\n//\n//\n//\n//\n//                                Implementations\n//\n//\n//\n//\n//\n//\n//\n\ntemplate<typename InputIt>\nauto calc_centre_and_eigenvectors(InputIt begin, InputIt end)\n    -> CentreEigenVectorResult<\n        typename std::iterator_traits<InputIt>::value_type>\n{\n   using T   = typename std::iterator_traits<InputIt>::value_type;\n   using Ret = CentreEigenVectorResult<T>;\n\n   Ret out;\n   const int sz = std::distance(begin, end);\n   const int N  = (sz == 0) ? -1 : begin->size();\n   if(sz < N) return out;\n\n   // Calculate the centre\n   T C;\n   for(auto i = 0; i < sz; ++i) C(i) = 0.0;\n   for(auto ii = begin; ii != end; ++ii) { C += *ii; }\n   C /= sz;\n\n   // Create matrices\n   MatrixXr A(sz, N);\n   int pos = 0;\n   for(auto ii = begin; ii != end; ++ii, ++pos) {\n      for(auto j = 0; j < N; ++j) A(pos, j) = ii->operator()(j) - C(j);\n   }\n\n   MatrixXr At  = A.transpose();\n   MatrixXr AtA = At * A;\n\n   MatrixXr U, V;\n   VectorXr D;\n   svd_UDV(A, U, D, V);\n\n   Expects(V.rows() == N);\n   Expects(V.cols() == N);\n\n   out.C = C;\n   out.Es.resize(N);\n   for(auto i = 0; i < N; ++i) {\n      auto& E  = out.Es[i];\n      E.second = D(i);\n      for(auto j = 0; j < N; ++j) { E.first(j) = V(j, i); }\n   }\n\n   return out;\n}\n\n// -------------------------------------------------------------------svd-3d-UDV\n// For best results, center and scale the data first.\ntemplate<typename InputIt> SVD3DRet svd_3d_UDV(InputIt start, InputIt finish)\n{\n   using T = typename std::iterator_traits<InputIt>::value_type;\n\n   const size_t n_rows     = size_t(std::distance(start, finish));\n   constexpr size_t n_cols = 3;\n   Expects(n_rows >= n_cols);\n\n   auto M  = MatrixXr(n_rows, n_cols);\n   int row = 0;\n   for(auto ii = start; ii != finish; ++ii) {\n      const T& o = *ii;\n      Expects(o.size() == n_cols);\n      for(int col = 0; col < int(n_cols); ++col) M(row, col) = real(o(col));\n      ++row;\n   }\n\n   MatrixXr Mt  = M.transpose();\n   MatrixXr MtM = Mt * M;\n\n   SVD3DRet ret;\n   svd_UDV(MtM, ret.U, ret.D, ret.V);\n\n   return {ret};\n}\n\n} // namespace perceive\n", "meta": {"hexsha": "a2f77d84ac977db1a4028e1c09830b2c929612e2", "size": 7866, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "multiview/multiview_cpp/src/perceive/utils/eigen-helpers.hpp", "max_stars_repo_name": "prcvlabs/multiview", "max_stars_repo_head_hexsha": "1a03e14855292967ffb0c0ec7fff855c5abbc9d2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-09-03T23:12:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T21:43:32.000Z", "max_issues_repo_path": "multiview/multiview_cpp/src/perceive/utils/eigen-helpers.hpp", "max_issues_repo_name": "prcvlabs/multiview", "max_issues_repo_head_hexsha": "1a03e14855292967ffb0c0ec7fff855c5abbc9d2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-09-08T02:57:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T05:33:02.000Z", "max_forks_repo_path": "multiview/multiview_cpp/src/perceive/utils/eigen-helpers.hpp", "max_forks_repo_name": "prcvlabs/multiview", "max_forks_repo_head_hexsha": "1a03e14855292967ffb0c0ec7fff855c5abbc9d2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-09-26T03:14:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T06:42:52.000Z", "avg_line_length": 31.0909090909, "max_line_length": 80, "alphanum_fraction": 0.5945842868, "num_tokens": 2212, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146780175245, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.716709012188222}}
{"text": "#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <sys/time.h>\n#include <stdlib.h>\n#include <math.h>\n#include <inttypes.h>\n#include <string.h>\n\n#include <adept_source.h>\n#include <adept_arrays.h>\nusing adept::adouble;\nusing adept::aMatrix;\nusing adept::aVector;\n\nusing adept::Vector;\n\nextern int enzyme_const;\ntemplate<typename Return, typename... T>\nReturn __enzyme_autodiff(T...);\n\nfloat tdiff(struct timeval *start, struct timeval *end) {\n  return (end->tv_sec-start->tv_sec) + 1e-6*(end->tv_usec-start->tv_usec);\n}\n\n\nstatic double sum(const double *x, size_t n) {\n    double res = 0;\n    for(int i=0; i<n; i++) {\n        res+=x[i];\n    }\n    return res;\n}\n\nstatic double max(double x, double y) {\n    return (x > y) ? x : y;\n}\n\nstatic adouble amax(adouble x, adouble y) {\n    return (x > y) ? x : y;\n}\n\nstatic double logsumexp(const double *__restrict x, size_t n) {\n  double A = x[0];\n  for(int i=0; i<n; i++) {\n    A = max(A, x[i]);\n  }\n  double sema = 0;\n  for(int i=0; i<n; i++) {\n    sema += exp(x[i] - A);\n  }\n  return log(sema) + A;\n}\n\n\nstatic adouble alogsumexp(const aVector &x, size_t n) {\n  adouble A = x[0];\n  for(int i=0; i<n; i++) {\n    A = amax(A, x[i]);\n  }\n  adouble ema[n];\n  for(int i=0; i<n; i++) {\n    ema[i] = exp(x[i] - A);\n  }\n  adouble sema = 0;\n  for(int i=0; i<n; i++)\n    sema += ema[i];\n  return log(sema) + A;\n}\n\n\nextern \"C\" {\n#include <adBuffer.h>\n}\n\n/*\n  Differentiation of logsumexp in reverse (adjoint) mode:\n   gradient     of useful results: *x logsumexp\n   with respect to varying inputs: *x\n   RW status of diff variables: *x:incr logsumexp:in-killed\n   Plus diff mem management of: x:in\n*/\nstatic void logsumexp_b(const double *__restrict x, double *xb, size_t n, double logsumexpb) {\n    double A = x[0];\n    double Ab = 0.0;\n    int branch;\n    double logsumexp;\n    for (int i = 0; i < n; ++i)\n        if (A < x[i]) {\n            A = x[i];\n            pushControl1b(0);\n        } else {\n            pushControl1b(1);\n            A = A;\n        }\n    double sema = 0;\n    double semab = 0.0;\n    for (int i = 0; i < n; ++i)\n        sema = sema + exp(x[i] - A);\n    semab = logsumexpb/sema;\n    Ab = logsumexpb;\n    {\n      double tempb;\n      for (int i = n-1; i > -1; --i) {\n          tempb = exp(x[i]-A)*semab;\n          xb[i] = xb[i] + tempb;\n          Ab = Ab - tempb;\n      }\n    }\n    for (int i = n-1; i > -1; --i) {\n        popControl1b(&branch);\n        if (branch == 0) {\n            xb[i] = xb[i] + Ab;\n            Ab = 0.0;\n        }\n    }\n    xb[0] = xb[0] + Ab;\n}\n\nadouble alogsumexp2(const aVector &x, size_t n) {\n  adouble A = x[0];\n  for(int i=0; i<n; i++) {\n    A = amax(A, x[i]);\n  }\n  return adept::log(adept::sum(exp(x - A))) + A;\n}\n\nstatic void adept_sincos(double *input, double *inputp, unsigned long n, unsigned long repeat) {\n  {\n  struct timeval start, end;\n  //gettimeofday(&start, NULL);\n \n  adept::Stack stack;\n \n  aVector inp(n);\n  for(int i=0; i<n; i++) inp(i) = input[i];\n  memset(inputp, 0, sizeof(double)*n);\n  double total = 0;\n\n  gettimeofday(&start, NULL);\n  for (int iter = 0; iter < repeat; iter++) {\n    stack.new_recording();\n    adouble resa = alogsumexp(inp, n);\n    stack.pause_recording();\n    total += resa.value();\n    stack.continue_recording();\n  }\n  gettimeofday(&end, NULL);\n\n  stack.pause_recording();\n\n  printf(\"adept forward (recording) %0.6f res'=%f\\n\", tdiff(&start, &end), total);\n  }\n  {\n  struct timeval start, end;\n  //gettimeofday(&start, NULL);\n \n  adept::Stack stack;\n \n  aVector inp(n);\n  for(int i=0; i<n; i++) inp(i) = input[i];\n  memset(inputp, 0, sizeof(double)*n);\n\n  gettimeofday(&start, NULL);\n  for (int iter = 0; iter < repeat; iter++) {\n    stack.new_recording();\n    adouble resa = alogsumexp(inp, n);\n    resa.set_gradient(1.0);\n    stack.reverse();\n    stack.pause_recording();\n    for (int i = 0; i < n; i++) {\n        inputp[i] += inp(i).get_gradient();\n    }\n    stack.continue_recording();\n  }\n  gettimeofday(&end, NULL);\n\n  stack.pause_recording();\n\n  printf(\"adept forward reverse %0.6f res'=%f\\n\", tdiff(&start, &end), sum(inputp, n));\n  }\n}\nstatic void adept2_sincos(double *input, double *inputp, unsigned long n, unsigned long repeat) {\n  {\n  struct timeval start, end;\n  //gettimeofday(&start, NULL);\n \n  adept::Stack stack;\n \n  aVector inp(n);\n  for(int i=0; i<n; i++) inp(i) = input[i];\n  memset(inputp, 0, sizeof(double)*n);\n  double total = 0;\n\n  gettimeofday(&start, NULL);\n  for (int iter = 0; iter < repeat; iter++) {\n    stack.new_recording();\n    adouble resa = alogsumexp2(inp, n);\n    stack.pause_recording();\n    total += resa.value();\n    stack.continue_recording();\n  }\n  gettimeofday(&end, NULL);\n\n  stack.pause_recording();\n\n  printf(\"adept2 forward (recording) %0.6f res'=%f\\n\", tdiff(&start, &end), total);\n  }\n  {\n  struct timeval start, end;\n  //gettimeofday(&start, NULL);\n \n  adept::Stack stack;\n \n  aVector inp(n);\n  for(int i=0; i<n; i++) inp(i) = input[i];\n  memset(inputp, 0, sizeof(double)*n);\n\n  gettimeofday(&start, NULL);\n  for (int iter = 0; iter < repeat; iter++) {\n    stack.new_recording();\n    adouble resa = alogsumexp2(inp, n);\n    resa.set_gradient(1.0);\n    stack.reverse();\n    stack.pause_recording();\n    for (int i = 0; i < n; i++) {\n        inputp[i] += inp(i).get_gradient();\n    }\n    stack.continue_recording();\n  }\n  gettimeofday(&end, NULL);\n\n  stack.pause_recording();\n\n  printf(\"adept2 forward reverse %0.6f res'=%f\\n\", tdiff(&start, &end), sum(inputp, n));\n  }\n}\n\nstatic void enzyme_sincos(double *input, double *inputp, unsigned long n, unsigned long repeat) {\n    double realinput = input[0];\n  {\n  struct timeval start, end;\n  gettimeofday(&start, NULL);\n  double total = 0;\n  for(int i=0; i<repeat; i++) {\n    input[0] = realinput + (double)i/10000000;\n    total += logsumexp(input, n);\n  }\n\n  gettimeofday(&end, NULL);\n  printf(\"enzyme forward %0.6f res'=%f\\n\", tdiff(&start, &end), total);\n  }\n  {\n      input[0] = realinput;\n  struct timeval start, end;\n  memset(inputp, 0, sizeof(double)*n);\n\n  gettimeofday(&start, NULL);\n\n  for(int i=0; i<repeat; i++) {\n    __enzyme_autodiff<void>(logsumexp, input, inputp, n);\n  }\n\n  gettimeofday(&end, NULL);\n  printf(\"enzyme forward and reverse %0.6f res'=%f\\n\", tdiff(&start, &end), sum(inputp, n));\n  }\n}\nstatic void tapenade_sincos(double *input, double *inputp, unsigned long n, unsigned long repeat) {\n    double realinput = input[0];\n  {\n  struct timeval start, end;\n  gettimeofday(&start, NULL);\n  double total = 0;\n  for(int i=0; i<repeat; i++) {\n    input[0] = realinput + (double)i/10000000;\n    total += logsumexp(input, n);\n  }\n\n  gettimeofday(&end, NULL);\n  printf(\"tapenade forward %0.6f res'=%f\\n\", tdiff(&start, &end), total);\n  }\n  {\n      input[0] = realinput;\n  struct timeval start, end;\n  memset(inputp, 0, sizeof(double)*n);\n\n  gettimeofday(&start, NULL);\n\n  for(int i=0; i<repeat; i++) {\n    logsumexp_b(input, inputp, n, 1.0);\n  }\n\n  gettimeofday(&end, NULL);\n  printf(\"tapenade forward and reverse %0.6f res'=%f\\n\", tdiff(&start, &end), sum(inputp, n));\n  }\n}\n\nint main(int argc, char** argv) {\n    if (argc < 2) {\n        printf(\"usage %s n repeat\\n\", argv[0]);\n        return 1;\n    }\n  unsigned long n = atoi(argv[1]);\n  unsigned long repeat = atoi(argv[2]);\n\n  double *input = new double[n];\n  double *inputp = new double[n];\n  for(int i=0; i<n; i++) {\n    input[i] = 3.1415926535 / (i+1);\n  }\n  \n  //adept_sincos(input, inputp, n, repeat);\n  \n  adept2_sincos(input, inputp, n, repeat);\n\n  tapenade_sincos(input, inputp, n, repeat);\n\n  enzyme_sincos(input, inputp, n, repeat);\n}\n\n", "meta": {"hexsha": "c68235c81e0443c4fc808de997764168170838dc", "size": 7558, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "enzyme/benchmarks/logsumexp/logsumexp.cpp", "max_stars_repo_name": "anandijain/Enzyme", "max_stars_repo_head_hexsha": "fcaeb498a7fcb941be02ca407444fbb81e31c02e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 674.0, "max_stars_repo_stars_event_min_datetime": "2020-10-05T17:55:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T11:18:11.000Z", "max_issues_repo_path": "enzyme/benchmarks/logsumexp/logsumexp.cpp", "max_issues_repo_name": "anandijain/Enzyme", "max_issues_repo_head_hexsha": "fcaeb498a7fcb941be02ca407444fbb81e31c02e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 119.0, "max_issues_repo_issues_event_min_datetime": "2020-10-07T00:47:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-06T16:46:58.000Z", "max_forks_repo_path": "enzyme/benchmarks/logsumexp/logsumexp.cpp", "max_forks_repo_name": "anandijain/Enzyme", "max_forks_repo_head_hexsha": "fcaeb498a7fcb941be02ca407444fbb81e31c02e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 55.0, "max_forks_repo_forks_event_min_datetime": "2020-10-10T14:45:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-30T05:51:07.000Z", "avg_line_length": 23.5451713396, "max_line_length": 99, "alphanum_fraction": 0.5919555438, "num_tokens": 2445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218327098193, "lm_q2_score": 0.7772998508568416, "lm_q1q2_score": 0.7166097030670087}}
{"text": "#include <boost/multiprecision/cpp_int.hpp>\r\n#include <iostream>\r\n\r\nusing namespace std;\r\nusing boost::multiprecision::cpp_int;\r\n\r\n// Returns n!\r\ncpp_int factorial(cpp_int n) {\r\n\tif(n == 0) {\r\n\t\treturn 1;\r\n\t}\r\n\treturn n * factorial(n - 1);\r\n}\r\n\r\ncpp_int sum_of_digits(cpp_int num) {\r\n\tcpp_int sum = 0;\r\n\twhile(num) {\r\n\t\tsum += num % 10;\r\n\t\tnum /= 10;\r\n\t}\r\n\treturn sum;\r\n}\r\n\r\nint main(int argc, char *argv[]) {\r\n\tcout << sum_of_digits(factorial(100)) << endl;\r\n\treturn 0;\r\n}", "meta": {"hexsha": "81f964f4fa62b11c223a84c3043f7635eb5d753f", "size": 473, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Solutions/1-50/20/Solution.cpp", "max_stars_repo_name": "kitegi/Edmonton", "max_stars_repo_head_hexsha": "774c9b2f72e7b2c6a3bc1b3329ef227ef39adf9d", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-07-16T13:30:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-16T18:17:40.000Z", "max_issues_repo_path": "Solutions/1-50/20/Solution.cpp", "max_issues_repo_name": "kitegi/Edmonton", "max_issues_repo_head_hexsha": "774c9b2f72e7b2c6a3bc1b3329ef227ef39adf9d", "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": "Solutions/1-50/20/Solution.cpp", "max_forks_repo_name": "kitegi/Edmonton", "max_forks_repo_head_hexsha": "774c9b2f72e7b2c6a3bc1b3329ef227ef39adf9d", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-16T22:56:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-16T22:56:07.000Z", "avg_line_length": 17.5185185185, "max_line_length": 48, "alphanum_fraction": 0.6194503171, "num_tokens": 135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554475, "lm_q2_score": 0.7718434978390746, "lm_q1q2_score": 0.7165862960452963}}
{"text": "#pragma once\n#include <NTL/RR.h>\n#include <utility>\n#include \"proper_primes.hpp\"\n\n// choice of the approximation praxis for the estimated fraction of an error\n// to appear in the next iteration of a bit-flipping decoder\n#define ROUNDING_PRAXIS round\n\n/* Probability that a variable node is correct, and a parity equation involving\n * it is satisfied */\nNTL::RR compute_p_cc(const uint64_t d_c, \n                   const uint64_t n, \n                   const uint64_t t){\n    NTL::RR result = NTL::RR(0);\n    uint64_t bound = (d_c - 1) < t ? d_c - 1 : t;\n\n    /* the number of errors falling in the PC equation should be at least \n     * the amount which cannot be placed in a non checked place          */\n    uint64_t LowerTHitBound = (n-d_c) < t ? t-(n-d_c) : 0;\n    /* and it should be even, since the PC equation must be satisfied */\n    LowerTHitBound = LowerTHitBound % 2 ? LowerTHitBound + 1 : LowerTHitBound;\n\n    for(uint64_t j = LowerTHitBound; j <= bound; j = j+2 ){\n        result += to_RR( binomial_wrapper(d_c-1,j) * binomial_wrapper(n-d_c,t-j) ) / \n                         to_RR( binomial_wrapper(n-1,t) );\n    }\n    return result;\n}\n\n/* Probability that a variable node is correct, and a parity equation involving\n * it is *not* satisfied */\nNTL::RR compute_p_ci(const uint64_t d_c, \n                   const uint64_t n,\n                   const uint64_t t){\n    NTL::RR result = NTL::RR(0);\n    uint64_t bound = (d_c - 1) < t ? d_c - 1 : t;\n\n    /* the number of errors falling in the PC equation should be at least \n     * the amount which cannot be placed in a non checked place          */\n    uint64_t LowerTHitBound = (n-d_c) < t ? t-(n-d_c) : 1;\n    /* and it should be odd, since the PC equation must be non satisfied */\n    LowerTHitBound = LowerTHitBound % 2 ? LowerTHitBound : LowerTHitBound + 1;\n\n    for(uint64_t j = LowerTHitBound; j <= bound; j = j+2 ){\n        result += to_RR( binomial_wrapper(d_c-1,j) * binomial_wrapper(n-d_c,t-j) )\n                 / to_RR( binomial_wrapper(n-1,t) );\n    }\n    return result;\n}\n\n/* Probability that a variable node is *not* correct, and a parity equation involving\n * it is *not* satisfied */\nNTL::RR compute_p_ic(const uint64_t d_c, \n                   const uint64_t n,\n                   const uint64_t t){\n    NTL::RR result = NTL::RR(0);\n    uint64_t UpperTBound = (d_c - 1) < t - 1 ? d_c - 1 : t - 1;\n\n    /* the number of errors falling in the PC equation should be at least \n     * the amount which cannot be placed in a non checked place          */\n    uint64_t LowerTHitBound = (n-d_c-1) < (t-1) ? (t-1)-(n-d_c-1) : 0;\n    /* and it should be even, since the PC equation must be unsatisfied (when \n     * accounting for the one we are considering as already placed*/\n    LowerTHitBound = LowerTHitBound % 2 ? LowerTHitBound + 1 : LowerTHitBound;\n\n    for(uint64_t j = LowerTHitBound; j <= UpperTBound; j = j+2 ){\n        result += NTL::to_RR( binomial_wrapper(d_c-1,j) * binomial_wrapper(n-d_c,t-j-1) ) \n                 / to_RR( binomial_wrapper(n-1,t-1) );\n    }\n    return result;\n}\n\n/* Probability that a variable node is *not* correct, and a parity equation involving\n * it is satisfied */\nNTL::RR compute_p_ii(const uint64_t d_c, \n                   const uint64_t n,\n                   const uint64_t t){\n\n    NTL::RR result = NTL::RR(0);\n    uint64_t bound = (d_c - 1) < t - 1 ? d_c - 1 : t - 1;\n    \n    /* the number of errors falling in the PC equation should be at least \n     * the amount which cannot be placed in a non checked place          */\n    uint64_t LowerTHitBound = (n-d_c) < (t-1) ? (t-1)-(n-d_c) : 1;\n    /* and it should be odd, since the PC equation must be satisfied (when \n     * accounting for the one we are considering as already placed)*/\n    LowerTHitBound = LowerTHitBound % 2 ? LowerTHitBound : LowerTHitBound +1;\n    for(uint64_t j = LowerTHitBound; j <= bound; j = j+2 ){\n        result += NTL::to_RR( binomial_wrapper(d_c-1,j) * binomial_wrapper(n-d_c,t-j-1) ) \n                 / to_RR( binomial_wrapper(n-1,t-1) );\n    }\n    return result;\n}\n\n/* note p_cc + p_ci = 1 */\n/* note p_ic + p_ii = 1 */\n\n/* Probability that a given erroneous variable is deemed as such, and is thus\n * corrected, given a threshold for the amount of unsatisfied parity check\n * equations. Called P_ic in most texts */\nNTL::RR ComputePrBitCorrection( const NTL::RR p_ic, \n                                const uint64_t d_v,\n                                const uint64_t t,\n                                const uint64_t threshold ){\n// \t\tPic=0; /* p_correct */\n// \t\tfor (j=b,dv,\n// \t\t\tterm=binomial(dv,j)*(p_ic^j)*(1-p_ic)^(dv-j);\n// \t\t\tPic=Pic+term;\n// \t\t);\n  NTL::RR result = NTL::RR(0), success, failure;\n  for (uint64_t j = threshold; j <= d_v; j++){\n     NTL::pow(success, p_ic, NTL::to_RR(j));\n     NTL::pow(failure, NTL::RR(1)-p_ic, NTL::to_RR(d_v-j));\n     result += NTL::to_RR(binomial_wrapper(d_v,j)) * success * failure;\n  }\n  return result;\n}\n\n/* Probability that a given correct variable is not deemed as such, and is thus\n * fault-induced, given a threshold for the amount of unsatisfied parity check\n * equations. Called P_ci in most texts, p_induce in official comment */\nNTL::RR ComputePrBitFaultInduction( const NTL::RR p_ci,\n                                    const uint64_t d_v,\n                                    const uint64_t t, /* unused */\n                                    const uint64_t threshold ){\n\n  NTL::RR result= NTL::RR(0), success, failure;\n  for (uint64_t j = threshold; j <= d_v; j++){\n     NTL::pow(success, p_ci, NTL::to_RR(j));\n     NTL::pow(failure, NTL::RR(1)-p_ci, NTL::to_RR(d_v-j));\n     result += NTL::to_RR(binomial_wrapper(d_v,j)) * success * failure;\n  }\n  return result;\n}\n\n/* computes the probability that toCorrect bits are corrected\n * known as P{N_ic = toCorrect}  */\nNTL::RR ComputePrBitCorrectionMulti( const NTL::RR p_ic, \n                                const uint64_t d_v,\n                                const uint64_t t,\n                                const uint64_t threshold,\n                                const uint64_t toCorrect){\n   NTL::RR ProbCorrectOne = ComputePrBitCorrection(p_ic,d_v,t,threshold);\n   return NTL::to_RR(binomial_wrapper(t,toCorrect)) * \n          NTL::pow(ProbCorrectOne,NTL::RR(toCorrect)) *\n          NTL::pow(1-ProbCorrectOne,NTL::RR(t-toCorrect));\n}\n\n/* computes the probability that toInduce faults are induced \n * known as P{N_ci = toInduce} or Pr{f_wrong = to_induce} */\nNTL::RR ComputePrBitInduceMulti(const NTL::RR p_ci, \n                                const uint64_t d_v,\n                                const uint64_t t,\n                                const uint64_t n,\n                                const uint64_t threshold,\n                                const uint64_t toInduce){\n//    if(toInduce <= 1 ){\n//        return NTL::RR(0);\n//    }    \n   NTL::RR ProbInduceOne = ComputePrBitFaultInduction(p_ci,d_v,t,threshold);\n   return NTL::to_RR(binomial_wrapper(n-t,toInduce)) * \n          NTL::pow(ProbInduceOne,NTL::RR(toInduce)) *\n          NTL::pow(1-ProbInduceOne,NTL::RR(n-t-toInduce));                                    \n}\n\nuint64_t FindNextNumErrors(const uint64_t n_0,\n                           const uint64_t p,\n                           const uint64_t d_v,\n                           const uint64_t t){\n    NTL::RR p_ci, p_ic;\n     p_ci = compute_p_ci(n_0*d_v,n_0*p,t);\n     p_ic = compute_p_ic(n_0*d_v,n_0*p,t);\n    uint64_t t_next=t;\n//      uint64_t best_threshold = (d_v - 1)/2;\n    for(uint64_t i = (d_v - 1)/2; i <= d_v - 1; i++){\n       NTL::RR t_approx=  t -\n                          t * ComputePrBitCorrection(p_ic, d_v, t, i) +\n                          (n_0*p - t) * ComputePrBitFaultInduction(p_ci, d_v, t, i);\n       unsigned long int t_curr = NTL::conv<unsigned long int>(NTL::ROUNDING_PRAXIS(t_approx)) ;\n       /*Note : we increase the threshold only if it improves strictly on the \n        * predicted error correction. */\n       if (t_curr < t_next){\n          t_next = t_curr;\n//           best_threshold = i;\n       }\n    }\n    /* considering that any code will correct a single bit error, if \n     * t_next == 1, we save a computation iteration and shortcut to t_next == 0*/\n    if (t_next == 1) {\n        t_next = 0;\n    }\n    return t_next;\n}\n\n/* computes the exact 1-iteration DFR and the best threshold on the number of\n * upcs to achieve it */\nstd::pair<NTL::RR,uint64_t> Find1IterDFR(const uint64_t n_0,\n                                         const uint64_t p,\n                                         const uint64_t d_v,\n                                         const uint64_t t){\n    NTL::RR p_ci, p_ic, P_correct, P_induce;\n    NTL::RR DFR, best_DFR = NTL::RR(1);\n    p_ci = compute_p_ci(n_0*d_v,n_0*p,t);\n    p_ic = compute_p_ic(n_0*d_v,n_0*p,t);\n    uint64_t best_threshold = (d_v - 1)/2;\n    for(uint64_t b = best_threshold; b <= d_v - 1; b++){\n       DFR = NTL::RR(1) - ComputePrBitCorrectionMulti(p_ic, d_v, t, b, t) * ComputePrBitInduceMulti(p_ci,d_v,t,n_0*p,b,0);\n       /*Note : we increase the threshold only if it improves strictly on the \n        * predicted error correction. */\n       if (DFR < best_DFR){\n          best_DFR = DFR;\n          best_threshold = b;\n       }\n    }\n//     std::cout << best_threshold << std::endl;\n    return std::make_pair(best_DFR,best_threshold);\n}\n\n\n/* computes the exact 1-iteration probability of leaving at most t_leftover\n * uncorrected errors out of t. */\nstd::pair<NTL::RR,uint64_t> Find1IterTLeftoverPr(const uint64_t n_0,\n                                         const uint64_t p,\n                                         const uint64_t d_v,\n                                         const uint64_t t,\n                                         const uint64_t t_leftover){\n    NTL::RR p_ci, p_ic;\n    NTL::RR DFR, best_DFR = NTL::RR(1);\n    p_ci = compute_p_ci(n_0*d_v,n_0*p,t);\n    p_ic = compute_p_ic(n_0*d_v,n_0*p,t);\n    int n= p*n_0;\n    uint64_t best_threshold = (d_v + 1)/2;\n    \n    for(uint64_t b = best_threshold; b <= d_v ; b++){\n       DFR = NTL::RR(0);\n       NTL::RR P_correct = ComputePrBitCorrection(p_ic, d_v, t,b);\n       NTL::RR P_induce = ComputePrBitFaultInduction(p_ci,d_v, t/* unused */,b);\n       for(int tau = 0 ; tau <= t_leftover; tau++){\n         for(int n_to_induce = 0 ; n_to_induce <= t_leftover; n_to_induce++) {\n             NTL::RR prob_induce_n = NTL::to_RR(binomial_wrapper(n-t,n_to_induce)) *\n                                     NTL::pow(P_induce,NTL::to_RR(n_to_induce)) *\n                                     NTL::pow(NTL::RR(1)-P_induce,NTL::to_RR(n-t-n_to_induce));\n             int n_to_correct = (int)t + n_to_induce - tau;\n             NTL::RR prob_correct_n = NTL::to_RR(binomial_wrapper(t,n_to_correct));\n                     prob_correct_n *= NTL::pow(P_correct,NTL::to_RR(n_to_correct));\n\n                     prob_correct_n *= NTL::pow(NTL::RR(1)-P_correct,NTL::to_RR((int)t-n_to_correct)); /*unsigned exp?*/\n             DFR += prob_correct_n*prob_induce_n;\n         }\n       }\n       DFR = NTL::RR(1) - DFR;\n       if (DFR < best_DFR){\n          best_DFR = DFR;\n          best_threshold = b;\n       }\n    }\n    return std::make_pair(best_DFR,best_threshold);\n}\n\n// find minimum p which, asymptotically, corrects all errors\n// search performed via binary search as the DFR is decreasing monot.\n// in of p\nuint64_t Findpth(const uint64_t n_0,\n                 const uint64_t d_v_prime,\n                 const uint64_t t){\n\n    unsigned int prime_idx = 0, prime_idx_prec;\n    uint64_t p = proper_primes[prime_idx];\n    while(p < d_v_prime || p < t ){\n          prime_idx++;\n          p=proper_primes[prime_idx];\n    }\n\n    uint64_t hi, lo;\n    lo = prime_idx;\n    hi = PRIMES_NO;\n    prime_idx_prec = lo;\n\n    uint64_t limit_error_num = t;\n    while(hi-lo > 1){\n        prime_idx_prec = prime_idx;\n        prime_idx = (lo+hi)/2;\n        p = proper_primes[prime_idx];\n        // compute number of remaining errors after +infty iters\n        limit_error_num = t;\n        uint64_t current_error_num;\n//        std::cout << \"using p:\"<< p << \", errors dropping as \";\n        do {\n            current_error_num = limit_error_num;\n            limit_error_num = FindNextNumErrors(n_0, p, d_v_prime, current_error_num);\n//           std::cout << limit_error_num << \" \";\n           } while ( \n                     (limit_error_num != current_error_num) && \n                     (limit_error_num != 0)\n                   );\n//        std::cout << std::endl;\n        if (limit_error_num > 0){\n            lo = prime_idx;\n        } else {\n            hi = prime_idx;\n        }\n    }\n    if(limit_error_num == 0) {\n        return proper_primes[prime_idx];\n    }\n    return proper_primes[prime_idx_prec];\n}\n", "meta": {"hexsha": "f5c8477ff4a32a79be97c8913c25a5e2d2db3f6e", "size": 12753, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "bit_error_probabilities.hpp", "max_stars_repo_name": "alexrow/LEDAtools", "max_stars_repo_head_hexsha": "f847707833650706519cc57f5956b8e1a17a157c", "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": "bit_error_probabilities.hpp", "max_issues_repo_name": "alexrow/LEDAtools", "max_issues_repo_head_hexsha": "f847707833650706519cc57f5956b8e1a17a157c", "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": "bit_error_probabilities.hpp", "max_forks_repo_name": "alexrow/LEDAtools", "max_forks_repo_head_hexsha": "f847707833650706519cc57f5956b8e1a17a157c", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-12T09:12:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-12T09:12:30.000Z", "avg_line_length": 41.2718446602, "max_line_length": 122, "alphanum_fraction": 0.5764918058, "num_tokens": 3590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088045171237, "lm_q2_score": 0.7718434925908524, "lm_q1q2_score": 0.7165862942305947}}
{"text": "/**\r\n * This file is part of https://github.com/adrelino/interpolation-methods\r\n *\r\n * Copyright (c) 2018 Adrian Haarbach <mail@adrian-haarbach.de>\r\n *\r\n * For the full copyright and license information, please view the LICENSE\r\n * file that was distributed with this source code.\r\n */\r\n#ifndef INTERPOL_DH_HPP\r\n#define INTERPOL_DH_HPP\r\n\r\n#include <Eigen/Dense>\r\n#include <Eigen/Geometry>\r\n#include <iostream>\r\n\r\n#include <hand_eye_calibration/DualQuaternion.h>\r\n\r\nnamespace interpol {\r\n\r\ntemplate<typename T>\r\nclass DH1;\r\n\r\n//We have a new type for (screw) tangent since multiplication with scalar is defined different there\r\ntemplate<typename T>\r\nclass DH1Tangent\r\n{\r\npublic:\r\n    DH1Tangent(const Eigen::Quaternion<T>& r,const Eigen::Quaternion<T>& d) : m_real(r), m_dual(d) {}\r\n\r\n    // dqTangent * scalar\r\n    DH1Tangent<T> operator*(const T& scale) const{\r\n        DH1Tangent<T> tt(m_real,m_dual);\r\n        tt.m_real.w() *= scale; //theta\r\n        tt.m_dual.w() *= scale; //d\r\n        return tt;\r\n    }\r\n\r\n    //implemented below\r\n    DH1<T> expScrewBen(void) const;\r\n    DH1<T> expScrew(void) const;\r\n    DH1<T> expT(bool useBenKenwrightImpl=false) const{\r\n        return useBenKenwrightImpl ? expScrewBen() : expScrew();\r\n    }\r\n\r\n    Eigen::Quaternion<T> m_real; // real part\r\n    Eigen::Quaternion<T> m_dual; // dual part\r\n\r\n    DH1<T> toDH(void){//for derivative\r\n        return DH1<T>(m_real,m_dual);\r\n    }\r\n};\r\n\r\n// scalar * dqTangent\r\ntemplate<typename T>\r\ninline DH1Tangent<T> operator*(T scale, DH1Tangent<T> t){\r\n    t.m_real.w() *= scale;\r\n    t.m_dual.w() *= scale;\r\n    return t;\r\n}\r\ntypedef DH1Tangent<float> DH1Tangentf;\r\ntypedef DH1Tangent<double> DH1Tangentd;\r\n\r\n\r\n\r\ntemplate<typename T>\r\nDH1<T>\r\noperator+(const DH1<T>& dq1, const DH1<T>& dq2);\r\n\r\ntemplate<typename T>\r\nclass DH1\r\n{\r\npublic:\r\n    DH1(){}\r\n    DH1(const Eigen::Quaternion<T>& r,\r\n        const Eigen::Quaternion<T>& d) : DH1(px::DualQuaternion<T>(r,d)) {}\r\n    DH1(const Eigen::Quaternion<T>& r,\r\n        const Eigen::Matrix<T, 3, 1>& t) : DH1(px::DualQuaternion<T>(r,t)) {}\r\n\r\n\r\n    void fromScrew(T theta, T d,\r\n                   const Eigen::Matrix<T, 3, 1>& l,\r\n                   const Eigen::Matrix<T, 3, 1>& m);\r\n    void toScrew  (T& theta, T& d, //added by us\r\n                   Eigen::Matrix<T, 3, 1>& l,\r\n                   Eigen::Matrix<T, 3, 1>& m) const;\r\n\r\n\r\n    DH1Tangent<T> logScrewBen(void) const;\r\n    DH1Tangent<T> logScrew(void) const;\r\n    DH1Tangent<T> logT(bool useBenKenwrightImpl=false) const{\r\n        return useBenKenwrightImpl ? logScrewBen() : logScrew();\r\n    }\r\n\r\n    DH1<T> conjugate(void) const { return DH1<T>(dq.conjugate());}\r\n    DH1<T> normalized(void) const {return DH1<T>(dq.normalized());}\r\n    Eigen::Quaternion<T> real() const {return dq.real();}\r\n    Eigen::Quaternion<T> dual() const {return dq.dual();}\r\n    Eigen::Quaternion<T> rotation(void) const {return dq.rotation();}\r\n    Eigen::Matrix<T, 3, 1> translation(void) const {return dq.translation();}\r\n    DH1<T> operator*(T scale) const {return DH1<T>(dq*scale);}\r\n    DH1<T> operator*(const DH1<T>& other) const {return DH1<T>(dq*other.dq);}\r\n    friend DH1<T> operator+<>(const DH1<T>& dq1, const DH1<T>& dq2);\r\n\r\n    DH1<T>& operator*=(const DH1<T>& other);//added by us\r\n\r\n\r\nprivate:\r\n    DH1(const px::DualQuaternion<T>& dq) : dq(dq) {}\r\n    px::DualQuaternion<T> dq;\r\n    //there must be a mistake here for the dual part....\r\n    //DH1<T> exp(void) const;\r\n    //DH1<T> exp(const DH1<T> base) const;\r\n    //px::DualQuaternion<T> log(void) const;\r\n    //px::DualQuaternion<T> log(const px::DualQuaternion<T> &b) const;\r\n};\r\n\r\ntemplate<typename T>\r\nDH1<T>&\r\nDH1<T>::operator*=(const DH1<T>& other)\r\n{\r\n    dq = dq * other.dq;\r\n    return *this;\r\n}\r\n\r\ntemplate<typename T>\r\nDH1<T>\r\noperator+(const DH1<T>& dh1, const DH1<T>& dh2)\r\n{\r\n    return DH1<T>(dh1.dq+dh2.dq);\r\n}\r\n\r\ntemplate<typename T>\r\nvoid\r\nDH1<T>::fromScrew(T theta, T d,\r\n        const Eigen::Matrix<T, 3, 1>& l,\r\n        const Eigen::Matrix<T, 3, 1>& m)\r\n{\r\n    //was provided in original github implementation.\r\n    dq.fromScrew(theta,d,l,m);\r\n    //is equal to:\r\n    //m_real = Eigen::AngleAxis<T>(theta, l);\r\n    //m_dual.w() = -0.5*d * std::sin(0.5*theta);\r\n    //m_dual.vec() = std::sin(0.5*theta) * m + d / 2.0 * std::cos(theta / 2.0) * l;\r\n}\r\n\r\n//modeled by hand as inverse of above\r\ntemplate<typename T>\r\nvoid\r\nDH1<T>::toScrew(T& theta, T& d,\r\n        Eigen::Matrix<T, 3, 1>& l,\r\n        Eigen::Matrix<T, 3, 1>& m) const\r\n{\r\n\r\n    Eigen::AngleAxis<T> ar(real()) ;\r\n    theta=ar.angle();\r\n    l=ar.axis();\r\n\r\n    d = -2.0 * dual().w() / (std::sin(0.5*theta));\r\n    m = (dual().vec() - 0.5*d*std::cos(0.5*theta)*l) / std::sin(0.5*theta);\r\n}\r\n\r\n//First half of ScLERPGeometricCosSin\r\ntemplate<typename T>\r\nDH1Tangent<T>\r\nDH1<T>::logScrewBen(void) const\r\n{\r\n    Eigen::Vector3d vr = real().vec();\r\n    Eigen::Vector3d vd = dual().vec();\r\n    double invr = 1.0 / vr.norm();\r\n\r\n    // Screw parameters\r\n    double  angle = 2.0 * std::acos( real().w() );\r\n    double  pitch = -2.0 * dual().w() * invr;\r\n    Eigen::Vector3d direction = vr * invr;\r\n    Eigen::Vector3d moment = (vd - direction*pitch*real().w()*0.5)*invr;\r\n\r\n    //TODO: absorb angle into norm of axis\r\n    Eigen::Quaterniond realTangent;\r\n    realTangent.w()=angle;//0\r\n    realTangent.vec()=direction;//* angle\r\n\r\n    //absorb translation into norm of moment\r\n    Eigen::Quaterniond dualTangent;\r\n    dualTangent.w()=pitch;//0;\r\n    dualTangent.vec()=moment;// * pitch;\r\n\r\n\r\n    return DH1Tangent<T>(realTangent, dualTangent);\r\n}\r\n\r\n//Second half of ScLERPGeometricCosSin\r\ntemplate<typename T>\r\nDH1<T>\r\nDH1Tangent<T>::expScrewBen(void) const\r\n{\r\n    //TODO: real and dual tangents should have w() = 0 and the norm absorbed into their vector part\r\n    Eigen::Vector3d vr = m_real.vec();\r\n    Eigen::Vector3d vd = m_dual.vec();\r\n\r\n    double angle = m_real.w();//vr.norm();\r\n    double pitch = m_dual.w();//vd.norm();\r\n\r\n    Eigen::Vector3d direction = vr; // / angle;\r\n    Eigen::Vector3d moment = vd;// / pitch;\r\n\r\n\r\n    // Convert back to dual-quaternion\r\n    double sinAngle = std::sin(0.5*angle);\r\n    double cosAngle = std::cos(0.5*angle);\r\n\r\n    Eigen::Vector3d axisReal = direction * sinAngle;\r\n    Eigen::Quaterniond real(cosAngle, axisReal.x(),axisReal.y(),axisReal.z());\r\n\r\n    Eigen::Vector3d axisDual = sinAngle*moment+pitch*0.5* cosAngle *direction;\r\n    Eigen::Quaterniond dual(-pitch*0.5*sinAngle, axisDual.x(),axisDual.y(),axisDual.z());\r\n\r\n    return DH1<T>(real, dual);\r\n}\r\n\r\n\r\ntemplate<typename T>\r\nDH1Tangent<T>\r\nDH1<T>::logScrew(void) const\r\n{\r\n    T theta,d;\r\n    Eigen::Matrix<T, 3, 1> axis, moment;\r\n    toScrew(theta,d,axis,moment); //putting amount of angle or translation in w(), so it is not 0!\r\n\r\n    //TODO: absorb angle and translation into norm of axis and moment\r\n    Eigen::Quaternion<T> real,dual;\r\n    real.w() = theta; //0;\r\n    real.vec() = axis; //*theta;\r\n//        real.w() = 0;\r\n//        real.vec() = axis*theta;\r\n\r\n    dual.w() = d; //0;\r\n    dual.vec() = moment; //*d;\r\n\r\n//        double m = moment.norm();\r\n//        dual.w() /=m;\r\n//        dual.vec() /= m;\r\n//        cout<<\"axis norm=\"<<axis.norm()<<\"  moment norm=\"<<m<<\" d=\"<<d<<endl;\r\n\r\n    return DH1Tangent<T>(real, dual);\r\n}\r\n\r\ntemplate<typename T>\r\nDH1<T>\r\nDH1Tangent<T>::expScrew(void) const\r\n{\r\n    DH1<T> dualQuat;\r\n    //TODO: get angle and translation from norm of axis and moment\r\n    dualQuat.fromScrew(\r\n                m_real.w(),//vec().norm(),\r\n                m_dual.w(),//vec().norm(),\r\n                m_real.vec(),//.normalized(),\r\n                m_dual.vec()//.normalized()\r\n                       );\r\n    return dualQuat;\r\n}\r\n\r\ntypedef DH1<float> DH1f;\r\ntypedef DH1<double> DH1d;\r\n\r\n} // ns interpol\r\n\r\n#endif // INTERPOL_DH_HPP\r\n", "meta": {"hexsha": "c1c50db9c3b87104c969e961094cd5b0b458c30c", "size": 7783, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/libinterpol/include/interpol/rigid/DH.hpp", "max_stars_repo_name": "adrelino/interpolation-methods", "max_stars_repo_head_hexsha": "094cbabbd0c25743d088a623f5913149c6b8a2ab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 81.0, "max_stars_repo_stars_event_min_datetime": "2018-08-31T03:26:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T04:01:44.000Z", "max_issues_repo_path": "src/libinterpol/include/interpol/rigid/DH.hpp", "max_issues_repo_name": "bygreencn/interpolation-methods", "max_issues_repo_head_hexsha": "508723d1bca10c350f1a83c2fd31c2227cc1c0a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-07-16T06:45:12.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-15T17:47:01.000Z", "max_forks_repo_path": "src/libinterpol/include/interpol/rigid/DH.hpp", "max_forks_repo_name": "bygreencn/interpolation-methods", "max_forks_repo_head_hexsha": "508723d1bca10c350f1a83c2fd31c2227cc1c0a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2018-09-20T18:37:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T15:04:37.000Z", "avg_line_length": 29.0410447761, "max_line_length": 102, "alphanum_fraction": 0.5978414493, "num_tokens": 2287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361533336451, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.7165439407251296}}
{"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 <numeric>\n#include <utility>\n#include <random>\n#include <cmath>\n#include <boost/math/special_functions/cardinal_b_spline.hpp>\n#include <boost/math/interpolators/detail/cubic_b_spline_detail.hpp>\n#ifdef BOOST_HAS_FLOAT128\n#include <boost/multiprecision/float128.hpp>\nusing boost::multiprecision::float128;\n#endif\n\nusing std::abs;\nusing boost::math::cardinal_b_spline;\nusing boost::math::cardinal_b_spline_prime;\nusing boost::math::forward_cardinal_b_spline;\nusing boost::math::cardinal_b_spline_double_prime;\n\n\ntemplate<class Real>\nvoid test_box()\n{\n    Real t = cardinal_b_spline<0>(Real(1.1));\n    Real expected = 0;\n    CHECK_ULP_CLOSE(expected, t, 0);\n    CHECK_ULP_CLOSE(expected, cardinal_b_spline_prime<0>(Real(1.1)), 0);\n\n    t = cardinal_b_spline<0>(Real(-1.1));\n    expected = 0;\n    CHECK_ULP_CLOSE(expected, t, 0);\n\n    Real h = Real(1)/Real(256);\n    for (t = -Real(1)/Real(2)+h; t < Real(1)/Real(2); t += h)\n    {\n        expected = 1;\n        CHECK_ULP_CLOSE(expected, cardinal_b_spline<0>(t), 0);\n        expected = 0;\n        CHECK_ULP_CLOSE(expected, cardinal_b_spline_prime<0>(Real(1.1)), 0);\n    }\n\n    for (t = h; t < 1; t += h)\n    {\n        expected = 1;\n        CHECK_ULP_CLOSE(expected, forward_cardinal_b_spline<0>(t), 0);\n    }\n}\n\ntemplate<class Real>\nvoid test_hat()\n{\n    Real t = cardinal_b_spline<1>(Real(2.1));\n    Real expected = 0;\n    CHECK_ULP_CLOSE(expected, t, 0);\n\n    t = cardinal_b_spline<1>(Real(-2.1));\n    expected = 0;\n    CHECK_ULP_CLOSE(expected, t, 0);\n\n    Real h = Real(1)/Real(256);\n    for (t = -1; t <= 1; t += h)\n    {\n        expected = 1-abs(t);\n        if(!CHECK_ULP_CLOSE(expected, cardinal_b_spline<1>(t), 0) )\n        {\n            std::cerr << \"  Problem at t = \" << t << \"\\n\";\n        }\n        if (t == -Real(1)) {\n            if (!CHECK_ULP_CLOSE(Real(1)/Real(2), cardinal_b_spline_prime<1>(t), 0)) {\n                std::cout << \"  Problem at t = \" << t << \"\\n\";\n            }\n        }\n        else if (t == Real(1)) {\n            CHECK_ULP_CLOSE(-Real(1)/Real(2), cardinal_b_spline_prime<1>(t), 0);\n        }\n        else if (t < 0) {\n            CHECK_ULP_CLOSE(Real(1), cardinal_b_spline_prime<1>(t), 0);\n        }\n        else if (t == 0) {\n            CHECK_ULP_CLOSE(Real(0), cardinal_b_spline_prime<1>(t), 0);\n        }\n        else if (t > 0) {\n            CHECK_ULP_CLOSE(Real(-1), cardinal_b_spline_prime<1>(t), 0);\n        }\n    }\n\n    for (t = 0; t < 2; t += h)\n    {\n        expected = 1 - abs(t-1);\n        CHECK_ULP_CLOSE(expected, forward_cardinal_b_spline<1>(t), 0);\n    }\n}\n\ntemplate<class Real>\nvoid test_quadratic()\n{\n    using std::abs;\n    auto b2 = [](Real x) {\n        Real absx = abs(x);\n        if (absx >= 3/Real(2)) {\n            return Real(0);\n        }\n        if (absx >= 1/Real(2)) {\n            Real t = absx - 3/Real(2);\n            return t*t/2;\n        }\n        Real t1 = absx - 1/Real(2);\n        Real t2 = absx + 1/Real(2);\n        return (2-t1*t1 -t2*t2)/2;\n    };\n\n    auto b2_prime = [&](Real x)->Real {\n        Real absx = abs(x);\n        Real signx  = 1;\n        if (x < 0) {\n            signx = -1;\n        }\n        if (absx >= 3/Real(2)) {\n            return Real(0);\n        }\n        if (absx >= 1/Real(2)) {\n            return (absx - 3/Real(2))*signx;\n        }\n        return -2*absx*signx;\n    };\n\n\n    Real h = 1/Real(256);\n    for (Real t = -5; t <= 5; t += h) {\n        Real expected = b2(t);\n        CHECK_ULP_CLOSE(expected, cardinal_b_spline<2>(t), 0);\n        expected = b2_prime(t);\n\n        if (!CHECK_ULP_CLOSE(expected, cardinal_b_spline_prime<2>(t), 0))\n        {\n            std::cerr << \"  Problem at t = \" << t << \"\\n\";\n        }\n\n    }\n}\n\ntemplate<class Real>\nvoid test_cubic()\n{\n    Real expected = Real(2)/Real(3);\n    Real computed = cardinal_b_spline<3, Real>(0);\n    CHECK_ULP_CLOSE(expected, computed, 0);\n\n    expected = Real(1)/Real(6);\n    computed = cardinal_b_spline<3, Real>(1);\n    CHECK_ULP_CLOSE(expected, computed, 0);\n\n    expected = Real(0);\n    computed = cardinal_b_spline<3, Real>(2);\n    CHECK_ULP_CLOSE(expected, computed, 0);\n\n    Real h = 1/Real(256);\n    for (Real t = -4; t <= 4; t += h) {\n        expected = boost::math::detail::b3_spline_prime<Real>(t);\n        computed = cardinal_b_spline_prime<3>(t);\n        CHECK_ULP_CLOSE(expected, computed, 0);\n        expected = boost::math::detail::b3_spline_double_prime<Real>(t);\n        computed = cardinal_b_spline_double_prime<3>(t);\n        if (!CHECK_ULP_CLOSE(expected, computed, 0)) {\n            std::cerr << \"  Problem at t = \" << t << \"\\n\";\n        }\n    }\n}\n\ntemplate<class Real>\nvoid test_quintic()\n{\n  Real expected = Real(11)/Real(20);\n  Real computed = cardinal_b_spline<5, Real>(0);\n  CHECK_ULP_CLOSE(expected, computed, 0);\n\n  expected = Real(13)/Real(60);\n  computed = cardinal_b_spline<5, Real>(1);\n  CHECK_ULP_CLOSE(expected, computed, 1);\n\n  expected = Real(1)/Real(120);\n  computed = cardinal_b_spline<5, Real>(2);\n  CHECK_ULP_CLOSE(expected, computed, 0);\n\n  expected = Real(0);\n  computed = cardinal_b_spline<5, Real>(3);\n  CHECK_ULP_CLOSE(expected, computed, 0);\n\n}\n\ntemplate<unsigned n, typename Real>\nvoid test_b_spline_derivatives()\n{\n    Real h = 1/Real(256);\n    Real supp = (n+Real(1))/Real(2);\n    for (Real t = -supp - 1; t <= supp+1; t+= h)\n    {\n        Real expected = cardinal_b_spline<n-1>(t+Real(1)/Real(2)) - cardinal_b_spline<n-1>(t - Real(1)/Real(2));\n        Real computed = cardinal_b_spline_prime<n>(t);\n        CHECK_MOLLIFIED_CLOSE(expected, computed, std::numeric_limits<Real>::epsilon());\n\n        expected = cardinal_b_spline<n-2>(t+1) - 2*cardinal_b_spline<n-2>(t) + cardinal_b_spline<n-2>(t-1);\n        computed = cardinal_b_spline_double_prime<n>(t);\n        CHECK_MOLLIFIED_CLOSE(expected, computed, 2*std::numeric_limits<Real>::epsilon());\n    }\n}\n\ntemplate<unsigned n, typename Real>\nvoid test_partition_of_unity()\n{\n  std::mt19937 gen(323723);\n  Real supp = (n+1.0)/2.0;\n  std::uniform_real_distribution<Real> dis(-supp, -supp+1);\n\n  for(size_t i = 0; i < 500; ++i) {\n    Real x = dis(gen);\n    Real one = 0;\n    while (x < supp) {\n        one += cardinal_b_spline<n>(x);\n        x += 1;\n    }\n    if(!CHECK_ULP_CLOSE(Real(1), one, n)) {\n      std::cerr << \"  Partition of unity failure at n = \" << n << \"\\n\";\n    }\n  }\n}\n\n\nint main()\n{\n    test_box<float>();\n    test_box<double>();\n    test_box<long double>();\n\n    test_hat<float>();\n    test_hat<double>();\n    test_hat<long double>();\n\n    test_quadratic<float>();\n    test_quadratic<double>();\n    test_quadratic<long double>();\n\n    test_cubic<float>();\n    test_cubic<double>();\n    test_cubic<long double>();\n\n    test_quintic<float>();\n    test_quintic<double>();\n    test_quintic<long double>();\n\n    test_partition_of_unity<1, double>();\n    test_partition_of_unity<2, double>();\n    test_partition_of_unity<3, double>();\n    test_partition_of_unity<4, double>();\n    test_partition_of_unity<5, double>();\n    test_partition_of_unity<6, double>();\n\n    test_b_spline_derivatives<3, double>();\n    test_b_spline_derivatives<4, double>();\n    test_b_spline_derivatives<5, double>();\n    test_b_spline_derivatives<6, double>();\n    test_b_spline_derivatives<7, double>();\n    test_b_spline_derivatives<8, double>();\n    test_b_spline_derivatives<9, double>();\n\n    test_b_spline_derivatives<3, long double>();\n    test_b_spline_derivatives<4, long double>();\n    test_b_spline_derivatives<5, long double>();\n    test_b_spline_derivatives<6, long double>();\n    test_b_spline_derivatives<7, long double>();\n    test_b_spline_derivatives<8, long double>();\n    test_b_spline_derivatives<9, long double>();\n\n\n#ifdef BOOST_HAS_FLOAT128\n    test_box<float128>();\n    test_hat<float128>();\n    test_quadratic<float128>();\n    test_cubic<float128>();\n    test_quintic<float128>();\n#endif\n\n    return boost::math::test::report_errors();\n}\n", "meta": {"hexsha": "0ec92cc954760348ff21c7186492f741c8a33134", "size": 8124, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/math/test/cardinal_b_spline_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/cardinal_b_spline_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/cardinal_b_spline_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": 27.9175257732, "max_line_length": 112, "alphanum_fraction": 0.6011816839, "num_tokens": 2434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436153333645, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.7165439361404644}}
{"text": "////////////////////////////////////////////////////////////////////\n//\n// $Id: myEigen.hxx 2021/06/05 13:36:04 kanai Exp $\n//\n// Copyright (c) 2021 Takashi Kanai\n// Released under the MIT license\n//\n////////////////////////////////////////////////////////////////////\n\n#ifndef _MYEIGEN_HXX\n#define _MYEIGEN_HXX 1\n\n#include <cmath>\nusing namespace std;\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n// return (double)Math.acos(dot(v1)/v1.length()/v.length());\n// Numerically, near 0 and PI are very bad condition for acos.\n// In 3-space, |atan2(sin,cos)| is much stable.\ntemplate <typename T>\nT angleT( Eigen::Matrix<T, 3, 1>& v1, Eigen::Matrix<T, 3, 1>& v2 ) {\n  Eigen::Matrix<T, 3, 1> c = v1.cross(v2);\n  T s = c.norm();\n\n  return std::fabs(std::atan2(s, v1.dot(v2)));\n};\n\n//typedef angleT<float> anglef;\n\n#if 0\nfloat anglef( Eigen::Vector3f& v1, Eigen::Vector3f& v2 ) {\n  // return (double)Math.acos(dot(v1)/v1.length()/v.length());\n  // Numerically, near 0 and PI are very bad condition for acos.\n  // In 3-space, |atan2(sin,cos)| is much stable.\n  Eigen::Vector3f c = v1.cross(v2);\n  float s = c.norm();\n\n  return std::fabs(std::atan2(s, v1.dot(v2)));\n};\n#endif\n\n\n#endif // _MYEIGEN_HXX\n\n", "meta": {"hexsha": "0891c87f74e1d4b3baa6421c21624fcfe20be37d", "size": 1197, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "myEigen.hxx", "max_stars_repo_name": "kanait/render_Eigen", "max_stars_repo_head_hexsha": "04e6941c26a0c2c2782da655c78ec5da1a86f09f", "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": "myEigen.hxx", "max_issues_repo_name": "kanait/render_Eigen", "max_issues_repo_head_hexsha": "04e6941c26a0c2c2782da655c78ec5da1a86f09f", "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": "myEigen.hxx", "max_forks_repo_name": "kanait/render_Eigen", "max_forks_repo_head_hexsha": "04e6941c26a0c2c2782da655c78ec5da1a86f09f", "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.4680851064, "max_line_length": 68, "alphanum_fraction": 0.5789473684, "num_tokens": 365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297754396141, "lm_q2_score": 0.7956581000631542, "lm_q1q2_score": 0.7165138101765822}}
{"text": "#include <Eigen/Sparse>\n#include <iostream>\n#include <vector>\n#include \"kron.hpp\"\n\n\nEigen::SparseMatrix<double> buildC(const Eigen::MatrixXd &A){\n\tint n= A.cols();\n\tEigen::SparseMatrix<double> C(n*n,n*n);\n\tEigen::MatrixXd I= Eigen::MatrixXd::Identity(n,n);\n\tEigen::MatrixXd C1,C2;\n\tkron(A,I,C1);kron(I,A,C2);\n\tC1+=C2;\n\t//std::cout << C1 << std::endl;\n\tstd::vector <Eigen::Triplet<double> > triplets;\n\tfor (int i=0; i<n*n; ++i){\n\t\tfor (int j=0; j<n*n; ++j){\n\t\t\tif (C1(i,j)!=0){\n\t\t\t\tEigen::Triplet<double> trpl(i,j,C1(i,j));\n\t\t\t\ttriplets.push_back(trpl);\n\t\t\t\t}\n\t\t}\n\t}\n\tC.setFromTriplets(triplets.begin(),triplets.end());\n\tC.makeCompressed();\n\treturn C;\n\t//TODO\n};\n\nvoid solveLyapunov(const Eigen::MatrixXd &A, Eigen::MatrixXd &X){\n\tint n= A.cols();\n\tEigen::SparseMatrix<double> C;\n\tC= buildC(A);\n\tEigen::MatrixXd I=Eigen::MatrixXd::Identity(n,n);\n\tEigen::VectorXd b=Eigen::MatrixXd::Map(I.data(),n*n,1);\n\tEigen::VectorXd x;\n\tEigen::SparseLU<Eigen::SparseMatrix<double> > solver; solver.compute(C);\n\tx=solver.solve(b);\n\tX=Eigen::MatrixXd::Map(x.data(),n,n);\n};\n\n\nint main(){\n\tint n=5;\n\tEigen::MatrixXd A(n,n),X(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\tstd::cout << A << std::endl;\n\t///Teilaufgabe 1g\n\t/*Eigen::SparseMatrix<double> C;\n\tC= buildC(A);\n\tstd::cout << C << std::endl;*/   \n\tsolveLyapunov(A,X);\n\tstd::cout << X << std::endl;\n\t\n\t///test\n\t/*Eigen::VectorXd y;\n\ty=Eigen::MatrixXd::Map(A.data(),4,1);\n\tstd::cout << y << std::endl;*/\n\treturn 0;\t\n}\n", "meta": {"hexsha": "d6ef77d53ea06e831bf77d25f31e5452829597a8", "size": 1503, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/PS2/BuildC.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/PS2/BuildC.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/PS2/BuildC.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.6393442623, "max_line_length": 86, "alphanum_fraction": 0.6121091151, "num_tokens": 548, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802350995703, "lm_q2_score": 0.7799929104825006, "lm_q1q2_score": 0.7164080717959653}}
{"text": "/*\n * Copyright Nick Thompson, 2020\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 <numeric>\n#include <utility>\n#include <random>\n#include <boost/math/interpolators/pchip.hpp>\n#include <boost/circular_buffer.hpp>\n#include <boost/assert.hpp>\n#ifdef BOOST_HAS_FLOAT128\n#include <boost/multiprecision/float128.hpp>\nusing boost::multiprecision::float128;\n#endif\n\n\nusing boost::math::interpolators::pchip;\n\ntemplate<typename Real>\nvoid test_constant()\n{\n\n    std::vector<Real> x{0,1,2,3, 9, 22, 81};\n    std::vector<Real> y(x.size());\n    for (auto & t : y) {\n        t = 7;\n    }\n\n    auto x_copy = x;\n    auto y_copy = y;\n    auto pchip_spline = pchip(std::move(x_copy), std::move(y_copy));\n    //std::cout << \"Constant value pchip spline = \" << pchip_spline << \"\\n\";\n\n    for (Real t = x[0]; t <= x.back(); t += 0.25) {\n        CHECK_ULP_CLOSE(Real(7), pchip_spline(t), 2);\n        CHECK_ULP_CLOSE(Real(0), pchip_spline.prime(t), 2);\n    }\n\n    boost::circular_buffer<Real> x_buf(x.size());\n    for (auto & t : x) {\n        x_buf.push_back(t);\n    }\n\n    boost::circular_buffer<Real> y_buf(x.size());\n    for (auto & t : y) {\n        y_buf.push_back(t);\n    }\n\n    auto circular_pchip_spline = pchip(std::move(x_buf), std::move(y_buf));\n\n    for (Real t = x[0]; t <= x.back(); t += 0.25) {\n        CHECK_ULP_CLOSE(Real(7), circular_pchip_spline(t), 2);\n        CHECK_ULP_CLOSE(Real(0), pchip_spline.prime(t), 2);\n    }\n\n    circular_pchip_spline.push_back(x.back() + 1, 7);\n    CHECK_ULP_CLOSE(Real(0), circular_pchip_spline.prime(x.back()+1), 2);\n\n}\n\ntemplate<typename Real>\nvoid test_linear()\n{\n    std::vector<Real> x{0,1,2,3};\n    std::vector<Real> y{0,1,2,3};\n\n    auto x_copy = x;\n    auto y_copy = y;\n    auto pchip_spline = pchip(std::move(x_copy), std::move(y_copy));\n\n    CHECK_ULP_CLOSE(y[0], pchip_spline(x[0]), 0);\n    CHECK_ULP_CLOSE(Real(1)/Real(2), pchip_spline(Real(1)/Real(2)), 10);\n    CHECK_ULP_CLOSE(y[1], pchip_spline(x[1]), 0);\n    CHECK_ULP_CLOSE(Real(3)/Real(2), pchip_spline(Real(3)/Real(2)), 10);\n    CHECK_ULP_CLOSE(y[2], pchip_spline(x[2]), 0);\n    CHECK_ULP_CLOSE(Real(5)/Real(2), pchip_spline(Real(5)/Real(2)), 10);\n    CHECK_ULP_CLOSE(y[3], pchip_spline(x[3]), 0);\n\n    x.resize(45);\n    y.resize(45);\n    for (size_t i = 0; i < x.size(); ++i) {\n        x[i] = i;\n        y[i] = i;\n    }\n\n    x_copy = x;\n    y_copy = y;\n    pchip_spline = pchip(std::move(x_copy), std::move(y_copy));\n    for (Real t = 0; t < x.back(); t += 0.5) {\n        CHECK_ULP_CLOSE(t, pchip_spline(t), 0);\n        CHECK_ULP_CLOSE(Real(1), pchip_spline.prime(t), 0);\n    }\n\n    x_copy = x;\n    y_copy = y;\n    // Test endpoint derivatives:\n    pchip_spline = pchip(std::move(x_copy), std::move(y_copy), Real(1), Real(1));\n    for (Real t = 0; t < x.back(); t += 0.5) {\n        CHECK_ULP_CLOSE(t, pchip_spline(t), 0);\n        CHECK_ULP_CLOSE(Real(1), pchip_spline.prime(t), 0);\n    }\n\n\n    boost::circular_buffer<Real> x_buf(x.size());\n    for (auto & t : x) {\n        x_buf.push_back(t);\n    }\n\n    boost::circular_buffer<Real> y_buf(x.size());\n    for (auto & t : y) {\n        y_buf.push_back(t);\n    }\n\n    auto circular_pchip_spline = pchip(std::move(x_buf), std::move(y_buf));\n\n    for (Real t = x[0]; t <= x.back(); t += 0.25) {\n        CHECK_ULP_CLOSE(t, circular_pchip_spline(t), 2);\n        CHECK_ULP_CLOSE(Real(1), circular_pchip_spline.prime(t), 2);\n    }\n\n    circular_pchip_spline.push_back(x.back() + 1, y.back()+1);\n\n    CHECK_ULP_CLOSE(Real(y.back() + 1), circular_pchip_spline(Real(x.back()+1)), 2);\n    CHECK_ULP_CLOSE(Real(1), circular_pchip_spline.prime(Real(x.back()+1)), 2);\n\n}\n\ntemplate<typename Real>\nvoid test_interpolation_condition()\n{\n    for (size_t n = 4; n < 50; ++n) {\n        std::vector<Real> x(n);\n        std::vector<Real> y(n);\n        std::default_random_engine rd;\n        std::uniform_real_distribution<Real> dis(0,1);\n        Real x0 = dis(rd);\n        x[0] = x0;\n        y[0] = dis(rd);\n        for (size_t i = 1; i < n; ++i) {\n            x[i] = x[i-1] + dis(rd);\n            y[i] = dis(rd);\n        }\n\n        auto x_copy = x;\n        auto y_copy = y;\n        auto s = pchip(std::move(x_copy), std::move(y_copy));\n        //std::cout << \"s = \" << s << \"\\n\";\n        for (size_t i = 0; i < x.size(); ++i) {\n            CHECK_ULP_CLOSE(y[i], s(x[i]), 2);\n        }\n\n        x_copy = x;\n        y_copy = y;\n        // The interpolation condition is not affected by the endpoint derivatives, even though these derivatives might be super weird:\n        s = pchip(std::move(x_copy), std::move(y_copy), Real(0), Real(0));\n        //std::cout << \"s = \" << s << \"\\n\";\n        for (size_t i = 0; i < x.size(); ++i) {\n            CHECK_ULP_CLOSE(y[i], s(x[i]), 2);\n        }\n\n    }\n}\n\ntemplate<typename Real>\nvoid test_monotonicity()\n{\n    for (size_t n = 4; n < 50; ++n) {\n        std::vector<Real> x(n);\n        std::vector<Real> y(n);\n        std::default_random_engine rd;\n        std::uniform_real_distribution<Real> dis(0,1);\n        Real x0 = dis(rd);\n        x[0] = x0;\n        y[0] = dis(rd);\n        // Monotone increasing:\n        for (size_t i = 1; i < n; ++i) {\n            x[i] = x[i-1] + dis(rd);\n            y[i] = y[i-1] + dis(rd);\n        }\n\n        auto x_copy = x;\n        auto y_copy = y;\n        auto s = pchip(std::move(x_copy), std::move(y_copy));\n        //std::cout << \"s = \" << s << \"\\n\";\n        for (size_t i = 0; i < x.size() - 1; ++i) {\n            Real tmin = x[i];\n            Real tmax = x[i+1];\n            Real val = y[i];\n            CHECK_ULP_CLOSE(y[i], s(x[i]), 2);\n            for (Real t = tmin; t < tmax; t += (tmax-tmin)/16) {\n                Real greater_val = s(t);\n                BOOST_ASSERT(val <= greater_val);\n                val = greater_val;\n            }\n        }\n\n\n        x[0] = dis(rd);\n        y[0] = dis(rd);\n        // Monotone decreasing:\n        for (size_t i = 1; i < n; ++i) {\n            x[i] = x[i-1] + dis(rd);\n            y[i] = y[i-1] - dis(rd);\n        }\n\n        x_copy = x;\n        y_copy = y;\n        s = pchip(std::move(x_copy), std::move(y_copy));\n        //std::cout << \"s = \" << s << \"\\n\";\n        for (size_t i = 0; i < x.size() - 1; ++i) {\n            Real tmin = x[i];\n            Real tmax = x[i+1];\n            Real val = y[i];\n            CHECK_ULP_CLOSE(y[i], s(x[i]), 2);\n            for (Real t = tmin; t < tmax; t += (tmax-tmin)/16) {\n                Real lesser_val = s(t);\n                BOOST_ASSERT(val >= lesser_val);\n                val = lesser_val;\n            }\n        }\n\n    }\n}\n\n\nint main()\n{\n#if (__GNUC__ > 7) || defined(_MSC_VER) || defined(__clang__)\n    test_constant<float>();\n    test_linear<float>();\n    test_interpolation_condition<float>();\n    test_monotonicity<float>();\n\n    test_constant<double>();\n    test_linear<double>();\n    test_interpolation_condition<double>();\n    test_monotonicity<double>();\n\n    test_constant<long double>();\n    test_linear<long double>();\n    test_interpolation_condition<long double>();\n    test_monotonicity<long double>();\n\n#ifdef BOOST_HAS_FLOAT128\n    test_constant<float128>();\n    test_linear<float128>();\n#endif\n#endif\n    return boost::math::test::report_errors();\n}\n", "meta": {"hexsha": "17db19a3320a4362a2d43ad0289f36c0ec48cb95", "size": 7345, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/pchip_test.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": "test/pchip_test.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": "test/pchip_test.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": 28.8039215686, "max_line_length": 135, "alphanum_fraction": 0.5466303608, "num_tokens": 2267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942171172604, "lm_q2_score": 0.7931059536292271, "lm_q1q2_score": 0.716408021474551}}
{"text": "#define BOOST_TEST_MODULE example\n#include <boost/test/included/unit_test.hpp>\n#include <boost/test/data/test_case.hpp>\n#include <boost/test/data/monomorphic.hpp>\n#include <sstream>\n\nclass fibonacci_dataset {\n    public:\n        using sample = int;\n        enum { arity = 1 };\n\n        struct iterator {\n            public:\n                iterator() : a{1}, b{1} { }\n\n                int operator*() const { return b; }\n                void operator++() {\n                    a = a + b;\n                    std::swap(a, b);\n                }\n\n            private:\n                int a;\n                int b;\n        };\n\n        fibonacci_dataset() { }\n\n        boost::unit_test::data::size_t size() const {\n            return boost::unit_test::data::BOOST_TEST_DS_INFINITE_SIZE; \n        }\n\n        iterator begin() const { return iterator(); }\n};\n\nnamespace boost { \n    namespace unit_test {\n        namespace data {\n            namespace monomorphic {\n                template <>\n                struct is_dataset<fibonacci_dataset> : boost::mpl::true_ { };\n            }\n        }\n    }\n}\n\nBOOST_DATA_TEST_CASE(\n    test1,\n    fibonacci_dataset() ^ boost::unit_test::data::make( \n                            { 1, 2, 3, 5, 8, 13, 21, 34, 55 }),\n    fib_actual,\n    expected)\n{\n    BOOST_TEST(fib_actual == expected);\n}\n", "meta": {"hexsha": "c575fce3291235d5acd85972aaf5948fdaa21409", "size": 1325, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "books/tech/cpp/boost/official_doc/11-correctness_and_testing/04-test/05-custom_dataset/main.cpp", "max_stars_repo_name": "ordinary-developer/education", "max_stars_repo_head_hexsha": "1b1f40dacab873b28ee01dfa33a9bd3ec4cfed58", "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": "books/tech/cpp/boost/official_doc/11-correctness_and_testing/04-test/05-custom_dataset/main.cpp", "max_issues_repo_name": "ordinary-developer/education", "max_issues_repo_head_hexsha": "1b1f40dacab873b28ee01dfa33a9bd3ec4cfed58", "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": "books/tech/cpp/boost/official_doc/11-correctness_and_testing/04-test/05-custom_dataset/main.cpp", "max_forks_repo_name": "ordinary-developer/education", "max_forks_repo_head_hexsha": "1b1f40dacab873b28ee01dfa33a9bd3ec4cfed58", "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.6607142857, "max_line_length": 77, "alphanum_fraction": 0.5033962264, "num_tokens": 295, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941988938414, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.7164080114387654}}
{"text": "#include \"writer.hpp\"\n#include <Eigen/Core>\n#include <cmath>\n#include <functional>\n#include <iostream>\n#include <stdexcept>\n\nvoid apply_boundary_conditions(Eigen::ArrayXXd &u, int k) {\n    auto N = u.rows();\n    u(0, k) = u(1, k);\n    u(N - 1, k) = u(N - 2, k);\n}\n\n//----------------upwindFDBegin----------------\n/// Uses forward Euler and upwind finite differences to compute u from time 0 to\n/// time T\n///\n/// @param[in] u0 the initial conditions in the physical domain, excluding\n/// ghost-points.\n/// @param[in] dt the time step size\n/// @param[in] T the solution is computed for the interval [0, T]. T is assumed\n/// to be a multiple of of dt.\n/// @param[in] a the advection velocity\n/// @param[in] domain left & right limit of the domain\n///\n/// @return returns the solution 'u' at every time-step and the corresponding\n/// time-steps. The solution `u` includes the ghost-points.\nstd::pair<Eigen::ArrayXXd, Eigen::VectorXd>\nupwindFD(const Eigen::VectorXd &u0,\n         double dt,\n         double T,\n         const std::function<double(double)> &a,\n         const std::pair<double, double> &domain) {\n\n    auto N = u0.size();\n    auto nsteps = int(round(T / dt));\n\n    auto u = Eigen::ArrayXXd(N + 2, nsteps + 1);\n    auto time = Eigen::VectorXd(nsteps + 1);\n\n    auto [xL, xR] = domain;\n    double dx = (xR - xL) / (N - 1.0);\n\n    /* Initialize u */\n    //// ANCSE_START_TEMPLATE\n    u.col(0).segment(1, N) = u0;\n    apply_boundary_conditions(u, 0);\n    time[0] = 0.0;\n    //// ANCSE_END_TEMPLATE\n\n    /* Main loop */\n    //// ANCSE_START_TEMPLATE\n    for (int k = 0; k < nsteps; k++) {\n        for (int j = 1; j < N + 1; j++) {\n\n            double x = xL + (j - 1) * dx;\n\n            double uL = u(j - 1, k);\n            double uM = u(j, k);\n            double uR = u(j + 1, k);\n            double ax = a(x);\n            double c = 0.5 * dt / dx;\n\n            u(j, k + 1)\n                = uM - c * (ax * (uR - uL) - fabs(ax) * (uR - 2 * uM + uL));\n        }\n        /* Outflow boundary conditions */\n        apply_boundary_conditions(u, k + 1);\n        time[k + 1] = (k + 1) * dt;\n    }\n    //// ANCSE_END_TEMPLATE\n\n    return {std::move(u), std::move(time)};\n}\n//----------------upwindFDEnd----------------\n\n//----------------centeredFDBegin----------------\n/// Uses forward Euler and centered finite differences to compute u from time 0\n/// to time T\n///\n/// @param[in] u0 the initial conditions, as column vector\n/// @param[in] dt the time step size\n/// @param[in] T the solution is computed for the interval [0, T]. T is assumed\n/// to be a multiple of of dt.\n/// @param[in] a the advection velocity\n/// @param[in] domain left & right limit of the domain\n///\n/// @return returns the solution 'u' at every time-step and the corresponding\n/// time-steps. The solution `u` includes the ghost-points.\nstd::pair<Eigen::ArrayXXd, Eigen::VectorXd>\ncenteredFD(const Eigen::VectorXd &u0,\n           double dt,\n           double T,\n           const std::function<double(double)> &a,\n           const std::pair<double, double> &domain) {\n\n    auto N = u0.size();\n    auto nsteps = int(round(T / dt));\n    auto u = Eigen::ArrayXXd(N + 2, nsteps + 1);\n    auto time = Eigen::VectorXd(nsteps + 1);\n\n    auto [xL, xR] = domain;\n    double dx = (xR - xL) / (N - 1.0);\n\n    /* Initialize u */\n    //// ANCSE_START_TEMPLATE\n    u.col(0).segment(1, N) = u0;\n    apply_boundary_conditions(u, 0);\n    time[0] = 0.0;\n    //// ANCSE_END_TEMPLATE\n\n    /* Main loop */\n    //// ANCSE_START_TEMPLATE\n    for (int k = 0; k < nsteps; k++) {\n        for (int j = 1; j < N + 1; j++) {\n            double x = xL + (j - 1) * dx;\n            u(j, k + 1)\n                = u(j, k)\n                  - dt / (2.0 * dx) * a(x) * (u(j + 1, k) - u(j - 1, k));\n        }\n\n        /* Outflow boundary conditions */\n        apply_boundary_conditions(u, k + 1);\n        time[k + 1] = (k + 1) * dt;\n    }\n    //// ANCSE_END_TEMPLATE\n\n    return {std::move(u), std::move(time)};\n}\n//----------------centeredFDEnd----------------\n\n/* Initial condition: rectangle */\ndouble ic(double x) {\n    if (x < 0.25 || x > 0.75)\n        return 0.0;\n    else\n        return 2.0;\n}\n\nint main() {\n    double T = 2.0;\n    double dt = 0.002; // Change this for timestep comparison\n    int N = 101;\n\n    double xL = 0.0;\n    double xR = 5.0;\n    auto domain = std::pair<double, double>{xL, xR};\n\n    auto a = [](double x) { return std::sin(2.0 * M_PI * x); };\n\n    Eigen::VectorXd u0(N);\n    double h = (xR - xL) / (N - 1.0);\n    /* Initialize u0 */\n    for (int i = 0; i < u0.size(); i++) {\n        u0[i] = ic(xL + h * i);\n    }\n\n    const auto &[u_upwind, time_upwind] = upwindFD(u0, dt, T, a, domain);\n    writeToFile(\"time_upwind.txt\", time_upwind);\n    writeMatrixToFile(\"u_upwind.txt\", u_upwind);\n\n    const auto &[u_centered, time_centered] = centeredFD(u0, dt, T, a, domain);\n    writeToFile(\"time_centered.txt\", time_centered);\n    writeMatrixToFile(\"u_centered.txt\", u_centered);\n}\n", "meta": {"hexsha": "db99de6040e690dd6fb32ff931c75c3e6cada8f2", "size": 4942, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "series0_solution/linear-transp-1d/linear_transport.cpp", "max_stars_repo_name": "BeatHubmann/19H-AdvNCSE", "max_stars_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-05T22:38:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-05T22:38:47.000Z", "max_issues_repo_path": "series0_solution/linear-transp-1d/linear_transport.cpp", "max_issues_repo_name": "BeatHubmann/19H-AdvNCSE", "max_issues_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "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": "series0_solution/linear-transp-1d/linear_transport.cpp", "max_forks_repo_name": "BeatHubmann/19H-AdvNCSE", "max_forks_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-08T20:43:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-08T20:43:27.000Z", "avg_line_length": 29.7710843373, "max_line_length": 80, "alphanum_fraction": 0.5455281263, "num_tokens": 1506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.859663743319094, "lm_q2_score": 0.8333246015211008, "lm_q1q2_score": 0.7163789463435218}}
{"text": "#ifndef MATHTOOLBOX_PROBABILITY_DISTRIBUTIONS_HPP\n#define MATHTOOLBOX_PROBABILITY_DISTRIBUTIONS_HPP\n\n#include <Eigen/Core>\n\nnamespace mathtoolbox\n{\n    // N(x | 0, 1)\n    double GetStandardNormalDist(const double x);\n\n    // d/dx N(x | 0, 1)\n    double GetStandardNormalDistDerivative(const double x);\n\n    // integral_{- inf, x} N(x' | 0, 1) dx'\n    double GetStandardNormalDistCdf(const double x);\n\n    // N(x | mu, sigma^2)\n    double GetNormalDist(const double x, const double mu, const double sigma_2);\n\n    // d/dx N(x | mu, sigma^2)\n    double GetNormalDistDerivative(const double x, const double mu, const double sigma_2);\n\n    // LogNormal(x | mu, sigma^2)\n    double GetLogNormalDist(const double x, const double mu, const double sigma_2);\n\n    // d/dx LogNormal(x | mu, sigma^2)\n    double GetLogNormalDistDerivative(const double x, const double mu, const double sigma_2);\n\n    // log{ LogNormal(x | mu, sigma^2) }\n    double GetLogOfLogNormalDist(const double x, const double mu, const double sigma_2);\n\n    // d/dx log{ LogNormal(x | mu, sigma^2) }\n    double GetLogOfLogNormalDistDerivative(const double x, const double mu, const double sigma_2);\n\n    // N(x | mu, Sigma)\n    double GetNormalDist(const Eigen::VectorXd& x,\n                         const Eigen::VectorXd& mu,\n                         const Eigen::MatrixXd& Sigma_inv,\n                         const double           Sigma_det);\n} // namespace mathtoolbox\n\n#endif // MATHTOOLBOX_PROBABILITY_DISTRIBUTIONS_HPP\n", "meta": {"hexsha": "c670200dab29faa9d03601107efd2ce8d50086c6", "size": 1488, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mathtoolbox/probability-distributions.hpp", "max_stars_repo_name": "yuki-koyama/mathtoolbox", "max_stars_repo_head_hexsha": "eb7449c3c489f465849a74405e72aff016a296f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 195.0, "max_stars_repo_stars_event_min_datetime": "2018-04-28T16:12:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:52:56.000Z", "max_issues_repo_path": "include/mathtoolbox/probability-distributions.hpp", "max_issues_repo_name": "amazing89/mathtoolbox", "max_issues_repo_head_hexsha": "8904bb06ced2ac501594f9574ef1ba3454b8e38e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 52.0, "max_issues_repo_issues_event_min_datetime": "2018-04-15T01:24:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-02T09:14:23.000Z", "max_forks_repo_path": "include/mathtoolbox/probability-distributions.hpp", "max_forks_repo_name": "amazing89/mathtoolbox", "max_forks_repo_head_hexsha": "8904bb06ced2ac501594f9574ef1ba3454b8e38e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 21.0, "max_forks_repo_forks_event_min_datetime": "2018-06-05T04:11:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T13:28:12.000Z", "avg_line_length": 34.6046511628, "max_line_length": 98, "alphanum_fraction": 0.6727150538, "num_tokens": 401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541643004809, "lm_q2_score": 0.7606506526772883, "lm_q1q2_score": 0.7162698546714472}}
{"text": "#include <iostream>\n#include <iterator>\n#include <algorithm>\n#include <math.h>\n#include <cmath>\n#include <boost/multiprecision/float128.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing namespace boost::multiprecision;\n\n\nclass Fibonacci{\n    cpp_int m_previousEven;\n    cpp_int m_currentEven;\n    cpp_int m_nextEven;\n\n    cpp_int even_sum(int limit) {\n        if(limit == 0){\n            return 0;\n        }\n        cpp_int ef1 = 0, ef2 = 2;\n        cpp_int sum = m_previousEven + m_currentEven;\n        int count = 0;\n\n        while (count <= limit-2) {\n            count++;\n            m_nextEven = 4*m_currentEven + m_previousEven;\n            m_previousEven = m_currentEven;\n            m_currentEven = m_nextEven;\n            sum += m_currentEven;\n        }\n\n        return sum;\n    }\n\npublic:\n    Fibonacci(){\n        m_previousEven = 0;\n        m_currentEven = 2;\n    }\n\n    cpp_int get_even_sum(int limit){\n        int m_totalEvenNumber;\n        m_totalEvenNumber = limit / 3;\n        return even_sum(m_totalEvenNumber);\n    }\n\n};\n\n\nint main()\n{\n    Fibonacci obj;\n    int m_input;\n    std::cout<<\"Enter nth number as Limit : \";\n    std::cin>> m_input;\n    std::cout<<\"Sum of Even Number within limit: \";\n    std::cout<<obj.get_even_sum(m_input);\n    return 0;\n}\n", "meta": {"hexsha": "66188a66f477660a81048e1bbd3530d394d378ff", "size": 1277, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "raviy0807/Fibonacci-Sum-of-Even", "max_stars_repo_head_hexsha": "a2d15502e10abae5601b26c16a0699cd8afbea7d", "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": "raviy0807/Fibonacci-Sum-of-Even", "max_issues_repo_head_hexsha": "a2d15502e10abae5601b26c16a0699cd8afbea7d", "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": "raviy0807/Fibonacci-Sum-of-Even", "max_forks_repo_head_hexsha": "a2d15502e10abae5601b26c16a0699cd8afbea7d", "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": 20.9344262295, "max_line_length": 58, "alphanum_fraction": 0.5990602976, "num_tokens": 318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541544761565, "lm_q2_score": 0.7606506418255927, "lm_q1q2_score": 0.7162698369800243}}
{"text": "/**\n * optimal_pow2_rational.cpp\n * This program finds a rational number of the form\n *     mult / 2^shift\n * which approximates a user-supplied fraction to within the roundoff\n * of multshiftround when multiplied by integers on a user-specified\n * range.\n *\n * Written in 2018 by Ben Tesch.\n * Originally distributed at https://github.com/slugrustle/numerical_routines\n *\n * To the extent possible under law, the author has dedicated all copyright\n * and related and neighboring rights to this software to the public domain\n * worldwide. This software is distributed without any warranty.\n * The text of the CC0 Public Domain Dedication should be reproduced at the\n * end of this file. If not, see http://creativecommons.org/publicdomain/zero/1.0/\n */\n\n#include <cinttypes>\n#include <iostream>\n#include <limits>\n#include <string>\n#include <stdexcept>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#include <boost/math/special_functions/round.hpp>\n\ntypedef boost::multiprecision::number<boost::multiprecision::backends::cpp_bin_float<80, boost::multiprecision::backends::digit_base_2, void, boost::int16_t, -16382, 16383>, boost::multiprecision::et_off> cpp_bin_float_80;\n\nint main(int argc, char *argv[])\n{\n  std::cout << \"\\n cmdline arguments: [range min] [range max] [fraction]\\n\" << std::endl;\n\n  if (argc != 4)\n  {\n    std::cout << \" ERROR: this program must be run with 3 arguments.\\n\" << std::endl;\n    return 0;\n  }\n\n  cpp_bin_float_80 range_min;\n  try { range_min = cpp_bin_float_80(argv[1]); }\n  catch (const std::runtime_error &e)\n  {\n    std::cout << \" ERROR: range min argument could not be converted to an 80-bit mantissa float.\\n\" << std::endl;\n    return 0;\n  }\n  if ((range_min < cpp_bin_float_80(std::numeric_limits<int64_t>::lowest())) | \n      (range_min > cpp_bin_float_80(std::numeric_limits<uint64_t>::max())))\n  {\n    std::cout << \" ERROR: range min argument is outside the allowed range [-2^63,2^64-1]\" << std::endl;\n    std::cout << \"   which is [\" << std::numeric_limits<int64_t>::lowest() << \", \" << std::numeric_limits<uint64_t>::max() << \"]\\n\" << std::endl;\n    return 0;\n  }\n  if (range_min != boost::math::round(range_min))\n  {\n    std::cout << \" ERROR: range min argument must be an integer.\\n\" << std::endl;\n    return 0;\n  }\n\n  cpp_bin_float_80 range_max;\n  try { range_max = cpp_bin_float_80(argv[2]); }\n  catch (const std::runtime_error &e)\n  {\n    std::cout << \" ERROR: range max argument could not be converted to an 80-bit mantissa float.\\n\" << std::endl;\n    return 0;\n  }\n  if ((range_max < cpp_bin_float_80(std::numeric_limits<int64_t>::lowest())) |\n      (range_max > cpp_bin_float_80(std::numeric_limits<uint64_t>::max())))\n  {\n    std::cout << \" ERROR: range max argument is outside the allowed range [-2^63,2^64-1]\" << std::endl;\n    std::cout << \"   which is [\" << std::numeric_limits<int64_t>::lowest() << \", \" << std::numeric_limits<uint64_t>::max() << \"]\\n\" << std::endl;\n    return 0;\n  }\n  if (range_max != boost::math::round(range_max))\n  {\n    std::cout << \" ERROR: range max argument must be an integer.\\n\" << std::endl;\n    return 0;\n  }\n\n  if (range_max < range_min)\n  {\n    std::cout << \" ERROR: range max must be greater than or equal to range min.\\n\" << std::endl;\n    return 0;\n  }\n\n  cpp_bin_float_80 fraction;\n  try { fraction = cpp_bin_float_80(argv[3]); }\n  catch (const std::runtime_error &e)\n  {\n    std::cout << \" ERROR: fraction argument could not be converted to an 80-bit mantissa float.\\n\" << std::endl;\n    return 0;\n  }\n  if ((fraction < cpp_bin_float_80(0.0)) |\n      (fraction > cpp_bin_float_80(std::numeric_limits<uint64_t>::max())))\n  {\n    std::cout << \" ERROR: fraction argument is outside the allowed range [0.0,2.0^64-1.0]\" << std::endl;\n    std::cout << \"   which is [0.0, \" << std::numeric_limits<uint64_t>::max() << \".0]\\n\" << std::endl;\n    return 0;\n  }\n\n  for (int8_t shift = 1; shift <= 63; shift++)\n  {\n    cpp_bin_float_80 two_exp     = cpp_bin_float_80(1ull << shift);\n    cpp_bin_float_80 approx_mult = boost::math::round(fraction * two_exp);\n    cpp_bin_float_80 min_prod    = range_min * approx_mult;\n    cpp_bin_float_80 approx_min  = min_prod / two_exp;\n    cpp_bin_float_80 max_prod    = range_max * approx_mult;\n    cpp_bin_float_80 approx_max  = max_prod / two_exp;\n    cpp_bin_float_80 ratio_min   = range_min * fraction;\n    cpp_bin_float_80 ratio_max   = range_max * fraction;\n\n    if (boost::multiprecision::fabs(approx_min-ratio_min) < cpp_bin_float_80(0.5) &&\n        boost::multiprecision::fabs(approx_max-ratio_max) < cpp_bin_float_80(0.5))\n    {\n      std::cout << \" The rational \" << std::setprecision(24) << approx_mult << \" / 2^\" << static_cast<int16_t>(shift) << \" = \";\n      std::cout << std::setprecision(24) << approx_mult / two_exp << std::endl;\n      std::cout << \"   approximates fraction = \" << std::setprecision(24) << fraction << std::endl;\n      std::cout << \"   to within roundoff when multiplied by numbers on the range\" << std::endl;\n      std::cout << \"   [\" << range_min << \", \" << range_max << \"].\\n\" << std::endl;\n\n      std::cout << \" The internal product\" << std::endl;\n      std::cout << \"   \" << range_min << \" * \" << approx_mult << \" = \" << std::setprecision(24) << min_prod << std::endl;\n      if (min_prod == cpp_bin_float_80(0.0))\n      {\n        std::cout << \"   will not underflow or overflow any integer type.\\n\" << std::endl;\n      }\n      else if (min_prod < cpp_bin_float_80(0.0))\n      {\n        if (min_prod < cpp_bin_float_80(std::numeric_limits<int64_t>::lowest()))\n        {\n          std::cout << \"   will underflow an int64_t.\\n\" << std::endl;\n        }\n        else if (min_prod < cpp_bin_float_80(std::numeric_limits<int32_t>::lowest()))\n        {\n          std::cout << \"   will underflow an int32_t but not an int64_t.\\n\" << std::endl;\n        }\n        else if (min_prod < cpp_bin_float_80(std::numeric_limits<int16_t>::lowest()))\n        {\n          std::cout << \"   will underflow an int16_t but not an int32_t.\\n\" << std::endl;\n        }\n        else if (min_prod < cpp_bin_float_80(std::numeric_limits<int8_t>::lowest()))\n        {\n          std::cout << \"   will underflow an int8_t but not an int16_t.\\n\" << std::endl;\n        }\n        else\n        {\n          std::cout << \"   will not underflow an int8_t.\\n\" << std::endl;\n        }\n      }\n      else if (min_prod > cpp_bin_float_80(0.0))\n      {\n        if (min_prod > cpp_bin_float_80(std::numeric_limits<uint64_t>::max()))\n        {\n          std::cout << \"   will overflow a uint64_t.\\n\" << std::endl;\n        }\n        else if (min_prod > cpp_bin_float_80(std::numeric_limits<int64_t>::max()))\n        {\n          std::cout << \"   will overflow an int64_t but not a uint64_t.\\n\" << std::endl;\n        }\n        else if (min_prod > cpp_bin_float_80(std::numeric_limits<uint32_t>::max()))\n        {\n          std::cout << \"   will overflow a uint32_t but not an int64_t.\\n\" << std::endl;\n        }\n        else if (min_prod > cpp_bin_float_80(std::numeric_limits<int32_t>::max()))\n        {\n          std::cout << \"   will overflow an int32_t but not a uint32_t.\\n\" << std::endl;\n        }\n        else if (min_prod > cpp_bin_float_80(std::numeric_limits<uint16_t>::max()))\n        {\n          std::cout << \"   will overflow a uint16_t but not an int32_t.\\n\" << std::endl;\n        }\n        else if (min_prod > cpp_bin_float_80(std::numeric_limits<int16_t>::max()))\n        {\n          std::cout << \"   will overflow an int16_t but not a uint16_t.\\n\" << std::endl;\n        }\n        else if (min_prod > cpp_bin_float_80(std::numeric_limits<uint8_t>::max()))\n        {\n          std::cout << \"   will overflow a uint8_t but not an int16_t.\\n\" << std::endl;\n        }\n        else if (min_prod > cpp_bin_float_80(std::numeric_limits<int8_t>::max()))\n        {\n          std::cout << \"   will overflow an int8_t but not a uint8_t.\\n\" << std::endl;\n        }\n        else\n        {\n          std::cout << \"   will not overflow an int8_t.\\n\" << std::endl;\n        }\n      }\n\n      std::cout << \" The internal product\" << std::endl;\n      std::cout << \"   \" << range_max << \" * \" << approx_mult << \" = \" << std::setprecision(24) << max_prod << std::endl;\n      if (max_prod == cpp_bin_float_80(0.0))\n      {\n        std::cout << \"   will not underflow or overflow any integer type.\\n\" << std::endl;\n      }\n      else if (max_prod < cpp_bin_float_80(0.0))\n      {\n        if (max_prod < cpp_bin_float_80(std::numeric_limits<int64_t>::lowest()))\n        {\n          std::cout << \"   will underflow an int64_t.\\n\" << std::endl;\n        }\n        else if (max_prod < cpp_bin_float_80(std::numeric_limits<int32_t>::lowest()))\n        {\n          std::cout << \"   will underflow an int32_t but not an int64_t.\\n\" << std::endl;\n        }\n        else if (max_prod < cpp_bin_float_80(std::numeric_limits<int16_t>::lowest()))\n        {\n          std::cout << \"   will underflow an int16_t but not an int32_t.\\n\" << std::endl;\n        }\n        else if (max_prod < cpp_bin_float_80(std::numeric_limits<int8_t>::lowest()))\n        {\n          std::cout << \"   will underflow an int8_t but not an int16_t.\\n\" << std::endl;\n        }\n        else\n        {\n          std::cout << \"   will not underflow an int8_t.\\n\" << std::endl;\n        }\n      }\n      else if (max_prod > cpp_bin_float_80(0.0))\n      {\n        if (max_prod > cpp_bin_float_80(std::numeric_limits<uint64_t>::max()))\n        {\n          std::cout << \"   will overflow a uint64_t.\\n\" << std::endl;\n        }\n        else if (max_prod > cpp_bin_float_80(std::numeric_limits<int64_t>::max()))\n        {\n          std::cout << \"   will overflow an int64_t but not a uint64_t.\\n\" << std::endl;\n        }\n        else if (max_prod > cpp_bin_float_80(std::numeric_limits<uint32_t>::max()))\n        {\n          std::cout << \"   will overflow a uint32_t but not an int64_t.\\n\" << std::endl;\n        }\n        else if (max_prod > cpp_bin_float_80(std::numeric_limits<int32_t>::max()))\n        {\n          std::cout << \"   will overflow an int32_t but not a uint32_t.\\n\" << std::endl;\n        }\n        else if (max_prod > cpp_bin_float_80(std::numeric_limits<uint16_t>::max()))\n        {\n          std::cout << \"   will overflow a uint16_t but not an int32_t.\\n\" << std::endl;\n        }\n        else if (max_prod > cpp_bin_float_80(std::numeric_limits<int16_t>::max()))\n        {\n          std::cout << \"   will overflow an int16_t but not a uint16_t.\\n\" << std::endl;\n        }\n        else if (max_prod > cpp_bin_float_80(std::numeric_limits<uint8_t>::max()))\n        {\n          std::cout << \"   will overflow a uint8_t but not an int16_t.\\n\" << std::endl;\n        }\n        else if (max_prod > cpp_bin_float_80(std::numeric_limits<int8_t>::max()))\n        {\n          std::cout << \"   will overflow an int8_t but not a uint8_t.\\n\" << std::endl;\n        }\n        else\n        {\n          std::cout << \"   will not overflow an int8_t.\\n\" << std::endl;\n        }\n      }\n      return 0;\n    }\n  }\n\n  std::cout << \" No rational with base 2 denominator was found that\" << std::endl;\n  std::cout << \"   approximates fraction = \" << std::setprecision(24) << fraction << std::endl;\n  std::cout << \"   to within roundoff when multiplied by numbers on the range\" << std::endl;\n  std::cout << \"   [\" << range_min << \", \" << range_max << \"]\" << std::endl;\n  std::cout << \"   for denominators ranging from 2 to 2^63 inclusive.\\n\" << std::endl;\n  return 0;\n}\n\n/*\nCreative Commons Legal Code\n\nCC0 1.0 Universal\n\n    CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE\n    LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN\n    ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS\n    INFORMATION ON AN \"AS-IS\" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES\n    REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS\n    PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM\n    THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED\n    HEREUNDER.\n\nStatement of Purpose\n\nThe laws of most jurisdictions throughout the world automatically confer\nexclusive Copyright and Related Rights (defined below) upon the creator\nand subsequent owner(s) (each and all, an \"owner\") of an original work of\nauthorship and/or a database (each, a \"Work\").\n\nCertain owners wish to permanently relinquish those rights to a Work for\nthe purpose of contributing to a commons of creative, cultural and\nscientific works (\"Commons\") that the public can reliably and without fear\nof later claims of infringement build upon, modify, incorporate in other\nworks, reuse and redistribute as freely as possible in any form whatsoever\nand for any purposes, including without limitation commercial purposes.\nThese owners may contribute to the Commons to promote the ideal of a free\nculture and the further production of creative, cultural and scientific\nworks, or to gain reputation or greater distribution for their Work in\npart through the use and efforts of others.\n\nFor these and/or other purposes and motivations, and without any\nexpectation of additional consideration or compensation, the person\nassociating CC0 with a Work (the \"Affirmer\"), to the extent that he or she\nis an owner of Copyright and Related Rights in the Work, voluntarily\nelects to apply CC0 to the Work and publicly distribute the Work under its\nterms, with knowledge of his or her Copyright and Related Rights in the\nWork and the meaning and intended legal effect of CC0 on those rights.\n\n1. Copyright and Related Rights. A Work made available under CC0 may be\nprotected by copyright and related or neighboring rights (\"Copyright and\nRelated Rights\"). Copyright and Related Rights include, but are not\nlimited to, the following:\n\n  i. the right to reproduce, adapt, distribute, perform, display,\n     communicate, and translate a Work;\n ii. moral rights retained by the original author(s) and/or performer(s);\niii. publicity and privacy rights pertaining to a person's image or\n     likeness depicted in a Work;\n iv. rights protecting against unfair competition in regards to a Work,\n     subject to the limitations in paragraph 4(a), below;\n  v. rights protecting the extraction, dissemination, use and reuse of data\n     in a Work;\n vi. database rights (such as those arising under Directive 96/9/EC of the\n     European Parliament and of the Council of 11 March 1996 on the legal\n     protection of databases, and under any national implementation\n     thereof, including any amended or successor version of such\n     directive); and\nvii. other similar, equivalent or corresponding rights throughout the\n     world based on applicable law or treaty, and any national\n     implementations thereof.\n\n2. Waiver. To the greatest extent permitted by, but not in contravention\nof, applicable law, Affirmer hereby overtly, fully, permanently,\nirrevocably and unconditionally waives, abandons, and surrenders all of\nAffirmer's Copyright and Related Rights and associated claims and causes\nof action, whether now known or unknown (including existing as well as\nfuture claims and causes of action), in the Work (i) in all territories\nworldwide, (ii) for the maximum duration provided by applicable law or\ntreaty (including future time extensions), (iii) in any current or future\nmedium and for any number of copies, and (iv) for any purpose whatsoever,\nincluding without limitation commercial, advertising or promotional\npurposes (the \"Waiver\"). Affirmer makes the Waiver for the benefit of each\nmember of the public at large and to the detriment of Affirmer's heirs and\nsuccessors, fully intending that such Waiver shall not be subject to\nrevocation, rescission, cancellation, termination, or any other legal or\nequitable action to disrupt the quiet enjoyment of the Work by the public\nas contemplated by Affirmer's express Statement of Purpose.\n\n3. Public License Fallback. Should any part of the Waiver for any reason\nbe judged legally invalid or ineffective under applicable law, then the\nWaiver shall be preserved to the maximum extent permitted taking into\naccount Affirmer's express Statement of Purpose. In addition, to the\nextent the Waiver is so judged Affirmer hereby grants to each affected\nperson a royalty-free, non transferable, non sublicensable, non exclusive,\nirrevocable and unconditional license to exercise Affirmer's Copyright and\nRelated Rights in the Work (i) in all territories worldwide, (ii) for the\nmaximum duration provided by applicable law or treaty (including future\ntime extensions), (iii) in any current or future medium and for any number\nof copies, and (iv) for any purpose whatsoever, including without\nlimitation commercial, advertising or promotional purposes (the\n\"License\"). The License shall be deemed effective as of the date CC0 was\napplied by Affirmer to the Work. Should any part of the License for any\nreason be judged legally invalid or ineffective under applicable law, such\npartial invalidity or ineffectiveness shall not invalidate the remainder\nof the License, and in such case Affirmer hereby affirms that he or she\nwill not (i) exercise any of his or her remaining Copyright and Related\nRights in the Work or (ii) assert any associated claims and causes of\naction with respect to the Work, in either case contrary to Affirmer's\nexpress Statement of Purpose.\n\n4. Limitations and Disclaimers.\n\n a. No trademark or patent rights held by Affirmer are waived, abandoned,\n    surrendered, licensed or otherwise affected by this document.\n b. Affirmer offers the Work as-is and makes no representations or\n    warranties of any kind concerning the Work, express, implied,\n    statutory or otherwise, including without limitation warranties of\n    title, merchantability, fitness for a particular purpose, non\n    infringement, or the absence of latent or other defects, accuracy, or\n    the present or absence of errors, whether or not discoverable, all to\n    the greatest extent permissible under applicable law.\n c. Affirmer disclaims responsibility for clearing rights of other persons\n    that may apply to the Work or any use thereof, including without\n    limitation any person's Copyright and Related Rights in the Work.\n    Further, Affirmer disclaims responsibility for obtaining any necessary\n    consents, permissions or other rights required for any use of the\n    Work.\n d. Affirmer understands and acknowledges that Creative Commons is not a\n    party to this document and has no duty or obligation with respect to\n    this CC0 or use of the Work.\n*/", "meta": {"hexsha": "9254139e431d9f9c95334a87c455c558b9f4f0a3", "size": 18469, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "integer/optimal_pow2_rational.cpp", "max_stars_repo_name": "slugrustle/numerical_routines", "max_stars_repo_head_hexsha": "50a8071a0bdb913ae4dca1045312d20da778189b", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-10-12T09:22:41.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-12T09:22:41.000Z", "max_issues_repo_path": "integer/optimal_pow2_rational.cpp", "max_issues_repo_name": "slugrustle/numerical_routines", "max_issues_repo_head_hexsha": "50a8071a0bdb913ae4dca1045312d20da778189b", "max_issues_repo_licenses": ["CC0-1.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": "integer/optimal_pow2_rational.cpp", "max_forks_repo_name": "slugrustle/numerical_routines", "max_forks_repo_head_hexsha": "50a8071a0bdb913ae4dca1045312d20da778189b", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.2352941176, "max_line_length": 222, "alphanum_fraction": 0.6725323515, "num_tokens": 4747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600903, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.7162124209613611}}
{"text": "#include <CGAL/Delaunay_triangulation_2.h>\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Triangulation_vertex_base_with_info_2.h>\n#include <Eigen/Geometry>\n#include <fstream>\n#include <iostream>\n#include <vtkDoubleArray.h>\n#include <vtkPointData.h>\n#include <vtkPolyData.h>\n#include <vtkPolyDataWriter.h>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\ntypedef CGAL::Triangulation_vertex_base_with_info_2<unsigned, K> Vb;\ntypedef CGAL::Triangulation_data_structure_2<Vb> Tds;\ntypedef CGAL::Delaunay_triangulation_2<K, Tds> Delaunay;\ntypedef Delaunay::Face_circulator Face_circulator;\ntypedef Delaunay::Face_handle Face_handle;\ntypedef Delaunay::Point Point;\ntypedef Eigen::Vector3d Vector3d;\ntypedef Eigen::VectorXd VectorXd;\ntypedef Eigen::Matrix3d Matrix3d;\ntypedef Eigen::Matrix3Xd Matrix3Xd;\ntypedef Eigen::Map<Matrix3Xd> Map3Xd;\ntypedef Eigen::Quaterniond Quaterniond;\ntypedef Eigen::AngleAxisd AngleAxisd;\n\nint main(int argc, char *argv[])\n{\n\n  // We expect four command line arguments:\n  // 1. Number of particles in the simulation\n  // 2. Name of data file from which to read rows\n  // 3. Row number to plot -- 0 indexed row number\n  // 4. Output VTK file name\n  if (argc < 4)\n  {\n    std::cout << \"Usage: ./plotRow <number_of_particles> <data_file> \"\n              << \"<row_num> <output_vtk_file>\" << std::endl;\n    return 0;\n  }\n\n  // The number of particles in the simulation\n  size_t N = std::stoi(std::string(argv[1]));\n\n  // The row number to be written to vtk file\n  size_t row = std::stoi(std::string(argv[3]));\n\n  std::ifstream inputfile(argv[2]);\n  if (!inputfile.is_open())\n  {\n    std::cout << \"Unable to open file \" << argv[2] << std::endl;\n    return 0;\n  }\n\n  //**********************************************************************//\n  // Now read the data file line by line\n  //\n\n  // The first line contains gamma and beta information\n  std::string line, ignore;\n  double_t gamma = 0, beta = 0;\n  std::getline(inputfile, line);\n  std::istringstream header(line);\n  header >> ignore >> gamma >> ignore >> beta;\n\n  // Skip to the required row\n  auto rowCount = 0;\n  while (rowCount < row)\n  {\n    std::getline(inputfile, line);\n    rowCount++;\n    continue;\n  }\n\n  std::getline(inputfile, line);\n  std::cout << \"Processing row \" << rowCount << std::endl;\n  std::istringstream rowStream(line);\n\n  // We will extract 3*N doubles representing particle positions\n  // from the stream\n  std::string value;\n  size_t valCount = 0;\n  Matrix3Xd positions(3, N);\n  while (valCount < 3 * N && rowStream.good())\n  {\n    std::getline(rowStream, value, ',');\n    positions(valCount % 3, valCount / 3) = std::stod(value);\n    valCount++;\n  }\n\n  // Read the rotation vectors\n  Matrix3Xd rotVecs(3, N);\n  valCount = 0;\n  while (valCount < 3 * N && rowStream.good())\n  {\n    std::getline(rowStream, value, ',');\n    rotVecs(valCount % 3, valCount / 3) = std::stod(value);\n    valCount++;\n  }\n\n  // Calculate point normals using the rotation vectors\n  Matrix3Xd normals(3, N);\n  Quaterniond zaxis(0.0, 0.0, 0.0, 1.0);\n  for (auto i = 0; i < N; ++i)\n  {\n    normals.col(i) = (Quaterniond(AngleAxisd(rotVecs.col(i).norm(),\n                                             rotVecs.col(i).normalized())) *\n                      zaxis *\n                      (Quaterniond(AngleAxisd(rotVecs.col(i).norm(),\n                                              rotVecs.col(i).normalized()))\n                           .conjugate()))\n                         .vec();\n  }\n\n  // Stereo graphic projection\n  Matrix3Xd points(3, N);\n\n  // Project points to unit sphere\n  points = positions.colwise().normalized();\n\n  // Reset the center of the sphere to origin by translating\n  Vector3d center = points.rowwise().mean();\n  points = points.colwise() - center;\n\n  // Rotate all points so that the point in 0th column is along z-axis\n  Vector3d c = points.col(0);\n  double_t cos_t = c(2);\n  double_t sin_t = std::sqrt(1 - cos_t * cos_t);\n  Vector3d axis;\n  axis << c(1), -c(0), 0.;\n  Matrix3d rotMat, axis_cross, outer;\n  axis_cross << 0., -axis(2), axis(1), axis(2), 0., -axis(0), -axis(1), axis(0),\n      0.;\n\n  outer.noalias() = axis * axis.transpose();\n\n  rotMat =\n      cos_t * Matrix3d::Identity() + sin_t * axis_cross + (1 - cos_t) * outer;\n  Matrix3Xd rPts(3, N);\n  rPts = rotMat * points; // The points on a sphere rotated\n\n  // Calculate the stereographic projections\n  Vector3d p0;\n  Map3Xd l0(&(rPts(0, 1)), 3, N - 1);\n  Matrix3Xd l(3, N - 1), proj(3, N - 1);\n  p0 << 0, 0, -1;\n  c = rPts.col(0);\n  l = (l0.colwise() - c).colwise().normalized();\n  for (auto j = 0; j < N - 1; ++j)\n  {\n    proj.col(j) = ((p0(2) - l0(2, j)) / l(2, j)) * l.col(j) + l0.col(j);\n  }\n\n  // Insert the projected points in a CGAL vertex_with_info vector\n  std::vector<std::pair<Point, unsigned>> verts;\n  for (auto j = 0; j < N - 1; ++j)\n  {\n    verts.push_back(std::make_pair(Point(proj(0, j), proj(1, j)), j + 1));\n  }\n\n  // Triangulate\n  Delaunay dt;\n  dt.insert(verts.begin(), verts.end());\n\n  // Write the finite faces of the triangulation to a VTK file\n  auto triangles = vtkSmartPointer<vtkCellArray>::New();\n  for (auto ffi = dt.finite_faces_begin(); ffi != dt.finite_faces_end();\n       ++ffi)\n  {\n    triangles->InsertNextCell(3);\n    for (auto j = 2; j >= 0; --j)\n      triangles->InsertCellPoint(ffi->vertex(j)->info());\n  }\n\n  // Iterate over infinite faces\n  Face_circulator fc = dt.incident_faces(dt.infinite_vertex()), done(fc);\n  if (fc != 0)\n  {\n    do\n    {\n      triangles->InsertNextCell(3);\n      for (auto j = 2; j >= 0; --j)\n      {\n        auto vh = fc->vertex(j);\n        auto id = dt.is_infinite(vh) ? 0 : vh->info();\n        triangles->InsertCellPoint(id);\n      }\n    } while (++fc != done);\n  }\n\n  // Write to vtk file\n  auto ptsArr = vtkSmartPointer<vtkDoubleArray>::New();\n  ptsArr->SetVoidArray((void *)positions.data(), 3 * N, 1);\n  ptsArr->SetNumberOfComponents(3);\n  auto pts = vtkSmartPointer<vtkPoints>::New();\n  pts->SetData(ptsArr);\n  auto poly = vtkSmartPointer<vtkPolyData>::New();\n  poly->SetPoints(pts);\n  poly->SetPolys(triangles);\n  auto normArr = vtkSmartPointer<vtkDoubleArray>::New();\n  normArr->SetVoidArray((void *)normals.data(), 3 * N, 1);\n  normArr->SetNumberOfComponents(3);\n  poly->GetPointData()->SetNormals(normArr);\n  auto wr = vtkSmartPointer<vtkPolyDataWriter>::New();\n  wr->SetFileName(argv[4]);\n  wr->SetInputData(poly);\n  wr->Write();\n\n  inputfile.close();\n  return 0;\n}\n", "meta": {"hexsha": "736c20f340b167c97de135f2e1b07583ff17ea7d", "size": 6451, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/PostProcess/PlotRow.cxx", "max_stars_repo_name": "amit112amit/oriented-particles", "max_stars_repo_head_hexsha": "1bb0f01a49d9bf33b88c4748025af756faf26688", "max_stars_repo_licenses": ["MIT", "BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-21T08:01:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-21T08:01:15.000Z", "max_issues_repo_path": "src/PostProcess/PlotRow.cxx", "max_issues_repo_name": "amit112amit/oriented-particles", "max_issues_repo_head_hexsha": "1bb0f01a49d9bf33b88c4748025af756faf26688", "max_issues_repo_licenses": ["MIT", "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/PostProcess/PlotRow.cxx", "max_forks_repo_name": "amit112amit/oriented-particles", "max_forks_repo_head_hexsha": "1bb0f01a49d9bf33b88c4748025af756faf26688", "max_forks_repo_licenses": ["MIT", "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": 30.429245283, "max_line_length": 80, "alphanum_fraction": 0.6282746861, "num_tokens": 1913, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947101574298, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.7161116722416107}}
{"text": "#ifndef _FFTTOOLS_HPP_\n#define _FFTTOOLS_HPP_\n\n#include <iostream>\n#include <iomanip>\n#include <complex>\n#include <cmath>\n#include <Eigen/Dense>\n#include <eigen3/Eigen/Dense>\n#include <unsupported/Eigen/FFT>\n\nnamespace fft_tools {\n\nEigen::MatrixXcf fft(const Eigen::MatrixXcf& timeMat);\n\nEigen::MatrixXcf fft(const Eigen::MatrixXf& timeMat);\n\nEigen::MatrixXcf ifft(const Eigen::MatrixXcf& freqMat);\n\nEigen::MatrixXcf fftshift(Eigen::MatrixXcf x, bool inverse_flag = false);\n\nEigen::MatrixXcf circshift(Eigen::MatrixXcf data, int shift_r, int shift_c);\n\n/**\n * @brief \n * \n * @tparam Scalar \n * @tparam SizeX \n * @tparam  \n * @tparam KSizeX \n * @tparam KSizeY \n * @param I \n * @param kernel \n * @param border_type 0: zero 1: border\n * @param conv_mode 0: full 1: valid\n * @return Eigen::Matrix< Scalar, SizeX, SizeY > \n */\nEigen::MatrixXcf  Convolution2(\n    const Eigen::MatrixXcf &I,\n    const Eigen::MatrixXcf &kernel,\n    int border_type,\n    int conv_mode);\n\nEigen::MatrixXcf  Convolution2(\n    const Eigen::MatrixXcf &I,\n    const Eigen::MatrixXcf &kernel,\n    int conv_mode = 0);\n\nstd::complex<float> getMatValue(\n    const Eigen::MatrixXcf& mat,\n    int r, int c, const int& border_type);\n}\n\n#endif", "meta": {"hexsha": "5aa323f2c2092daf23cdaf43c006fd82c91c14ad", "size": 1205, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mathtools/inc/ffttools.hpp", "max_stars_repo_name": "lygbuaa/eco_tracker", "max_stars_repo_head_hexsha": "d77afb97d356769bfe5f7d9cb5e96b3cf40c4601", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2019-04-20T05:38:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-08T06:30:41.000Z", "max_issues_repo_path": "mathtools/inc/ffttools.hpp", "max_issues_repo_name": "lygbuaa/eco_tracker", "max_issues_repo_head_hexsha": "d77afb97d356769bfe5f7d9cb5e96b3cf40c4601", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-06-06T11:12:06.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-10T11:27:12.000Z", "max_forks_repo_path": "mathtools/inc/ffttools.hpp", "max_forks_repo_name": "lygbuaa/eco_tracker", "max_forks_repo_head_hexsha": "d77afb97d356769bfe5f7d9cb5e96b3cf40c4601", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-07-12T03:47:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-08T06:44:17.000Z", "avg_line_length": 22.3148148148, "max_line_length": 76, "alphanum_fraction": 0.7045643154, "num_tokens": 352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009642742805, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.7160586566953413}}
{"text": "#ifndef _polyvec_curve_bezier_h_\n#define _polyvec_curve_bezier_h_\n\n// Eigen\n#include <Eigen/Core>\n\n#include \"curve.hpp\"\n\nnamespace polyvec {\n\n//The intrinsic parameters of a Bezier are the control points in the order \n//  c1x, c1y, c2x, c2y, c3x, c3y, c4x, c4y\nclass BezierCurve : public GlobFitCurve{\npublic:\n    BezierCurve() = default;\n\n\tGlobFitCurveType get_type() const { return GLOBFIT_CURVE_BEZIER; }\n\tint n_params() const { return 8; }\n\n    Eigen::Vector2d pos ( const double t ) const override;\n    Eigen::Vector2d dposdt ( const double t ) const override;\n    Eigen::Vector2d dposdtdt ( const double t ) const override;\n\tEigen::Vector2d dposdtdtdt ( const double t ) const override;\n\n    Eigen::Matrix2Xd dposdparams ( const double t ) const override;\n    Eigen::Matrix2Xd dposdtdparams ( const double t ) const override;\n    Eigen::Matrix2Xd dposdtdtdparams ( const double t ) const override;\n\tEigen::Matrix2Xd dposdtdtdtdparams ( const double t ) const override;\n\n    double project ( const Eigen::Vector2d& point ) const override;\n\n    Eigen::VectorXd dtprojectdparams ( const double t, const Eigen::Vector2d& point ) const override;\n    Eigen::Matrix2Xd dposprojectdparams ( const double t, const Eigen::VectorXd& dtprojectdparams ) const override;\n    Eigen::Matrix2Xd dposdtprojectdparams ( const double t, const Eigen::VectorXd& dtprojectdparams ) const override;\n\n    void set_control_points ( const Eigen::Matrix2Xd& control_points_d0_in );\n    const Eigen::Matrix2Xd& get_control_points() const;\n    constexpr static int n_control_points() {\n        return 4;\n    }\n\n\tvoid set_params(const Eigen::VectorXd& params) override;\n\tEigen::VectorXd get_params() const override;\n\n    Eigen::Matrix2Xd get_tesselation2() const override;\n    Eigen::VectorXd  get_tesselationt() const override;\n\n    double length() const;\n    Eigen::VectorXd dlengthdparams();\n\n\tGlobFitCurve* clone() const { return new BezierCurve(*this); }\n\n\tgeom::aabb get_bounding_box() const;\n\n\tBezierCurve(const Eigen::Matrix2Xd& C);\n\n\tstd::pair<GlobFitCurve*, GlobFitCurve*> split(double t) const;\n\nprivate:\n    constexpr static unsigned _n_tesselation = 50;    \n\n    Eigen::Matrix2Xd _control_points_d0;\n    Eigen::Matrix2Xd _control_points_d1;\n    Eigen::Matrix2Xd _control_points_d2;\n\tEigen::Matrix2Xd _control_points_d3;\n    Eigen::Matrix3Xd _tesselation;\n};\n\n}\n\n#endif // _polyvec_curve_bezier_h_", "meta": {"hexsha": "b765bca4d1c93add30a9c5c13094174d65e8368c", "size": 2384, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/polyvec/curve-tracer/curve_bezier.hpp", "max_stars_repo_name": "ShnitzelKiller/polyfit", "max_stars_repo_head_hexsha": "51ddc6365a794db1678459140658211cb78f65b1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2020-08-17T17:25:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T05:49:12.000Z", "max_issues_repo_path": "include/polyvec/curve-tracer/curve_bezier.hpp", "max_issues_repo_name": "ShnitzelKiller/polyfit", "max_issues_repo_head_hexsha": "51ddc6365a794db1678459140658211cb78f65b1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-08-26T13:54:59.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-21T07:19:22.000Z", "max_forks_repo_path": "include/polyvec/curve-tracer/curve_bezier.hpp", "max_forks_repo_name": "ShnitzelKiller/polyfit", "max_forks_repo_head_hexsha": "51ddc6365a794db1678459140658211cb78f65b1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-08-26T23:26:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-04T09:06:07.000Z", "avg_line_length": 33.5774647887, "max_line_length": 117, "alphanum_fraction": 0.7428691275, "num_tokens": 648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336303, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.7160586530632784}}
{"text": "#include <iostream>\nusing namespace std;\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\nint main( int argc, char** argv )\n{\n    Eigen::Matrix<float, 2, 3> matrix_23;\n    Eigen::Vector3d v_3d;\n    Eigen::Matrix<float,3,1> vd_3d;\n    Eigen::Matrix3d matrix_33 = Eigen::Matrix3d::Ones();\n    Eigen::MatrixXd matrix_x;\n\n    matrix_23 << 1, 2, 3, 4, 5, 6;\n    cout << matrix_23 << endl;\n\n    v_3d << 3, 2, 1;\n    vd_3d << 4,5,6;\n\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    matrix_33 = Eigen::Matrix3d::Random();      \n    cout << matrix_33 << endl << endl;\n    cout << matrix_33.transpose() << endl; \n    cout << matrix_33.sum() << endl; \n    cout << matrix_33.trace() << endl; \n    cout << 10*matrix_33 << endl; \n    cout << matrix_33.inverse() << endl;\n    cout << matrix_33.determinant() << endl; \n\n    cout <<\"hello world\"  << endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "b34f2af32c5406fface2fb1782b86ccf998a2947", "size": 1003, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "eigenMatrix.cpp", "max_stars_repo_name": "kai-wang99/slambook", "max_stars_repo_head_hexsha": "c5fe717efe4d5490c85f12f3553f59d7bb148fb2", "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": "eigenMatrix.cpp", "max_issues_repo_name": "kai-wang99/slambook", "max_issues_repo_head_hexsha": "c5fe717efe4d5490c85f12f3553f59d7bb148fb2", "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": "eigenMatrix.cpp", "max_forks_repo_name": "kai-wang99/slambook", "max_forks_repo_head_hexsha": "c5fe717efe4d5490c85f12f3553f59d7bb148fb2", "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.075, "max_line_length": 73, "alphanum_fraction": 0.5882352941, "num_tokens": 338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853655, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.7160126990989762}}
{"text": "#include \"math_unit_test.hpp\"\n\n#include <boost/config.hpp>\n#include <boost/multiprecision/number.hpp>\n#include <boost/math/fft/multiprecision_complex.hpp>\n#ifdef BOOST_MATH_USE_FLOAT128\n#include <boost/multiprecision/complex128.hpp>\n#endif\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#include <boost/multiprecision/cpp_complex.hpp>\n\n#include <boost/math/fft/bsl_backend.hpp>\n#if defined(__GNUC__)\n#include <boost/math/fft/fftw_backend.hpp>\n#include <boost/math/fft/gsl_backend.hpp>\n#include <boost/multiprecision/mpfr.hpp>\n#include <boost/multiprecision/mpc.hpp>\n#endif\n#include <vector>\n#include <iterator>\n#include <iostream>\n#include <boost/core/demangle.hpp>\n#include <boost/random.hpp>\n\nusing namespace boost::math::fft;\n\ntemplate<class T>\nvoid print(const std::vector<T>& V)\n{\n  std::cout << \"Size: \" << V.size() << '\\n';\n  std::cout << \"[\";\n  for(auto x: V)\n    std::cout << x << \", \";\n  std::cout<< \"]\\n\";\n}\n\ntemplate<class Backend, class Complex = std::complex<typename Backend::value_type>>\nvoid test_r2c(int n,int tolerance=1)\n{\n  using Real    = typename Backend::value_type;\n  // using Complex = boost::multiprecision::complex<Real>;\n  const Real tol = tolerance*std::numeric_limits<Real>::epsilon();\n  \n  boost::random::mt19937 rng;\n  boost::random::uniform_real_distribution<double> U(0.0,1.0);\n  \n  std::vector<Real> A(n);\n  std::vector<Complex> B(A.size());\n  \n  for(unsigned int i=0;i<A.size();++i)\n  {\n    A[i] = U(rng);\n    B[i] = Complex{A[i],0.0};\n  }\n  \n  std::vector<Real> HC,iHC;\n  Backend rplan(A.size());\n  rplan.real_to_halfcomplex(A.begin(),A.end(),std::back_inserter(HC));\n  rplan.halfcomplex_to_real(HC.begin(),HC.end(),std::back_inserter(iHC));\n  //print(A);\n  //print(HC);\n  //print(iHC);\n  \n  std::vector<Complex> TB;\n  bsl_dft<Complex> cplan(B.size());\n  cplan.forward(B.begin(),B.end(),std::back_inserter(TB));\n  \n  using std::abs;\n  \n  // check if the inverse recovers the original array\n  {\n    Real diff{0.0};\n    const Real inv_n = Real{1.0}/n;\n    for(unsigned int i=0;i<A.size();++i)\n    {\n      diff += abs(A[i]-iHC[i]*inv_n);\n    }\n    diff /= A.size();\n    CHECK_MOLLIFIED_CLOSE(Real{0.0},diff,tol);\n  }\n  // check if the halfcomplex contains the non-redundant complex components\n  {\n    Real diff{0.0};\n    \n    diff += abs(TB[0]-HC[0]);\n    for(int i=1,j=n-1;i<=j;++i,--j)\n    {\n      diff += abs(TB[i].real()-HC[i]);\n      \n      if(i<j)\n      diff += abs(TB[j].imag()-HC[j]);\n    }\n    diff /= n;\n    CHECK_MOLLIFIED_CLOSE(Real{0.0},diff,tol);\n  }\n}\n\nint main()\n{\n  // corner cases\n#if defined(__GNUC__)\n  test_r2c<fftw_rdft<double>>(1);\n  test_r2c<gsl_rdft<double>>(1);\n#endif\n  test_r2c<bsl_rdft<double>>(1);\n  \n#ifdef BOOST_MATH_USE_FLOAT128\n  test_r2c< bsl_rdft<boost::multiprecision::float128>,\n            boost::multiprecision::complex128 >(1);\n#endif\n    test_r2c< bsl_rdft<boost::multiprecision::cpp_bin_float_100>,\n              boost::multiprecision::cpp_complex_100 >(1);\n    test_r2c< bsl_rdft<boost::multiprecision::cpp_bin_float_quad>,\n              boost::multiprecision::cpp_complex_quad >(1);\n  \n  // primes \n  for(auto n: std::vector<int>{2,3,5,7,11,13,17,19})\n  {\n#if defined(__GNUC__)\n    test_r2c<fftw_rdft<double>>(n,4);\n    test_r2c<gsl_rdft<double>>(n,16);\n#endif\n    test_r2c<bsl_rdft<double>>(n,4);\n    \n#ifdef BOOST_MATH_USE_FLOAT128\n    test_r2c< bsl_rdft<boost::multiprecision::float128>,\n              boost::multiprecision::complex128 >(n,4);\n#endif\n    test_r2c< bsl_rdft<boost::multiprecision::cpp_bin_float_100>,\n              boost::multiprecision::cpp_complex_100 >(n,4);\n    test_r2c< bsl_rdft<boost::multiprecision::cpp_bin_float_quad>,\n              boost::multiprecision::cpp_complex_quad >(n,4);\n  }\n  \n  // powers of two\n  for(auto n: std::vector<int>{2,4,8,16,32,64,128})\n  {\n#if defined(__GNUC__)\n    test_r2c<fftw_rdft<double>>(n,4);\n    test_r2c<gsl_rdft<double>>(n,4);\n#endif\n    test_r2c<bsl_rdft<double>>(n,4);\n    \n#ifdef BOOST_MATH_USE_FLOAT128\n    test_r2c< bsl_rdft<boost::multiprecision::float128>,\n              boost::multiprecision::complex128 >(n,4);\n#endif\n    test_r2c< bsl_rdft<boost::multiprecision::cpp_bin_float_100>,\n              boost::multiprecision::cpp_complex_100 >(n,4);\n    test_r2c< bsl_rdft<boost::multiprecision::cpp_bin_float_quad>,\n              boost::multiprecision::cpp_complex_quad >(n,4);\n  }\n  // composite\n  for(auto n: std::vector<int>{6,9,10,12,14,15,18,20,21,22,24,25,26,27,28,30})\n  {\n#if defined(__GNUC__)\n    test_r2c<fftw_rdft<double>>(n,8);\n    test_r2c<gsl_rdft<double>>(n,16);\n#endif\n    test_r2c<bsl_rdft<double>>(n,4);\n    \n#ifdef BOOST_MATH_USE_FLOAT128\n    test_r2c< bsl_rdft<boost::multiprecision::float128>,\n              boost::multiprecision::complex128 >(n,4);\n#endif\n    test_r2c< bsl_rdft<boost::multiprecision::cpp_bin_float_100>,\n              boost::multiprecision::cpp_complex_100 >(n,4);\n    test_r2c< bsl_rdft<boost::multiprecision::cpp_bin_float_quad>,\n              boost::multiprecision::cpp_complex_quad >(n,4);\n  }  \n\n  // TODO: fix this\n  // test_r2c< bsl_rdft<boost::multiprecision::mpfr_float_100>,\n  //           boost::multiprecision::mpc_complex_100 >(n,4;\n  return boost::math::test::report_errors();\n}\n\n", "meta": {"hexsha": "8887b44fb3d71ceba148706c64ee9914a6b3a556", "size": 5184, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/fft_real_to_complex.cpp", "max_stars_repo_name": "BoostGSoC21/math", "max_stars_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_stars_repo_licenses": ["BSL-1.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": "test/fft_real_to_complex.cpp", "max_issues_repo_name": "BoostGSoC21/math", "max_issues_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 30.0, "max_issues_repo_issues_event_min_datetime": "2021-06-22T12:59:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-02T09:27:49.000Z", "max_forks_repo_path": "test/fft_real_to_complex.cpp", "max_forks_repo_name": "BoostGSoC21/math", "max_forks_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-07T21:15:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-07T21:15:02.000Z", "avg_line_length": 29.1235955056, "max_line_length": 83, "alphanum_fraction": 0.6612654321, "num_tokens": 1576, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970654616712, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.7159711521539971}}
{"text": "#include <iostream>\n#include <armadillo>\n#include <tuple>\n#include <cstdlib>     /* srand, rand */\n#include <ctime>       /* time */\n#include \"logistic_function.hpp\"\n#include \"neural.hpp\"\nusing matrix=arma::Mat<double>;\nsize_t const max_epochs = 1000; \nconst double lambda = 0.8;\nconst double tolerance = 0.000001;\n/**\nEvaluate Output\n Given\n  Input  data X(input_dim,1)\n  hidden-layer (input_dim,hidden_layer_size)\n  Output (hidden_layer_size,out_put_size)\n Compute \n  Output of FFNN\n   \n*/\nmatrix Evaluate(matrix const& X, matrix const& hiddenLayer, matrix const& outputLayer)\n\t{\n\tmatrix inp = X; //21*m\n\tmatrix hidden = inp.t()*hiddenLayer; // m*21*21*4 -> m*4\n\tmatrix output = LogisticFunction::fn(hidden)*outputLayer; // m*4 * 4 *3 -> m*3\n\treturn LogisticFunction::fn(output).t();//3*m\n\t}\n\nmatrix EvaluateWithBias(matrix const& inp, matrix const& hiddenLayer, matrix const& outputLayer)\n\t{\n\t\n\tmatrix hidden = hiddenLayer.t()*inp; //  4*m\n\thidden = LogisticFunction::fn(hidden);//4*m\n\tmatrix hiddenInput = arma::join_cols(arma::ones(1, inp.n_cols), hidden);//5*m\n\tmatrix output = outputLayer.t()*hiddenInput; // (5.3)'*5.m -> 3.m\n\treturn LogisticFunction::fn(output);\n\t}\n/**\nCalculate cost using cross entropy\n*/\ndouble CalcCost(matrix const& target, matrix const& output)\n\t{\n\n\tdouble sum = 0.0;\n\tsize_t item_count = target.n_elem;\n\tfor (size_t i = 0; i < item_count; ++i)\n\t\t{\n\t\tdouble y = target[i];\n\t\tdouble val = output[i];\n\t\tsum = sum - y*log(val) - (1 - y)*log(1 - val);\n\t\t}\n\treturn sum / target.n_cols;\n\t}\n\n\n/**Back Propogation\n Ignore lambda \n Problem statement:\n Given \n  X the feature mector of m column vectors of size feature_size\n  Y the result vector of m column vectors of label_size\n  hidden_layer_size \n  Theta1: weight vector of hidden_layer_size columns each of size (feature_size )\n  Theta2: weight vector of label_size columns each of size (hidden_layer_size)\nCompute\n  cost using cross entropy\n  Theta1_gardient: weight vector of hidden_layer_size columns each of size (feature_size )\n  Theta2_gradient: weight vector of size label_size columns each of size (hidden_layer_size )\n  ...using sigmoid\n\nUpdates:\n\tAdding bias\n\n*/\nstd::tuple<double,matrix,matrix> \nBackProp(\n\t matrix & a1, matrix & y, matrix const& Theta1, matrix const& Theta2\n\t)\n\t{\n\n\t// This generates [0 1 2 3 ... (ElementCount(trainingData) - 1)]. The\n\t// sequence will be used to iterate through the training data.\n\tsize_t m = a1.n_cols;\n\n\n\tmatrix theta1_gradient(Theta1);\n\ttheta1_gradient.zeros();\n\tmatrix theta2_gradient(Theta2);\n\ttheta2_gradient.zeros();\n\t\n\tmatrix output(Theta2.n_cols, 1);\n\n\tfor (size_t j = m; j > 0; --j)\n\t\t{\n\t\tint k = rand() % j;\n\t\ta1.swap_cols(j - 1, k);\n\t\ty.swap_cols(j - 1, k);\n\t\t}\n\toutput = EvaluateWithBias(a1, Theta1, Theta2);\n\tdouble cost = CalcCost(y, output);\n\t\n\tmatrix z2 = Theta1.t()*a1;\n\tmatrix a2 = arma::join_cols(arma::ones(1, m), LogisticFunction::fn(z2));\n\n\tmatrix z3 = Theta2.t()*a2;\n\tmatrix a3 = LogisticFunction::fn(z3);\n\tmatrix delta3 = a3 - y;\n\ttheta2_gradient += a2*delta3.t();\n\tmatrix delta2 = (Theta2*delta3) % arma::join_cols(arma::ones(1, m), LogisticFunction::deriv(a2.rows(1, a2.n_rows - 1)));\n\tdelta2 = delta2.rows(1, delta2.n_rows-1);\n\ttheta1_gradient += a1*delta2.t();\n\ttheta1_gradient = theta1_gradient / m + lambda*arma::join_cols(arma::zeros(1, Theta1.n_cols), Theta1.rows(1, Theta1.n_rows - 1));\n\ttheta2_gradient = theta2_gradient / m + lambda*arma::join_cols(arma::zeros(1, Theta2.n_cols), Theta2.rows(1, Theta2.n_rows - 1));\n\treturn std::make_tuple(cost, theta1_gradient, theta2_gradient);\n\t}\n\n/**\nTrain Network\n Ignore lambda and bias\n Given:\n  X the feature mector of m column vectors of size feature_size\n  Y the result vector of m column vectors of label_size\n  hidden_layer_size \n Compute:\n  Theta1: weight vector of hidden_layer_size columns each of size (feature_size + 1)\n  Theta2: weight vector of size label_size columns each of size (hidden_layer_size +1)\n Update:\n  Adding bias\t\n*/\n\nstd::tuple<matrix,matrix>\nTrainNetwork(\n\tmatrix const& X, matrix y,size_t hidden_layer_size\n\t)\n\t{\n\tmatrix theta1;\n\ttheta1.randu(X.n_rows+1, hidden_layer_size);\n\tmatrix theta2;\n\ttheta2.randu(hidden_layer_size+1, y.n_rows);\n\tdouble eta =0.5;\n\tsize_t m = X.n_cols;\n\tmatrix a1 = arma::join_cols(arma::ones(1, m), X); \n\tdouble prev_cost = 1000.0;\n\tfor(size_t epoch = 0; epoch < max_epochs; ++epoch)\n\t\t{\n\t\tmatrix delta1,delta2;\n\t\tdouble cost=0.0;\n\t\tstd::tie(cost,delta1,delta2) = BackProp(a1,y,theta1,theta2);\n\t\ttheta1 = theta1 - eta *  delta1;\n\t\ttheta2 = theta2 - eta *  delta2;\n\t\t//std::cout << epoch << \":\" << cost << std::endl;\n\t\tif (abs(prev_cost - cost) < tolerance)\n\t\t\tbreak;\n\t\tprev_cost = cost;\n\t\t}\n\treturn std::make_tuple(theta1,theta2); \n\t}\n\n/**\nPredict \n\tGiven \n\t Neural Network\n\t Input sample\n    Compute \n\t Class it belongs to\n*/\nmatrix Predict(matrix const& input, matrix const& hiddenLayer, matrix const& outputLayer)\n\t{\n\tmatrix output = EvaluateWithBias(input, hiddenLayer, outputLayer);\n\tmatrix result(output.n_rows, output.n_cols);\n\tfor (size_t i = 0; i < output.n_cols; ++i)\n\t\t{\n\t\tmatrix cur = output.unsafe_col(i);\n\t\tdouble max = cur[0];\n\t\tsize_t index = 0;\n\t\tfor (size_t j = 1; j < cur.n_elem; ++j)\n\t\t\t{\n\t\t\tif (cur[j] > max)\n\t\t\t\t{\n\t\t\t\tmax = cur[j];\n\t\t\t\tindex = j;\n\t\t\t\t}\n\t\t\t}\n\t\tfor (size_t j = 0; j < output.n_rows; ++j)\n\t\t\t{\n\t\t\tresult(j, i) = index == j ? 1.0 : 0.0;\n\t\t\t}\n\t\t}\n\treturn result;\n\t}\ndouble ComputeError(matrix const& result, matrix const& labels)\n\t{\n\tdouble error = 0.0;\n\tfor (size_t j = 0; j < result.n_elem; ++j)\n\t\terror += abs(result[j] - labels[j]);\n\treturn error / 2.0;\n\t}\n", "meta": {"hexsha": "92a9a91f87cd10c54940c5693aa8cf7197a7f18c", "size": 5552, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SimpleNN/neural.cpp", "max_stars_repo_name": "theSundayProgrammer/FFNN", "max_stars_repo_head_hexsha": "7de99ceb39012870136ecd1906c29b4ee3ad2f2b", "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": "SimpleNN/neural.cpp", "max_issues_repo_name": "theSundayProgrammer/FFNN", "max_issues_repo_head_hexsha": "7de99ceb39012870136ecd1906c29b4ee3ad2f2b", "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": "SimpleNN/neural.cpp", "max_forks_repo_name": "theSundayProgrammer/FFNN", "max_forks_repo_head_hexsha": "7de99ceb39012870136ecd1906c29b4ee3ad2f2b", "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.8994974874, "max_line_length": 130, "alphanum_fraction": 0.6878602305, "num_tokens": 1668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418241572634, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.7158249064129463}}
{"text": "//  (C) Copyright Nick Thompson 2020.\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// Deliberately contains some unicode characters:\n// \n// boost-no-inspect\n//\n#include <iostream>\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/tools/simple_continued_fraction.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n\nusing boost::math::constants::root_two;\nusing boost::math::constants::phi;\nusing boost::math::constants::pi;\nusing boost::math::constants::e;\nusing boost::math::constants::zeta_three;\nusing boost::math::tools::simple_continued_fraction;\n\nint main()\n{\n    using Real = boost::multiprecision::cpp_bin_float_100;\n    auto phi_cfrac = simple_continued_fraction(phi<Real>());\n    std::cout << \"\u03c6 \u2248 \" << phi_cfrac << \"\\n\\n\";\n\n    auto pi_cfrac = simple_continued_fraction(pi<Real>());\n    std::cout << \"\u03c0 \u2248 \" << pi_cfrac << \"\\n\";\n    std::cout << \"Known: [3; 7, 15, 1, 292, 1, 1, 1, 2, 1, 3, 1, 14, 2, 1, 1, 2, 2, 2, 2, 1, 84, 2, 1, 1, 15, 3, 13, 1, 4, 2, 6, 6, 99, 1, 2, 2, 6, 3, 5, 1, 1, 6, 8, 1, 7, 1, 2, 3, 7, 1, 2, 1, 1, 12, 1, 1, 1, 3, 1, 1, 8, 1, 1, 2, 1, 6, 1, 1, 5, 2, 2, 3, 1, 2, 4, 4, 16, 1, 161, 45, 1, 22, 1, 2, 2, 1, 4, 1, 2, 24, 1, 2, 1, 3, 1, 2, 1, ...]\\n\\n\";\n\n    auto rt_cfrac = simple_continued_fraction(root_two<Real>());\n    std::cout << \"\u221a2 \u2248 \" << rt_cfrac << \"\\n\\n\";\n\n    auto e_cfrac = simple_continued_fraction(e<Real>());\n    std::cout << \"e \u2248 \" << e_cfrac << \"\\n\";\n\n    // Correctness can be checked in Mathematica via: ContinuedFraction[Zeta[3], 500]\n    auto z_cfrac = simple_continued_fraction(zeta_three<Real>());\n    std::cout << \"\u03b6(3) \u2248 \" << z_cfrac << \"\\n\";\n}\n", "meta": {"hexsha": "4eaa83050af7b79fc953abb859dfb4b382e229ff", "size": 1772, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/to_continued_fraction.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/to_continued_fraction.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/to_continued_fraction.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": 42.1904761905, "max_line_length": 345, "alphanum_fraction": 0.6258465011, "num_tokens": 692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237605, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.7155572514755708}}
{"text": "/*\n* compile with flags:   g++ test.cc softmax_classifier.cc   ../datasets/datasets.cc -std=c++14 -larmadillo -I ../../include/\n* author: Yuzhen Liu\n* Date: 2019.3.29 10:55\n*/\n\n#include <iostream>\n#include <armadillo>\n#include <cmath>\n#include <linear/linear_regressor.h>\n#include <datasets/datasets.h>\n\nusing namespace std;\nusing namespace arma;\n\nint main() {\n    Datasets dataset = Datasets(\"boston\");\n\n    // Linear_Regressor linear_regressor = Linear_Regressor(0.02);\n    Linear_Regressor linear_regressor = Linear_Regressor();\n    linear_regressor.train(dataset.x, dataset.y);\n\n    vec res = linear_regressor.predict(dataset.x);\n    printf(\"The sum loss is:\\n\");\n    vec dis = res - dataset.y;\n    // dis.print();\n    join_rows(res, dataset.y).print();\n    cout << \"The standard deviation is: \" << stddev(dis) << endl;\n    \n    return 0;\n}\n\n", "meta": {"hexsha": "536057b24b2eba57ce920a4004ac16214f1204db", "size": 846, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/linear_test.cc", "max_stars_repo_name": "codestorm04/Machine_Learning_CPP", "max_stars_repo_head_hexsha": "50bbe9c7b8c387cd9690b9c338639ae62fda1cf5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-06-05T09:31:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-13T13:37:44.000Z", "max_issues_repo_path": "examples/linear_test.cc", "max_issues_repo_name": "codestorm04/Machine_Learning_CPP", "max_issues_repo_head_hexsha": "50bbe9c7b8c387cd9690b9c338639ae62fda1cf5", "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": "examples/linear_test.cc", "max_forks_repo_name": "codestorm04/Machine_Learning_CPP", "max_forks_repo_head_hexsha": "50bbe9c7b8c387cd9690b9c338639ae62fda1cf5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2019-11-15T04:43:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-26T15:59:30.000Z", "avg_line_length": 25.6363636364, "max_line_length": 124, "alphanum_fraction": 0.6749408983, "num_tokens": 221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107931567176, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.7155452336903687}}
{"text": "#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n\n#include <CGAL/natural_neighbor_coordinates_2.h>\n#include <CGAL/Interpolation_gradient_fitting_traits_2.h>\n#include <CGAL/sibson_gradient_fitting.h>\n#include <CGAL/interpolation_functions.h>\n\n#include <CGAL/Triangulation_vertex_base_with_info_2.h>\n#include <CGAL/Regular_triangulation_2.h>\n\n#include <boost/iterator/function_output_iterator.hpp>\n\n#include <iostream>\n#include <iterator>\n#include <utility>\n#include <vector>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel    K;\ntypedef CGAL::Interpolation_gradient_fitting_traits_2<K>       Traits;\n\ntypedef K::FT                                                  Coord_type;\ntypedef K::Point_2                                             Bare_point;\ntypedef K::Weighted_point_2                                    Weighted_point;\ntypedef K::Vector_2                                            Vector;\n\ntemplate <typename V, typename G>\nstruct Value_and_gradient\n{\n  Value_and_gradient() : value(), gradient(CGAL::NULL_VECTOR) {}\n\n  V value;\n  G gradient;\n};\n\ntypedef CGAL::Triangulation_vertex_base_with_info_2<\n                Value_and_gradient<Coord_type, Vector>, K,\n                CGAL::Regular_triangulation_vertex_base_2<K> > Vb;\ntypedef CGAL::Regular_triangulation_face_base_2<K> Fb;\ntypedef CGAL::Triangulation_data_structure_2<Vb, Fb>           Tds;\ntypedef CGAL::Regular_triangulation_2<K, Tds>                  Regular_triangulation;\ntypedef Regular_triangulation::Vertex_handle                   Vertex_handle;\n\nint main()\n{\n  Regular_triangulation rt;\n\n  auto value_function = [](const Vertex_handle& a) -> std::pair<Coord_type, bool>\n  {\n    return std::make_pair(a->info().value, true);\n  };\n\n  auto gradient_function = [](const Vertex_handle& a) -> std::pair<Vector, bool>\n  {\n    return std::make_pair(a->info().gradient, a->info().gradient != CGAL::NULL_VECTOR);\n  };\n\n  auto gradient_output_iterator\n    = boost::make_function_output_iterator\n    ([](const std::pair<Vertex_handle, Vector>& p)\n     {\n       p.first->info().gradient = p.second;\n     });\n\n  // parameters for spherical function:\n  Coord_type a(0.25), bx(1.3), by(-0.7), c(0.2);\n  for (int y=0; y<4; y++) {\n    for (int x=0; x<4; x++) {\n      Weighted_point p(Bare_point(x,y), (x-y)/3. /*weight*/);\n      Vertex_handle vh = rt.insert(p);\n      Coord_type value = a + bx*x + by*y + c*(x*x+y*y);\n      vh->info().value = value;\n    }\n  }\n\n  CGAL::sibson_gradient_fitting_rn_2(rt,\n                                     gradient_output_iterator,\n                                     CGAL::Identity<std::pair<Vertex_handle, Vector> >(),\n                                     value_function,\n                                     Traits());\n\n  // coordinate computation\n  Weighted_point p(Bare_point(1.6, 1.4), -0.3 /*weight*/);\n  std::vector<std::pair<Vertex_handle, Coord_type> > coords;\n  typedef CGAL::Identity<std::pair<Vertex_handle, Coord_type> > Identity;\n  Coord_type norm = CGAL::regular_neighbor_coordinates_2(rt,\n                                                         p,\n                                                         std::back_inserter(coords),\n                                                         Identity()).second;\n\n  // Sibson interpolant: version without sqrt:\n  std::pair<Coord_type, bool> res = CGAL::sibson_c1_interpolation_square(coords.begin(),\n                                                                         coords.end(),\n                                                                         norm,\n                                                                         p,\n                                                                         value_function,\n                                                                         gradient_function,\n                                                                         Traits());\n\n  if(res.second)\n    std::cout << \"Tested interpolation on \" << p\n              << \" interpolation: \" << res.first << \" exact: \"\n              << a + bx * p.x()+ by * p.y()+ c*(p.x()*p.x()+p.y()*p.y())\n              << std::endl;\n  else\n    std::cout << \"C^1 Interpolation not successful.\" << std::endl\n              << \" not all gradients are provided.\"  << std::endl\n              << \" You may resort to linear interpolation.\" << std::endl;\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "edd2c6698e2329b8567378dcb09ec22c61122fac", "size": 4365, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Interpolation/examples/Interpolation/sibson_interpolation_rn_vertex_with_info_2.cpp", "max_stars_repo_name": "ffteja/cgal", "max_stars_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 3227.0, "max_stars_repo_stars_event_min_datetime": "2015-03-05T00:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:20:35.000Z", "max_issues_repo_path": "Interpolation/examples/Interpolation/sibson_interpolation_rn_vertex_with_info_2.cpp", "max_issues_repo_name": "ffteja/cgal", "max_issues_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 5574.0, "max_issues_repo_issues_event_min_datetime": "2015-03-05T00:01:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:08:11.000Z", "max_forks_repo_path": "Interpolation/examples/Interpolation/sibson_interpolation_rn_vertex_with_info_2.cpp", "max_forks_repo_name": "ffteja/cgal", "max_forks_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1274.0, "max_forks_repo_forks_event_min_datetime": "2015-03-05T00:01:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:47:56.000Z", "avg_line_length": 39.3243243243, "max_line_length": 91, "alphanum_fraction": 0.5388316151, "num_tokens": 938, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026618464796, "lm_q2_score": 0.7799928900257126, "lm_q1q2_score": 0.7154895542419145}}
{"text": "#include <Eigen/LU>\n#include <cmath>\n#include <mathtoolbox/rbf-interpolation.hpp>\n\nusing Eigen::Map;\nusing Eigen::MatrixXd;\nusing Eigen::PartialPivLU;\nusing Eigen::VectorXd;\nusing std::function;\nusing std::vector;\n\nmathtoolbox::RbfInterpolator::RbfInterpolator(const function<double(const double)>& rbf_kernel,\n                                              const bool                            use_polynomial_term)\n    : m_rbf_kernel(rbf_kernel), m_use_polynomial_term(use_polynomial_term)\n{\n}\n\nvoid mathtoolbox::RbfInterpolator::SetData(const MatrixXd& X, const VectorXd& y)\n{\n    assert(y.rows() == X.cols());\n\n    this->m_X = X;\n    this->m_y = y;\n}\n\nvoid mathtoolbox::RbfInterpolator::CalcWeights(const bool use_regularization, const double lambda)\n{\n    const int num_data = m_y.rows();\n\n    // Construct the symmetric matrix of RBF values\n    MatrixXd Phi{num_data, num_data};\n    for (int i = 0; i < num_data; ++i)\n    {\n        for (int j = i; j < num_data; ++j)\n        {\n            const double value = m_rbf_kernel((m_X.col(i) - m_X.col(j)).norm());\n\n            Phi(i, j) = value;\n            Phi(j, i) = value;\n        }\n    }\n\n    if (m_use_polynomial_term)\n    {\n        const int dim = m_X.rows();\n\n        MatrixXd P{num_data, dim + 1};\n\n        P.block(0, 0, num_data, 1)   = MatrixXd::Ones(num_data, 1);\n        P.block(0, 1, num_data, dim) = m_X.transpose();\n\n        MatrixXd A = MatrixXd::Zero(num_data + dim + 1, num_data + dim + 1);\n\n        A.block(0, 0, num_data, num_data)       = Phi;\n        A.block(0, num_data, num_data, dim + 1) = P;\n        A.block(num_data, 0, dim + 1, num_data) = P.transpose();\n\n        VectorXd b = VectorXd::Zero(num_data + dim + 1);\n\n        b.segment(0, num_data) = m_y;\n\n        VectorXd solution;\n        if (use_regularization)\n        {\n            const auto I = MatrixXd::Identity(num_data + dim + 1, num_data + dim + 1);\n\n            solution = PartialPivLU<MatrixXd>(A.transpose() * A + lambda * I).solve(A.transpose() * b);\n        }\n        else\n        {\n            solution = PartialPivLU<MatrixXd>(A).solve(b);\n        }\n\n        m_w = solution.segment(0, num_data);\n        m_v = solution.segment(num_data, dim + 1);\n    }\n    else\n    {\n        const auto     I = MatrixXd::Identity(num_data, num_data);\n        const MatrixXd A = use_regularization ? Phi.transpose() * Phi + lambda * I : Phi;\n        const VectorXd b = use_regularization ? Phi.transpose() * m_y : m_y;\n\n        m_w = PartialPivLU<MatrixXd>(A).solve(b);\n    }\n}\n\ndouble mathtoolbox::RbfInterpolator::CalcValue(const VectorXd& x) const\n{\n    assert(x.rows() == m_X.rows());\n\n    const int num_data = m_w.rows();\n    const int dim      = x.rows();\n\n    // Calculate the distance for each data point via broadcasting\n    const Eigen::VectorXd norms = (m_X.colwise() - x).colwise().norm();\n\n    // Calculate the RBF value associated with each data point\n    // TODO: This part can be further optimized for performance by vectorization\n    VectorXd rbf_values{num_data};\n    for (int i = 0; i < num_data; ++i)\n    {\n        rbf_values(i) = m_rbf_kernel(norms(i));\n    }\n\n    // Calculate the weighted sum using dot product\n    const double rbf_term = m_w.dot(rbf_values);\n\n    if (m_use_polynomial_term)\n    {\n        const double polynomial_term = m_v(0) + x.transpose() * m_v.segment(1, dim);\n\n        return rbf_term + polynomial_term;\n    }\n    else\n    {\n        return rbf_term;\n    }\n}\n", "meta": {"hexsha": "f424bfdb42ce7a183e128b0f539fef18dbd0804b", "size": 3431, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/rbf-interpolation.cpp", "max_stars_repo_name": "yuki-koyama/mathtoolbox", "max_stars_repo_head_hexsha": "eb7449c3c489f465849a74405e72aff016a296f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 195.0, "max_stars_repo_stars_event_min_datetime": "2018-04-28T16:12:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:52:56.000Z", "max_issues_repo_path": "src/rbf-interpolation.cpp", "max_issues_repo_name": "yuki-koyama/mathtoolbox", "max_issues_repo_head_hexsha": "eb7449c3c489f465849a74405e72aff016a296f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 52.0, "max_issues_repo_issues_event_min_datetime": "2018-04-15T01:24:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-02T09:14:23.000Z", "max_forks_repo_path": "src/rbf-interpolation.cpp", "max_forks_repo_name": "yuki-koyama/mathtoolbox", "max_forks_repo_head_hexsha": "eb7449c3c489f465849a74405e72aff016a296f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 21.0, "max_forks_repo_forks_event_min_datetime": "2018-06-05T04:11:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T13:28:12.000Z", "avg_line_length": 28.8319327731, "max_line_length": 104, "alphanum_fraction": 0.5966190615, "num_tokens": 934, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026573249612, "lm_q2_score": 0.7799928900257126, "lm_q1q2_score": 0.7154895507151624}}
{"text": "// C/C++ includes\n#include <cfloat>\n#include <vector>\n#include <iostream>\n\n//Eigen includes\n#include <Eigen/Core>\n\ndouble _bin_size = 1;\n\n/**\n * @brief returns all the voxels that are traversed by a ray going from start to end\n * @param start : continous world position where the ray starts\n * @param end   : continous world position where the ray end\n * @return vector of voxel ids hit by the ray in temporal order\n *\n * J. Amanatides, A. Woo. A Fast Voxel Traversal Algorithm for Ray Tracing. Eurographics '87\n */\n\nstd::vector<Eigen::Vector3i> voxel_traversal(Eigen::Vector3d ray_start, Eigen::Vector3d ray_end) {\n  std::vector<Eigen::Vector3i> visited_voxels;\n\n  // This id of the first/current voxel hit by the ray.\n  // Using floor (round down) is actually very important,\n  // the implicit int-casting will round up for negative numbers.\n  Eigen::Vector3i current_voxel(std::floor(ray_start[0]/_bin_size),\n                                std::floor(ray_start[1]/_bin_size),\n                                std::floor(ray_start[2]/_bin_size));\n\n  // The id of the last voxel hit by the ray.\n  // TODO: what happens if the end point is on a border?\n  Eigen::Vector3i last_voxel(std::floor(ray_end[0]/_bin_size),\n                             std::floor(ray_end[1]/_bin_size),\n                             std::floor(ray_end[2]/_bin_size));\n\n  // Compute normalized ray direction.\n  Eigen::Vector3d ray = ray_end-ray_start;\n  //ray.normalize();\n\n  // In which direction the voxel ids are incremented.\n  double stepX = (ray[0] >= 0) ? 1:-1; // correct\n  double stepY = (ray[1] >= 0) ? 1:-1; // correct\n  double stepZ = (ray[2] >= 0) ? 1:-1; // correct\n\n  // Distance along the ray to the next voxel border from the current position (tMaxX, tMaxY, tMaxZ).\n  double next_voxel_boundary_x = (current_voxel[0]+stepX)*_bin_size; // correct\n  double next_voxel_boundary_y = (current_voxel[1]+stepY)*_bin_size; // correct\n  double next_voxel_boundary_z = (current_voxel[2]+stepZ)*_bin_size; // correct\n\n  // tMaxX, tMaxY, tMaxZ -- distance until next intersection with voxel-border\n  // the value of t at which the ray crosses the first vertical voxel boundary\n  double tMaxX = (ray[0]!=0) ? (next_voxel_boundary_x - ray_start[0])/ray[0] : DBL_MAX; //\n  double tMaxY = (ray[1]!=0) ? (next_voxel_boundary_y - ray_start[1])/ray[1] : DBL_MAX; //\n  double tMaxZ = (ray[2]!=0) ? (next_voxel_boundary_z - ray_start[2])/ray[2] : DBL_MAX; //\n\n  // tDeltaX, tDeltaY, tDeltaZ --\n  // how far along the ray we must move for the horizontal component to equal the width of a voxel\n  // the direction in which we traverse the grid\n  // can only be FLT_MAX if we never go in that direction\n  double tDeltaX = (ray[0]!=0) ? _bin_size/ray[0]*stepX : DBL_MAX;\n  double tDeltaY = (ray[1]!=0) ? _bin_size/ray[1]*stepY : DBL_MAX;\n  double tDeltaZ = (ray[2]!=0) ? _bin_size/ray[2]*stepZ : DBL_MAX;\n\n  Eigen::Vector3i diff(0,0,0);\n  bool neg_ray=false;\n  if (current_voxel[0]!=last_voxel[0] && ray[0]<0) { diff[0]--; neg_ray=true; }\n  if (current_voxel[1]!=last_voxel[1] && ray[1]<0) { diff[1]--; neg_ray=true; }\n  if (current_voxel[2]!=last_voxel[2] && ray[2]<0) { diff[2]--; neg_ray=true; }\n  visited_voxels.push_back(current_voxel);\n  if (neg_ray) {\n    current_voxel+=diff;\n    visited_voxels.push_back(current_voxel);\n  }\n\n  while(last_voxel != current_voxel) {\n    if (tMaxX < tMaxY) {\n      if (tMaxX < tMaxZ) {\n        current_voxel[0] += stepX;\n        tMaxX += tDeltaX;\n      } else {\n        current_voxel[2] += stepZ;\n        tMaxZ += tDeltaZ;\n      }\n    } else {\n      if (tMaxY < tMaxZ) {\n        current_voxel[1] += stepY;\n        tMaxY += tDeltaY;\n      } else {\n        current_voxel[2] += stepZ;\n        tMaxZ += tDeltaZ;\n      }\n    }\n    visited_voxels.push_back(current_voxel);\n  }\n  return visited_voxels;\n}\n\nint main (int, char**) {\n  Eigen::Vector3d ray_start(0,0,0);\n  Eigen::Vector3d ray_end(3,2,2);\n  std::cout << \"Voxel size: \" << _bin_size << std::endl;\n  std::cout << \"Starting position: \" << ray_start.transpose() << std::endl;\n  std::cout << \"Ending position: \" << ray_end.transpose() << std::endl;\n  std::cout << \"Voxel ID's from start to end:\" << std::endl;\n  std::vector<Eigen::Vector3i> ids = voxel_traversal(ray_start,ray_end);\n\n  for (auto& i : ids) {\n    std::cout << \"> \" << i.transpose() << std::endl;\n  }\n  std::cout << \"Total number of traversed voxels: \" << ids.size() << std::endl;\n  return 0;\n}\n", "meta": {"hexsha": "8207744d344e891c7bd4dc784b08fa018ec823e5", "size": 4413, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "francisengelmann/fast_voxel_traversal", "max_stars_repo_head_hexsha": "9664f0bde1943e69dbd1942f95efc31901fbbd42", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 79.0, "max_stars_repo_stars_event_min_datetime": "2016-02-24T05:07:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T08:46:50.000Z", "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "swr06/fast_voxel_traversal", "max_issues_repo_head_hexsha": "9664f0bde1943e69dbd1942f95efc31901fbbd42", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2016-12-22T06:39:07.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-27T06:14:32.000Z", "max_forks_repo_path": "main.cpp", "max_forks_repo_name": "swr06/fast_voxel_traversal", "max_forks_repo_head_hexsha": "9664f0bde1943e69dbd1942f95efc31901fbbd42", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2017-04-02T13:13:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T10:10:33.000Z", "avg_line_length": 39.0530973451, "max_line_length": 101, "alphanum_fraction": 0.6440063449, "num_tokens": 1362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636754, "lm_q2_score": 0.7956581049086031, "lm_q1q2_score": 0.7153932068198754}}
{"text": "/**\n * @ file\n * @ brief NPDE homework TEMPLATE MAIN FILE\n * @ author\n * @ date\n * @ copyright Developed at SAM, ETH Zurich\n */\n\n#define _USE_MATH_DEFINES\n\n#include <Eigen/Core>\n#include <cmath>\n#include <fstream>\n#include <iostream>\n\n#include \"fluxlimitedfv.h\"\n\ntypedef std::numeric_limits<double> dbl;\n\nusing namespace FluxLimitedFV;\n\nint main(int /*argc*/, char** /*argv*/) {\n  std::cout.precision(dbl::max_digits10);\n\n  /* ADVECTION PROBLEM */\n  // Data\n  double T = 1.0;\n  unsigned int nb_timesteps[8] = {10, 20, 40, 80, 160, 320, 640, 1280};\n\n  // Parameter coefficient\n  double beta = 1.0;\n\n  // Flux limiter function\n  auto phi = [](double theta) {\n    return (abs(theta) + theta) / (1.0 + abs(theta));\n  };\n\n  // Initial conditions A and B as lambda functions\n  auto mu0_A_fn = [](double x) -> double {\n    if (x < 1) {\n      return 0.0;\n    } else if (x < 2) {\n      return pow(sin(0.5 * M_PI * (x - 1)), 2);\n    } else {\n      return 1.0;\n    }\n  };\n  auto mu0_B_fn = [](double x) -> double {\n    if ((1 < x) && (x < 2)) {\n      return 1.0;\n    } else {\n      return 0.0;\n    }\n  };\n\n  Eigen::VectorXd error_L1_mu0_A = Eigen::VectorXd::Zero(8);\n  Eigen::VectorXd error_L1_mu0_B = Eigen::VectorXd::Zero(8);\n  double tau, h;\n  int N;\n  Eigen::VectorXd fluxlimAdvection_sol_A, fluxlimAdvection_sol_B;\n\n  for (int k = 0; k < 8; k++) {\n    tau = T / nb_timesteps[k];\n    h = 1.2 * tau;\n    N = std::round(5.0 / h);\n\n    // Discrete initial conditions\n    Eigen::VectorXd mu0_A(N);\n    for (int j = 0; j < N; j++) {\n      mu0_A(j) = mu0_A_fn(h * j);\n    }\n    Eigen::VectorXd mu0_B(N);\n    for (int j = 0; j < N; j++) {\n      mu0_B(j) = mu0_B_fn(h * j);\n    }\n\n    fluxlimAdvection_sol_A =\n        fluxlimAdvection(beta, mu0_A, h, tau, nb_timesteps[k], phi);\n    fluxlimAdvection_sol_B =\n        fluxlimAdvection(beta, mu0_B, h, tau, nb_timesteps[k], phi);\n\n    // Computing the L1 errors\n    double sum_A = 0.0;\n    double sum_B = 0.0;\n    for (int j = 0; j < N; j++) {\n      sum_A = sum_A +\n              std::abs(h * (fluxlimAdvection_sol_A(j) - mu0_A_fn(j * h - T)));\n      sum_B = sum_B +\n              std::abs(h * (fluxlimAdvection_sol_B(j) - mu0_B_fn(j * h - T)));\n    }\n    error_L1_mu0_A[k] = sum_A;\n    error_L1_mu0_B[k] = sum_B;\n  }\n\n  std::cout << \"\" << std::endl;\n  std::cout << \"--------------\" << std::endl;\n  std::cout << \"error_L1_mu0_A\" << std::endl;\n  std::cout << \"--------------\" << std::endl;\n  std::cout << \"M\";\n  std::cout << \"\\t error\" << std::endl;\n  for (int k = 0; k < 8; k++) {\n    std::cout << nb_timesteps[k];\n    std::cout << \"\\t\";\n    std::cout << error_L1_mu0_A[k] << std::endl;\n  }\n  std::cout << \"\\n\" << std::endl;\n  std::cout << \"--------------\" << std::endl;\n  std::cout << \"error_L1_mu0_B\" << std::endl;\n  std::cout << \"--------------\" << std::endl;\n  std::cout << \"M\";\n  std::cout << \"\\t error\" << std::endl;\n  for (int k = 0; k < 8; k++) {\n    std::cout << nb_timesteps[k];\n    std::cout << \"\\t\";\n    std::cout << error_L1_mu0_B[k] << std::endl;\n  }\n  std::cout << \"\" << std::endl;\n\n  // Output results to csv files\n  Eigen::VectorXd x_advection(N);\n  for (int j = 0; j < N; j++) {\n    x_advection(j) = j * h;\n  }\n  const static Eigen::IOFormat CSVFormat(Eigen::StreamPrecision,\n                                         Eigen::DontAlignCols, \", \", \"\\n\");\n  std::ofstream fluxlimAdvection_sol_A_csv;\n  fluxlimAdvection_sol_A_csv.open(CURRENT_BINARY_DIR\n                                  \"/fluxlimAdvection_sol_A.csv\");\n  fluxlimAdvection_sol_A_csv << x_advection.transpose().format(CSVFormat)\n                             << std::endl;\n  fluxlimAdvection_sol_A_csv\n      << fluxlimAdvection_sol_A.transpose().format(CSVFormat) << std::endl;\n  fluxlimAdvection_sol_A_csv.close();\n  std::cout << \"Generated \" CURRENT_BINARY_DIR \"/fluxlimAdvection_sol_A.csv\"\n            << std::endl;\n  std::system(\"python3 \" CURRENT_SOURCE_DIR \"/plot_sol.py \" CURRENT_BINARY_DIR\n              \"/fluxlimAdvection_sol_A.csv \" CURRENT_BINARY_DIR\n              \"/fluxlimAdvection_sol_A.eps\");\n\n  std::ofstream fluxlimAdvection_sol_B_csv;\n  fluxlimAdvection_sol_B_csv.open(CURRENT_BINARY_DIR\n                                  \"/fluxlimAdvection_sol_B.csv\");\n  fluxlimAdvection_sol_B_csv << x_advection.transpose().format(CSVFormat)\n                             << std::endl;\n  fluxlimAdvection_sol_B_csv\n      << fluxlimAdvection_sol_B.transpose().format(CSVFormat) << std::endl;\n  fluxlimAdvection_sol_B_csv.close();\n  std::cout << \"Generated \" CURRENT_BINARY_DIR \"/fluxlimAdvection_sol_B.csv\"\n            << std::endl;\n  std::system(\"python3 \" CURRENT_SOURCE_DIR \"/plot_sol.py \" CURRENT_BINARY_DIR\n              \"/fluxlimAdvection_sol_B.csv \" CURRENT_BINARY_DIR\n              \"/fluxlimAdvection_sol_B.eps\");\n\n  /* BURGERS FLUX PROBLEM */\n  // Discretization parameters\n  T = 2.0;\n  tau = T / nb_timesteps[7];\n  h = 1.2 * tau;\n  N = std::round(5.0 / h);\n\n  // Initial conditions A and B as lambda functions\n  auto mu0_fn = [](double x) -> double {\n    if (x < 2) {\n      return -1.0;\n    } else if (x < 3) {\n      return 1.0;\n    } else {\n      return -1.0;\n    }\n  };\n\n  Eigen::VectorXd mu0(N);\n  for (int j = 0; j < N; j++) {\n    mu0(j) = mu0_fn(h * j);\n  }\n\n  Eigen::VectorXd fluxlimBurgers_sol =\n      fluxlimBurgers(mu0, h, tau, nb_timesteps[6], phi);\n\n  Eigen::VectorXd x_Burgers(N);\n  for (int j = 0; j < N; j++) {\n    x_Burgers(j) = j * h;\n  }\n\n  std::ofstream fluxlimBurgers_sol_csv;\n  fluxlimBurgers_sol_csv.open(CURRENT_BINARY_DIR \"/fluxlimBurgers_sol.csv\");\n  fluxlimBurgers_sol_csv << x_Burgers.transpose().format(CSVFormat)\n                         << std::endl;\n  fluxlimBurgers_sol_csv << fluxlimBurgers_sol.transpose().format(CSVFormat)\n                         << std::endl;\n  fluxlimBurgers_sol_csv.close();\n  std::cout << \"Generated \" CURRENT_BINARY_DIR \"/fluxlimBurgers_sol.csv\"\n            << std::endl;\n  std::system(\"python3 \" CURRENT_SOURCE_DIR \"/plot_sol.py \" CURRENT_BINARY_DIR\n              \"/fluxlimBurgers_sol.csv \" CURRENT_BINARY_DIR\n              \"/fluxlimBurgers_sol.eps\");\n\n}  // main\n", "meta": {"hexsha": "01259229d88631cb0b0c0dfb9adef506a3866048", "size": 6043, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/FluxLimitedFV/templates/fluxlimitedfv_main.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": "homeworks/FluxLimitedFV/templates/fluxlimitedfv_main.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": "homeworks/FluxLimitedFV/templates/fluxlimitedfv_main.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": 30.3668341709, "max_line_length": 78, "alphanum_fraction": 0.5844779083, "num_tokens": 1865, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699436, "lm_q2_score": 0.7956580927949807, "lm_q1q2_score": 0.7153932002297996}}
{"text": "#include \"MLTest.h\"\n\n#include <mlpack/core.hpp>\n#include <mlpack/methods/neighbor_search/neighbor_search.hpp>\n#include <iostream>\n//#include <armadillo>\n\nusing namespace mlpack;\nusing namespace mlpack::neighbor; // NeighborSearch and NearestNeighborSort\nusing namespace mlpack::metric; // ManhattanDistance\n\nnamespace mv\n{\n    \n    MLTest::MLTest()\n\t{\n\t}\n\n    MLTest::~MLTest()\n\t{\n\t}\n\n\tvoid MLTest::Run()\n\t{\n        // Load the data from data.csv (hard-coded).  Use CLI for simple command-line\n        // parameter handling.\n        arma::mat data(\"0.339406815,0.843176636,0.472701471; \\\n                  0.212587646,0.351174901,0.81056695;  \\\n                  0.160147626,0.255047893,0.04072469;  \\\n                  0.564535197,0.943435462,0.597070812\");\n        data = data.t();\n\n        // Use templates to specify that we want a NeighborSearch object which uses\n        // the Manhattan distance.\n        NeighborSearch<NearestNeighborSort, ManhattanDistance> nn(data);\n\n        // Create the object we will store the nearest neighbors in.\n        arma::Mat<size_t> neighbors;\n        arma::mat distances; // We need to store the distance too.\n\n        // Compute the neighbors.\n        nn.Search(1, neighbors, distances);\n\n        \n        // Write each neighbor and distance using Log.\n        for (size_t i = 0; i < neighbors.n_elem; ++i)\n        {\n            std::cout << \"Nearest neighbor of point \" << i << \" is point \"\n                << neighbors[i] << \" and the distance is \" << distances[i] << \".\" << std::endl;\n        }\n\n        //arma::arma_rng::set_seed_random();\n        //\n        //// Create a 4x4 random matrix and print it on the screen\n        //arma::Mat<double> A = arma::randu(4,4);\n        //std::cout << \"A:\\n\" << A << \"\\n\";\n        //\n        //// Multiply A with his transpose:\n        //std::cout << \"A * A.t() =\\n\";\n        //std::cout << A * A.t() << \"\\n\";\n        //\n        //// Access/Modify rows and columns from the array:\n        //A.row(0) = A.row(1) + A.row(3);\n        //A.col(3).zeros();\n        //std::cout << \"add rows 1 and 3, store result in row 0, also fill 4th column with zeros:\\n\";\n        //std::cout << \"A:\\n\" << A << \"\\n\";\n        //\n        //// Create a new diagonal matrix using the main diagonal of A:\n        //arma::Mat<double>B = arma::diagmat(A);\n        //std::cout << \"B:\\n\" << B << \"\\n\";\n\t}\n}\n", "meta": {"hexsha": "de76914ab4eae937f7556c69511156bc5b40f23e", "size": 2363, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/MLTest.cpp", "max_stars_repo_name": "vstanchevici/mvisus", "max_stars_repo_head_hexsha": "516b34884c66bf64679ae15c64c1ba7f0c99ed68", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-10-05T17:26:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-05T17:26:25.000Z", "max_issues_repo_path": "source/MLTest.cpp", "max_issues_repo_name": "vstanchevici/mvisus", "max_issues_repo_head_hexsha": "516b34884c66bf64679ae15c64c1ba7f0c99ed68", "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": "source/MLTest.cpp", "max_forks_repo_name": "vstanchevici/mvisus", "max_forks_repo_head_hexsha": "516b34884c66bf64679ae15c64c1ba7f0c99ed68", "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.3698630137, "max_line_length": 101, "alphanum_fraction": 0.5577655523, "num_tokens": 639, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.7981867849406659, "lm_q1q2_score": 0.715376006443995}}
{"text": "#include \"normal.hpp\"\n\n#include <gtest/gtest.h>\n\n#include <boost/random/mersenne_twister.hpp>\n\nusing namespace MultidimensionalArray;\nusing namespace ProbabilityDistributions;\n\nTEST(NormalTest, Likelihood) {\n  boost::random::mt19937 rng;\n  const unsigned int n_samples = 100;\n  Normal<double> dist(0, 1);\n  Array<double> samples;\n  dist.sample(samples, n_samples, rng);\n\n  double likelihood1 = dist.log_likelihood(samples);\n\n  dist.MLE(samples);\n\n  double likelihood2 = dist.log_likelihood(samples);\n\n  EXPECT_GE(likelihood2, likelihood1);\n\n  EXPECT_LT(0, dist.get_sigma());\n}\n\nTEST(NormalTest, MLE) {\n  boost::random::mt19937 rng;\n  const unsigned int n_samples = 100;\n  Normal<double> dist(0, 1);\n  Array<double> samples;\n  dist.sample(samples, n_samples, rng);\n  dist.MLE(samples);\n\n  double mu = dist.get_mu(), sigma = dist.get_sigma();\n  double eps = 1e-2;\n  double ll = dist.log_likelihood(samples);\n\n  dist.set_mu(mu + eps);\n  EXPECT_GE(ll, dist.log_likelihood(samples));\n  dist.set_mu(mu - eps);\n  EXPECT_GE(ll, dist.log_likelihood(samples));\n  dist.set_mu(mu);\n\n  dist.set_sigma(sigma + eps);\n  EXPECT_GE(ll, dist.log_likelihood(samples));\n  dist.set_sigma(sigma - eps);\n  EXPECT_GE(ll, dist.log_likelihood(samples));\n  dist.set_sigma(sigma);\n}\n\nTEST(NormalTest, Samples) {\n  boost::random::mt19937 rng;\n  const unsigned int n_samples = 100;\n  Normal<double> dist(0, 1);\n  Array<double> samples;\n  dist.sample(samples, n_samples, rng);\n  for (size_t i = 0; i < n_samples; i++) {\n    EXPECT_LT(-5, samples(i,0));\n    EXPECT_GT(5, samples(i,0));\n  }\n}\n", "meta": {"hexsha": "5d8252504c12b92d45f9e7b3a60025840c9c080a", "size": 1559, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/normal.cpp", "max_stars_repo_name": "mirandaconrado/probability-distributions", "max_stars_repo_head_hexsha": "6b7d86e181237eb134e6df6da60200beed66922f", "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/normal.cpp", "max_issues_repo_name": "mirandaconrado/probability-distributions", "max_issues_repo_head_hexsha": "6b7d86e181237eb134e6df6da60200beed66922f", "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/normal.cpp", "max_forks_repo_name": "mirandaconrado/probability-distributions", "max_forks_repo_head_hexsha": "6b7d86e181237eb134e6df6da60200beed66922f", "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.359375, "max_line_length": 54, "alphanum_fraction": 0.7062219371, "num_tokens": 416, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476800298183, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7153475962557154}}
{"text": "#pragma once\n\n#include <stdio.h>\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <Utils/IO/IOUtilities.hpp>\n#include <iostream>\n\nnamespace myUtils {\n\n// =============================================================================\n// Matrix Utils\n// =============================================================================\nEigen::MatrixXd hStack(const Eigen::MatrixXd& a_, const Eigen::MatrixXd& b_);\nEigen::MatrixXd vStack(const Eigen::MatrixXd& a_, const Eigen::MatrixXd& b_);\nEigen::MatrixXd vStack(const Eigen::VectorXd& a_, const Eigen::VectorXd& b_);\nEigen::MatrixXd deleteRow(const Eigen::MatrixXd& a_, int row);\n\n// =============================================================================\n// Simple Trajectory Generator\n// =============================================================================\ndouble smooth_changing(double ini, double end, double moving_duration,\n                       double curr_time);\ndouble smooth_changing_vel(double ini, double end, double moving_duration,\n                           double curr_time);\ndouble smooth_changing_acc(double ini, double end, double moving_duration,\n                           double curr_time);\nvoid getSinusoidTrajectory(double initTime_, const Eigen::VectorXd& midPoint_,\n                           const Eigen::VectorXd& amp_,\n                           const Eigen::VectorXd& freq_, double evalTime_,\n                           Eigen::VectorXd& p_, Eigen::VectorXd& v_,\n                           Eigen::VectorXd& a_);\n\n// =============================================================================\n// ETC\n// =============================================================================\n\ndouble computeAlphaGivenBreakFrequency(double hz, double dt);\n\ndouble bind_half_pi(double);\n\nbool isEqual(const Eigen::VectorXd a, const Eigen::VectorXd b,\n             const double threshold = 0.00001);\ndouble CropValue(double value, double min, double max, std::string source);\ndouble CropValue(double value, double min, double max);\n\nEigen::VectorXd CropVector(Eigen::VectorXd value, Eigen::VectorXd min,\n                           Eigen::VectorXd max, std::string source);\n\nEigen::MatrixXd CropMatrix(Eigen::MatrixXd value, Eigen::MatrixXd min,\n                           Eigen::MatrixXd max, std::string source);\n\nbool isInBoundingBox(const Eigen::VectorXd& val, const Eigen::VectorXd& lb,\n                     const Eigen::VectorXd& ub);\n\nEigen::MatrixXd GetRelativeMatrix(const Eigen::MatrixXd value,\n                                  const Eigen::MatrixXd min,\n                                  const Eigen::MatrixXd max);\n\nEigen::VectorXd GetRelativeVector(const Eigen::VectorXd value,\n                                  const Eigen::VectorXd min,\n                                  const Eigen::VectorXd max);\n\nEigen::VectorXd eulerIntegration(const Eigen::VectorXd& x,\n                                 const Eigen::VectorXd& xdot, double dt);\n\nEigen::VectorXd doubleIntegration(const Eigen::VectorXd& q,\n                                  const Eigen::VectorXd& alpha,\n                                  const Eigen::VectorXd& alphad, double dt);\n\nEigen::Matrix3d VecToso3(const Eigen::Vector3d& omg);\nEigen::MatrixXd Adjoint(const Eigen::MatrixXd& R, const Eigen::Vector3d& p);\n\ndouble QuatToYaw(const Eigen::Quaternion<double> q);\n\n// Euler ZYX \n//     Represents either:\n//     extrinsic XYZ rotations: Fixed-frame roll, then fixed-frame pitch, then fixed-frame yaw.\n//     or intrinsic ZYX rotations: Body-frame yaw, body-frame pitch, then body-frame roll \n//\n//     The equation is similar, but the values for fixed and body frame rotations are different.\n// World Orientation is R = Rz*Ry*Rx\nEigen::Quaterniond EulerZYXtoQuat(const double roll, const double pitch, const double yaw);\n\n// Quaternion to Euler ZYX \nEigen::Vector3d QuatToEulerZYX(const Eigen::Quaterniond & quat_in);\n\n\n// ZYX extrinsic rotation rates to world angular velocity\n// angular vel = [wx, wy, wz]\nEigen::Vector3d EulerZYXRatestoAngVel(const double roll, const double pitch, const double yaw,\n                                      const double roll_rate, const double pitch_rate, const double yaw_rate);\n\nvoid avoid_quat_jump(const Eigen::Quaternion<double> &des_ori, Eigen::Quaternion<double> &act_ori);\n}  // namespace myUtils\n", "meta": {"hexsha": "33fe3c8fc97cf8396834435e7bf941e1f93e64fa", "size": 4298, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Utils/Math/MathUtilities.hpp", "max_stars_repo_name": "stevenjj/PnC", "max_stars_repo_head_hexsha": "e1e417dbd507f174bb2661247cb4360b6ee0ada7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-04T22:36:54.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-04T22:36:54.000Z", "max_issues_repo_path": "Utils/Math/MathUtilities.hpp", "max_issues_repo_name": "stevenjj/PnC", "max_issues_repo_head_hexsha": "e1e417dbd507f174bb2661247cb4360b6ee0ada7", "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": "Utils/Math/MathUtilities.hpp", "max_forks_repo_name": "stevenjj/PnC", "max_forks_repo_head_hexsha": "e1e417dbd507f174bb2661247cb4360b6ee0ada7", "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.7708333333, "max_line_length": 110, "alphanum_fraction": 0.5863192182, "num_tokens": 802, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767842777551, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7153475812258111}}
{"text": "// Copyright (c) 2000-2021, Heiko Bauke\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions\n// are met:\n//\n//   * Redistributions of source code must retain the above copyright\n//     notice, this list of conditions and the following disclaimer.\n//\n//   * Redistributions in binary form must reproduce the above\n//     copyright notice, this list of conditions and the following\n//     disclaimer in the documentation and/or other materials provided\n//     with the distribution.\n//\n//   * Neither the name of the copyright holder nor the names of its\n//     contributors may be used to endorse or promote products derived\n//     from this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n// OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include <cinttypes>\n#include <ciso646>\n\n#define BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#include <boost/mpl/list.hpp>\n\n#include <trng/linear_algebra.hpp>\n\n\n//-----------------------------------------------------------------------------------------\n\nBOOST_AUTO_TEST_SUITE(test_suite_linear_algebra)\n\n//-----------------------------------------------------------------------------------------\n\nBOOST_AUTO_TEST_SUITE(test_suite_vector)\nBOOST_AUTO_TEST_CASE(test_basic) {\n  {\n    trng::vector<int, 6> v1{1, 2, 3, 4, 5, 6};\n    trng::vector<int, 6> v2{1, 2, 3, 4, 5, 255};\n    {\n      const bool ok = v1 == v1;\n      BOOST_TEST(ok, \"vectors are equal\");\n    }\n    {\n      const bool ok = v1 != v2;\n      BOOST_TEST(ok, \"vectors do not equal\");\n    }\n  }\n  {\n    auto init1 = [](size_t i) { return std::uint8_t(i); };\n    auto init2 = [](size_t i) { return std::uint8_t(3 * i); };\n    trng::vector<std::uint8_t, 256> v_256_1(init1);\n    trng::vector<std::uint8_t, 256> v_256_2(init2);\n    trng::vector<std::uint8_t, 256> v_256_3(v_256_1 + v_256_2);\n    bool ok{true};\n    for (std::size_t i{0}; i < 256; ++i) {\n      ok = ok and (static_cast<std::uint8_t>(v_256_1(i) + v_256_2(i)) == v_256_3(i));\n    }\n    BOOST_TEST(ok, \"sum vector ok\");\n  }\n  {\n    auto init = [](size_t i) { return std::uint8_t(i); };\n    trng::vector<std::uint8_t, 256> v_256_1(init);\n    trng::vector<std::uint8_t, 256> v_256_2(std::uint8_t(13) * v_256_1);\n    bool ok{true};\n    for (std::size_t i{0}; i < 256; ++i) {\n      ok = ok and (static_cast<std::uint8_t>(13 * v_256_1(i)) == v_256_2(i));\n    }\n    BOOST_TEST(ok, \"product vector ok\");\n  }\n  {\n    auto init = [](size_t i) { return std::uint8_t(i); };\n    trng::vector<std::uint8_t, 256> v_256_1(init);\n    trng::vector<std::uint8_t, 256> v_256_2(v_256_1 * std::uint8_t(13));\n    bool ok{true};\n    for (std::size_t i{0}; i < 256; ++i) {\n      ok = ok and (static_cast<std::uint8_t>(13 * v_256_1(i)) == v_256_2(i));\n    }\n    BOOST_TEST(ok, \"product vector ok\");\n  }\n  {\n    trng::matrix<int, 2> A{1, 3,  //\n                           2, 4};\n    trng::vector<int, 2> b{3, 7};\n    trng::vector<int, 2> c{24, 34};\n    auto c2 = A * b;\n    const bool ok{c2 == c};\n    BOOST_TEST(ok, \"matrix vector product ok\");\n  }\n  {\n    trng::matrix<int, 2> A{1, 3,  //\n                           2, 4};\n    trng::matrix<int, 2> B{1, 3,  //\n                           2, -4};\n    trng::matrix<int, 2> C{7, -9,  //\n                           10, -10};\n    auto C2 = A * B;\n    const bool ok{C2 == C};\n    BOOST_TEST(ok, \"matrix matrix product ok\");\n  }\n  {\n    trng::matrix<int, 2> A{1, 3,  //\n                           2, 4};\n    trng::matrix<int, 2> A_5{1069, 2337,  //\n                             1558, 3406};\n    auto A_5_2 = trng::power(A, 5);\n    const bool ok{A_5_2 == A_5};\n    BOOST_TEST(ok, \"matrix matrix power ok\");\n  }\n}\nBOOST_AUTO_TEST_SUITE_END()\n\n//-----------------------------------------------------------------------------------------\n\nBOOST_AUTO_TEST_SUITE(test_suite_GF2)\nBOOST_AUTO_TEST_CASE(test_add) {\n  const trng::GF2 zero(false);\n  const trng::GF2 one(true);\n  BOOST_TEST(zero + zero == zero, \"addition 0 + 0\");\n  BOOST_TEST(zero + one == one, \"addition 0 + 1\");\n  BOOST_TEST(one + zero == one, \"addition 1 + 0\");\n  BOOST_TEST(one + one == zero, \"addition 1 + 1\");\n}\n\nBOOST_AUTO_TEST_CASE(test_mult) {\n  const trng::GF2 zero(false);\n  const trng::GF2 one(true);\n  BOOST_TEST((zero * zero == zero), \"multiplication 0 * 0\");\n  BOOST_TEST((zero * one == zero), \"multiplication 0 * 1\");\n  BOOST_TEST((one * zero == zero), \"multiplication 1 * 0\");\n  BOOST_TEST((one * one == one), \"multiplication 1 * 1\");\n}\n\nBOOST_AUTO_TEST_CASE(test_matrix_power) {\n  const trng::GF2 zero(false);\n  const trng::GF2 one(true);\n  trng::matrix<trng::GF2, 4> A{one,  one, zero, one,   //\n                               one,  one, one,  zero,  //\n                               one,  one, zero, zero,  //\n                               zero, one, zero, one};\n  trng::matrix<trng::GF2, 4> A_8{one,  one, zero, one,   //\n                                 one,  one, one,  zero,  //\n                                 one,  one, zero, zero,  //\n                                 zero, one, zero, one};\n  auto A_8_2 = trng::power(A, 8);\n  const bool ok{A_8_2 == A_8};\n  BOOST_TEST(ok, \"matrix matrix power in GF2 ok\");\n}\nBOOST_AUTO_TEST_SUITE_END()\n\n//-----------------------------------------------------------------------------------------\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "0590b79134de6fd36acc022a2715ccc138a2c208", "size": 6097, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tests/test_linear_algebra.cc", "max_stars_repo_name": "joseasoler/trng4", "max_stars_repo_head_hexsha": "589bdf263821706fd845843912d4241f9c89ba3e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 80.0, "max_stars_repo_stars_event_min_datetime": "2015-03-23T15:47:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T06:35:10.000Z", "max_issues_repo_path": "tests/test_linear_algebra.cc", "max_issues_repo_name": "joseasoler/trng4", "max_issues_repo_head_hexsha": "589bdf263821706fd845843912d4241f9c89ba3e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2015-09-16T23:58:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-08T20:41:07.000Z", "max_forks_repo_path": "tests/test_linear_algebra.cc", "max_forks_repo_name": "joseasoler/trng4", "max_forks_repo_head_hexsha": "589bdf263821706fd845843912d4241f9c89ba3e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2015-07-16T16:54:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T20:50:47.000Z", "avg_line_length": 36.2916666667, "max_line_length": 91, "alphanum_fraction": 0.5696244054, "num_tokens": 1759, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240964782012, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7152909650726711}}
{"text": "//\n// Created by rdelfin on 4/21/16.\n//\n\n#pragma once\n\n#include <Eigen/Dense>\n\nclass MatUtil {\npublic:\n    static Eigen::VectorXd vectorize(const Eigen::MatrixXd& mat);\n    static Eigen::MatrixXd matricise(const Eigen::VectorXd& vec, long rows, long cols);\n};\n\n", "meta": {"hexsha": "0bb97e6280143804e83e0fc972d8571d5b908f92", "size": 261, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/heat-equation-calc/include/heat-equation-calc/MatUtil.hpp", "max_stars_repo_name": "rdelfin/heat-simulation", "max_stars_repo_head_hexsha": "0f178c0934c88ee6071afbe42efcb7dc49fd4461", "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": "src/heat-equation-calc/include/heat-equation-calc/MatUtil.hpp", "max_issues_repo_name": "rdelfin/heat-simulation", "max_issues_repo_head_hexsha": "0f178c0934c88ee6071afbe42efcb7dc49fd4461", "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": "src/heat-equation-calc/include/heat-equation-calc/MatUtil.hpp", "max_forks_repo_name": "rdelfin/heat-simulation", "max_forks_repo_head_hexsha": "0f178c0934c88ee6071afbe42efcb7dc49fd4461", "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": 17.4, "max_line_length": 87, "alphanum_fraction": 0.6973180077, "num_tokens": 67, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.865224073888819, "lm_q1q2_score": 0.7152909537858465}}
{"text": "// Fractool\n#include <fractool/macros.hpp>\n#include <fractool/ftcore/generate_julia.hpp>\n\n// Internal\n#include <algorithm>\n#include <complex>\n\n// External\n#include <boost/log/trivial.hpp>\n\n/**\n * Run julia set generation algorithm\n */\nvoid generate_julia(unsigned size_x, unsigned size_y, unsigned char* param_buffer)\n{\n    // Print message\n    BOOST_LOG_TRIVIAL(info) << \"Generating julia...\";\n\n    // Parameter\n    std::complex<float> c(-0.4, 0.6);\n\n    // Helper variables\n    float gsc = 4.0;                            // Grid scale\n    float x0 = (float)size_x/2;                 // Center x value\n    float y0 = (float)size_y/2;                 // Center y value\n    float scl = gsc / std::min(size_x, size_y); // Final scale factor\n    BOOST_LOG_TRIVIAL(debug) << \"Grid scale: \" << gsc;\n    BOOST_LOG_TRIVIAL(debug) << \"Origin Point (x0, y0): (\" << x0 << \",\" << y0 << \")\";\n    BOOST_LOG_TRIVIAL(debug) << \"Final Scale: \" << scl;\n\n    // Run iteration algorithm\n    std::complex<float> z;\n    unsigned char n;\n    for (unsigned j = 0; j < size_y; ++j) {\n        for (unsigned i = 0; i < size_x; ++i) {\n            // Initialize z\n            z = std::complex<float>(i - x0, y0 - j) * scl;\n\n            // Iteration\n            n = 0;\n            while (n < 255 && std::abs(z) < 2) {\n                z = z*z + c;\n                n += 1;\n            }\n\n            // Log output\n            BOOST_LOG_TRIVIAL(trace) \n                << \"Pixel (\" << i << \",\" << j << \"): \"\n                << \"c = \" << c << \" n = \" << (int)n;\n            \n            // Set parameter\n            param_buffer[ARRAY2D(size_x, i, j)] = n;\n        }\n    }\n}", "meta": {"hexsha": "b43af84262c24e4d70233d36835e7b83c9007941", "size": 1642, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ftcore/generate_julia.cpp", "max_stars_repo_name": "andydevs/fractool", "max_stars_repo_head_hexsha": "856fa59c5db3e5657415a6e78e92c07d21b42b6c", "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/ftcore/generate_julia.cpp", "max_issues_repo_name": "andydevs/fractool", "max_issues_repo_head_hexsha": "856fa59c5db3e5657415a6e78e92c07d21b42b6c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23.0, "max_issues_repo_issues_event_min_datetime": "2021-11-02T13:35:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-22T00:36:06.000Z", "max_forks_repo_path": "src/ftcore/generate_julia.cpp", "max_forks_repo_name": "andydevs/fractool", "max_forks_repo_head_hexsha": "856fa59c5db3e5657415a6e78e92c07d21b42b6c", "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.3214285714, "max_line_length": 85, "alphanum_fraction": 0.496954933, "num_tokens": 463, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308036221031, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.7152821010401046}}
{"text": "/*\n * Bayes++ the Bayesian Filtering Library\n * Copyright (c) 2002 Michael Stevens\n * See accompanying Bayes++.htm for terms and conditions of use.\n *\n * $Id$\n */\n\n/*\n * Example of using Bayesian Filter Class to solve a simple problem.\n *\n * The example implements a simple quadratic observer.\n *  This tries to estimate the state of system while also trying to\n *  calibrate a simple linear model of the system which includes\n *  a scale factor and a bias.\n *  Estimating both the system state and a scale factor results in a\n *  quadratic (product of two states and therefore non-linear) observation.\n *  The system model is a 1D brownian motion with a known perturbation.\n */\n\n#include \"BayesFilter/infFlt.hpp\"\n#include \"Test/random.hpp\"\n#include <cmath>\n#include <iostream>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/random.hpp>\n\nnamespace\n{\n\tnamespace FM = Bayesian_filter_matrix;\n\tusing namespace FM;\n\n\t// Choose Filtering Scheme to use\n\ttypedef Bayesian_filter::Information_scheme FilterScheme;\n\n\t// Square \n\ttemplate <class scalar>\n\tinline scalar sqr(scalar x)\n\t{\n\t\treturn x*x;\n\t}\n\n\t// Random numbers from Boost\n\tBayesian_filter_test::Boost_random localRng;\n\n\t// Constant Dimensions\n\tconst unsigned NX = 3;\t\t\t// Filter State dimension \t(SystemState, Scale, Bias)\n\n\t// Filter Parameters\n\t// Noise on observing system state\n\tconst Float OBS_NOISE = 0.01;\n\t// Prediction Noise: no Prediction noise as pertubation is known\n\tconst Float X_NOISE = 0.0;\t// System State\t\n\tconst Float S_NOISE = 0.0;\t// Scale\n\tconst Float B_NOISE = 0.0;\t// Bias\n\t// Filter's Initial state uncertainty: System state is unknown\n\tconst Float i_X_NOISE = 1000.;\n\tconst Float i_S_NOISE = 0.1;\n\tconst Float i_B_NOISE = 0.1;\n\n}//namespace\n\n\n/*\n * Prediction model\n * Linear state predict model with additive control input\n */\nclass QCpredict : public Bayesian_filter::Linrz_predict_model\n{\n\tFloat motion;\n\tmutable FM::Vec fx;\npublic:\n\tQCpredict();\n\t\t;\n\tvoid predict(const FM::Vec& u)\n\t{\n\t\tmotion = u[0];\n\t}\n\tconst FM::Vec& f(const FM::Vec& x) const\n\t{\n\t\t// Constant scale and bias, system state perturbed by control input\n\t\tfx = x;\n\t\tfx[0] += motion;\n\t\treturn fx;\n\t};\n};\n\nQCpredict::QCpredict() : Bayesian_filter::Linrz_predict_model(NX, NX), fx(NX)\n{\n\tFM::identity (Fx);\n\n\t// Setup constant noise model: G is identity\n\tq[0] = sqr(X_NOISE);\n\tq[1] = sqr(S_NOISE);\n\tq[2] = sqr(B_NOISE);\n\tFM::identity (G);\n}\n\n\n/*\n * Quadratic observation model\n */\nclass QCobserve : public Bayesian_filter::Linrz_uncorrelated_observe_model\n{\n\tmutable FM::Vec z_pred;\npublic:\n\tQCobserve ();\n\tconst FM::Vec& h(const FM::Vec& x) const\n\t{\t// Quadratic Observation model\n\t\tz_pred[0] = x[0] * x[1] + x[2];\n\t\treturn z_pred;\n\t};\n\tvoid state (const FM::Vec& x)\n\t// Linearised model, Jacobian of h at x\n\t{\n\t\tHx(0,0) = x[1];\n\t\tHx(0,1) = x[0];\n\t\tHx(0,2) = 1.;\n\t}\n};\n\nQCobserve::QCobserve () :\n\tBayesian_filter::Linrz_uncorrelated_observe_model(NX,1), z_pred(1)\n{\n\t// Observation Noise variance\n\tZv[0] = OBS_NOISE*OBS_NOISE;\n}\n\n\nint main()\n{\n\t// Global setup for test output\n\tstd::cout.flags(std::ios::scientific); std::cout.precision(6);\n\n\t// Setup the test filters\n\tFM::Vec x_true (NX);\n\n\t// True State to be observed\n\tx_true[0] = 10.;\t// System State\n\tx_true[1] = 1.0;\t// Scale\n\tx_true[2] = 0.0;\t// Bias\n\n\tstd::cout << \"Quadratic Calibration\" << std::endl;\n\tstd::cout << \"Init \" << x_true << std::endl;\n\n\n\t// Construct Prediction and Observation model and Calibration filter\n\tQCpredict linearPredict;\n\tQCobserve nonlinObserve;\n\tFilterScheme obsAndCalib (NX);\n\n\t// Give the filter an true initial guess of the system state\n\tobsAndCalib.x[0] = x_true[0];\n\tobsAndCalib.x[1] = 1.;\t\t// Assumed initial Scale\n\tobsAndCalib.x[2] = 0.;\t\t// Assumed initial Bias\n\tobsAndCalib.X.clear();\n\tobsAndCalib.X(0,0) = sqr(i_X_NOISE);\n\tobsAndCalib.X(1,1) = sqr(i_S_NOISE);\n\tobsAndCalib.X(2,2) = sqr(i_B_NOISE);\n\n\tobsAndCalib.init ();\n\n\t// Iterate the filter with test observations\n\tFM::Vec u(1), z_true(1), z(1);\n\tfor (unsigned i = 0; i < 100; i++ )\n\t{\n\t\t// Predict true state using Brownian control input \n\t\tlocalRng.normal (u);\t\t\t\t// normally distributed\n\t\tx_true[0] += u[0];\n\t\tlinearPredict.predict (u);\n\n\t\t// Predict filter with known perturbation\n\t\tobsAndCalib.predict (linearPredict);\n\n\t\t// True Observation: Quadratic observation model\n\t\tz_true[0] = x_true[0] * x_true[1] + x_true[2];\n\n\t\t// Observation with additive noise\n\t\tlocalRng.normal (z, z_true[0], OBS_NOISE);\t// normally distributed mean z_true[0], stdDev OBS_NOISE.\n\n\t\t// Filter observation using model linearised at state estimate x\n\t\tnonlinObserve.state (obsAndCalib.x);\n\t\tobsAndCalib.observe (nonlinObserve, z);\n\t}\n\n\t// Update the filter to state and covariance are available\n\tobsAndCalib.update ();\n\n\t// Print everything: True, filter, covariance\n\tstd::cout << \"True \" << x_true <<  std::endl;\n\tstd::cout << \"Calb \" << obsAndCalib.x << std::endl;\n\tstd::cout << obsAndCalib.X << std::endl;\n\treturn 0;\n}\n", "meta": {"hexsha": "dc5ea5c39a78f420fcfc609fddb20e5a412210c2", "size": 4910, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuadCalib/QuadCalib.cpp", "max_stars_repo_name": "Exadios/Bayes-", "max_stars_repo_head_hexsha": "a1cd9efe2e840506d887bec9b246fd936f2b71e5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-04-02T21:45:49.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-19T01:59:02.000Z", "max_issues_repo_path": "QuadCalib/QuadCalib.cpp", "max_issues_repo_name": "Exadios/Bayes-", "max_issues_repo_head_hexsha": "a1cd9efe2e840506d887bec9b246fd936f2b71e5", "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": "QuadCalib/QuadCalib.cpp", "max_forks_repo_name": "Exadios/Bayes-", "max_forks_repo_head_hexsha": "a1cd9efe2e840506d887bec9b246fd936f2b71e5", "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.1794871795, "max_line_length": 102, "alphanum_fraction": 0.6949083503, "num_tokens": 1467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.8006919949619793, "lm_q1q2_score": 0.7152656904519574}}
{"text": "#include <stan/math/rev/scal.hpp>\n#include <gtest/gtest.h>\n#include <boost/math/special_functions/gamma.hpp>\n#include <test/unit/math/rev/scal/fun/nan_util.hpp>\n#include <test/unit/math/rev/scal/util.hpp>\n\nTEST(AgradRev,gamma_p_var_var) {\n  AVAR a = 0.5;\n  AVAR b = 1.0;\n  AVAR f = gamma_p(a,b);\n  EXPECT_FLOAT_EQ(boost::math::gamma_p(0.5,1.0),f.val());\n\n  AVEC x = createAVEC(a,b);\n  VEC g;\n  f.grad(x,g);\n  EXPECT_FLOAT_EQ(-0.389837, g[0]);\n  EXPECT_FLOAT_EQ(boost::math::gamma_p_derivative(0.5,1.0), g[1]);\n  \n  a = -0.5;\n  EXPECT_THROW(gamma_p(a,b), std::domain_error);\n\n  b = -1.0;\n  EXPECT_THROW(gamma_p(a,b), std::domain_error);\n}\nTEST(AgradRev,gamma_p_double_var) {\n  double a = 0.5;\n  AVAR b = 1.0;\n  AVAR f = gamma_p(a,b);\n  EXPECT_FLOAT_EQ(boost::math::gamma_p(0.5,1.0),f.val());\n\n  AVEC x = createAVEC(b);\n  VEC g;\n  f.grad(x,g);\n  EXPECT_FLOAT_EQ(boost::math::gamma_p_derivative(0.5,1.0), g[0]);\n\n  a = -0.5;\n  EXPECT_THROW(gamma_p(a,b), std::domain_error);\n\n  b = -1.0;\n  EXPECT_THROW(gamma_p(a,b), std::domain_error);\n}\nTEST(AgradRev,gamma_p_var_double) {\n  AVAR a = 0.5;\n  double b = 1.0;\n  AVAR f = gamma_p(a,b);\n  EXPECT_FLOAT_EQ(boost::math::gamma_p(0.5,1.0),f.val());\n\n  AVEC x = createAVEC(a);\n  VEC g;\n  f.grad(x,g);\n  EXPECT_FLOAT_EQ(-0.389837, g[0]);\n\n  a = -0.5;\n  EXPECT_THROW(gamma_p(a,b), std::domain_error);\n\n  b = -1.0;\n  EXPECT_THROW(gamma_p(a,b), std::domain_error);\n}\n\nstruct gamma_p_fun {\n  template <typename T0, typename T1>\n  inline \n  typename stan::return_type<T0,T1>::type\n  operator()(const T0& arg1,\n             const T1& arg2) const {\n    return gamma_p(arg1,arg2);\n  }\n};\n\nTEST(AgradRev, gamma_p_nan) {\n  gamma_p_fun gamma_p_;\n  test_nan(gamma_p_,0.5,1.0,false,true);\n}\n\nTEST(AgradRev, check_varis_on_stack) {\n  AVAR a = 0.5;\n  AVAR b = 1.0;\n  test::check_varis_on_stack(stan::math::gamma_p(a, b));\n  test::check_varis_on_stack(stan::math::gamma_p(a, 1.0));\n  test::check_varis_on_stack(stan::math::gamma_p(0.5, b));\n}\n", "meta": {"hexsha": "6f97cb2b98e19cf435691f26501aae5d3badc769", "size": 1964, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/rev/scal/fun/gamma_p_test.cpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "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": "cmdstan/stan/lib/stan_math/test/unit/math/rev/scal/fun/gamma_p_test.cpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "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": "cmdstan/stan/lib/stan_math/test/unit/math/rev/scal/fun/gamma_p_test.cpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "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.9512195122, "max_line_length": 66, "alphanum_fraction": 0.6563136456, "num_tokens": 713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.8376199714402812, "lm_q1q2_score": 0.7152543819679604}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// QuickBook Example\n\n// Copyright (c) 2020 Digvijay Janartha, Hamirpur, India.\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//[covered_by\n//` Checks if the first geometry is inside or on border the second geometry\n\n#include <iostream>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n\nnamespace bg = boost::geometry; /*< Convenient namespace alias >*/\n\nint main()\n{\n    // Checks if the first geometry is inside or on border the second geometry.\n    bg::model::polygon<bg::model::d2::point_xy<double> > poly1;\n    bg::read_wkt(\"POLYGON((0 2,0 3,2 4,1 2,0 2))\", poly1);\n    bg::model::polygon<bg::model::d2::point_xy<double> > poly2;\n    bg::read_wkt(\"POLYGON((0 4,3 4,2 2,0 1,0 4))\", poly2);\n    bool check_covered = bg::covered_by(poly1, poly2);\n    if (check_covered) {\n         std::cout << \"Covered: Yes\" << std::endl;\n    } else {\n        std::cout << \"Covered: No\" << std::endl;\n    }\n\n    bg::model::polygon<bg::model::d2::point_xy<double> > poly3;\n    bg::read_wkt(\"POLYGON((-1 -1,-3 -4,-7 -7,-4 -3,-1 -1))\", poly3);\n    check_covered = bg::covered_by(poly1, poly3);\n    if (check_covered) {\n         std::cout << \"Covered: Yes\" << std::endl;\n    } else {\n        std::cout << \"Covered: No\" << std::endl;\n    }\n\n    // This should return true since both polygons are same, so they are lying on each other.\n    check_covered = bg::covered_by(poly1, poly1);\n    if (check_covered) {\n         std::cout << \"Covered: Yes\" << std::endl;\n    } else {\n        std::cout << \"Covered: No\" << std::endl;\n    }\n\n    return 0;\n}\n\n//]\n\n\n//[covered_by_output\n/*`\nOutput:\n[pre\nCovered: Yes\n\n[$img/algorithms/covered_by.png]\n\nCovered: No\nCovered: Yes\n]\n*/\n//]\n", "meta": {"hexsha": "72eee97ef3be85b9c8dbfb2af1c5eda70a4f318a", "size": 1932, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/src/examples/algorithms/covered_by.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/algorithms/covered_by.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": "doc/src/examples/algorithms/covered_by.cpp", "max_forks_repo_name": "jkerkela/geometry", "max_forks_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_forks_repo_licenses": ["BSL-1.0"], "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": 27.2112676056, "max_line_length": 93, "alphanum_fraction": 0.6371635611, "num_tokens": 597, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.8376199613065411, "lm_q1q2_score": 0.7152543733146305}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  Vector2f v = Vector2f::Random();\nJacobiRotation<float> G;\nG.makeGivens(v.x(), v.y());\ncout << \"Here is the vector v:\" << endl << v << endl;\nv.applyOnTheLeft(0, 1, G.adjoint());\ncout << \"Here is the vector J' * v:\" << endl << v << endl;\n  return 0;\n}\n", "meta": {"hexsha": "3a57ca642c17ca8ca37bba18e93b5c7d326abe81", "size": 386, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_Jacobi_makeGivens.cpp", "max_stars_repo_name": "TANHAIYU/Self-calibration-using-Homography-Constraints", "max_stars_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-03-17T16:34:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-17T18:30:13.000Z", "max_issues_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_Jacobi_makeGivens.cpp", "max_issues_repo_name": "TANHAIYU/planecalib", "max_issues_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "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": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_Jacobi_makeGivens.cpp", "max_forks_repo_name": "TANHAIYU/planecalib", "max_forks_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "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": 21.4444444444, "max_line_length": 58, "alphanum_fraction": 0.6347150259, "num_tokens": 118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.8104789178257653, "lm_q1q2_score": 0.7151891772513997}}
{"text": "/*\n * Copyright Nick Thompson, 2017\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#include \"math_unit_test.hpp\"\n#include <boost/type_index.hpp>\n#include <boost/math/special_functions/chebyshev.hpp>\n#include <boost/math/special_functions/chebyshev_transform.hpp>\n#include <boost/math/special_functions/sinc.hpp>\n\n#if !defined(TEST1) && !defined(TEST2) && !defined(TEST3) && !defined(TEST4)\n#  define TEST1\n#  define TEST2\n#  define TEST3\n#  define TEST4\n#endif\n\nusing boost::math::chebyshev_t;\nusing boost::math::chebyshev_t_prime;\nusing boost::math::chebyshev_u;\nusing boost::math::chebyshev_transform;\n\n\ntemplate<class Real>\nvoid test_sin_chebyshev_transform()\n{\n    using boost::math::chebyshev_transform;\n    using boost::math::constants::half_pi;\n    using std::sin;\n    using std::cos;\n    using std::abs;\n\n    Real tol = std::numeric_limits<Real>::epsilon();\n    auto f = [](Real x)->Real { return sin(x); };\n    Real a = 0;\n    Real b = 1;\n    chebyshev_transform<Real> cheb(f, a, b, tol);\n\n    Real x = a;\n    while (x < b)\n    {\n        Real s = sin(x);\n        Real c = cos(x);\n        CHECK_ABSOLUTE_ERROR(s, cheb(x), tol);\n        CHECK_ABSOLUTE_ERROR(c, cheb.prime(x), 150*tol);\n        x += static_cast<Real>(1)/static_cast<Real>(1 << 7);\n    }\n\n    Real Q = cheb.integrate();\n\n    CHECK_ABSOLUTE_ERROR(1 - cos(static_cast<Real>(1)), Q, 100*tol);\n}\n\n\ntemplate<class Real>\nvoid test_sinc_chebyshev_transform()\n{\n    using std::cos;\n    using std::sin;\n    using std::abs;\n    using boost::math::sinc_pi;\n    using boost::math::chebyshev_transform;\n    using boost::math::constants::half_pi;\n\n    Real tol = 100*std::numeric_limits<Real>::epsilon();\n    auto f = [](Real x) { return boost::math::sinc_pi(x); };\n    Real a = 0;\n    Real b = 1;\n    chebyshev_transform<Real> cheb(f, a, b, tol/50);\n\n    Real x = a;\n    while (x < b)\n    {\n        Real s = sinc_pi(x);\n        Real ds = (cos(x)-sinc_pi(x))/x;\n        if (x == 0) { ds = 0; }\n\n        CHECK_ABSOLUTE_ERROR(s, cheb(x), tol);\n        CHECK_ABSOLUTE_ERROR(ds, cheb.prime(x), 10*tol);\n        x += static_cast<Real>(1)/static_cast<Real>(1 << 7);\n    }\n\n    Real Q = cheb.integrate();\n    //NIntegrate[Sinc[x], {x, 0, 1}, WorkingPrecision -> 200, AccuracyGoal -> 150, PrecisionGoal -> 150, MaxRecursion -> 150]\n    Real Q_exp = boost::lexical_cast<Real>(\"0.94608307036718301494135331382317965781233795473811179047145477356668\");\n    CHECK_ABSOLUTE_ERROR(Q_exp, Q, tol);\n}\n\n\n\n//Examples taken from \"Approximation Theory and Approximation Practice\", by Trefethen\ntemplate<class Real>\nvoid test_atap_examples()\n{\n    using std::sin;\n    using std::exp;\n    using std::sqrt;\n    using boost::math::constants::half;\n    using boost::math::sinc_pi;\n    using boost::math::chebyshev_transform;\n    using boost::math::constants::half_pi;\n\n    Real tol = 10*std::numeric_limits<Real>::epsilon();\n    auto f1 = [](Real x) { return ((0 < x) - (x < 0)) - x/2; };\n    auto f2 = [](Real x) { Real t = sin(6*x); Real s = sin(x + exp(2*x));\n                           Real u = (0 < s) - (s < 0);\n                           return t + u; };\n\n    //auto f3 = [](Real x) { return sin(6*x) + sin(60*exp(x)); };\n    //auto f4 = [](Real x) { return 1/(1+1000*(x+half<Real>())*(x+half<Real>())) + 1/sqrt(1+1000*(x-Real(1)/Real(2))*(x-Real(1)/Real(2)));};\n    Real a = -1;\n    Real b = 1;\n    chebyshev_transform<Real> cheb1(f1, a, b, tol);\n    chebyshev_transform<Real> cheb2(f2, a, b, tol);\n    //chebyshev_transform<Real> cheb3(f3, a, b, tol);\n\n    Real x = a;\n    while (x < b)\n    {\n        // f1 and f2 are not differentiable; standard convergence rate theorems don't apply.\n        // Basically, the max refinements are always hit; so the error is not related to the precision of the type.\n        Real acceptable_error = sqrt(tol);\n        Real acceptable_error_2 = 9e-4;\n        if (std::is_same<Real, long double>::value)\n        {\n            acceptable_error = 1.6e-5;\n        }\n        if (std::is_same<Real, double>::value)\n        {\n            acceptable_error *= 500;\n        }\n        CHECK_ABSOLUTE_ERROR(f1(x), cheb1(x), acceptable_error);\n\n        CHECK_ABSOLUTE_ERROR(f2(x), cheb2(x), acceptable_error_2);\n        x += static_cast<Real>(1)/static_cast<Real>(1 << 7);\n    }\n}\n\n\n//Validate that the Chebyshev polynomials are well approximated by the Chebyshev transform.\ntemplate<class Real>\nvoid test_chebyshev_chebyshev_transform()\n{\n    Real tol = 500*std::numeric_limits<Real>::epsilon();\n    // T_0 = 1:\n    auto t0 = [](Real) { return 1; };\n    chebyshev_transform<Real> cheb0(t0, -1, 1);\n    CHECK_ABSOLUTE_ERROR(2, cheb0.coefficients()[0], tol);\n\n    Real x = -1;\n    while (x < 1)\n    {\n        CHECK_ABSOLUTE_ERROR(1, cheb0(x), tol);\n        CHECK_ABSOLUTE_ERROR(Real(0), cheb0.prime(x), tol);\n        x += static_cast<Real>(1)/static_cast<Real>(1 << 7);\n    }\n\n    // T_1 = x:\n    auto t1 = [](Real x) { return x; };\n    chebyshev_transform<Real> cheb1(t1, -1, 1);\n    CHECK_ABSOLUTE_ERROR(Real(1), cheb1.coefficients()[1], tol);\n\n    x = -1;\n    while (x < 1)\n    {\n        CHECK_ABSOLUTE_ERROR(x, cheb1(x), tol);\n        CHECK_ABSOLUTE_ERROR(Real(1), cheb1.prime(x), tol);\n        x += static_cast<Real>(1)/static_cast<Real>(1 << 7);\n    }\n\n\n    auto t2 = [](Real x) { return 2*x*x-1; };\n    chebyshev_transform<Real> cheb2(t2, -1, 1);\n    CHECK_ABSOLUTE_ERROR(Real(1), cheb2.coefficients()[2], tol);\n\n    x = -1;\n    while (x < 1)\n    {\n        CHECK_ABSOLUTE_ERROR(t2(x), cheb2(x), tol);\n        CHECK_ABSOLUTE_ERROR(4*x, cheb2.prime(x), tol);\n        x += static_cast<Real>(1)/static_cast<Real>(1 << 7);\n    }\n}\n\nint main()\n{\n#ifdef TEST1\n    test_chebyshev_chebyshev_transform<float>();\n    test_sin_chebyshev_transform<float>();\n    test_atap_examples<float>();\n    test_sinc_chebyshev_transform<float>();\n#endif\n#ifdef TEST2\n    test_chebyshev_chebyshev_transform<double>();\n    test_sin_chebyshev_transform<double>();\n    test_atap_examples<double>();\n    test_sinc_chebyshev_transform<double>();\n#endif\n#ifdef TEST3\n    test_chebyshev_chebyshev_transform<long double>();\n    test_sin_chebyshev_transform<long double>();\n    test_atap_examples<long double>();\n    test_sinc_chebyshev_transform<long double>();\n#endif\n#ifdef TEST4\n#ifdef BOOST_HAS_FLOAT128\n    test_chebyshev_chebyshev_transform<__float128>();\n    test_sin_chebyshev_transform<__float128>();\n    test_atap_examples<__float128>();\n    test_sinc_chebyshev_transform<__float128>();\n#endif\n#endif\n\n    return boost::math::test::report_errors();\n}\n\n\n", "meta": {"hexsha": "cae79cf6b9ddca34ac19c8a706c11d650d09d348", "size": 6643, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/chebyshev_transform_test.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": "test/chebyshev_transform_test.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": "Libs/boost_1_76_0/libs/math/test/chebyshev_transform_test.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "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": 30.1954545455, "max_line_length": 140, "alphanum_fraction": 0.6319433991, "num_tokens": 1997, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278633625322, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.7151891676388404}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main()\n{\n  MatrixXf m(2,2);\n  MatrixXf n(2,2);\n  MatrixXf result(2,2);\n\n  m << 1,2,\n       3,4;\n  n << 5,6,\n       7,8;\n\n  result = m * n;\n  cout << \"-- Matrix m*n: --\" << endl << result << endl << endl;\n  result = m.array() * n.array();\n  cout << \"-- Array m*n: --\" << endl << result << endl << endl;\n  result = m.cwiseProduct(n);\n  cout << \"-- With cwiseProduct: --\" << endl << result << endl << endl;\n  result = m.array() + 4;\n  cout << \"-- Array m + 4: --\" << endl << result << endl << endl;\n}\n", "meta": {"hexsha": "1014275116afd9366790b7d4cfe64dd8f65c820a", "size": 591, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Eigen-3.3/doc/examples/Tutorial_ArrayClass_interop_matrix.cpp", "max_stars_repo_name": "shareq2005/CarND-MPC-Project", "max_stars_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3457.0, "max_stars_repo_stars_event_min_datetime": "2018-06-09T15:36:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-01T22:09:25.000Z", "max_issues_repo_path": "src/Eigen-3.3/doc/examples/Tutorial_ArrayClass_interop_matrix.cpp", "max_issues_repo_name": "shareq2005/CarND-MPC-Project", "max_issues_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 851.0, "max_issues_repo_issues_event_min_datetime": "2017-11-27T15:09:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:26:38.000Z", "max_forks_repo_path": "src/Eigen-3.3/doc/examples/Tutorial_ArrayClass_interop_matrix.cpp", "max_forks_repo_name": "shareq2005/CarND-MPC-Project", "max_forks_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1380.0, "max_forks_repo_forks_event_min_datetime": "2017-06-12T23:58:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:52:48.000Z", "avg_line_length": 21.8888888889, "max_line_length": 71, "alphanum_fraction": 0.5211505922, "num_tokens": 196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505453836383, "lm_q2_score": 0.7905303285397349, "lm_q1q2_score": 0.715153692855778}}
{"text": "/** @file 16.cpp Problem 16: Power digit sum\n *\n * 2**15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.\n *\n * What is the sum of the digits of the number 2**1000?\n */\n\n#include \"cpp_int_util.hpp\"                 // sum_digits\n\n/// @cond\n#include <boost/multiprecision/cpp_int.hpp> // cpp_int\n\n#include <iostream>                         // cout\n/// @endcond\n\nusing boost::multiprecision::cpp_int;\n\nint sum(int n)\n{\n    cpp_int i = 1;\n    for (int p = 0; p < n; ++p)\n        i *= 2;\n    return cpp_int_util::sum_digits(i);\n}\n\nint main()\n{\n    assert(sum(15) == 26);\n    std::cout << sum(1000) << std::endl;\n}\n", "meta": {"hexsha": "64e7d0ca6ffe6ee4e03346f2201f23af4450979f", "size": 622, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/16.cpp", "max_stars_repo_name": "jeffs/cpp-euler", "max_stars_repo_head_hexsha": "b42a8a70fad782569a699a028968bc1a60bd5c44", "max_stars_repo_licenses": ["BSL-1.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": "src/16.cpp", "max_issues_repo_name": "jeffs/cpp-euler", "max_issues_repo_head_hexsha": "b42a8a70fad782569a699a028968bc1a60bd5c44", "max_issues_repo_licenses": ["BSL-1.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": "src/16.cpp", "max_forks_repo_name": "jeffs/cpp-euler", "max_forks_repo_head_hexsha": "b42a8a70fad782569a699a028968bc1a60bd5c44", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.064516129, "max_line_length": 69, "alphanum_fraction": 0.5546623794, "num_tokens": 197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942377652496, "lm_q2_score": 0.8031738034238806, "lm_q1q2_score": 0.7150610091122802}}
{"text": "// #define BOOST_TEST_DYN_LINK\n// #define BOOST_TEST_MODULE ShockFrontTests\n#include <boost/test/unit_test.hpp>\n\n#include <iostream>\n#include <memory>\n\n#include \"common/services/shockFront.hpp\"\n\nnamespace cs = ble::src::common::services;\n\nnamespace ble::tests::unit_tests::common::services::shock_front {\n\nvoid case1()\n{\n    // arrange\n    double expected = 0.33355000000000001;\n    double kmu = 0.125; // = mw / moil;\n    double n = 2.0;\n\n    // act\n    double actual = cs::shock_front::get_shock_front(n, kmu);\n\n    // assert\n    BOOST_CHECK_CLOSE(expected, actual, 1e-8);\n}\n\nvoid case2()\n{\n    // arrange\n    double expected = 0.8163999999999999; // wxmaxima gives 0.8164965809277261;\n    double kmu = 2.0; // = mw / moil;\n    double n = 2.0;\n\n    // act\n    double actual = cs::shock_front::get_shock_front(n, kmu);\n\n    // assert\n    BOOST_CHECK_CLOSE(expected, actual, 1e-8);\n}\n\n}", "meta": {"hexsha": "bcd51eae7acc3d591f068971c7a5069e131e77b8", "size": 886, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/unit_tests/common/services/shockFrontTests.cpp", "max_stars_repo_name": "erythrocyte/bleqt", "max_stars_repo_head_hexsha": "4abd7b2991e77d2cc344ecf3a1c3ee47d9d559d5", "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/unit_tests/common/services/shockFrontTests.cpp", "max_issues_repo_name": "erythrocyte/bleqt", "max_issues_repo_head_hexsha": "4abd7b2991e77d2cc344ecf3a1c3ee47d9d559d5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 71.0, "max_issues_repo_issues_event_min_datetime": "2020-09-04T13:52:54.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-04T20:19:49.000Z", "max_forks_repo_path": "tests/unit_tests/common/services/shockFrontTests.cpp", "max_forks_repo_name": "erythrocyte/ble", "max_forks_repo_head_hexsha": "b9e00bd02a3493de24fdb8d4edff4effcd62daa8", "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.0952380952, "max_line_length": 79, "alphanum_fraction": 0.664785553, "num_tokens": 269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942290328345, "lm_q2_score": 0.803173801068221, "lm_q1q2_score": 0.715061000001403}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <boost/numeric/mtl/mtl.hpp>\n#include <boost/numeric/itl/itl.hpp>\n\ntemplate <typename At, typename Lt, typename Ut>\nvoid dense_ilu_0(const At& As, const Lt& Ls, const Ut& Us)\n{\n    mtl::dense2D<double> LU(As);\n     \n    const std::size_t n= num_rows(LU);\n    for (std::size_t i= 1; i < n; i++) \n\tfor (std::size_t k= 0; k < i; k++) {\n\t    LU[i][k]/= LU[k][k];\n\t    for (std::size_t j= k + 1; j < n; j++)\n\t\tif (LU[i][j] != 0)\n\t\t    LU[i][j]-= LU[i][k] * LU[k][j];\n\t}\n    std::cout << \"Factorizing A = \\n\" << As << \"-> LU = \\n\" << LU;\n    // std::cout << \"L = \\n\" << Ls << \"\\nU = \\n\" << Us;\n\n    if (std::abs(LU[3][2] - Ls[3][2]) > 0.001) throw \"Wrong value in L for sparse ILU(0) factorization\";\n\n    if (std::abs(LU[3][3] - 1. / Us[3][3]) > 0.001) throw \"Wrong value in U for sparse ILU(0) factorization\";\n}\n\n\nint main()\n{\n    // For a more realistic example set sz to 1000 or larger\n    const int size = 3, N = size * size; \n\n    typedef mtl::compressed2D<double>  matrix_type;\n    mtl::compressed2D<double>          A(N, N), dia(N, N);\n    laplacian_setup(A, size, size);\n    // dia= 1.0; A+= dia;\n    \n   \n    itl::pc::ilu_0<matrix_type>        P(A);\n    mtl::dense_vector<double>          x(N, 1.0), b(N);\n    \n    if(size > 1 && size < 4)\n\tdense_ilu_0(A, P.get_L(), P.get_U());\n\n    b = A * x;\n    x= 0;\n    \n    itl::cyclic_iteration<double> iter(b, N, 1.e-6, 0.0, 5);\n    bicgstab(A, x, b, P, iter);\n    \n    return 0;\n}\n", "meta": {"hexsha": "b3bc2419d882b4cc00c84516c453312d40adaa54", "size": 1879, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/itl/test/ilu_0_bicgstab_test.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/itl/test/ilu_0_bicgstab_test.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/itl/test/ilu_0_bicgstab_test.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 29.8253968254, "max_line_length": 109, "alphanum_fraction": 0.5683874401, "num_tokens": 662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942348544447, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.7150609962882466}}
{"text": "// transition_dist.cpp\n// (c) 2021-01 David Merrell\n//\n// Implementation of TransitionDist class\n// and its subclasses.\n\n#define __STDCPP_WANT_MATH_SPEC_FUNCS__ 1\n\n#include \"transition_dist.h\"\n#include \"contingency_table.h\"\n#include <cmath>\n#include <string>\n\n//// If we're on __linux__, use the std::beta function\n//#ifdef __linux__\n//\n//float my_beta(float a, float b){\n//    return std::beta(a,b);\n//}\n//\n//// If we're on __APPLE__ or _WIN32, use the boost::math::beta function\n//// (which seems to be slower...)\n//#else\n\n#include <boost/math/special_functions/beta.hpp>\nfloat my_beta(float a, float b){\n    return boost::math::beta(a,b);\n}\n\n//#endif \n\n\n////////////////////////////////\n// Beta distribution\n////////////////////////////////\n\nfloat binom_coeff(int n, int k){\n    return 1.0/((n+1.0)*my_beta(n-k+1,k+1));\n}\n\nfloat binom_prob(int N, float p, int x){\n    return binom_coeff(N,x) * pow(p,x) * pow(1.0 - p, N-x);\n}\n\nstd::vector<float> initialize_binom_probs(int N, float p){\n    std::vector<float> probs = std::vector<float>(N+1, 0);\n    for(int i=0; i < N+1; i++){\n        probs[i] = binom_prob(N, p, i);\n    }\n    return probs;\n}\n\n\nBinomTransitionDist::BinomTransitionDist(float pr_a0, float pr_a1,\n                                         float pr_b0, float pr_b1){\n    prior_a0 = pr_a0;\n    prior_a1 = pr_a1;\n    prior_b0 = pr_b0;\n    prior_b1 = pr_b1;\n}\n\nvoid BinomTransitionDist::set_state_action(ContingencyTable ct, \n                                           short unsigned int a_size,\n                                           short unsigned int b_size){\n    // compute smoothed point estimates\n    float a_smoothing = prior_a0 + prior_a1;\n    float b_smoothing = prior_b0 + prior_b1;\n\n    float p_a = (float(ct.a1) + prior_a1) / (float(ct.a0 + ct.a1) + a_smoothing);\n    a_probs = initialize_binom_probs(a_size, p_a);\n\n    float p_b = (float(ct.b1) + prior_b1) / (float(ct.b0 + ct.b1) + b_smoothing);\n    b_probs = initialize_binom_probs(b_size, p_b);\n\n}\n\n\n////////////////////////////////\n// Beta-Binomial distribution\n////////////////////////////////\n\nfloat beta_binom_prob(int N, float pr_0, float pr_1, int x){\n    return binom_coeff(N,x) * my_beta(x+pr_1, N - x + pr_0) / my_beta(pr_1, pr_0);\n}\n\n\nstd::vector<float> initialize_beta_binom_probs(int N, float prior_0, float prior_1){\n    std::vector<float> probs = std::vector<float>(N+1, 0);\n    for(int i=0; i < N+1; i++){\n        probs[i] = beta_binom_prob(N, prior_0, prior_1, i);\n    }\n    return probs;\n}\n\n\nBetaBinomTransitionDist::BetaBinomTransitionDist(float pr_a0, float pr_a1,\n                                                 float pr_b0, float pr_b1){\n    prior_a0 = pr_a0;\n    prior_a1 = pr_a1;\n    prior_b0 = pr_b0;\n    prior_b1 = pr_b1;\n}\n\n\nvoid BetaBinomTransitionDist::set_state_action(ContingencyTable ct, \n                                          short unsigned int size_a,\n                                          short unsigned int size_b){\n    a_probs = initialize_beta_binom_probs(size_a, \n                                          ct.a0 + prior_a0,\n                                          ct.a1 + prior_a1);\n\n    b_probs = initialize_beta_binom_probs(size_b, \n                                          ct.b0 + prior_b0,\n                                          ct.b1 + prior_b1);\n}\n\n/////////////////////////////////\n// Factory method\n/////////////////////////////////\nTransitionDist* TransitionDist::make_transition_dist(std::string tr_dist_type,\n                                                     float pr_a0, float pr_a1,\n                                                     float pr_b0, float pr_b1){\n    if (tr_dist_type == \"binom\"){\n      return new BinomTransitionDist(pr_a0, pr_a1, pr_b0, pr_b1);\n    }\n    else if(tr_dist_type == \"beta_binom\"){\n      return new BetaBinomTransitionDist(pr_a0, pr_a1, pr_b0, pr_b1);\n    }\n    else{\n      std::cerr << tr_dist_type << \" not a valid value for transition distribution.\" << std::endl;\n      throw(1);\n    }\n\n}\n", "meta": {"hexsha": "e8c1d059e42d43108bf338a8aae4aab73c51f41f", "size": 3974, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/transition_dist.cpp", "max_stars_repo_name": "dpmerrell/blockRARopt", "max_stars_repo_head_hexsha": "10a52784ce75df92744112f6bc2d350f941cbdac", "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/transition_dist.cpp", "max_issues_repo_name": "dpmerrell/blockRARopt", "max_issues_repo_head_hexsha": "10a52784ce75df92744112f6bc2d350f941cbdac", "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/transition_dist.cpp", "max_forks_repo_name": "dpmerrell/blockRARopt", "max_forks_repo_head_hexsha": "10a52784ce75df92744112f6bc2d350f941cbdac", "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.437037037, "max_line_length": 98, "alphanum_fraction": 0.5546049321, "num_tokens": 1029, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628703, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.7149615192534826}}
{"text": "//\n//  EuropeanOption.cpp\n//  VI.3 Option Pricing\n//\n//  Created by Zhehao Li on 2020/4/27.\n//  Copyright \u00a9 2020 Zhehao Li. All rights reserved.\n//\n\n#include \"EuropeanOption.hpp\"\n#include <boost/math/distributions/normal.hpp>\n\n\n/* Private Memeber Functions */\n// Call price\ndouble EuropeanOption::CallPrice(double S) const{                   // S is the price of underlying assets\n    double tmp = sig * sqrt(T);\n    double d1 = ( log(S / K) + (b + (sig * sig) * 0.5 ) * T ) / tmp;\n    double d2 = d1 - tmp;\n\n    boost::math::normal_distribution<double> stdNormal(0.0, 1.0);   // Create a normal dstn object\n    \n    return ( S * exp((b - r) * T) * cdf(stdNormal, d1) ) - ( K * exp(- r * T) * cdf(stdNormal, d2) );\n}\n\n// Put price\ndouble EuropeanOption::PutPrice(double S) const{\n    double tmp = sig * sqrt(T);\n    double d1 = ( log(S / K) + (b + (sig * sig) * 0.5 ) * T ) / tmp;\n    double d2 = d1 - tmp;\n    \n    boost::math::normal_distribution<double> stdNormal(0.0, 1.0);   // Create a normal dstn object\n\n    return ( K * exp(- r * T) * cdf(stdNormal, -d2) ) - ( S * exp((b - r) * T) * cdf(stdNormal, -d1) );\n}\n\n// Call delta\ndouble EuropeanOption::CallDelta(double S) const{\n    double tmp = sig * sqrt(T);\n    double d1 = ( log(S / K) + (b + (sig * sig) * 0.5 ) * T ) / tmp;\n\n    boost::math::normal_distribution<double> stdNormal(0.0, 1.0);   // Create a normal dstn object\n    \n    return exp((b - r) * T) * cdf(stdNormal, d1);\n}\n\n// Put delta\ndouble EuropeanOption::PutDelta(double S) const{\n    double tmp = sig * sqrt(T);\n    double d1 = ( log(S / K) + (b + (sig * sig) * 0.5 ) * T ) / tmp;\n    \n    boost::math::normal_distribution<double> stdNormal(0.0, 1.0);   // Create a normal dstn object\n\n    return exp((b - r) * T) * ( cdf(stdNormal, d1) - 1.0 );\n}\n\n// Gamma\ndouble EuropeanOption::CallPutGamma(double S) const{\n    double tmp = S * sig * sqrt(T);\n    double d1 = ( log(S / K) + (b + (sig * sig) * 0.5 ) * T ) / tmp;\n    \n    boost::math::normal_distribution<double> stdNormal(0.0, 1.0);\n    \n    return exp((b - r) * T) * pdf(stdNormal, d1) / tmp;\n}\n\n\n\n/* Public Memeber Functions */\n// Default constructor\nEuropeanOption::EuropeanOption(): K(110.0), T(0.5), r(0.05), sig(0.2), b(0.05) {\n    //\n}\n\n// Copy constructor\nEuropeanOption::EuropeanOption(const EuropeanOption & option2) : K(option2.K), T(option2.T), r(option2.r), b(option2.b), sig(option2.sig) {\n    //\n}\n\n\n\n// Destructor\nEuropeanOption::~EuropeanOption() {}\n\n// Assignment Operators\nEuropeanOption & EuropeanOption::operator = (const EuropeanOption & option2) {\n    if (this == &option2) {\n        return *this;\n    }\n    else{\n        Option::operator=(option2);\n        K   = option2.K;\n        T   = option2.T;\n        r   = option2.r;\n        b   = option2.b;\n        sig = option2.sig;\n        \n        return *this;\n    }\n}\n\n// Accessing functions\n// Get the price of sensitvit of option\ndouble EuropeanOption::getValue(optionOutput output, double S) const{\n    \n    switch (output) {\n        case value:\n            return Value(S);\n        case delta:\n            return Delta(S);\n        case gama:\n            return Gamma(S);\n        default:\n            return 0;\n    }\n}\n\n// Compute the price of option\ndouble EuropeanOption::Value(double S) const{\n    if (optType == \"C\") {\n        return CallPrice(S);\n    }\n    else{\n        return PutPrice(S);\n    }\n}\n\n// Compute the delta of option\ndouble EuropeanOption::Delta(double S) const{\n    if (optType == \"C\") {\n        return CallDelta(S);\n    }\n    else{\n        return PutDelta(S);\n    }\n}\n\n// Compute the gamma of option\ndouble EuropeanOption::Gamma(double S) const{\n    return CallPutGamma(S);\n}\n\n// Put-Call Parity\ndouble EuropeanOption::PutCallParity(double S){\n    \n    if (optType == \"C\") {\n        double P = CallPrice(S) + K * exp(- r * T) - S;\n        return P;\n    }\n    else{\n        double C = PutPrice(S) + S - K * exp(- r * T);\n        return C;\n    }\n}\n\n// Check if Put-Call Party holds\nbool EuropeanOption::PutCallParity(double CP, double S){\n\n    double P = PutCallParity(S);\n    \n    if (fabs(P - CP) < 1e-4) {\n        return true;\n    }\n    else{\n        return false;\n    }\n}\n\n\n// Modifier functions\n// Change the type of option\nvoid EuropeanOption::toggle(){\n    \n    if (optType == \"C\") {\n        optType = \"P\";\n    }\n    else{\n        optType = \"C\";\n    }\n}\n\nvoid EuropeanOption::setValue(double val, optionInput input){\n    \n    switch (input) {\n        case strike:\n            K = val;\n            break;\n        case maturity:\n            T = val;\n            break;\n        case rate:\n            r = val;\n            break;\n        case cost:\n            b = val;\n            break;\n        case volatility:\n            sig = val;\n            break;\n        default:\n            break;\n    }\n}\n", "meta": {"hexsha": "fa5e1495532d959d1e9979f3c501427143a4173a", "size": 4774, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Level_9_HW/A&B_ExactPricingMethod/A&B_ExactPricingMethod/EuropeanOption.cpp", "max_stars_repo_name": "ZhehaoLi9705/QuantNet_CPP", "max_stars_repo_head_hexsha": "a889f4656e757842f4163b0cda7e098cc6ad1193", "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": "Level_9_HW/A&B_ExactPricingMethod/A&B_ExactPricingMethod/EuropeanOption.cpp", "max_issues_repo_name": "ZhehaoLi9705/QuantNet_CPP", "max_issues_repo_head_hexsha": "a889f4656e757842f4163b0cda7e098cc6ad1193", "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": "Level_9_HW/A&B_ExactPricingMethod/A&B_ExactPricingMethod/EuropeanOption.cpp", "max_forks_repo_name": "ZhehaoLi9705/QuantNet_CPP", "max_forks_repo_head_hexsha": "a889f4656e757842f4163b0cda7e098cc6ad1193", "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.5172413793, "max_line_length": 139, "alphanum_fraction": 0.5527859238, "num_tokens": 1382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133498259924, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.7149457081050642}}
{"text": "#include \"angular_gauss.hpp\"\n\n#include <array>\n#include <cassert>\n#include <cmath>\n\n#include <boost/math/special_functions/erf.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n\n#include \"types/types.hpp\"\n\nnamespace ublas = boost::numeric::ublas;\n\nvoid AngularGauss::InvMatrix(const ublas::matrix<double>& input_mat, ublas::matrix<double>& inverse_mat) {\n    ublas::matrix<double> A(input_mat);\n\n    ublas::permutation_matrix<std::size_t> pm(A.size1());\n    int factorization_status = ublas::lu_factorize(A, pm);\n    assert(factorization_status == 0);\n\n    inverse_mat.assign(ublas::identity_matrix<double>(A.size1()));\n    lu_substitute(A, pm, inverse_mat);\n}\n\ndouble AngularGauss::Det(const ublas::matrix<double>& m) const {\n    assert(m.size1() == 3 && m.size2() == 3);\n\n    const double a = m(0, 0);\n    const double b = m(0, 1);\n    const double c = m(0, 2);\n    const double d = m(1, 0);\n    const double e = m(1, 1);\n    const double f = m(1, 2);\n    const double g = m(2, 0);\n    const double h = m(2, 1);\n    const double k = m(2, 2);\n\n    const double determinant =\n        (a * ((e * k) - (f * h))) - (b * ((k * d) - (f * g))) + (c * ((d * h) - (e * g)));\n\n    return determinant;\n}\n\ndouble AngularGauss::InnerProduct(const Vector& x, const Vector& y) const {\n    double result = 0;\n    for (int i = 0; i < 3; ++i)\n        for (int j = 0; j < 3; ++j)\n            result += lambda(i, j) * x.at(i) * y.at(j);\n\n    return result;\n}\n\nAngularGauss::AngularGauss(const Vector& mean_vec, const ublas::matrix<double>& cov_mat) {\n    assert(cov_mat.size1() == 3 && cov_mat.size2() == 3);\n\n    std::copy(mean_vec.begin(), mean_vec.end(), mean.begin());\n    lambda = ublas::matrix<double>(3,3);\n    InvMatrix(cov_mat, lambda);\n    det_lambda = Det(lambda);\n    mean_norm  = std::sqrt(InnerProduct(mean, mean));\n}\n\ndouble AngularGauss::Calc(const CoordsOfPoint& u) const {\n    double u_norm = std::sqrt(InnerProduct(u, u));\n    double z      = InnerProduct(mean, u) / u_norm;\n\n    double coeff = std::exp(-0.5 * mean_norm * mean_norm) * std::sqrt(det_lambda) /\n                   (4 * M_PI * u_norm * u_norm * u_norm);\n\n    return coeff * (z * std::sqrt(M_2_PI) +\n                    std::exp(0.5 * z * z) * (1 + z * z) * (1 + boost::math::erf(z / M_SQRT2)));\n}\n\nconst std::array<double, 3> AngularGauss::Mean(void) const {\n    return std::array<double, 3>{mean};\n}\n", "meta": {"hexsha": "f1638c404ac21fcb4165a8d48e07d3decd945744", "size": 2400, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "server/distributions/angular_gauss.cpp", "max_stars_repo_name": "Bychin/uniformization-tool-on-sphere", "max_stars_repo_head_hexsha": "f5068d792aadb0dd8e694c348d068b6a8bcd8888", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-24T08:30:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-24T08:30:58.000Z", "max_issues_repo_path": "server/distributions/angular_gauss.cpp", "max_issues_repo_name": "Bychin/uniformization-tool-on-sphere", "max_issues_repo_head_hexsha": "f5068d792aadb0dd8e694c348d068b6a8bcd8888", "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": "server/distributions/angular_gauss.cpp", "max_forks_repo_name": "Bychin/uniformization-tool-on-sphere", "max_forks_repo_head_hexsha": "f5068d792aadb0dd8e694c348d068b6a8bcd8888", "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": 30.7692307692, "max_line_length": 106, "alphanum_fraction": 0.6070833333, "num_tokens": 741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133498259924, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.7149456979054108}}
{"text": "#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <boost/timer.hpp>\n#include <cassert>\n\n// O(NlogN)\nint kthMin1(std::vector<int>& data, int k) {\n    std::sort(data.begin(), data.end());\n\n    return data[k - 1];\n}\n\n// O(NlogN)\nint kthMin2(const std::vector<int>& data, int k) {\n    std::priority_queue<int> pq;\n    for (const auto& num : data) {\n        pq.push(num);\n        if (pq.size() > k) {\n            pq.pop();\n        }\n    }\n\n    return pq.top();\n}\n\n// O(N + klogN)\nint kthMin3(std::vector<int>& data, int k) {\n    std::make_heap(data.begin(), data.end(), std::greater<>());\n\n    for (int i = k - 1; i > 0; i--) {\n        std::pop_heap(data.begin(), data.end(), std::greater<>());\n        data.pop_back();\n    }\n\n    return data.front();\n}\n\nint partition(std::vector<int>& data, int low, int high) {\n    int i = low;\n    int j = high + 1;\n    int pivot = data[low];\n    while (true) {\n        while (data[++i] < pivot) {\n            if (i == high) break;\n        }\n\n        while (data[--j] > pivot) {\n            if (j == low) break;\n        }\n\n        if (i >= j) break;\n\n        std::swap(data[i], data[j]);\n    }\n\n    std::swap(data[low], data[j]);\n\n    return j;\n}\n\n// O(N) average case\nint kthMin4(std::vector<int>& data, int k) {\n    k--;\n    int low = 0;\n    int high = data.size() - 1;\n    while (high > low) {\n        int middle = partition(data, low, high);\n        if (middle == k) return data[k];\n        else if (middle > k) high = middle - 1;\n        else low = middle + 1;\n    }\n\n    return data[low];\n}\n\nstd::vector<std::vector<int>> createVectors(int row, int col) {\n    static std::uniform_int_distribution<int> distribution(\n            std::numeric_limits<int>::min(),\n            std::numeric_limits<int>::max()\n    );\n    static std::default_random_engine generator;\n\n    std::vector<int> data(col);\n    std::generate(data.begin(), data.end(),\n                  []() { return distribution(generator); });\n\n    return {row, data};\n}\n\n\nint main() {\n    const int NUMS_LENGTH = 100;\n    auto test_cases = createVectors(4, NUMS_LENGTH);\n\n    std::random_device device;\n    std::default_random_engine engine(device());\n    std::uniform_int_distribution<int> dist(1, 100);\n\n    const int K = dist(engine);\n\n    boost::timer t1;\n    int k1 = kthMin1(test_cases[0], K);\n    std::cout << t1.elapsed() * 1000 << std::endl;\n\n    boost::timer t2;\n    int k2 = kthMin2(test_cases[1], K);\n    std::cout << t2.elapsed() * 1000 << std::endl;\n\n    boost::timer t3;\n    int k3 = kthMin3(test_cases[2], K);\n    std::cout << t3.elapsed() * 1000 << std::endl;\n\n    boost::timer t4;\n    int k4 = kthMin4(test_cases[3], K);\n    std::cout << t4.elapsed() * 1000 << std::endl;\n\n    assert(k1 == k2 && k2 == k3 && k3 == k4);\n\n    return 0;\n}\n", "meta": {"hexsha": "66180a22debd219f7739a543168386ec150633cd", "size": 2783, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kth-min/main.cpp", "max_stars_repo_name": "JoshuaTang/blogs", "max_stars_repo_head_hexsha": "1f37e7c90d02ff6d8aed0a9842cfa3c8a7490ccb", "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": "kth-min/main.cpp", "max_issues_repo_name": "JoshuaTang/blogs", "max_issues_repo_head_hexsha": "1f37e7c90d02ff6d8aed0a9842cfa3c8a7490ccb", "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": "kth-min/main.cpp", "max_forks_repo_name": "JoshuaTang/blogs", "max_forks_repo_head_hexsha": "1f37e7c90d02ff6d8aed0a9842cfa3c8a7490ccb", "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": 22.6260162602, "max_line_length": 66, "alphanum_fraction": 0.5454545455, "num_tokens": 811, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.7147605857861317}}
{"text": "#include <gtest/gtest.h>\n\n#include \"helpers.hh\"\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\nusing namespace std;\nusing namespace Eigen;\n\nconst Vector3d origin(0, 0, 0);\n\nTEST (EigenTests, transforms)\n{\n  // Combine multiple translations, rotations (and scalings) by multiplying\n  // them together.\n\n  // Rotate around X by 90 degrees, then transform 1 unit along +Z (which is\n  // now pointing along -Y from the original frame due to the rotation.)\n\n  Affine3d transform(AngleAxisd(M_PI/2, Vector3d::UnitX()) * Translation3d(0, 0, 1));\n\n  // Use the right-hand-rule to determine the direction of rotations.\n\n  // Matrix multiplication is not commutative. Multiplying a set of transforms\n  // in different orders gives different results.\n\n  // Calculate the transform's effect on a point in space by multiplying the\n  // transform by the vector.\n\n  // Eigen's vector types are columns. They may only be post-multiplied with\n  // transformation matrices.\n\n  // Even though a transformation matrix may be both pre and post multiplied\n  // with a vector, Eigen only supports the latter.\n  // You multiply T*V. V*T will not compile.\n\n  EXPECT_TRUE ( VectorsEqual ( Vector3d(0, -1, 0), transform * origin ) );\n\n  // The transform not only moves points, but rotates them.\n  // Transforming non-origin values will demonstrate this.\n\n  EXPECT_TRUE ( VectorsEqual ( Vector3d(0, -1, 1), transform * Vector3d::UnitY() ) );\n\n  // It's more useful to think of transforms as operating upon coordinate\n  // frames rather than points. Transforms map points in one coordinate space\n  // to another.\n\n  // Consider a transform from the agent's torso frame to the frame of the\n  // left ankle. This simple example only involves translation, but the following\n  // discussion holds in the presence of rotations too.\n\n  Affine3d torsoLeftAnkle(Translation3d(\n    -0.074/2,\n    -0.005,\n    -0.1222 - 0.093 - 0.093));\n\n  // Multiplying by the origin gives:\n\n  EXPECT_TRUE ( VectorsEqual ( Vector3d(-0.074/2, -0.005, -0.1222 - 0.093 - 0.093),\n                               torsoLeftAnkle * origin ) );\n\n  // In this case, the vector multiplied should be considered in the 'ankle' frame.\n  // The result is position of the same point in the 'torso' frame.\n\n  // A convention we use in the code is to name transforms \"AB\", where A is one\n  // space, and B is another.\n\n  // In this way:\n  //   AB * Vb = Va\n\n  // `torsoLeftAnkle * origin` gives the position of the ankle's origin in\n  // the torso's frame:\n\n  // A transform may be inverted.\n  //   BA = AB.inverse()\n\n  Affine3d leftAnkleTorso(torsoLeftAnkle.inverse());\n\n  // `leftAnkleTorso * origin` gives the position of the torso's origin in\n  // the left ankle's frame:\n\n  EXPECT_TRUE ( VectorsEqual ( Vector3d(0.074/2, 0.005, 0.1222 + 0.093 + 0.093),\n                               leftAnkleTorso * origin ) );\n\n  // The transform may be deconstructed into translation and rotation components\n\n  EXPECT_TRUE ( VectorsEqual ( Vector3d(0, -1, 0), transform.translation() ) );\n\n  EXPECT_TRUE ( MatricesEqual ( AngleAxisd(M_PI/2, Vector3d::UnitX()).matrix(),\n                                transform.rotation() ) );\n}\n", "meta": {"hexsha": "f8be836c3da63bf5fd774163aed82bab2f10e43a", "size": 3152, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/EigenTests.cc", "max_stars_repo_name": "drewnoakes/bold-humanoid", "max_stars_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "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": "test/EigenTests.cc", "max_issues_repo_name": "drewnoakes/bold-humanoid", "max_issues_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "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": "test/EigenTests.cc", "max_forks_repo_name": "drewnoakes/bold-humanoid", "max_forks_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "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": 33.8924731183, "max_line_length": 85, "alphanum_fraction": 0.6849619289, "num_tokens": 829, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045966995028, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.7147605813132523}}
{"text": "/*\n * Copyright Nick Thompson, 2017\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#define BOOST_TEST_MODULE chebyshev_transform_test\n\n#include <boost/cstdfloat.hpp>\n#include <boost/type_index.hpp>\n#include <boost/test/included/unit_test.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/math/special_functions/chebyshev.hpp>\n#include <boost/math/special_functions/chebyshev_transform.hpp>\n#include <boost/math/special_functions/sinc.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n\n#if !defined(TEST1) && !defined(TEST2) && !defined(TEST3) && !defined(TEST4)\n#  define TEST1\n#  define TEST2\n#  define TEST3\n#  define TEST4\n#endif\n\nusing boost::multiprecision::cpp_bin_float_quad;\nusing boost::multiprecision::cpp_bin_float_50;\nusing boost::multiprecision::cpp_bin_float_100;\nusing boost::math::chebyshev_t;\nusing boost::math::chebyshev_t_prime;\nusing boost::math::chebyshev_u;\nusing boost::math::chebyshev_transform;\n\n\ntemplate<class Real>\nvoid test_sin_chebyshev_transform()\n{\n    using boost::math::chebyshev_transform;\n    using boost::math::constants::half_pi;\n    using std::sin;\n    using std::cos;\n    using std::abs;\n\n    Real tol = 10*std::numeric_limits<Real>::epsilon();\n    auto f = [](Real x) { return sin(x); };\n    Real a = 0;\n    Real b = 1;\n    chebyshev_transform<Real> cheb(f, a, b, tol);\n\n    Real x = a;\n    while (x < b)\n    {\n        Real s = sin(x);\n        Real c = cos(x);\n        if (abs(s) < tol)\n        {\n            BOOST_CHECK_SMALL(cheb(x), 100*tol);\n            BOOST_CHECK_CLOSE_FRACTION(c, cheb.prime(x), 100*tol);\n        }\n        else\n        {\n            BOOST_CHECK_CLOSE_FRACTION(s, cheb(x), 100*tol);\n            if (abs(c) < tol)\n            {\n                BOOST_CHECK_SMALL(cheb.prime(x), 100*tol);\n            }\n            else\n            {\n                BOOST_CHECK_CLOSE_FRACTION(c, cheb.prime(x), 100*tol);\n            }\n        }\n        x += static_cast<Real>(1)/static_cast<Real>(1 << 7);\n    }\n\n    Real Q = cheb.integrate();\n\n    BOOST_CHECK_CLOSE_FRACTION(1 - cos(static_cast<Real>(1)), Q, 100*tol);\n}\n\n\ntemplate<class Real>\nvoid test_sinc_chebyshev_transform()\n{\n    using std::cos;\n    using std::sin;\n    using std::abs;\n    using boost::math::sinc_pi;\n    using boost::math::chebyshev_transform;\n    using boost::math::constants::half_pi;\n\n    Real tol = 500*std::numeric_limits<Real>::epsilon();\n    auto f = [](Real x) { return boost::math::sinc_pi(x); };\n    Real a = 0;\n    Real b = 1;\n    chebyshev_transform<Real> cheb(f, a, b, tol/50);\n\n    Real x = a;\n    while (x < b)\n    {\n        Real s = sinc_pi(x);\n        Real ds = (cos(x)-sinc_pi(x))/x;\n        if (x == 0) { ds = 0; }\n        if (s < tol)\n        {\n            BOOST_CHECK_SMALL(cheb(x), tol);\n        }\n        else\n        {\n            BOOST_CHECK_CLOSE_FRACTION(s, cheb(x), tol);\n        }\n\n        if (abs(ds) < tol)\n        {\n            BOOST_CHECK_SMALL(cheb.prime(x), 5 * tol);\n        }\n        else\n        {\n            BOOST_CHECK_CLOSE_FRACTION(ds, cheb.prime(x), 300*tol);\n        }\n        x += static_cast<Real>(1)/static_cast<Real>(1 << 7);\n    }\n\n    Real Q = cheb.integrate();\n    //NIntegrate[Sinc[x], {x, 0, 1}, WorkingPrecision -> 200, AccuracyGoal -> 150, PrecisionGoal -> 150, MaxRecursion -> 150]\n    Real Q_exp = boost::lexical_cast<Real>(\"0.94608307036718301494135331382317965781233795473811179047145477356668\");\n    BOOST_CHECK_CLOSE_FRACTION(Q_exp, Q, tol);\n}\n\n\n\n//Examples taken from \"Approximation Theory and Approximation Practice\", by Trefethen\ntemplate<class Real>\nvoid test_atap_examples()\n{\n    using std::sin;\n    using boost::math::constants::half;\n    using boost::math::sinc_pi;\n    using boost::math::chebyshev_transform;\n    using boost::math::constants::half_pi;\n\n    Real tol = 10*std::numeric_limits<Real>::epsilon();\n    auto f1 = [](Real x) { return ((0 < x) - (x < 0)) - x/2; };\n    auto f2 = [](Real x) { Real t = sin(6*x); Real s = sin(x + exp(2*x));\n                           Real u = (0 < s) - (s < 0);\n                           return t + u; };\n\n    auto f3 = [](Real x) { return sin(6*x) + sin(60*exp(x)); };\n\n    auto f4 = [](Real x) { return 1/(1+1000*(x+half<Real>())*(x+half<Real>())) + 1/sqrt(1+1000*(x-.5)*(x-0.5));};\n    Real a = -1;\n    Real b = 1;\n    chebyshev_transform<Real> cheb1(f1, a, b);\n    chebyshev_transform<Real> cheb2(f2, a, b, tol);\n    //chebyshev_transform<Real> cheb3(f3, a, b, tol);\n\n    Real x = a;\n    while (x < b)\n    {\n        //Real s = f1(x);\n        if (sizeof(Real) == sizeof(float))\n        {\n           BOOST_CHECK_CLOSE_FRACTION(f1(x), cheb1(x), 4e-3);\n        }\n        else\n        {\n           BOOST_CHECK_CLOSE_FRACTION(f1(x), cheb1(x), 1.3e-5);\n        }\n        BOOST_CHECK_CLOSE_FRACTION(f2(x), cheb2(x), 5e-3);\n        //BOOST_CHECK_CLOSE_FRACTION(f3(x), cheb3(x), 100*tol);\n        x += static_cast<Real>(1)/static_cast<Real>(1 << 7);\n    }\n}\n\n//Validate that the Chebyshev polynomials are well approximated by the Chebyshev transform.\ntemplate<class Real>\nvoid test_chebyshev_chebyshev_transform()\n{\n    Real tol = 500*std::numeric_limits<Real>::epsilon();\n    // T_0 = 1:\n    auto t0 = [](Real) { return 1; };\n    chebyshev_transform<Real> cheb0(t0, -1, 1);\n    BOOST_CHECK_CLOSE_FRACTION(cheb0.coefficients()[0], 2, tol);\n\n    Real x = -1;\n    while (x < 1)\n    {\n        BOOST_CHECK_CLOSE_FRACTION(cheb0(x), 1, tol);\n        BOOST_CHECK_SMALL(cheb0.prime(x), tol);\n        x += static_cast<Real>(1)/static_cast<Real>(1 << 7);\n    }\n\n    // T_1 = x:\n    auto t1 = [](Real x) { return x; };\n    chebyshev_transform<Real> cheb1(t1, -1, 1);\n    BOOST_CHECK_CLOSE_FRACTION(cheb1.coefficients()[1], 1, tol);\n\n    x = -1;\n    while (x < 1)\n    {\n        if (x == 0)\n        {\n            BOOST_CHECK_SMALL(cheb1(x), tol);\n        }\n        else\n        {\n            BOOST_CHECK_CLOSE_FRACTION(cheb1(x), x, tol);\n        }\n        BOOST_CHECK_CLOSE_FRACTION(cheb1.prime(x), 1, tol);\n        x += static_cast<Real>(1)/static_cast<Real>(1 << 7);\n    }\n\n\n    auto t2 = [](Real x) { return 2*x*x-1; };\n    chebyshev_transform<Real> cheb2(t2, -1, 1);\n    BOOST_CHECK_CLOSE_FRACTION(cheb2.coefficients()[2], 1, tol);\n\n    x = -1;\n    while (x < 1)\n    {\n        BOOST_CHECK_CLOSE_FRACTION(cheb2(x), t2(x), tol);\n        if (x != 0)\n        {\n            BOOST_CHECK_CLOSE_FRACTION(cheb2.prime(x), 4*x, tol);\n        }\n        else\n        {\n            BOOST_CHECK_SMALL(cheb2.prime(x), tol);\n        }\n        x += static_cast<Real>(1)/static_cast<Real>(1 << 7);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(chebyshev_transform_test)\n{\n#ifdef TEST1\n    test_chebyshev_chebyshev_transform<float>();\n    test_sin_chebyshev_transform<float>();\n    test_atap_examples<float>();\n    test_sinc_chebyshev_transform<float>();\n#endif\n#ifdef TEST2\n    test_chebyshev_chebyshev_transform<double>();\n    test_sin_chebyshev_transform<double>();\n    test_atap_examples<double>();\n    test_sinc_chebyshev_transform<double>();\n#endif\n#ifdef TEST3\n    test_chebyshev_chebyshev_transform<long double>();\n    test_sin_chebyshev_transform<long double>();\n    test_atap_examples<long double>();\n    test_sinc_chebyshev_transform<long double>();\n#endif\n#ifdef TEST4\n#ifdef BOOST_HAS_FLOAT128\n    test_chebyshev_chebyshev_transform<__float128>();\n    test_sin_chebyshev_transform<__float128>();\n    test_atap_examples<__float128>();\n    test_sinc_chebyshev_transform<__float128>();\n#endif\n#endif\n}\n", "meta": {"hexsha": "9c65626f35e6fbc61758f379a086415f0982f33b", "size": 7618, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/math/test/chebyshev_transform_test.cpp", "max_stars_repo_name": "Bpowers4/turicreate", "max_stars_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11356.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T19:42:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:55:25.000Z", "max_issues_repo_path": "src/external/boost/boost_1_68_0/libs/math/test/chebyshev_transform_test.cpp", "max_issues_repo_name": "Bpowers4/turicreate", "max_issues_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2402.0, "max_issues_repo_issues_event_min_datetime": "2017-12-08T22:31:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:25:52.000Z", "max_forks_repo_path": "src/external/boost/boost_1_68_0/libs/math/test/chebyshev_transform_test.cpp", "max_forks_repo_name": "Bpowers4/turicreate", "max_forks_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 29.0763358779, "max_line_length": 125, "alphanum_fraction": 0.6094775532, "num_tokens": 2270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.7146232323290418}}
{"text": "/***********************************************************************\nThis file is part of the librjmcmc project source files.\n\nCopyright : Institut Geographique National (2008-2012)\nContributors : Mathieu Br\u00e9dif, Olivier Tournaire, Didier Boldo\nemail : librjmcmc@ign.fr\n\nThis software is a generic C++ library for stochastic optimization.\n\nThis software is governed by the CeCILL license under French law and\nabiding by the rules of distribution of free software. You can use,\nmodify and/or redistribute the software under the terms of the CeCILL\nlicense as circulated by CEA, CNRS and INRIA at the following URL\n\"http://www.cecill.info\".\n\nAs a counterpart to the access to the source code and rights to copy,\nmodify and redistribute granted by the license, users are provided only\nwith a limited warranty and the software's author, the holder of the\neconomic rights, and the successive licensors have only limited liability.\n\nIn this respect, the user's attention is drawn to the risks associated\nwith loading, using, modifying and/or developing or reproducing the\nsoftware by the user in light of its specific status of free software,\nthat may mean that it is complicated to manipulate, and that also\ntherefore means that it is reserved for developers and experienced\nprofessionals having in-depth computer knowledge. Users are therefore\nencouraged to load and test the software's suitability as regards their\nrequirements in conditions enabling the security of their systems and/or\ndata to be ensured and, more generally, to use and operate it in the\nsame conditions as regards security.\n\nThe fact that you are presently reading this means that you have had\nknowledge of the CeCILL license and that you accept its terms.\n\n***********************************************************************/\n\n#ifndef __GAMMA_DISTRIBUTION_HPP__\n#define __GAMMA_DISTRIBUTION_HPP__\n\n#include <boost/random/gamma_distribution.hpp>\n#include <boost/math/distributions/gamma.hpp>\n\nnamespace rjmcmc {\n\n    // beta^alpha * x^(alpha-1) * exp(-beta * x) / Gamma(alpha)\n    class gamma_distribution {\n    public:\n        typedef double real_type;\n        typedef boost::gamma_distribution<real_type>          rand_distribution_type;\n        typedef boost::math::gamma_distribution<real_type>    math_distribution_type;\n\n        gamma_distribution(real_type alpha, real_type beta)\n            : m_rand(alpha,beta)\n            , m_math(alpha,1./beta)\n        {}\n\n        // new/old: (mean^(n1-n0) * n0! / n1!\n        real_type pdf_ratio(real_type x0, real_type x1) const\n        {\n            return pow(x1/x0,m_rand.alpha()-1)*exp(m_rand.beta()*(x0-x1));\n        }\n\n        real_type pdf(real_type x) const\n        {\n            return boost::math::pdf(m_math, x);\n        }\n\n        template<typename Engine>\n        inline real_type operator()(Engine& e) const { return m_rand(e); }\n\n    private:\n        mutable rand_distribution_type m_rand;\n        math_distribution_type m_math;\n    };\n\n}; // namespace rjmcmc\n\n#endif // __GAMMA_DISTRIBUTION_HPP__\n", "meta": {"hexsha": "61b238d8f3cfa6bd25f20a2338bfff2e232618e5", "size": 3035, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/rjmcmc/rjmcmc/distribution/gamma_distribution.hpp", "max_stars_repo_name": "qc2105/librjmcmc", "max_stars_repo_head_hexsha": "6e031a9f6f3612394f8918c745700ae41d2aa586", "max_stars_repo_licenses": ["CECILL-B"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2015-02-17T17:07:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-02T16:49:02.000Z", "max_issues_repo_path": "include/rjmcmc/rjmcmc/distribution/gamma_distribution.hpp", "max_issues_repo_name": "qc2105/librjmcmc", "max_issues_repo_head_hexsha": "6e031a9f6f3612394f8918c745700ae41d2aa586", "max_issues_repo_licenses": ["CECILL-B"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2015-09-24T09:39:33.000Z", "max_issues_repo_issues_event_max_datetime": "2016-01-03T13:22:49.000Z", "max_forks_repo_path": "include/rjmcmc/rjmcmc/distribution/gamma_distribution.hpp", "max_forks_repo_name": "qc2105/librjmcmc", "max_forks_repo_head_hexsha": "6e031a9f6f3612394f8918c745700ae41d2aa586", "max_forks_repo_licenses": ["CECILL-B"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2015-03-18T17:32:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-04T21:38:16.000Z", "avg_line_length": 38.417721519, "max_line_length": 85, "alphanum_fraction": 0.7008237232, "num_tokens": 652, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096067182449, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.714558993779978}}
{"text": "#include <dlib/global_optimization.h>\n#include <dlib/matrix.h>\n#include <dlib/svm.h>\n\n#include <plot.h>\n\n#include <iostream>\n#include <random>\n#include <vector>\n\nusing SampleType = dlib::matrix<double, 1, 1>;\nusing Samples = std::vector<SampleType>;\nusing Labels = std::vector<SampleType>;\n\nSamples LinSpace(double s, double e, size_t n) {\n  Samples x_values(n);\n  double step = (e - s) / n;\n  double v = s;\n  for (size_t i = 0; i < n; ++i) {\n    x_values[i](0, 0) = v;\n    v += step;\n  }\n  x_values[n - 1] = e;\n\n  return x_values;\n}\n\nstd::pair<Samples, Labels> GenerateData(size_t num_samples, size_t seed) {\n  Samples x_values(num_samples);\n  Labels y_values(num_samples);\n\n  std::mt19937 re(seed);\n  std::normal_distribution<double> dist;\n\n  for (size_t i = 0; i < num_samples; ++i) {\n    auto x_val = dist(re);\n    x_values[i](0, 0) = x_val;\n\n    auto y_val = std::cos(M_PI * x_val) + (dist(re) * 0.3);\n    y_values[i](0, 0) = y_val;\n  }\n  return {x_values, y_values};\n}\n\nint main(int /*argc*/, char** /*argv*/) {\n  using namespace dlib;\n\n  // Generate data\n  Samples samples;\n  Labels labels;\n  std::tie(samples, labels) = GenerateData(1000, 435635);\n\n  auto mm = std::minmax_element(\n      samples.begin(), samples.end(),\n      [](const auto& a, const auto& b) { return a(0, 0) < b(0, 0); });\n  std::pair<double, double> x_minmax{*mm.first, *mm.second};\n\n  // Normalize data\n  vector_normalizer<SampleType> x_normalizer;\n  x_normalizer.train(samples);\n  std::for_each(samples.begin(), samples.end(), x_normalizer);\n\n  vector_normalizer<SampleType> y_normalizer;\n  y_normalizer.train(labels);\n  std::for_each(labels.begin(), labels.end(), y_normalizer);\n\n  std::vector<double> raw_labels(labels.size());\n  for (size_t i = 0; i < labels.size(); ++i) {\n    raw_labels[i] = labels[i](0, 0);\n  }\n\n  // Randomize data\n  randomize_samples(samples, raw_labels);\n\n  // Define cross validation function\n  auto CrossValidationScore = [&](const double gamma, const double c,\n                                  const double degree_in) {\n    auto degree = std::floor(degree_in);\n    using KernelType = dlib::polynomial_kernel<SampleType>;\n    dlib::svr_trainer<KernelType> trainer;\n    trainer.set_kernel(KernelType(gamma, c, degree));\n\n    std::cout << \"gamma: \" << std::setw(11) << gamma << \"  c: \" << std::setw(11)\n              << c << \"  degree: \" << std::setw(11) << degree;\n    std::cout.flush();\n\n    dlib::matrix<double> result = dlib::cross_validate_regression_trainer(\n        trainer, samples, raw_labels, 10);\n    std::cout << std::setw(11) << \"  MSE: \" << result(0, 0) << std::setw(11)\n              << \"  MAE: \" << result(0, 2) << std::endl;\n\n    return result(0, 0);\n  };\n\n  // Search for the best parameters\n  auto result = find_min_global(\n      CrossValidationScore,\n      {0.01, 1e-8, 5},  // minimum values for gamma, c, and degree\n      {0.1, 1, 15},     // maximum values for gamma, c, and degree\n      max_function_calls(50));\n\n  double gamma = result.x(0);\n  double c = result.x(1);\n  double degree = result.x(2);\n\n  std::cout << \" best cross validation score: \" << result.y << std::endl;\n  std::cout << \" best gamma: \" << gamma << \"   best c: \" << c\n            << \"    best degree: \" << degree << std::endl;\n\n  // Train model\n  using KernelType = dlib::polynomial_kernel<SampleType>;\n  dlib::svr_trainer<KernelType> trainer;\n  trainer.set_kernel(KernelType(gamma, c, degree));\n  auto descision_func = trainer.train(samples, raw_labels);\n\n  // Plot perdictions\n  auto new_samples = LinSpace(x_minmax.first, x_minmax.second, 50);\n  std::for_each(new_samples.begin(), new_samples.end(), x_normalizer);\n\n  std::vector<double> predictions(new_samples.size());\n  std::transform(new_samples.begin(), new_samples.end(), predictions.begin(),\n                 descision_func);\n\n  plotcpp::Plot plt;\n  plt.SetTerminal(\"png\");\n  plt.SetOutput(\"plot.png\");\n  plt.SetTitle(\"SVM Polynomial kernel regression\");\n  plt.SetXLabel(\"x\");\n  plt.SetYLabel(\"y\");\n  plt.SetAutoscale();\n  plt.GnuplotCommand(\"set grid\");\n\n  std::vector<double> x_coords(samples.size());\n  std::transform(samples.begin(), samples.end(), x_coords.begin(),\n                 [](auto& m) { return m(0, 0); });\n\n  std::vector<double> x_pred_coords(new_samples.size());\n  std::transform(new_samples.begin(), new_samples.end(), x_pred_coords.begin(),\n                 [](auto& m) { return m(0, 0); });\n\n  plt.Draw2D(plotcpp::Points(x_coords.begin(), x_coords.end(),\n                             raw_labels.begin(), \"orig\", \"lc rgb 'black' pt 7\"),\n             plotcpp::Lines(x_pred_coords.begin(), x_pred_coords.end(),\n                            predictions.begin(), \"pred\", \"lc rgb 'red' lw 2\"));\n  plt.Flush();\n\n  return 0;\n}\n", "meta": {"hexsha": "8e6aa1ad636cc57618717e2746cd2cc4fe600914", "size": 4697, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Chapter03/dlib/grid-dlib.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": "Chapter03/dlib/grid-dlib.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": "Chapter03/dlib/grid-dlib.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": 31.5234899329, "max_line_length": 80, "alphanum_fraction": 0.6255056419, "num_tokens": 1326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070011518829, "lm_q2_score": 0.7853085909370423, "lm_q1q2_score": 0.7145577849583349}}
{"text": "#include <iostream>\n#include <array>\n#include <cmath>\n#include <tuple>\n#include <cassert>\n#include <NTL/ZZ.h>\n#include <NTL/vector.h>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\nusing namespace NTL;\n\n//ex. compile:\n//g++ -o <exe> remainder_alg_first_pass.cpp -std=c++11 -march=native -O2 -lntl -lgmp -lgmpxx -pthread\n\n\n// to compile and run on linux use\n// g++ -o <executable file name> remainder_alg_first_pass.cpp\n// ./<executable file name>\n\n\n//note that everywhere it says 'int' we will eventually want to use GMP or whatnot\n//ints are too small...\n\n//translates indices in trees to indices in arrays\n//if you want left child of (i,j), do (i+1, 2*j)\n//right child is (i+1, 2*j+1), and parent is (i-1, j//2)\nint flatten_index(int i, int j)\n{\n\tassert (j <= pow(2,i) - 1);\n\treturn pow(2,i) +j-1;\n}\n\n//gives tree indices from array index\ntuple<int, int> lift_index(int k)\n{\n\tint i = log2(k+1);\n\tint j = k + 1 - pow(2,i);\n\n\treturn make_tuple(i,j);\n}\n\n\nvoid print_tree(Vec<ZZ> & X)\n{\n\tcout << endl;\n\tfor (int i = 0; i < X.length(); i++)\n\t{\n\t\tcout << X[i] << \" , \";\n\t}\n\tcout << endl;\n}\n\n\n//reflects a tree on the y-axis in place\nvoid reflect_tree(Vec<ZZ> & X) //why doesn't mutability work the way I think it does?\n{\n\tint depth = log2(X.length());\n\n\tfor (int i = 1; i <= depth; i++)\n\t{\n\t\tint width = pow(2,i);\n\n\t\tfor (int j = 0; 2*j < width; j++)\n\t\t{\n\t\t\tint a = flatten_index(i,j);\n\t\t\tint b = flatten_index(i, width-j-1);\n\n\t\t\t//this switches the two locations\n\t\t\tX[b] = X[a]^X[b];\n\t\t\tX[a] = X[a]^X[b];\n\t\t\tX[b] = X[a]^X[b];\n\t\t}\n\t}\n}\n\nVec<ZZ> zero_vector(int N)\n{\n\tVec<ZZ> ret;\n\tret.SetLength(N);\n\tfor (int i = 0; i < N; i++)\n\t{\n\t\tret[i] = 0;\n\t}\n\n\treturn ret;\n}\n\n//given an array of size N, returns the product tree of size 2N\n//assumes N is a power of 2\n//it won't have to be (we can pad it etc.) but this is just a preliminary version\nVec<ZZ> product_tree(Vec<ZZ> &X, Vec<ZZ> &mtree)\n{\n\n\t//INPUT: a list of integers; OUTPUT: a product tree of double the size\n\tint depth = log2(X.length()); //round this UP when not power of 2\n\n\tVec<ZZ> ptree;\n\tptree = zero_vector(2*X.length()-1);\n\n\n\n\t//initialize leaves\n\tfor (int j = 0; j < pow(2, depth); j++)\n\t{\n\t\tint leaf = flatten_index(depth,j);\n\n\t\tptree[leaf] = X[j];\n\n\t\tif (mtree[leaf] != 0)\n\t\t{\n\t\t\tptree[leaf] %= mtree[leaf];\n\t\t}\n\t}\n\n\n\n\t//build up the product tree recursively\n\tfor (int i = depth-1; i >= 0; i--)\n\t{\n\t\tfor (int j = 0; j < pow(2,i); j++)\n\t\t{\n\t\t\tint parent = flatten_index(i,j);\n\t\t\tint left = 2*parent + 1;\n\t\t\tint right = left + 1;\n\n\t\t\t//padding is not necessary if on this step we catch IndexError with 1\n\t\t\tptree[parent] = ptree[left]*ptree[right];\n\n\t\t\tif (mtree[parent] != 0)\n\t\t\t{\n\t\t\t\tptree[parent] %= mtree[parent];\n\t\t\t}\n\n\t\t}\n\t}\n\n\treturn ptree;\n}\n\n\nVec<ZZ> accumulating_tree(Vec<ZZ> &X, Vec<ZZ> &mtree)\n{\n\t//code cut from body of accumulating_remainder_tree\n\t//this can be used to store the product tree of A modulo the mi\n\t//this can be applied to any tree; for our applications we will only apply it to product trees\n\t//INPUT: a tree; OUTPUT: accumulating tree (of same size)\n\tassert (X.length() == mtree.length());\n\n\tint depth = log2(X.length());\n\n\tVec<ZZ> acctree;\n\tacctree.SetLength(X.length());\n\tacctree[0] = 1;\n\n\tfor (int i = 0; i < depth; i++)\n\t{\n\t\tfor (int j = 0; j < pow(2,i); j++)\n\t\t{\n\t\t\tint parent = flatten_index(i,j);\n\t\t\tint left = 2*parent + 1;\n\t\t\tint right = left+1;\n\n\t\t\tacctree[left] = acctree[parent];\n\t\t\tacctree[right] = acctree[parent]*X[left];\n\n\t\t\tif (mtree[left] != 0)\n\t\t\t{\n\t\t\t\tacctree[left] %= mtree[left];\n\t\t\t}\n\n\t\t\tif (mtree[right] != 0)\n\t\t\t{\n\t\t\t\tacctree[right] %= mtree[right];\n\t\t\t}\n\t\t}\n\t}\n\n\treturn acctree;\n\n}\n\n\n\n//so might make sense to pad beginning of m with a 1, and pad end of A with a 1\n//given A0, A1, ... An, and m0, m1, ... mn, this returns\n//1, A0 mod m1, A0*A1 mod m2, ... A0*...An-1 mod mn\nVec<ZZ> accumulating_remainder_tree(Vec<ZZ> &A, Vec<ZZ> &m)\n{\n\tassert (A.length() == m.length());\n\n\tint depth = log2(A.length());\n\n\tVec<ZZ> ztree = zero_vector(2*m.length()-1);\n\n\tVec<ZZ> m_ptree = product_tree(m, ztree);\n\n\t//print_tree(m_ptree);\n\treflect_tree(m_ptree);\n\tVec<ZZ> m_acctree = accumulating_tree(m_ptree, ztree);\n\treflect_tree(m_acctree);\n\treflect_tree(m_ptree);\n\n\t//Vec<ZZ> m_acctree = reflect_tree(accumulating_tree(reflect_tree(m_ptree), ztree));\n\n\t//print_tree(m_acctree);\n\n\t//this power tree is reduced modulo the reflected m_ftree\n\tVec<ZZ> A_ptree = product_tree(A, m_acctree);\n\t//delete m_acctree;\n\n\t//print_tree(A_ptree);\n\n\tVec<ZZ> A_rtree = accumulating_tree(A_ptree, m_ptree);\n\n\t//print_tree(A_rtree);\n\n\t//need a nice array slice here...\n\tVec<ZZ> C;\n\tC.SetLength(A.length());\n\n\tfor (int j = 0; j < pow(2,depth); j++)\n\t{\n\t\tC[j] = A_rtree[flatten_index(depth, j)];\n\t}\n\n\treturn C;\n\t\n}\n\n\n\nint main()\n{\n\tlong N = pow(2,16);\n\n\tVec<ZZ> A;\n\tVec<ZZ> m;\n\n\tA.SetLength(N);\n\tm.SetLength(N);\n\n\trandom_device rd;\n\tmt19937 mt(rd());\n\tuniform_int_distribution<int> dist(1, N);\n\n\tfor(int i = 0; i < N; i++){\n\t\tint bitsize = log2(i+1)+2;\n\n\t\t\n\t\tA[i] = dist(mt);\n\t\tm[i] = dist(mt);\n\n\t}\n\n\n\t//Vec<ZZ> ztree = zero_vector(2*N);\n\n\t//print_tree(A);\n\t//print_tree(m);\n\n\tauto start = chrono::high_resolution_clock::now();\n\tVec<ZZ> remainders = accumulating_remainder_tree(A,m);\n\tauto finish = chrono::high_resolution_clock::now();\n\n\tchrono::duration<double> runtime = finish-start;\n\n\t//print_tree(remainders);\n\tcout << runtime.count() << endl;\n\n\n\n\n}", "meta": {"hexsha": "e928af046e4c4a6c39a04147c8ee7a9b17ec1f5d", "size": 5346, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "archives/remainder_alg_first_pass.cpp", "max_stars_repo_name": "adienes/remainder-tree", "max_stars_repo_head_hexsha": "0aa76214ab6f2a4389ec45a239ea660749989a90", "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": "archives/remainder_alg_first_pass.cpp", "max_issues_repo_name": "adienes/remainder-tree", "max_issues_repo_head_hexsha": "0aa76214ab6f2a4389ec45a239ea660749989a90", "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": "archives/remainder_alg_first_pass.cpp", "max_forks_repo_name": "adienes/remainder-tree", "max_forks_repo_head_hexsha": "0aa76214ab6f2a4389ec45a239ea660749989a90", "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.3695652174, "max_line_length": 101, "alphanum_fraction": 0.6260755705, "num_tokens": 1756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.7143631541341697}}
{"text": "//\n//  main.cpp\n//  NRM - Newton-Raphson Method (for regression problem)\n//\n//  Created by Zhalgas Baibatyr on 1/19/16.\n//  Copyright \u00a9 2016 Zhalgas Baibatyr. All rights reserved.\n//\n\n/*\n\n    DEGREE ----- the degree of a polynomial in regression function\n    N_SAMPLES -- number of training samples\n    N_FEATURES - number of given input features\n    Hessian ---- Hessian matrix\n    features --- input features, including intercept term (x\u2092 = 1)\n    target ----- target (output) values\n    params ----- parameters (weights) with initial values (zeros)\n    hypothesis - hypothesis function\n    dCost ------ derivative of a cost function\n\n*/\n\n#include <armadillo>\n\nusing namespace arma;\n\nint main()\n{\n    /* Loading initial data: */\n    mat initData;\n    initData.load(\"../data/regression1\", arma_ascii);\n\n    /* Initializing constants: */\n    const uword DEGREE = 5;\n    const uword N_SAMPLES  = initData.n_rows;\n    const uword N_FEATURES = initData.n_cols - 1;\n\n    /* Transforming input data using polynomial formula: */\n    mat features(N_SAMPLES, DEGREE * N_FEATURES + 1);\n    features.col(0) = ones<vec>(N_SAMPLES);\n    for (int i = 0; i < N_FEATURES; ++i)\n    {\n        for (int j = 1; j <= DEGREE; ++j)\n        {\n            features.col(i * DEGREE + j) = pow(initData.col(i), j);\n        }\n    }\n\n    /* Preparing other data: */\n    vec target = initData.col(initData.n_cols - 1);\n    vec params = zeros<vec>(features.n_cols);\n    vec hypothesis;\n    vec dCost;\n    mat Hessian;\n\n    wall_clock timer;\n    double elapsedTime;\n    timer.tic();\n\n    /* Newton-Raphson Method performs here: */\n    Hessian = features.t() * features;\n    while (true)\n    {\n        /* Calculating hypothesis values and updating parameters: */\n        hypothesis = features * params;\n        dCost = features.t() * (hypothesis - target) / N_SAMPLES;\n        params -= Hessian.i() * dCost;\n     /* params -= solve(Hessian, dCost); */\n\n        /* Checking how close to the minimum: */\n        if (norm(dCost) < 1e-5)\n        {\n            hypothesis = features * params;\n            break;\n        }\n    }\n\n    /* Measuring the performance of the algorithm: */\n    elapsedTime = timer.toc();\n    printf(\"Elapsed time: %f sec.\\n\\n\", elapsedTime);\n\n    mat outputData = join_rows(initData.cols(0, initData.n_cols - 2), hypothesis);\n    outputData.save(\"outputData\", arma_ascii);\n    hypothesis.save(\"hypothesis\", arma_ascii);\n    params.save(\"params\", arma_ascii);\n\n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "fc9f62ed9b824d6b4b1b6dbf7952198e6e19774f", "size": 2475, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Regression/NRM/main.cpp", "max_stars_repo_name": "presscorp/ML", "max_stars_repo_head_hexsha": "6a77577fbeb5e5e6a80bf404504634d5d47f191b", "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": "Regression/NRM/main.cpp", "max_issues_repo_name": "presscorp/ML", "max_issues_repo_head_hexsha": "6a77577fbeb5e5e6a80bf404504634d5d47f191b", "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": "Regression/NRM/main.cpp", "max_forks_repo_name": "presscorp/ML", "max_forks_repo_head_hexsha": "6a77577fbeb5e5e6a80bf404504634d5d47f191b", "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.808988764, "max_line_length": 82, "alphanum_fraction": 0.6185858586, "num_tokens": 624, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894520743981, "lm_q2_score": 0.7981867777396211, "lm_q1q2_score": 0.7142091095066649}}
{"text": "#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/random_convex_hull_in_disc_2.h>\n#include <CGAL/Polygon_2_algorithms.h>\n#include <boost/random.hpp>\n#include <iostream>\n#include <vector>\nusing namespace CGAL;\n\ntypedef Exact_predicates_inexact_constructions_kernel          K;\ntypedef K::Point_2                                       Point;\ntypedef K::FT                                                                                 FT;\n\nconst double RADIUS=1.0;\nint main( )\n{\n   int N=10000;\n   std::vector<Point> v;\n   boost::mt19937 gen;\n   gen.seed(0u);\n\n   random_convex_hull_in_disc_2(N,RADIUS,gen,std::back_inserter(v),K());\n   size_t size = v.size();\n   FT area=polygon_area_2(v.begin(),v.end(),K());\n   std::cout<<\"A random convex polygon inscribed in a disc with \"<<size<<\" vertices and area \"<<area<<\" has been generated.\"<<std::endl;\n\n   return 0;\n}\n", "meta": {"hexsha": "02c5a2c245f10555052de2f728f394367b50807f", "size": 892, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Generator/examples/Generator/random_convex_hull_2.cpp", "max_stars_repo_name": "ffteja/cgal", "max_stars_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 3227.0, "max_stars_repo_stars_event_min_datetime": "2015-03-05T00:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:20:35.000Z", "max_issues_repo_path": "Generator/examples/Generator/random_convex_hull_2.cpp", "max_issues_repo_name": "ffteja/cgal", "max_issues_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 5574.0, "max_issues_repo_issues_event_min_datetime": "2015-03-05T00:01:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:08:11.000Z", "max_forks_repo_path": "Generator/examples/Generator/random_convex_hull_2.cpp", "max_forks_repo_name": "ffteja/cgal", "max_forks_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1274.0, "max_forks_repo_forks_event_min_datetime": "2015-03-05T00:01:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:47:56.000Z", "avg_line_length": 31.8571428571, "max_line_length": 136, "alphanum_fraction": 0.6244394619, "num_tokens": 220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693731004241, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.7141633094861031}}
{"text": "#include \"testsuite.h\"\n#include <blitz/array.h>\n#include <blitz/tinyvec2.h>\n\nBZ_USING_NAMESPACE(blitz)\n\nclass crap {\npublic:\n  double operator()(double x) const {return x+1;};\n  BZ_DECLARE_FUNCTOR(crap);\n};\n\ntemplate<typename T>\nvoid test_1d(T& B)\n{\n  B = -2, 5, 4, 3, 1, 1;\n\n    BZTEST(sum(B) == 12);\n    BZTEST(mean(B) == 2);\n    BZTEST(min(B) == -2);\n    BZTEST(max(B) == 5);\n    BZTEST(product(B) == -120);\n    BZTEST(first(B>0) == 1);\n    BZTEST(last(B>3) == 2);\n    BZTEST(count(B>0) == 5);\n    BZTEST(any(B>0));\n    BZTEST(!any(B>10));\n    BZTEST(!all(B>0));\n    BZTEST(all(B>-10));\n\n    BZTEST(all(maxIndex(B)==1));\n    BZTEST(all(minIndex(B)==0));\n\n    MinMaxValue<int> mm=minmax(B);\n    BZTEST(mm.min==-2);\n    BZTEST(mm.max==5);\n}\n\n// pass in an expression with value\n// (-2, 5, 4, 3, 1, 1)\ntemplate<typename T>\nvoid test_1dexpr(const T& B)\n{\n    BZTEST(sum(B) == 12);\n    BZTEST(mean(B) == 2);\n    BZTEST(min(B) == -2);\n    BZTEST(max(B) == 5);\n    BZTEST(product(B) == -120);\n    BZTEST(first(B>0) == 1);\n    BZTEST(last(B>3) == 2);\n    BZTEST(count(B>0) == 5);\n    BZTEST(any(B>0));\n    BZTEST(!any(B>10));\n    BZTEST(!all(B>0));\n    BZTEST(all(B>-10));\n\n    BZTEST(all(maxIndex(B)==1));\n    BZTEST(all(minIndex(B)==0));\n\n    MinMaxValue<typename T::T_numtype> mm=minmax(B);\n    BZTEST(mm.min==-2);\n    BZTEST(mm.max==5);\n}\n\nvoid grabner()\n{\n  BZ_USING_NAMESPACE(blitz::tensor)\n  Array<float, 2> a1(2, 2), a2(2, 2), a3(2, 2);\n  Array<float, 4> a4(2, 2, 2, 2);\n  Array<float, 2> a5(2, 2), a6(2, 2);\n  a1 = 1, 0, 0, 1;\n  a2 = a1;\n  a3 = a1;\n  a4 = a1(i, k) * a2(l,k) * a3(j, l);\n  a5 = sum(sum(a4, l), k);\n  a6 = sum(sum(a1(i, k) * a2(l,k) * a3(j, l), l),k);\n  BZTEST(all(a5==a6));\n}\n\nint main()\n{\n    Array<int,2> A(4,3);\n\n    A = 0,  1, 2,\n        3,  4, 5,\n        6,  7, 8,\n        9, 10, 11;\n\n    BZTEST(sum(A) == 11*12/2);\n    BZTEST(min(A) == 0);\n    BZTEST(max(A) == 11);\n\n    MinMaxValue<int> mm = minmax(A);\n    //std::cerr << mm.min << ' ' << mm.max << std::endl;\n    BZTEST(mm.min == 0);\n    BZTEST(mm.max == 11);\n\n    BZTEST(product(A) == 0);\n    BZTEST(all(A >= 0));\n    BZTEST(any(A == 7));\n    BZTEST(count(A > 1 && A < 5) == 3);\n    BZTEST(sum(pow2(A)) == 506);\n\n    BZ_USING_NAMESPACE(blitz::tensor)\n\n    BZTEST(sum(min(A,j)) == 0+3+6+9);\n    BZTEST(sum(max(A(j,i),j)) == 9+10+11);\n\n    Array<int,1> B(6);\n    test_1d(B);\n    TinyVector<int,6> Bv;\n    test_1d(Bv);\n\n    Array<int,3> C(2,2,2);\n    C = 1, 0, 2, 3, 4, 7, 6, 5;\n\n    BZTEST(sum(C) == 7*8/2);\n    BZTEST(all(C <= 7));\n    BZTEST(any(C == 5));\n    BZTEST(!any(C == 8));\n    BZTEST(sum(C(k,j,i)) == 7*8/2);\n    BZTEST(sum(C(j,k,i)) == 7*8/2);\n\n    // test behavior reported in bug 2058441\n    BZTEST(sum(sum(sum(C,k),j)) == 7*8/2);\n    Array<int,1> Cred(2);\n    Cred=sum(sum(C,k),j);\n    BZTEST(sum(Cred) == 7*8/2);\n    grabner();\n\n    mm = minmax(C);\n    BZTEST(mm.min == 0);\n    BZTEST(mm.max == 7);\n    /* these don't work\n    mm = minmax(C(i,j,k));\n    BZTEST(mm.min == 0);\n    BZTEST(mm.max == 7);\n    mm = minmax(C(k,j,i));\n    BZTEST(mm.min == 0);\n    BZTEST(mm.max == 7);\n    mm = minmax(C(j,k,i));\n    BZTEST(mm.min == 0);\n    BZTEST(mm.max == 7);\n    */\n\n    // test expression reductions\n\n    cout << \"Testing unary expression reductions\\n\";\n    B= 2, -5, -4, -3, -1, -1;\n    test_1dexpr(-B);\n    cout << \"Testing binary expression reductions\\n\";\n    B= -3, 4, 3, 2, 0, 0;\n    test_1dexpr(B+1);\n    Array<float,1> BB(6);\n    cout << \"Testing function expression reductions\\n\";\n    B=-2, 25, 16, 9, 1, 0;\n    BB = 1, .5, .5, .5, 2, 0;\n    test_1dexpr(pow(B,BB));\n    cout << \"Testing where expression reductions\\n\";\n    B = -2, -30, 4, 3, 0, -1;\n    BB = -2, 5, 3, -1, 1, 1;\n    test_1dexpr(where(B>BB,B,BB));\n\n    cout << \"Testing functor expression reductions\\n\";\n    B = -2, 5, 4, 3, 1, 1;\n    crap c;\n    test_1dexpr(c(B)-1);\n\n    return 0;\n}\n\n", "meta": {"hexsha": "5a742e4a6d6e78c309e00d08ee02763538c2ea43", "size": 3848, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/testsuite/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/testsuite/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/testsuite/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": 22.3720930233, "max_line_length": 56, "alphanum_fraction": 0.512993763, "num_tokens": 1604, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436167620237, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.7141295528359727}}
{"text": "/*\n* compile with flags:   g++ test.cc softmax_classifier.cc   ../datasets/datasets.cc -std=c++14 -larmadillo -I ../../include/\n* author: Yuzhen Liu\n* Date: 2019.3.29 10:55\n*/\n\n#include <iostream>\n#include <armadillo>\n#include <svm/svm.h>\n#include <svm/kernel_funcs.h>\n#include <datasets/datasets.h>\n\nusing namespace std;\nusing namespace arma;\n\nint main() {\n    Datasets dataset = Datasets(\"iris\");\n    mat x = dataset.x.head_cols(100);\n    vec y = dataset.y.head(100);\n    // negative labeled as -1\n    y = y.replace(0, -1);\n\n\n    // // mat x = {{0, 1}, {1, 0}, {1,1}, {-1,0}, {0,-1}, {-1,-1}};\n    // mat x = {{0, 1, 1, -1, 0, -1},\n    //          {1, 0, 1, 0, -1, -1}};\n    // vec y = {1, 1, 1, -1, -1, -1};\n    // // f(X) --> y = -x;\n\n    SVM svm = SVM();\n    svm.train(x, y);\n    vec res = svm.predict(x);\n\n    printf(\"The sum loss is: \\n\");\n    vec dis = res - y;\n    // dis.print();\n    join_rows(res, y).print();\n    // cout << \"The accuracy is: \" << dis / (double)x.n_elem << endl;\n    \n    return 0;\n}\n\n", "meta": {"hexsha": "59b05c1aa3d878ef27f175589c870aecf79f98a1", "size": 1013, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/svm_test.cc", "max_stars_repo_name": "codestorm04/Machine_Learning_CPP", "max_stars_repo_head_hexsha": "50bbe9c7b8c387cd9690b9c338639ae62fda1cf5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-06-05T09:31:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-13T13:37:44.000Z", "max_issues_repo_path": "examples/svm_test.cc", "max_issues_repo_name": "codestorm04/Machine_Learning_CPP", "max_issues_repo_head_hexsha": "50bbe9c7b8c387cd9690b9c338639ae62fda1cf5", "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": "examples/svm_test.cc", "max_forks_repo_name": "codestorm04/Machine_Learning_CPP", "max_forks_repo_head_hexsha": "50bbe9c7b8c387cd9690b9c338639ae62fda1cf5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2019-11-15T04:43:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-26T15:59:30.000Z", "avg_line_length": 23.5581395349, "max_line_length": 124, "alphanum_fraction": 0.5222112537, "num_tokens": 351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465152482724, "lm_q2_score": 0.763483758172699, "lm_q1q2_score": 0.7141218726554887}}
{"text": "#include <LinearModel.hpp>\n\n#include <Eigen/Dense>\n#include <Utils.hpp>\n#include <algorithm>\n#include <cstring>\n#include <iostream>\n#include <iterator>\n#include <random>\n#include <vector>\n\nLinearModel::LinearModel(int weights_count, bool is_classification) : BaseModel(weights_count, is_classification) {\n    weights = new double[weights_count + 1];\n    // Init all weights and biases between -1.0 and 1.0\n    for (int i = 0; i < weights_count + 1; i++) {\n        weights[i] = ml::rand(-1, 1);\n    }\n}\n\nvoid LinearModel::train(const Eigen::MatrixXd& train_inputs, const Eigen::MatrixXd& train_outputs, int epochs, double learning_rate) {\n    const size_t sample_count = train_inputs.rows();\n    const size_t inputs_size = train_inputs.cols();\n    const size_t outputs_size = train_outputs.cols();\n\n    if (is_classification) {\n        std::vector<int> trainingSetOrder(sample_count);\n\n        for (int i = 0; i < trainingSetOrder.size(); i++) {\n            trainingSetOrder[i] = i;\n        }\n\n        Eigen::MatrixXd activation(sample_count, outputs_size);\n\n        // Iterate with epochs\n        for (int i = 0; i < epochs; i++) {\n            // *** Predict Function ***\n\n            // compute activation fonction\n            predict(train_inputs, activation);  // or `predict(train_inputs.row(trainingSetID), activation);` in trainingSetOrder loops to predict by row\n\n            // shuffle the training set\n            ml::random_shuffle<int>(trainingSetOrder);\n\n            // for each training set\n            for (int j = 0; j < trainingSetOrder.size(); j++) {\n                // select a training set ID\n                int trainingSetID = trainingSetOrder[j];\n\n                // *** Learn Function ***\n\n                // Backpropagation of error on weights / Adjust the weights\n                for (int k = 0; k < outputs_size; k++) {\n                    const double target_value = train_outputs(trainingSetID, k);\n                    const double actual_value = activation(trainingSetID, k);\n\n                    double error = actual_value - target_value;\n                    if (is_classification) {\n                        error *= (actual_value * actual_value);\n                    }\n\n                    for (int l = 0; l < inputs_size; l++) {\n                        const double entry_value = train_inputs(trainingSetID, l);\n\n                        weights[l] -= (learning_rate * error * entry_value);\n                    }\n                    weights[weights_count] -= (learning_rate * error * 1);  // bias\n                }\n            }\n        }\n    } else { // to be verified\n        // Add a column of one (at the right), for the bias\n        Eigen::MatrixXd tmp(train_inputs.rows(), train_inputs.cols() + 1);\n        Eigen::VectorXd vec(train_inputs.rows());\n        for (int i = 0; i < train_inputs.rows(); i++) {\n            vec(i) = 1;\n        }\n        tmp << train_inputs, vec;\n\n        // Compute the transpose\n        Eigen::MatrixXd inputs_transposed = tmp.transpose();\n        Eigen::MatrixXd inv_inputs_transposed = (inputs_transposed * tmp).completeOrthogonalDecomposition().pseudoInverse();\n\n        // Compute weights\n        Eigen::MatrixXd w = inv_inputs_transposed * inputs_transposed * train_outputs;\n\n        for (int i = 0; i < inputs_size + 1; i++) {\n            weights[i] = w(i, 0);\n        }\n    }\n}\n\ndouble LinearModel::_activation(double value) const {\n    if (is_classification) {\n        value = std::tanh(value);\n        return (value != 0) ? (value > 0) ? 1 : -1 : 0;\n    } else {\n        return value;\n    }\n}\n\nvoid LinearModel::predict(const Eigen::MatrixXd& inputs, Eigen::MatrixXd& outputs){\n    assert(inputs.rows() == outputs.rows());  // or maybe resize outputs\n\n    // for each sample\n    for (int i = 0; i < inputs.rows(); i++) {\n        // Loop on outputs (here we have only one output)\n        for (int j = 0; j < outputs.cols(); j++) {\n            double activation = weights[weights_count];\n\n            // Loop on inputs\n            for (int k = 0; k < inputs.cols(); k++) {\n                activation += inputs(i, k) * weights[k];\n            }\n\n            // compute the _sigmoid of the activation\n            outputs(i, j) = _activation(activation);\n        }\n    }\n}", "meta": {"hexsha": "55fab4434ef947dfe93aacf3c4010a602f77b112", "size": 4242, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/src/LinearModel.cpp", "max_stars_repo_name": "florianvazelle/AnimeML", "max_stars_repo_head_hexsha": "5808a09de8be0a308d40107777430cc886ad076c", "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": "cpp/src/LinearModel.cpp", "max_issues_repo_name": "florianvazelle/AnimeML", "max_issues_repo_head_hexsha": "5808a09de8be0a308d40107777430cc886ad076c", "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": "cpp/src/LinearModel.cpp", "max_forks_repo_name": "florianvazelle/AnimeML", "max_forks_repo_head_hexsha": "5808a09de8be0a308d40107777430cc886ad076c", "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": 35.6470588235, "max_line_length": 153, "alphanum_fraction": 0.56718529, "num_tokens": 960, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465080392797, "lm_q2_score": 0.763483758172699, "lm_q1q2_score": 0.7141218671515398}}
{"text": "#include \"VectorMath.h\"\n#include <Eigen/Dense>\n#include <random>\n#include <iostream>\n\nusing namespace Eigen;\n\nconst Matrix3d VectorMath::crossProductMatrix(const Eigen::Vector3d &v)\n{\n    Matrix3d result;\n    result << 0, -v[2], v[1],\n            v[2], 0, -v[0],\n            -v[1], v[0], 0;\n    return result;\n}\n\nconst Matrix3d VectorMath::rotationMatrix(const Vector3d &axisAngle)\n{\n    double theta = axisAngle.norm();\n    Vector3d thetahat = axisAngle/theta;\n\n    if(theta == 0)\n        thetahat.setZero();\n\n    Matrix3d result;\n    result.setIdentity();\n    result = cos(theta)*result + sin(theta)*crossProductMatrix(thetahat) + (1-cos(theta))*thetahat*thetahat.transpose();\n    return result;\n}\n\ndouble VectorMath::randomUnitIntervalReal()\n{\n    return double(rand())/double(RAND_MAX);\n}\n\nconst Vector3d VectorMath::axisAngle(const Matrix3d &rotationMatrix)\n{\n    Matrix3d I;\n    I.setIdentity();\n    Matrix3d RminusI = rotationMatrix - I;\n\n    JacobiSVD<Matrix3d> svd(RminusI, ComputeFullV);\n    //assert(fabs(svd.singularValues()[2]) < 1e-8);\n    Vector3d axis = svd.matrixV().col(2);\n    Vector3d testAxis = perpToAxis(axis);\n    Vector3d resultAxis = rotationMatrix*testAxis;\n    double theta = atan2(testAxis.cross(resultAxis).dot(axis), testAxis.dot(resultAxis));\n    return theta*axis;\n}\n\nconst Vector3d VectorMath::perpToAxis(const Vector3d &v)\n{\n    int mincoord = 0;\n    double minval = std::numeric_limits<double>::infinity();\n    for(int i=0; i<3; i++)\n    {\n        if(fabs(v[i]) < minval)\n        {\n            mincoord = i;\n            minval = fabs(v[i]);\n        }\n    }\n    Vector3d other(0,0,0);\n    other[mincoord] = 1.0;\n    Vector3d result = v.cross(other);\n    result.normalize();\n    return result;\n}\n\nconst Matrix3d VectorMath::TMatrix(const Vector3d &v)\n{\n    double vnormsq = v.dot(v);    \n    Matrix3d I;\n    I.setIdentity();\n    if(vnormsq < 1e-8)\n        return I;\n\n    Matrix3d R = rotationMatrix(v);\n    return (v*v.transpose() + (R.transpose()-I)*crossProductMatrix(v))/vnormsq;\n}\n\nconst Matrix3d VectorMath::DrotVector(const Vector3d &axisangle, const Vector3d &rotatingVector)\n{\n    Matrix3d R = rotationMatrix(axisangle);\n    Matrix3d result = -R * crossProductMatrix(rotatingVector) * TMatrix(axisangle);\n    return result;\n}\n\nconst Eigen::Vector3d VectorMath::randomPointOnSphere()\n{\n    std::random_device r;\n    std::mt19937 generator(r());\n    std::normal_distribution<double> distribution(0.0,1.0);\n    Vector3d vec(distribution(generator), distribution(generator), distribution(generator));\n    vec /= vec.norm();\n    return vec;\n}\n", "meta": {"hexsha": "7064f642041be5773b30b422efdd734f8987aa49", "size": 2580, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "VectorMath.cpp", "max_stars_repo_name": "Reimilia/DiscreteElasticRods", "max_stars_repo_head_hexsha": "1651b29ec41d03e2fa9898148f1a70a5e2845537", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-01-02T12:28:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T00:03:30.000Z", "max_issues_repo_path": "VectorMath.cpp", "max_issues_repo_name": "Reimilia/DiscreteElasticRods", "max_issues_repo_head_hexsha": "1651b29ec41d03e2fa9898148f1a70a5e2845537", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-01-17T07:14:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-17T07:14:52.000Z", "max_forks_repo_path": "VectorMath.cpp", "max_forks_repo_name": "Reimilia/DiscreteElasticRods", "max_forks_repo_head_hexsha": "1651b29ec41d03e2fa9898148f1a70a5e2845537", "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": 26.3265306122, "max_line_length": 120, "alphanum_fraction": 0.6600775194, "num_tokens": 731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.903294214513915, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.7140814632521587}}
{"text": "/** \\file  main.cpp\r\n    \\brief Test and demonstration program.\r\n           Copyright 2006, 2010, 2013 by Erik Schloegl \r\n     */\r\n\r\n#include <iostream> \r\n#include <cstdlib>\r\n#include <boost/bind.hpp>\r\n#include \"BlackScholesAsset.hpp\"\r\n#include \"Payoff.hpp\"\r\n#include \"Binomial.hpp\"\r\n\r\nusing namespace quantfin;\r\n \r\n/** Test and demonstration for finite difference schemes.\r\n\r\n    Command-line arguments:\r\n      -# initial stock price.\r\n         The default is 100.\r\n      -# interest rate.\r\n         The default is 5%.\r\n      -# volatility.\r\n         The default is 30%.\r\n      -# maturity.\r\n         The default is 1.5.\r\n      -# moneyness.\r\n         The default is 1 (at the money).\r\n      -# N, time line refinement.\r\n         The default is 10.\r\n  */\r\nint main(int argc,char* argv[]) \r\n{\r\n  using std::cout;\r\n  using std::endl;\r\n  using std::flush;\r\n\r\n  int i,j;\r\n  try {\r\n    for (i=0;i<argc;i++) cout << argv[i] << ' ';\r\n\tcout << endl;\r\n    double S = 100.0;\r\n    if (argc>1) S = atof(argv[1]);\r\n    double r = 0.05;\r\n    if (argc>2) r = atof(argv[2]);\r\n    double sgm = 0.3;\r\n    if (argc>3) sgm = atof(argv[3]);\r\n    double mat = 1.5;\r\n    if (argc>4) mat = atof(argv[4]);\r\n    double K = 1.0;\r\n    if (argc>5) K = atof(argv[5]);\r\n    K *= S;\r\n    int N = 10;\r\n    if (argc>6) N = atoi(argv[6]);\r\n    Array<double,1> T(N+1);\r\n    firstIndex idx;\r\n    double dt = mat/N;\r\n    T = idx*dt;\r\n    ConstVol vol(sgm);\r\n    BlackScholesAsset stock(&vol,S);\r\n    cout << \"S: \" << S << \"\\nK: \" << K << \"\\nr: \" << r << \"\\nT: \" << mat << \"\\nsgm: \" << sgm << endl;\r\n    double CFcall = stock.option(mat,K,r);\r\n    double CFput  = stock.option(mat,K,r,-1);\r\n    double CFiput = stock.option(T(N/2),K,r,-1);\r\n    cout << \"Closed form call: \" << CFcall << endl;\r\n    cout << \"Closed form put: \" << CFput << endl;\r\n    cout << \"Closed form intermediate maturity put: \" << CFiput << endl;\r\n    cout << \"Time line refinement: \" << N << endl;\r\n    cout << \"Creating BinomialLattice object\" << endl;\r\n    BinomialLattice btree(stock,r,mat,N);  \r\n    Payoff call(K);\r\n    Payoff put(K,-1);\r\n    boost::function<double (double)> f;\r\n    f = boost::bind(std::mem_fun(&Payoff::operator()),&call,_1);\r\n    btree.apply_payoff(N-1,f);\r\n    btree.rollback(N-1,0);\r\n    cout << \"Binomial call (CRR): \" << btree.result() << \"\\nDifference to closed form: \" << CFcall - btree.result() << endl;\r\n    btree.set_JarrowRudd();\r\n    btree.apply_payoff(N-1,f);\r\n    btree.rollback(N-1,0);\r\n    cout << \"Binomial call (JR): \" << btree.result() << \"\\nDifference to closed form: \" << CFcall - btree.result() << endl;\r\n    f = boost::bind(std::mem_fun(&Payoff::operator()),&put,_1);\r\n    btree.set_CoxRossRubinstein();\r\n    btree.apply_payoff(N-1,f);\r\n    btree.rollback(N-1,0);\r\n    cout << \"Binomial put (CRR): \" << btree.result() << \"\\nDifference to closed form: \" << CFput - btree.result() << endl;\r\n    btree.set_JarrowRudd();\r\n    btree.apply_payoff(N-1,f);\r\n    btree.rollback(N-1,0);\r\n    cout << \"Binomial put (JR): \" << btree.result() << \"\\nDifference to closed form: \" << CFput - btree.result() << endl;\r\n    btree.set_Tian();\r\n    btree.apply_payoff(N-1,f);\r\n    btree.rollback(N-1,0);\r\n    cout << \"Binomial put (Tian): \" << btree.result() << \"\\nDifference to closed form: \" << CFput - btree.result() << endl;\r\n    btree.set_LeisenReimer(K);\r\n    btree.apply_payoff(N-1,f);\r\n    btree.rollback(N-1,0);\r\n    cout << \"Binomial put (LR): \" << btree.result() << \"\\nDifference to closed form: \" << CFput - btree.result() << endl;\r\n    EarlyExercise amput(put);\r\n    boost::function<double (double,double)> g;\r\n    g = boost::bind(boost::mem_fn(&EarlyExercise::operator()),&amput,_1,_2);\r\n    btree.set_CoxRossRubinstein();\r\n    btree.apply_payoff(N-1,f);\r\n    btree.rollback(N-1,0,g);\r\n    cout << \"Binomial American put (CRR): \" << btree.result() << endl;\r\n    btree.set_JarrowRudd();\r\n    btree.apply_payoff(N-1,f);\r\n    btree.rollback(N-1,0,g);\r\n    cout << \"Binomial American put (JR): \" << btree.result() << endl;\r\n    btree.set_LeisenReimer(K);\r\n    btree.apply_payoff(N-1,f);\r\n    btree.rollback(N-1,0,g);\r\n    cout << \"Binomial American put (LR): \" << btree.result() << endl;\r\n\r\n    // with dividends\r\n    stock.dividend_yield(0.03);\r\n    CFcall = stock.option(mat,K,r);\r\n    CFput  = stock.option(mat,K,r,-1);\r\n    cout << \"Closed form call: \" << CFcall << endl;\r\n    cout << \"Closed form put: \" << CFput << endl;\r\n    f = boost::bind(std::mem_fun(&Payoff::operator()),&call,_1);\r\n    btree.set_CoxRossRubinstein();\r\n    btree.apply_payoff(N-1,f);\r\n    btree.rollback(N-1,0);\r\n    cout << \"Binomial call (CRR): \" << btree.result() << endl;\r\n    btree.set_JarrowRudd();\r\n    btree.apply_payoff(N-1,f);\r\n    btree.rollback(N-1,0);\r\n    cout << \"Binomial call (JR): \" << btree.result() << endl;\r\n    btree.set_LeisenReimer(K);\r\n    btree.apply_payoff(N-1,f);\r\n    btree.rollback(N-1,0);\r\n    cout << \"Binomial call (LR): \" << btree.result() << endl;\r\n    f = boost::bind(std::mem_fun(&Payoff::operator()),&put,_1);\r\n    btree.set_CoxRossRubinstein();\r\n    btree.apply_payoff(N-1,f);\r\n    btree.rollback(N-1,0);\r\n    cout << \"Binomial put (CRR): \" << btree.result() << endl;\r\n    btree.set_JarrowRudd();\r\n    btree.apply_payoff(N-1,f);\r\n    btree.rollback(N-1,0);\r\n    cout << \"Binomial put (JR): \" << btree.result() << endl;\r\n    btree.set_Tian();\r\n    btree.apply_payoff(N-1,f);\r\n    btree.rollback(N-1,0);\r\n    cout << \"Binomial put (Tian): \" << btree.result() << endl;\r\n    btree.set_LeisenReimer(K);\r\n    btree.apply_payoff(N-1,f);\r\n    btree.rollback(N-1,0);\r\n    cout << \"Binomial put (LR): \" << btree.result() << endl;\r\n    btree.set_CoxRossRubinstein();\r\n    btree.apply_payoff(N-1,f);\r\n    btree.rollback(N-1,0,g);\r\n    cout << \"Binomial American put (CRR): \" << btree.result() << endl;\r\n    btree.set_JarrowRudd();\r\n    btree.apply_payoff(N-1,f);\r\n    btree.rollback(N-1,0,g);\r\n    cout << \"Binomial American put (JR): \" << btree.result() << endl;\r\n    btree.set_LeisenReimer(K);\r\n    btree.apply_payoff(N-1,f);\r\n    btree.rollback(N-1,0,g);\r\n    cout << \"Binomial American put (LR): \" << btree.result() << endl;\r\n\t} // end of try block\r\n\r\n  catch (std::logic_error xcpt) {\r\n    std::cerr << xcpt.what() << endl; }\r\n  catch (std::runtime_error xcpt) {\r\n    std::cerr << xcpt.what() << endl; }\r\n  catch (...) {\r\n    std::cerr << \"Other exception caught\" << endl; }\r\n  \r\n  return 0;\r\n}\r\n", "meta": {"hexsha": "74fbcf5c9785b70a3ed8d864f27fe3bb7c384cad", "size": 6375, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Chapter 3/BinomialExample.cpp", "max_stars_repo_name": "RoelofBerg/QuantFinCode", "max_stars_repo_head_hexsha": "a0d32b51fb46cf591242cf9981bdd86ea7b37898", "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": "Chapter 3/BinomialExample.cpp", "max_issues_repo_name": "RoelofBerg/QuantFinCode", "max_issues_repo_head_hexsha": "a0d32b51fb46cf591242cf9981bdd86ea7b37898", "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": "Chapter 3/BinomialExample.cpp", "max_forks_repo_name": "RoelofBerg/QuantFinCode", "max_forks_repo_head_hexsha": "a0d32b51fb46cf591242cf9981bdd86ea7b37898", "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": 36.8497109827, "max_line_length": 125, "alphanum_fraction": 0.5741176471, "num_tokens": 1966, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888302, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.7140659739469628}}
{"text": "#include \"tools.h\"\n#include \"logger.h\"\n#include <iostream>\n\n#include <boost/assert.hpp>\n#include <boost/format.hpp>\n\nusing Eigen::VectorXd;\nusing Eigen::MatrixXd;\nusing std::vector;\n\nstatic const Eigen::IOFormat HeavyFormat = Eigen::IOFormat(Eigen::StreamPrecision, 1, \", \", \";\\n\", \"[\", \"]\", \"[\", \"]\");\n\nstatic double Cross2d(const Eigen::Vector2d &vec1, const Eigen::Vector2d &vec2) {\n    return vec1[0] * vec2[1] - vec1[1] * vec2[0];\n}\n\nEigen::Vector4d Tools::CalculateRMSE(const vector<Eigen::Vector4d> &estimations,\n                                     const vector<Eigen::Vector4d> &ground_truth) {\n    BOOST_ASSERT(estimations.size() == ground_truth.size());\n    Eigen::Vector4d rmse;\n\n    const size_t data_size = estimations.size();\n    if (data_size < 1) {\n        BOOST_LOG_TRIVIAL(error) << (boost::format(\"Got invalid size, estimations.size()=%zu, ground_truth.size()=%zu.\")\n                                     % estimations.size() % ground_truth.size()).str();\n        return rmse;\n    }\n\n    Eigen::Map<const Eigen::Array4Xd> estimations_map(reinterpret_cast<const double*>(estimations.data()),\n                                                      4, data_size);\n    Eigen::Map<const Eigen::Array4Xd> ground_truth_map(reinterpret_cast<const double*>(ground_truth.data()),\n                                                       4, data_size);\n    rmse = ((estimations_map - ground_truth_map).square().rowwise().sum() / data_size).sqrt();\n    BOOST_LOG_TRIVIAL(info) << (boost::format(\"rmse=%s\") % rmse.transpose().format(HeavyFormat)).str();\n    return rmse;\n}\n\nEigen::Matrix<double, 3, 4> Tools::CalculateJacobian(const VectorXd& x_state) {\n   auto J = Eigen::Matrix<double, 3, 4>();\n   const double &px = x_state[0];\n   const double &py = x_state[1];\n   const double &vx = x_state[2];\n   const double &vy = x_state[3];\n   const double p_norm = x_state.topRows<2>().norm();\n   const double p_norm2 = p_norm * p_norm;\n\n   if (std::abs(p_norm) < 1e-6) {\n       return J;\n   }\n\n   J <<\n       // row1\n       px / p_norm, py / p_norm, 0.0, 0.0,\n       // row2\n       -py / p_norm2, px / p_norm2, 0.0, 0.0,\n       // row3\n       py * (Cross2d(x_state.bottomRows<2>(), x_state.topRows<2>())) / (p_norm * p_norm2),\n       px * (Cross2d(x_state.topRows<2>(), x_state.bottomRows<2>())) / (p_norm * p_norm2),\n       px / p_norm, py / p_norm;\n\n    return J;\n}\n", "meta": {"hexsha": "5de8f82baa4d41b6d83f712c2ef4928d77b0ef7b", "size": 2365, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tools.cpp", "max_stars_repo_name": "kunlin596/CarND-Extended-Kalman-Filter-Project", "max_stars_repo_head_hexsha": "130a8e3555b94edb494dcbcef20d3620176cf21a", "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/tools.cpp", "max_issues_repo_name": "kunlin596/CarND-Extended-Kalman-Filter-Project", "max_issues_repo_head_hexsha": "130a8e3555b94edb494dcbcef20d3620176cf21a", "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/tools.cpp", "max_forks_repo_name": "kunlin596/CarND-Extended-Kalman-Filter-Project", "max_forks_repo_head_hexsha": "130a8e3555b94edb494dcbcef20d3620176cf21a", "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.953125, "max_line_length": 120, "alphanum_fraction": 0.5949260042, "num_tokens": 659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.8479677545357568, "lm_q1q2_score": 0.7138409970804821}}
{"text": "/// @file  eval.hpp\n/// @brief Declarations for evaluation methods\n\n#pragma once\n#ifndef OGT_EVAL_EVAL_HPP\n#define OGT_EVAL_EVAL_HPP\n\n#include <ogt/config.hpp>\n#include <ogt/util/chain_merge.hpp>\n#include <Eigen/Dense>\n#include <functional>\n#include <vector>\n\nnamespace OGT_NAMESPACE {\nnamespace eval {\n\n/// Calculate raw stress. This is the sum of the squared error of the distances.\n/// It takes its minimum at zero, which indicates a perfect embedding.\n/// If requested, the estimated distances can first be scaled by the optimal\n/// constant to minimize stress.\n/// The scaled versions of these values can be used to compare embeddings of the\n/// same dataset, but as they are not normalized they cannot be compared across\n/// datasets.\n///\n/// The unscaled version is referred to as \\sigma_r in:\n/// [1] I. Borg & P. Groenen (1997): Modern multidimensional scaling: theory\n///     and applications. Springer.\ndouble mdsStress(const Eigen::MatrixXd& dhat, const Eigen::MatrixXd& dtrue,\n\tbool scaled = false);\n\n/// Calculate normed stress. This is a normalized version of mdsStress(), which\n/// can thus be compared between different datasets.\n/// It takes its minimum at zero, which indicates a perfect embedding.\n///\n/// The unscaled version is referred to as Stress-1 or \\sigma_1 in:\n/// [1] I. Borg & P. Groenen (1997): Modern multidimensional scaling: theory\n///     and applications. Springer.\ndouble mdsNormedStress(const Eigen::MatrixXd& dhat,\n\tconst Eigen::MatrixXd& dtrue, bool scaled = false);\n\n/// Calculate normed rank stress. That is, the normalized sum-squared amount by\n/// which each similarity constraint is violated.\n/// This essentially treats dist(i,j) as the target distance for dist(k,l)\n/// if dist(i,j) immediately precedes dist(k,l) in the partial order of\n/// distances.\ndouble mdsNormedRankStress(const Eigen::MatrixXd& dhat,\n\tconst OGT_NAMESPACE::util::ChainMerge& order);\n\n/// Calculate the root mean squared error of the distances, after finding the\n/// scaling which minimizes this error.\n/// In other words, we report RMSE for the best linear fit between the\n/// distance matrices.\ndouble distRmse(const Eigen::MatrixXd& dhat, const Eigen::MatrixXd& dtrue);\n\n/// Calculate the Kendall's tau-b of two distance vectors to other points.\n/// Does so in O(n log n) time, using\n/// Knight's Algorithm](http://adereth.github.io/blog/2013/10/30/efficiently-computing-kendalls-tau/).\ndouble kendallTau(const Eigen::VectorXd& d1, const Eigen::VectorXd& d2);\n\n/// Calculate the mean Kendall's tau-b of rankings by each row.\ndouble meanKendallTau(const Eigen::MatrixXd& dhat,\n\tconst Eigen::MatrixXd& dtrue);\n\n/// Calculate the weighted Kendall's tau of two vectors of numbers.\n/// The tau value is given for vectors r and s. The function w provides\n/// a weight for each rank in the list.\n///\n/// [1] S. Vigna, A Weighted Correlation Index for Rankings with Ties. WWW, 2015\ndouble weightedTau(const Eigen::VectorXd& r, const Eigen::VectorXd& s,\n\tstd::function<double(size_t /* rank */)> w);\n\n/// Calculate the weighted Kendall's tau of two vectors of numbers.\n/// The tau value is given for vectors r and s. The functions w1 and w2 provide\n/// weights for each rank in the list.\n///\n/// [1] S. Vigna, A Weighted Correlation Index for Rankings with Ties. WWW, 2015\ndouble weightedTau(const Eigen::VectorXd& r, const Eigen::VectorXd& s,\n\tstd::function<double(size_t /* rank */)> w1,\n\tstd::function<double(size_t /* rank */)> w2);\n\n/// The hyperbolic tau: weightedTau with rank weight 1/(1 + r).\ndouble hyperbolicTau(const Eigen::VectorXd& r, const Eigen::VectorXd& s);\n\n/// Calculate the mean hyperbolic tau of rankings by each row.\ndouble meanHyperbolicTau(const Eigen::MatrixXd& dhat,\n\tconst Eigen::MatrixXd& dtrue);\n\n} // end namespace eval\n} // end namespace OGT_NAMESPACE\n#endif /* OGT_EVAL_EVAL_HPP */\n", "meta": {"hexsha": "490f2750427026ffbec6263481ca80088ff0795d", "size": 3830, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ogt/eval/eval.hpp", "max_stars_repo_name": "jesand/lloe", "max_stars_repo_head_hexsha": "66235b16fb8cfbb39f72a289c320e701bde94159", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-08-11T21:31:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-30T09:23:04.000Z", "max_issues_repo_path": "include/ogt/eval/eval.hpp", "max_issues_repo_name": "jesand/lloe", "max_issues_repo_head_hexsha": "66235b16fb8cfbb39f72a289c320e701bde94159", "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": "include/ogt/eval/eval.hpp", "max_forks_repo_name": "jesand/lloe", "max_forks_repo_head_hexsha": "66235b16fb8cfbb39f72a289c320e701bde94159", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-08-11T21:31:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-27T20:57:26.000Z", "avg_line_length": 42.0879120879, "max_line_length": 102, "alphanum_fraction": 0.738381201, "num_tokens": 931, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995482, "lm_q2_score": 0.8031738034238807, "lm_q1q2_score": 0.713827775762726}}
{"text": "// (C) Copyright John Maddock 2006\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#ifdef _MSC_VER\n#  pragma warning(disable: 4512) // assignment operator could not be generated.\n#  pragma warning(disable: 4510) // default constructor could not be generated.\n#  pragma warning(disable: 4610) // can never be instantiated - user defined constructor required.\n#endif\n\n#include <iostream>\n#include <iomanip>\n#include <boost/math/distributions/binomial.hpp>\n\nvoid find_max_sample_size(double p, unsigned successes)\n{\n   //\n   // p         = success ratio.\n   // successes = Total number of observed successes.\n   //\n   // Calculate how many trials we can have to ensure the\n   // maximum number of successes does not exceed \"successes\".\n   // A typical use would be failure analysis, where you want\n   // zero or fewer \"successes\" with some probability.\n   //\n   using namespace std;\n   using namespace boost::math;\n\n   // Print out general info:\n   cout <<\n      \"________________________\\n\"\n      \"Maximum Number of Trials\\n\"\n      \"________________________\\n\\n\";\n   cout << setprecision(7);\n   cout << setw(40) << left << \"Success ratio\" << \"=  \" << p << \"\\n\";\n   cout << setw(40) << left << \"Maximum Number of \\\"successes\\\" permitted\" << \"=  \" << successes << \"\\n\";\n   //\n   // Define a table of confidence intervals:\n   //\n   double alpha[] = { 0.5, 0.25, 0.1, 0.05, 0.01, 0.001, 0.0001, 0.00001 };\n   //\n   // Print table header:\n   //\n   cout << \"\\n\\n\"\n           \"____________________________\\n\"\n           \"Confidence        Max Number\\n\" \n           \" Value (%)        Of Trials \\n\"\n           \"____________________________\\n\";\n   //\n   // Now print out the data for the table rows.\n   //\n   for(unsigned i = 0; i < sizeof(alpha)/sizeof(alpha[0]); ++i)\n   {\n      // Confidence value:\n      cout << fixed << setprecision(3) << setw(10) << right << 100 * (1-alpha[i]);\n      // calculate trials:\n      double t = binomial_distribution<>::find_maximum_number_of_trials(successes, p, alpha[i]);\n      t = floor(t);\n      // Print Trials:\n      cout << fixed << setprecision(0) << setw(15) << right << t << endl;\n   }\n   cout << endl;\n}\n\nint main()\n{\n   find_max_sample_size(1.0/1000, 0);\n   find_max_sample_size(1.0/10000, 0);\n   find_max_sample_size(1.0/100000, 0);\n   find_max_sample_size(1.0/1000000, 0);\n\n   return 0;\n}\n\n", "meta": {"hexsha": "8d3a16069b8607c789a6f4dc87186708f653553e", "size": 2472, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/example/binomial_sample_sizes.cpp", "max_stars_repo_name": "mike-code/boost_1_38_0", "max_stars_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-06-25T23:20:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-14T19:38:34.000Z", "max_issues_repo_path": "libs/math/example/binomial_sample_sizes.cpp", "max_issues_repo_name": "boost-cmake/vintage", "max_issues_repo_head_hexsha": "dcfb7da3177134eddaee6789d6f582259cb0d6ee", "max_issues_repo_licenses": ["BSL-1.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/math/example/binomial_sample_sizes.cpp", "max_forks_repo_name": "boost-cmake/vintage", "max_forks_repo_head_hexsha": "dcfb7da3177134eddaee6789d6f582259cb0d6ee", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-07-26T08:07:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-25T23:20:21.000Z", "avg_line_length": 32.1038961039, "max_line_length": 105, "alphanum_fraction": 0.6306634304, "num_tokens": 668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.888758793492457, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.7138277721213029}}
{"text": "//\n//  FunctionsTest.cpp\n//  Cynapse\n//\n//\n\n#include <Eigen/Dense>\n\n#include \"catch.hpp\"\n#include \"../Functions.hpp\"\n\n\nTEST_CASE(\"Functions sigmoid\", \"[Functions]\") {\n    REQUIRE(sigmoid(1000) == 1.0);\n    REQUIRE(sigmoid(0.0) == 0.5);\n    REQUIRE(sigmoid(-1000) == 0.0);\n}\n\nTEST_CASE(\"Functions sigmoid_derivative\", \"[Functions]\") {\n    REQUIRE(sigmoid_derivative(1000) == 0.0);\n    REQUIRE(sigmoid_derivative(0.0) == 0.25);\n    REQUIRE(sigmoid_derivative(-1000) == 0.0);\n}\n\nTEST_CASE(\"Functions heaviside\", \"[Functions]\") {\n    REQUIRE(heaviside(0.49) == 0.0);\n    REQUIRE(heaviside(0.5) == 1.0);\n    REQUIRE(heaviside(0.51) == 1.0);\n}\n\nTEST_CASE(\"Functions quadratic_cost_derivative\", \"[Functions]\") {\n    Eigen::MatrixXd m(2,2);\n    m(0,0) = 3;\n    m(1,0) = 2.5;\n    m(0,1) = -1;\n    m(1,1) = 4;\n    \n    Eigen::MatrixXd n(2,2);\n    m(0,0) = 10;\n    m(1,0) = -3.5;\n    m(0,1) = -6;\n    m(1,1) = 2;\n    \n    \n    Eigen::MatrixXd result = m - n;\n    REQUIRE(quadratic_cost_derivative(m, n) == result);\n}\n", "meta": {"hexsha": "2627be5baa32365d7ef240ca671de88e78d0625c", "size": 1006, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/FunctionsTest.cpp", "max_stars_repo_name": "samueljackson92/cynapse", "max_stars_repo_head_hexsha": "29bd5a50edb8b5413aca094341a52cb4c85b186c", "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/test/FunctionsTest.cpp", "max_issues_repo_name": "samueljackson92/cynapse", "max_issues_repo_head_hexsha": "29bd5a50edb8b5413aca094341a52cb4c85b186c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-10-09T16:31:03.000Z", "max_issues_repo_issues_event_max_datetime": "2015-10-30T07:06:21.000Z", "max_forks_repo_path": "src/test/FunctionsTest.cpp", "max_forks_repo_name": "samueljackson92/cynapse", "max_forks_repo_head_hexsha": "29bd5a50edb8b5413aca094341a52cb4c85b186c", "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": 20.9583333333, "max_line_length": 65, "alphanum_fraction": 0.5775347913, "num_tokens": 357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083608, "lm_q2_score": 0.8198933293122507, "lm_q1q2_score": 0.7137968928854821}}
{"text": "/*****************************************************************************\n*\n* Rokko: Integrated Interface for libraries of eigenvalue decomposition\n*\n* Copyright (C) 2012-2015 Rokko Developers https://github.com/t-sakashita/rokko\n*\n* Distributed under the Boost Software License, Version 1.0. (See accompanying\n* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n*\n*****************************************************************************/\n\n#ifndef ROKKO_UTILITY_LAPLACIAN_MATRIX_HPP\n#define ROKKO_UTILITY_LAPLACIAN_MATRIX_HPP\n\n#include <cmath>\n#include <stdexcept>\n#include <boost/throw_exception.hpp>\n#include <rokko/localized_matrix.hpp>\n\nnamespace rokko {\n\nclass laplacian_matrix {\npublic:\n  template<typename T>\n  static void multiply(int dim, const T* x, T* y) {\n    y[0] = x[0] - x[1];\n    y[dim-1] = 2 * x[dim-1] - x[dim - 2];\n    for (int k = 1; k < (dim-1); ++k) { // from 1 to end-1\n      y[k] = - x[k-1] + 2 * x[k] - x[k+1];\n    }\n  }\n\n  template<typename T>\n  static void multiply(int dim, const std::vector<T>& v, std::vector<T>& w) {\n    multiply(dim, &v[0], &w[0]);\n  }\n\n  template<typename T, typename MATRIX_MAJOR>\n  static void generate(rokko::localized_matrix<T, MATRIX_MAJOR>& mat) {\n    if (mat.rows() != mat.cols())\n      BOOST_THROW_EXCEPTION(std::invalid_argument(\"laplacian_matrix::generate() : non-square matrix\"));\n    mat.setZero();\n    int n = mat.rows();\n    mat(0, 0) = 1; mat(0, 1) = -1;\n    mat(n-1, n-2) = -1;  mat(n-1, n-1) = 2;\n    for(int i = 1; i < n-1; ++i) {\n      mat(i, i-1) = -1;\n      mat(i, i) = 2;\n      mat(i, i+1) = -1;\n    }\n  }\n  \n  // calculate k-th smallest eigenvalue of dim-dimensional Laplacian matrix (k=0...dim-1)\n  static double eigenvalue(int dim, int k) {\n    return 2 * (1 - std::cos(M_PI * (2 * k + 1) / (2 * dim + 1)));\n  }\n};\n    \n} // namespace rokko\n\n#endif // ROKKO_UTILITY_LAPLACIAN_MATRIX_HPP\n", "meta": {"hexsha": "ab3bb3125348b5f070d0c5c220cc6b0fb62a0dd6", "size": 1892, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "rokko/utility/laplacian_matrix.hpp", "max_stars_repo_name": "wistaria/rokko", "max_stars_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "max_stars_repo_licenses": ["BSL-1.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": "rokko/utility/laplacian_matrix.hpp", "max_issues_repo_name": "wistaria/rokko", "max_issues_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "max_issues_repo_licenses": ["BSL-1.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": "rokko/utility/laplacian_matrix.hpp", "max_forks_repo_name": "wistaria/rokko", "max_forks_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5161290323, "max_line_length": 103, "alphanum_fraction": 0.5750528541, "num_tokens": 586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972650509008, "lm_q2_score": 0.8198933293122506, "lm_q1q2_score": 0.713796890132723}}
{"text": "// HardCoded.cpp\n//\n// C++ code to price an option, essential algorithms.\n//\n// We take CEV model with a choice of the elaticity parameter\n// and the Euler method. We give option price and number of times\n// S hits the origin.\n//\n// (C) Datasim Education BC 2008-2011\n//\n#include <boost/tuple/tuple.hpp>\n#include <boost/tuple/tuple_io.hpp>\n#include \"OptionData.hpp\" \n#include \"UtilitiesDJD/RNG/NormalGenerator.hpp\"\n#include \"UtilitiesDJD/Geometry/Range.cpp\"\n#include <cmath>\n#include <iostream>\n\ntemplate <class T> void print(const std::vector<T>& myList)\n{  // A generic print function for vectors\n\n\tstd::cout << std::endl << \"Size of vector is \" << l.size() << \"\\n[\";\n\n\t// We must use a const iterator here, otherwise we get a compiler error.\n\tstd::vector<T>::const_iterator i;\n\tfor (i = myList.begin(); i != myList.end(); ++i)\n\t{\n\t\tstd::cout << *i << \",\";\n\n\t}\n\n\tstd::cout << \"]\\n\";\n}\ntemplate <typename Type>\nboost::tuple<Type, Type> SDSE(const std::vector<Type>& price, const Type& r, const Type& T)\n{\n\tType temp1(0), temp2(0);\n\tfor (int i = 0; i < price.size(); i++)\n\t{\n\t\ttemp1 += price[i] * price[i];\n\t\ttemp2 += price[i];\n\t}\n\n\tint M = price.size();\n\tType sd = sqrt(temp1 - 1 / M * temp2 * temp2) * exp(-2 * r * T) / (M - 1);\n\tType se = sd / sqrt(M);\n\n\treturn boost::make_tuple(sd, se);\n}\nnamespace SDEDefinition\n{ // Defines drift + diffusion + data\n\n\tOptionData* data;\t\t\t\t// The data for the option MC\n\n\tdouble drift(double t, double X)\n\t{ // Drift term\n\n\t\treturn (data->r) * X; // r - D\n\t}\n\n\n\tdouble diffusion(double t, double X)\n\t{ // Diffusion term\n\n\t\tdouble betaCEV = 1.0;\n\t\treturn data->sig * pow(X, betaCEV);\n\n\t}\n\n\tdouble diffusionDerivative(double t, double X)\n\t{ // Diffusion term, needed for the Milstein method\n\n\t\tdouble betaCEV = 1.0;\n\t\treturn 0.5 * (data->sig) * (betaCEV)*pow(X, 2.0 * betaCEV - 1.0);\n\t}\n} // End of namespace\n\n\nint main()\n{\n\tstd::cout << \"1 factor MC with explicit Euler\" << endl;\n\n\t// Store Batch 1 to Batch 2 data in a vector.\n\ttypedef boost::tuple<double, double, double, double, double> TupleFive;\n\tvector<TupleFive> vecBatch;\n\tvecBatch.push_back(boost::make_tuple(0.25, 65.0, 0.30, 0.08, 60.0));\n\tvecBatch.push_back(boost::make_tuple(1.00, 100.0, 0.20, 0.00, 100.0));\n\t//Batch 4: T = 30.0, K = 100.0, sig = 0.30, r = 0.08, S = 100.0 (C = 92.17570, P = 1.24750)\n\t//vecBatch.push_back(boost::make_tuple(30.00, 100.0, 0.30, 0.08, 100.0));\n\n\t// Vector to store the prices of put and call.\n\tvector<double> vecCallPrice, vecPutPrice;\n\tfor (int i = 0; i < vecBatch.size(); i++)\n\t{\n\t\tOptionData myOption;\n\t\tmyOption.T = vecBatch[i].get<0>();\n\t\tmyOption.K = vecBatch[i].get<1>();\n\t\tmyOption.sig = vecBatch[i].get<2>();\n\t\tmyOption.r = vecBatch[i].get<3>();\n\t\tmyOption.type = 1;\n\t\tdouble S_0 = vecBatch[i].get<4>();\n\t\tlong N = 100;\n\t\tstd::cout << \"Number of subintervals in time: \";\n\t\tstd::cin >> N;\n\n\t\t// Create the basic SDE (Context class)\n\t\tRange<double> range(0.0, myOption.T);\n\t\tdouble VOld = S_0;\n\t\tdouble VNew;\n\n\t\tstd::vector<double> x = range.mesh(N);\n\n\n\t\t// V2 mediator stuff\n\t\tlong NSim = 50000;\n\t\tstd::cout << \"Number of simulations: \";\n\t\tstd::cin >> NSim;\n\n\t\tdouble k = myOption.T / double(N);\n\t\tdouble sqrk = sqrt(k);\n\n\t\t// Normal random number\n\t\tdouble dW;\n\t\t// Call option price.\n\t\tdouble price1 = 0.0;\n\t\t// Put option price.\n\t\tdouble price2 = 0.0;\n\n\t\t// NormalGenerator is a base class\n\t\tNormalGenerator* myNormal = new BoostNormal();\n\n\t\tusing namespace SDEDefinition;\n\t\tSDEDefinition::data = &myOption;\n\n\t\tstd::vector<double> res;\n\t\tint coun = 0; // Number of times S hits origin\n\n\t\t// A.\n\t\tfor (long i = 1; i <= NSim; ++i)\n\t\t{ // Calculate a path at each iteration\n\n\t\t\tif ((i / 10000) * 10000 == i)\n\t\t\t{// Give status after each 1000th iteration\n\n\t\t\t\tstd::cout << i << std::endl;\n\t\t\t}\n\n\t\t\tVOld = S_0;\n\t\t\tfor (unsigned long index = 1; index < x.size(); ++index)\n\t\t\t{\n\n\t\t\t\t// Create a random number\n\t\t\t\tdW = myNormal->getNormal();\n\n\t\t\t\t// The FDM (in this case explicit Euler)\n\t\t\t\tVNew = VOld + (k * drift(x[index - 1], VOld))\n\t\t\t\t\t+ (sqrk * diffusion(x[index - 1], VOld) * dW);\n\n\t\t\t\tVOld = VNew;\n\n\t\t\t\t// Spurious values\n\t\t\t\tif (VNew <= 0.0) coun++;\n\t\t\t}\n\t\t\tdouble tmp1 = myOption.myPayOffFunction(VNew);\n\t\t\tprice1 += (tmp1) / double(NSim);\n\t\t\tvecCallPrice.push_back(tmp1);\n\t\t\tmyOption.type = -1;\n\t\t\tdouble tmp2 = myOption.myPayOffFunction(VNew);\n\t\t\tprice2 += (tmp2) / double(NSim);\n\t\t\tvecPutPrice.push_back(tmp2);\n\t\t\tmyOption.type = 1;\n\t\t}\n\n\n\n\t\t// D. Finally, discounting the average price.\n\t\tprice1 *= exp(-myOption.r * myOption.T);\n\t\tprice2 *= exp(-myOption.r * myOption.T);\n\n\t\t// Cleanup; V2 use scoped pointer\n\t\tdelete myNormal;\n\n\t\tstd::cout << \"Price, after discounting: Call = \" << price1 << \", Put = \" << price2 << std::endl;\n\t\tstd::cout << \"Number of times origin is hit: \" << coun << endl;\n\n\t\t// Print SD and SE.\n\t\tboost::tuple<double, double> tupleCall = SDSE<double>(vecCallPrice, myOption.r, myOption.T);\n\t\tboost::tuple<double, double> tuplePut = SDSE<double>(vecPutPrice, myOption.r, myOption.T);\n\t\tstd::cout << \"Batch \" << i + 1 << \", Call: NT = \" << N << \", NSIM = \" << NSim\n\t\t\t<< \", SD = \" << tupleCall.get<0>() << \", SE = \" << tupleCall.get<1>() << endl;\n\t\tstd::cout << \"Batch \" << i + 1 << \", Put: NT = \" << N << \", NSIM = \" << NSim\n\t\t\t<< \", SD = \" << tuplePut.get<0>() << \", SE = \" << tuplePut.get<1>() << endl;\n\t}\n\treturn 0;\n}", "meta": {"hexsha": "40f611bccf7d4eaa3007f7564be239476ccaba68", "size": 5295, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Level9/Level9/Level9/Group D/TestMC.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": "Level9/Level9/Level9/Group D/TestMC.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": "Level9/Level9/Level9/Group D/TestMC.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": 27.1538461538, "max_line_length": 98, "alphanum_fraction": 0.6166194523, "num_tokens": 1747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391624034103, "lm_q2_score": 0.826711791935942, "lm_q1q2_score": 0.7137760366477164}}
{"text": "//------------------------------------------------------------------------------\n/// \\file OptionalMonad_tests.cpp\n/// \\ref Ivan \u010cuki\u0107, Functional Programming in C++,  Manning Publications;\n/// 1st edition (November 19, 2018). ISBN-13: 978-1617293818\n//------------------------------------------------------------------------------\n#include \"Categories/Monads/OptionalMonad.h\"\n\n#include <boost/test/unit_test.hpp>\n#include <optional>\n#include <string>\n\nusing Categories::Monads::OptionalMonad::endomorphism_morphism_map;\nusing Categories::Monads::OptionalMonad::multiplication_component;\n\nBOOST_AUTO_TEST_SUITE(Categories)\nBOOST_AUTO_TEST_SUITE(Monads)\nBOOST_AUTO_TEST_SUITE(OptionalMonad_tests)\n\n// cf. \u010cuki\u0107 (2018), Ch. 10\n\nstd::optional<std::string> user_full_name(const std::string& login)\n{\n  return {};\n}\n\nstd::optional<std::string> to_html(const std::string& text)\n{\n  return {};\n}\n\nstd::optional<std::string> usable_user_full_name(const std::string& login)\n{\n  if (login == \"None\")\n  {\n    return {};\n  }\n\n  return std::make_optional<std::string>(login);\n}\n\nstd::optional<std::string> usable_to_html(const std::string& text)\n{\n  if (text == \"No address\")\n  {\n    return {};\n  }\n\n  return std::make_optional<std::string>(text);\n}\n\n// Testfunctions act as morphisms f : X \\to T(Y) where T is the endomorphism.\n// T : X \\to T(X), where T(X) is of type std::optional\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(TestFunctionsBehavesAsAMorphism)\n{\n  {\n    const std::string test_name {\"Jean-Francois Roberval\"};\n    // result of morphism f of type T(Y), as f : X \\to T(Y)\n    const auto result = usable_user_full_name(test_name);\n    BOOST_TEST(static_cast<bool>(result));\n    BOOST_TEST((result.value() == \"Jean-Francois Roberval\"));\n  }\n  {\n    const std::string test_name {\"None\"};\n    // result of morphism f of type T(Y), as f : X \\to T(Y)\n    const auto result = usable_user_full_name(test_name);\n    BOOST_TEST(!static_cast<bool>(result));\n  }\n  {\n    const std::string test_address {\"lapresse.ca\"};\n    // result of morphism f of type T(Y), as f : X \\to T(Y)\n    const auto result = usable_to_html(test_address);\n    BOOST_TEST(static_cast<bool>(result));\n    BOOST_TEST((result.value() == \"lapresse.ca\"));    \n  }\n  {\n    const std::string test_address {\"No address\"};\n    // result of morphism f of type T(Y), as f : X \\to T(Y)\n    const auto result = usable_to_html(test_address);\n    BOOST_TEST(!static_cast<bool>(result));\n  }\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(EndomorphismMorphismMapWorksOnFunctionReturningStdOptional)\n{\n  const auto test_full_name =\n    std::make_optional<std::string>(\"Jacques Cartier\");\n\n  BOOST_TEST_REQUIRE((test_full_name.value() == \"Jacques Cartier\"));\n  BOOST_TEST_REQUIRE(static_cast<bool>(test_full_name));\n\n  const auto result =\n    endomorphism_morphism_map(test_full_name, usable_user_full_name);\n\n  BOOST_TEST(static_cast<bool>(result));\n  BOOST_TEST((result.value() == test_full_name.value()));\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(ComposeMorphismMapWithMultiplicationComponent)\n{\n  const auto test_full_name =\n    std::make_optional<std::string>(\"Samuel de Champlain\");\n\n  const auto result =\n    multiplication_component(\n      endomorphism_morphism_map(test_full_name, usable_user_full_name));\n\n  BOOST_TEST(static_cast<bool>(result));\n  BOOST_TEST((result.value() == test_full_name.value()));  \n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(UseMainFromOptionalMonadExampleFromCukic)\n{\n  std::optional<std::string> login;\n\n  multiplication_component(\n    endomorphism_morphism_map(\n      multiplication_component(\n        endomorphism_morphism_map(\n          login,\n          user_full_name)),\n      to_html));\n\n  auto login_and_user_full_name =\n    multiplication_component(\n      endomorphism_morphism_map(\n        multiplication_component(\n          endomorphism_morphism_map(\n            login,\n            user_full_name)),\n        to_html)); \n\n  BOOST_TEST(true);\n}\n\nBOOST_AUTO_TEST_SUITE_END() // OptionalMonad_tests\nBOOST_AUTO_TEST_SUITE_END() // Monads\nBOOST_AUTO_TEST_SUITE_END() // Categories", "meta": {"hexsha": "993f01e0d547f5e6d8dd2c7d743f5f4269305b00", "size": 4635, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Voltron/Source/UnitTests/Categories/Monads/OptionalMonad_tests.cpp", "max_stars_repo_name": "ernestyalumni/HrdwCCppCUDA", "max_stars_repo_head_hexsha": "17ed937dea06431a4d5ca103f993ea69a6918734", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-02-09T19:44:51.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-09T19:44:51.000Z", "max_issues_repo_path": "Voltron/Source/UnitTests/Categories/Monads/OptionalMonad_tests.cpp", "max_issues_repo_name": "ernestyalumni/HrdwCCppCUDA", "max_issues_repo_head_hexsha": "17ed937dea06431a4d5ca103f993ea69a6918734", "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": "Voltron/Source/UnitTests/Categories/Monads/OptionalMonad_tests.cpp", "max_forks_repo_name": "ernestyalumni/HrdwCCppCUDA", "max_forks_repo_head_hexsha": "17ed937dea06431a4d5ca103f993ea69a6918734", "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.9655172414, "max_line_length": 80, "alphanum_fraction": 0.5883495146, "num_tokens": 957, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.7137760323963189}}
{"text": "\n//  (C) Copyright John Maddock 2006.\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#ifndef BOOST_MATH_SPECIAL_SPHERICAL_HARMONIC_HPP\n#define BOOST_MATH_SPECIAL_SPHERICAL_HARMONIC_HPP\n\n#ifdef _MSC_VER\n#pragma once\n#endif\n\n#include <boost/math/special_functions/legendre.hpp>\n#include <boost/math/tools/workaround.hpp>\n#include <complex>\n\nnamespace boost{\nnamespace math{\n\nnamespace detail{\n\n//\n// Calculates the prefix term that's common to the real\n// and imaginary parts.  Does *not* fix up the sign of the result\n// though.\n//\ntemplate <class T, class Policy>\ninline T spherical_harmonic_prefix(unsigned n, unsigned m, T theta, const Policy& pol)\n{\n   BOOST_MATH_STD_USING\n\n   if(m > n)\n      return 0;\n\n   T sin_theta = sin(theta);\n   T x = cos(theta);\n\n   T leg = detail::legendre_p_imp(n, m, x, static_cast<T>(pow(fabs(sin_theta), T(m))), pol);\n   \n   T prefix = boost::math::tgamma_delta_ratio(static_cast<T>(n - m + 1), static_cast<T>(2 * m), pol);\n   prefix *= (2 * n + 1) / (4 * constants::pi<T>());\n   prefix = sqrt(prefix);\n   return prefix * leg;\n}\n//\n// Real Part:\n//\ntemplate <class T, class Policy>\nT spherical_harmonic_r(unsigned n, int m, T theta, T phi, const Policy& pol)\n{\n   BOOST_MATH_STD_USING  // ADL of std functions\n\n   bool sign = false;\n   if(m < 0)\n   {\n      // Reflect and adjust sign if m < 0:\n      sign = m&1;\n      m = abs(m);\n   }\n   if(m&1)\n   {\n      // Check phase if theta is outside [0, PI]:\n      T mod = boost::math::tools::fmod_workaround(theta, T(2 * constants::pi<T>()));\n      if(mod < 0)\n         mod += 2 * constants::pi<T>();\n      if(mod > constants::pi<T>())\n         sign = !sign;\n   }\n   // Get the value and adjust sign as required:\n   T prefix = spherical_harmonic_prefix(n, m, theta, pol);\n   prefix *= cos(m * phi);\n   return sign ? T(-prefix) : prefix;\n}\n\ntemplate <class T, class Policy>\nT spherical_harmonic_i(unsigned n, int m, T theta, T phi, const Policy& pol)\n{\n   BOOST_MATH_STD_USING  // ADL of std functions\n\n   bool sign = false;\n   if(m < 0)\n   {\n      // Reflect and adjust sign if m < 0:\n      sign = !(m&1);\n      m = abs(m);\n   }\n   if(m&1)\n   {\n      // Check phase if theta is outside [0, PI]:\n      T mod = boost::math::tools::fmod_workaround(theta, T(2 * constants::pi<T>()));\n      if(mod < 0)\n         mod += 2 * constants::pi<T>();\n      if(mod > constants::pi<T>())\n         sign = !sign;\n   }\n   // Get the value and adjust sign as required:\n   T prefix = spherical_harmonic_prefix(n, m, theta, pol);\n   prefix *= sin(m * phi);\n   return sign ? T(-prefix) : prefix;\n}\n\ntemplate <class T, class U, class Policy>\nstd::complex<T> spherical_harmonic(unsigned n, int m, U theta, U phi, const Policy& pol)\n{\n   BOOST_MATH_STD_USING\n   //\n   // Sort out the signs:\n   //\n   bool r_sign = false;\n   bool i_sign = false;\n   if(m < 0)\n   {\n      // Reflect and adjust sign if m < 0:\n      r_sign = m&1;\n      i_sign = !(m&1);\n      m = abs(m);\n   }\n   if(m&1)\n   {\n      // Check phase if theta is outside [0, PI]:\n      U mod = boost::math::tools::fmod_workaround(theta, 2 * constants::pi<U>());\n      if(mod < 0)\n         mod += 2 * constants::pi<U>();\n      if(mod > constants::pi<U>())\n      {\n         r_sign = !r_sign;\n         i_sign = !i_sign;\n      }\n   }\n   //\n   // Calculate the value:\n   //\n   U prefix = spherical_harmonic_prefix(n, m, theta, pol);\n   U r = prefix * cos(m * phi);\n   U i = prefix * sin(m * phi);\n   //\n   // Add in the signs:\n   //\n   if(r_sign)\n      r = -r;\n   if(i_sign)\n      i = -i;\n   static const char* function = \"boost::math::spherical_harmonic<%1%>(int, int, %1%, %1%)\";\n   return std::complex<T>(policies::checked_narrowing_cast<T, Policy>(r, function), policies::checked_narrowing_cast<T, Policy>(i, function));\n}\n\n} // namespace detail\n\ntemplate <class T1, class T2, class Policy>\ninline std::complex<typename tools::promote_args<T1, T2>::type> \n   spherical_harmonic(unsigned n, int m, T1 theta, T2 phi, const Policy& pol)\n{\n   typedef typename tools::promote_args<T1, T2>::type result_type;\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\n   return detail::spherical_harmonic<result_type, value_type>(n, m, static_cast<value_type>(theta), static_cast<value_type>(phi), pol);\n}\n\ntemplate <class T1, class T2>\ninline std::complex<typename tools::promote_args<T1, T2>::type> \n   spherical_harmonic(unsigned n, int m, T1 theta, T2 phi)\n{\n   return boost::math::spherical_harmonic(n, m, theta, phi, policies::policy<>());\n}\n\ntemplate <class T1, class T2, class Policy>\ninline typename tools::promote_args<T1, T2>::type \n   spherical_harmonic_r(unsigned n, int m, T1 theta, T2 phi, const Policy& pol)\n{\n   typedef typename tools::promote_args<T1, T2>::type result_type;\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\n   return policies::checked_narrowing_cast<result_type, Policy>(detail::spherical_harmonic_r(n, m, static_cast<value_type>(theta), static_cast<value_type>(phi), pol), \"bost::math::spherical_harmonic_r<%1%>(unsigned, int, %1%, %1%)\");\n}\n\ntemplate <class T1, class T2>\ninline typename tools::promote_args<T1, T2>::type \n   spherical_harmonic_r(unsigned n, int m, T1 theta, T2 phi)\n{\n   return boost::math::spherical_harmonic_r(n, m, theta, phi, policies::policy<>());\n}\n\ntemplate <class T1, class T2, class Policy>\ninline typename tools::promote_args<T1, T2>::type \n   spherical_harmonic_i(unsigned n, int m, T1 theta, T2 phi, const Policy& pol)\n{\n   typedef typename tools::promote_args<T1, T2>::type result_type;\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\n   return policies::checked_narrowing_cast<result_type, Policy>(detail::spherical_harmonic_i(n, m, static_cast<value_type>(theta), static_cast<value_type>(phi), pol), \"boost::math::spherical_harmonic_i<%1%>(unsigned, int, %1%, %1%)\");\n}\n\ntemplate <class T1, class T2>\ninline typename tools::promote_args<T1, T2>::type \n   spherical_harmonic_i(unsigned n, int m, T1 theta, T2 phi)\n{\n   return boost::math::spherical_harmonic_i(n, m, theta, phi, policies::policy<>());\n}\n\n} // namespace math\n} // namespace boost\n\n#endif // BOOST_MATH_SPECIAL_SPHERICAL_HARMONIC_HPP\n\n\n\n", "meta": {"hexsha": "33b25744805d386749caa3d91d5fea5adaf51b7c", "size": 6302, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/boost/math/special_functions/spherical_harmonic.hpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 71.0, "max_stars_repo_stars_event_min_datetime": "2015-01-17T00:29:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-09T02:59:16.000Z", "max_issues_repo_path": "boost/boost/math/special_functions/spherical_harmonic.hpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2016-01-11T05:20:05.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-06T11:37:24.000Z", "max_forks_repo_path": "boost/boost/math/special_functions/spherical_harmonic.hpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 44.0, "max_forks_repo_forks_event_min_datetime": "2015-03-18T09:20:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-21T08:09:17.000Z", "avg_line_length": 30.7414634146, "max_line_length": 234, "alphanum_fraction": 0.6562995874, "num_tokens": 1838, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009526726544, "lm_q2_score": 0.7799928900257127, "lm_q1q2_score": 0.7136162381624215}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n\n\nvoid eigenValueSolver()\n{\n    // ComplexEigenSolver<MatrixXcf> ces;\n    Eigen::EigenSolver<Eigen::MatrixXd> ces;\n    Eigen::MatrixXd A(4, 4);\n    A(0, 0) = 18;\n    A(0, 1) = -9;\n    A(0, 2) = -27;\n    A(0, 2) = 24;\n    A(1, 0) = -9;\n    A(1, 1) = 4.5;\n    A(1, 2) = 13.5;\n    A(1, 3) = -12;\n    A(2, 0) = -27;\n    A(2, 1) = 13.5;\n    A(2, 2) = 40.5;\n    A(2, 3) = -36;\n    A(3, 0) = 24;\n    A(3, 1) = -12;\n    A(3, 2) = -36;\n    A(3, 3) = 32;\n    ces.compute(A);\n    std::cout << \"The eigenvalues of A are:\" << std::endl\n         << ces.eigenvalues() << std::endl;\n    std::cout << \"The matrix of eigenvectors, V, is:\" <<std::endl\n         << ces.eigenvectors() << std::endl\n         << std::endl;\n    //  complex<float> lambda =  ces.eigenvalues()[0];\n    //  cout << \"Consider the first eigenvalue, lambda = \" << lambda << endl;\n    //  VectorXcf v = ces.eigenvectors().col(0);\n    //  cout << \"If v is the corresponding eigenvector, then lambda * v = \" <<\n    //  endl << lambda * v << endl;\n    //  cout << \"... and A * v = \" << endl << A * v << endl << endl;\n    //\n    //  cout << \"Finally, V * D * V^(-1) = \" << endl\n    //       << ces.eigenvectors() * ces.eigenvalues().asDiagonal() *\n    //       ces.eigenvectors().inverse() << endl;\n}\n\nint main()\n{\n\n}\n", "meta": {"hexsha": "e563ea32fa06b60ab34dbaebd81e34d23b27cf98", "size": 1309, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/eigen_value_eigen_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/eigen_value_eigen_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/eigen_value_eigen_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": 27.2708333333, "max_line_length": 78, "alphanum_fraction": 0.4812834225, "num_tokens": 502, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741308615412, "lm_q2_score": 0.7490872131147276, "lm_q1q2_score": 0.7135611009722557}}
{"text": "#ifndef _EMBEDDINGSTORE_H\n#define _EMBEDDINGSTORE_H\n\n#include <Eigen/Dense>\n#include <Eigen/Core>\n#include \"word2vec.hpp\"\n#include <vector>\n#include <string>\n#include <iostream>\n#include <fstream>\n#include \"IEmbeddingModel.hpp\"\n#include \"vpTree.hpp\"\n#include \"math.h\"\n#include <map>\n\n\nusing namespace std;\nusing namespace Eigen;\n\n\n\nclass EmbeddingStore\n{\n    private:\n        static double eucl_dist(const VectorXf& a, const VectorXf& b)\n        {\n            double dist = 0 ;\n            for(int i = 0; i < a.size(); i++)\n                dist += pow( a[i] - b[i],2);\n            return sqrt(dist);\n        }\n        static double cosine_dist(const VectorXf& a, const VectorXf& b)\n        {\n            double dot = 0, norm_1 = 0, norm_2 = 0;\n            for(int i = 0; i < a.size(); i++)\n            {\n                dot += a[i] * b[i];\n                norm_1 += pow(a[i], 2);\n                norm_2 += pow(b[i], 2);\n            }\n\n            return dot / (sqrt(norm_1)* sqrt(norm_2) );\n        } \n        //Am I sure that here should be a vector?\n        vector<string> vocab;\n        vector<VectorXf> vectors;\n        map<string, int> word2index;\n        //unordered_map<VectorXf, string> v2w;\n        MatrixXf Embeddings;\n        VpTree<VectorXf, eucl_dist> EmbeddingTree;\n\n  \n    public:\n    VectorXf operator[](string word);\n    EmbeddingStore();\n    ~EmbeddingStore();\n    EmbeddingStore(IEmbeddingModel &model);\n    MatrixXd readMatrix(const char *filename);\n    void writeMatrix(const char *filename, MatrixXd mat);\n    void find_k_nierest(string word, int k, \n                       vector<string>& results, vector<double>& dists);\n\n    void dbscan(float eps, int minPts);\n    float similarity();\n\n    VectorXf get_sif(string sentence, map<string, int> tf, float alpha);\n    string find_nierest(string word);\n};\n\n#endif", "meta": {"hexsha": "ce2248090e5ddad320f87fb4cdb2da68a804635a", "size": 1832, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "EmbeddingStore.hpp", "max_stars_repo_name": "Astromis/tinyEmbeddingsEngine", "max_stars_repo_head_hexsha": "fea1beb7b3fd32640f788209f79cc47312a20efb", "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": "EmbeddingStore.hpp", "max_issues_repo_name": "Astromis/tinyEmbeddingsEngine", "max_issues_repo_head_hexsha": "fea1beb7b3fd32640f788209f79cc47312a20efb", "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": "EmbeddingStore.hpp", "max_forks_repo_name": "Astromis/tinyEmbeddingsEngine", "max_forks_repo_head_hexsha": "fea1beb7b3fd32640f788209f79cc47312a20efb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-28T09:38:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-28T09:38:52.000Z", "avg_line_length": 26.1714285714, "max_line_length": 72, "alphanum_fraction": 0.5840611354, "num_tokens": 474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178969328287, "lm_q2_score": 0.7853085808877581, "lm_q1q2_score": 0.713545431209539}}
{"text": "#include <cassert>\n#include <chrono>\n#include <cmath>\n#include <cstdlib>\n#include <fstream>\n#include <initializer_list>\n#include <iostream>\n#include <ostream>\n#include <random>\n#include <string>\n#include <vector>\n\n#include <Eigen/Core>\n#include <Eigen/LU>\n\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\nusing Eigen::seq;\n\nMatrixXd read_tableau(const std::string& filePath) {\n  std::ifstream file(filePath);\n  if(!file.is_open())\n    throw std::ifstream::failure(\"File could not be opened\");\n  int m, n;\n  file >> m >> n;\n  MatrixXd tableau(m+1, n+1);\n  for (int i = 0; i < m + 1; i++)\n      for (int j = 0; j < n + 1; j++)\n        file >> tableau(i, j);\n  file.close();\n  return tableau;\n}\n\nauto initialize(int m, int n) {\n  VectorXd x(n), y(m), s(n);\n  double mu;\n  std::random_device r;\n  std::default_random_engine engine(r());\n  std::uniform_real_distribution<> u_dist(-1.0, 1.0);\n  double positive_lower = std::nextafter(0, std::numeric_limits<double>::max());\n  // Positive uniform distribution\n  std::uniform_real_distribution<> u_dist_pos(positive_lower, 1.0);\n  for(int i = 0; i < n; i++) {\n    x(i) = u_dist_pos(engine);\n    s(i) = u_dist_pos(engine);\n  }\n  for (int i = 0; i < m; i++)\n    y(i) = u_dist(engine);\n  mu = u_dist_pos(engine);\n  return std::make_tuple(x, y, s, mu);\n}\n\ndouble get_alpha(const VectorXd& vec, const VectorXd& delta_vec) {\n  assert(vec.size() == delta_vec.size());\n  int size = vec.size();\n  double alpha = std::numeric_limits<double>::max();\n  bool all_delta_nonnegative= true;\n  double ratio;\n  for(int i = 0; i < size; i++)\n    if(delta_vec(i) < 0 && (ratio = -(vec(i) / delta_vec(i))) < alpha) {\n      alpha = ratio;\n      all_delta_nonnegative = false;\n    }\n  return all_delta_nonnegative ? 1.0 : alpha;\n}\n\nauto interior_point(const MatrixXd& A, const VectorXd& b, const VectorXd& c,\n                    double eps = 10e-6, double max_norm = 10e6,\n                    int k_max = 1000) {\n  int m = A.rows(), n = A.cols();\n  assert(m == b.size());\n  assert(n == c.size());\n  double sq_norm, max_sq_norm = std::pow(max_norm, 2);\n  constexpr double fraction = 1 - 10e-7;\n  double theta = (n > 13) ? (1 - 3.5 / std::sqrt(n)) : 0.5;\n  auto [x, y, s, mu] = initialize(m, n);\n  int k = 0;\n  do {\n    MatrixXd S = s.asDiagonal();\n    MatrixXd D = (x.array() / s.array()).matrix().asDiagonal();\n    VectorXd rho_P = b - A * x;\n    VectorXd rho_D = c - A.transpose() * y - s;\n    VectorXd v = (mu - (x.array() * s.array())).matrix().transpose();\n    VectorXd delta_y = -((A * D * A.transpose()).inverse() *\n                         (A * S.inverse() * v - A * D * rho_D - rho_P));\n    VectorXd delta_s = -(A.transpose() * delta_y) + rho_D;\n    VectorXd delta_x = S.inverse() * v - D * delta_s;\n    double alpha = fraction * std::min(get_alpha(x, delta_x),\n                                       get_alpha(s, delta_s));\n    VectorXd x_new = x + alpha * delta_x;\n    VectorXd y_new = y + alpha * delta_y;\n    VectorXd s_new = s + alpha * delta_s;\n\n    // Concatenate vectors.\n    VectorXd joined(x.size() + y.size() + s.size());\n    joined << x, y, s;\n    VectorXd joined_new(x_new.size() + y_new.size() + s_new.size());\n    joined_new << x_new, y_new, s_new;\n    sq_norm = (joined_new - joined).squaredNorm();\n    // sq_norm = std::max({\n    //     (x_new - x).squaredNorm(),\n    //     (y_new - y).squaredNorm(),\n    //     (s_new - s).squaredNorm()\n    //   });\n    x = x_new;\n    y = y_new;\n    s = s_new;\n    mu *= theta;\n    k++;\n  } while((x.transpose() * s > eps) &&\n          (k < k_max) &&\n          (sq_norm < max_sq_norm));\n  if(x.transpose() * s < eps)\n    return std::make_tuple(x, y);\n  else if(sq_norm > max_sq_norm)\n    throw std::invalid_argument(\"Algorithm did not converge. Norm exceeded.\");\n  else\n    throw std::invalid_argument(\"Algorithm did not converge.\"\n                                \"Number of maximum iterations exceeded.\");\n}\n\nint main(int argc, char** argv) {\n  // Process command-line arguments\n  std::string file_path = \"\";\n  std::vector<std::string> args(argv + 1, argv + argc);\n  for(auto arg = args.begin(); arg != args.end(); arg++) {\n    if(*arg == \"-i\")\n      file_path = *(++arg);\n  }\n  if(file_path.empty()) {\n    std::cout << \"USAGE: pdip -i <file>\" << std::endl;\n    return EXIT_FAILURE;\n  }\n\n  MatrixXd tableau;\n  try {\n    tableau = read_tableau(file_path);\n  }\n  catch(std::ifstream::failure& ex) {\n    std::cout << ex.what() << std::endl;\n    return EXIT_FAILURE;\n  }\n  auto start = std::chrono::steady_clock::now();\n\n  int m = tableau.rows() - 1, n = tableau.cols() - 1;\n  MatrixXd A = tableau(seq(0, m-1), seq(0, n-1));\n  VectorXd b = tableau(seq(0, m-1), n);\n  VectorXd c = tableau(m, seq(0, n-1));\n\n  VectorXd x_sum = VectorXd::Zero(n);\n  VectorXd y_sum = VectorXd::Zero(m);\n  int n_runs = 30;\n  for (int i = 0; i < n_runs; i++) {\n    auto [x, y] = interior_point(A, b, c, 10e-10);\n    x_sum += x;\n    y_sum += y;\n  }\n\n  std::cout << \"Average solutions after \" << n_runs << \" executions:\"\n            << std::endl;\n  VectorXd x_avg = x_sum.transpose().array() / n_runs;\n  VectorXd y_avg = y_sum.transpose().array() / n_runs;\n\n  auto end = std::chrono::steady_clock::now();\n\n  std::cout << \"x:\" << std::endl << x_avg << std::endl;\n  std::cout << std::endl;\n  std::cout << \"y:\" << std::endl << y_avg << std::endl;\n  std::cout << std::endl;\n  std::cout << \"optimum:\" << std::endl << x_avg.dot(c) << std::endl;\n  std::cout << std::endl;\n  std::cout << \"Running time: \"\n            << std::chrono::duration_cast<std::chrono::microseconds>(end - start).count() / n_runs\n            << '\\n';\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "fcbc0819658e400bcdd2dada8fff921076baa1e8", "size": 5592, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "claudiu-ghiga/interior-point", "max_stars_repo_head_hexsha": "7d0311a8d6f202665672686c24c920417623a12e", "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": "claudiu-ghiga/interior-point", "max_issues_repo_head_hexsha": "7d0311a8d6f202665672686c24c920417623a12e", "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": "claudiu-ghiga/interior-point", "max_forks_repo_head_hexsha": "7d0311a8d6f202665672686c24c920417623a12e", "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.593220339, "max_line_length": 98, "alphanum_fraction": 0.5811874106, "num_tokens": 1676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837705, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.713545427323001}}
{"text": "#include \"boost/numeric/ublas/make_unbounded_array.hpp\"\n\n#include \"boost/numeric/ublas/Newton.hpp\"\n#include \"boost/numeric/ublas/Davidon_Fletcher_Powell.hpp\"\n#include <boost/numeric/ublas/io.hpp>\n\n#include \"test.hpp\"\n\nvoid print(const boost::numeric::ublas::Function<> & f, const vector_t & solution, double epsilon, std::size_t number_iteration) {\n    std::cout << \"Precision:            \" << epsilon << std::endl;\n    std::cout << \"Number of iterations: \" << number_iteration << std::endl;\n    std::cout << \"Function value:       \" << f(solution) << std::endl;\n    std::cout << \"Computed solution:    \" << solution << std::endl << std::endl;\n}\n\nint main() {\n    std::ios_base::sync_with_stdio(false);\n    std::cout.precision(10);\n    using namespace boost::numeric::ublas;\n\n    auto epsilon = 1E-9;\n    std::size_t number_iteration = 0;\n    vector_t solution;\n\n    Function<> f(2, function, gradient, hessian);\n    //vector_t x(make_unbounded_array({ -1.2, 1.0 }));\n    vector_t x(make_unbounded_array({ -0.5, 0.5 }));\n    //vector_t x(make_unbounded_array({ -8.0, 9.0 }));\n\n    solution = DavidonFletcherPowell(f, x, epsilon, number_iteration = 0);\n    std::cout << \"Davidon-Fletcher-Powell:\" << std::endl;\n    print(f, solution, epsilon, number_iteration);\n\n    solution = Newton(f, x, epsilon, number_iteration = 0);\n    std::cout << \"Newton:\" << std::endl;\n    print(f, solution, epsilon, number_iteration);\n\n    return 0;\n}\n", "meta": {"hexsha": "252f50fb8df7153e98541a8077e3ec783bb648b9", "size": 1431, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "ATetiukhin/Davidon_Fletcher_Powell", "max_stars_repo_head_hexsha": "92f96b5e8552b86613fc5a5ac7f29bd653dbee1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-07-08T03:35:40.000Z", "max_stars_repo_stars_event_max_datetime": "2017-02-26T19:19:38.000Z", "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "ATetiukhin/Davidon_Fletcher_Powell", "max_issues_repo_head_hexsha": "92f96b5e8552b86613fc5a5ac7f29bd653dbee1f", "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": "ATetiukhin/Davidon_Fletcher_Powell", "max_forks_repo_head_hexsha": "92f96b5e8552b86613fc5a5ac7f29bd653dbee1f", "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.775, "max_line_length": 130, "alphanum_fraction": 0.6547868623, "num_tokens": 399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554444, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.7134932318796398}}
{"text": "#ifndef RKIMPLEMENTER\n\n#define RKIMPLEMENTER\n\n#include <Eigen/Dense>\n#include <vector>\n\n\n\n\n/**\n * \n * Implementation of an explicit Runge Kutta Solver. See the documentation for more information.\n * \n */\ntemplate <class Step> class ExplicitRungeKuttaIntegrator {\n\n    public:\n        /**\n         * Constructor for the ExplicitRungeKuttaIntegrator\n         * \n         * @param A the coefficients matrix A of a butcher scheme\n         * @param b the weights vector for a butcher scheme. Note that we are taking a column vector whereas in a butcher tableau this would be a row vector (though doesn't matter if one uses VectorXd in Eigen).\n         */\n        ExplicitRungeKuttaIntegrator(const Eigen::MatrixXd &A, const Eigen::VectorXd &b):A(A),b(b),size(A.cols()){\n        }\n\n        /**\n         * The solve methods applies an explicit Runge Kutta method to a given ODE\n         * \n         * @param f the function we are integrating over\n         * @param time the time interval we want to integrate over\n         * @param y0 the initial state of the system\n         * @param steps the number of integration steps we would like to make (number of steps equals number of runge kutta method evaluations)\n         * \n         * @return a std::vector of states, one for every integration step performed. The first step will be the supplied y0.\n         */\n        template<typename Function>\n        std::vector<Step> solve(Function &&f, double time, const Step &y0, unsigned int steps){\n\n            std::vector<Step> stepsVector;\n            \n            // as advertised the first position will be our initial state\n            stepsVector.push_back(y0);\n\n            // knowing the total time and number of steps allows us to calculate the time we integrate over every step\n            double h = time / steps;\n\n            // now we call the solver \"steps\" times to do the actual integration\n            for(unsigned int i = 0; i < steps; i++){\n                // integrate and directly add to our list\n                stepsVector.push_back(iteration(f,stepsVector.back(),h));\n            }\n            \n            return stepsVector;\n\n\n        }\n\n    private:\n        /**\n         * This function computes on single runge kutta step and returns its result.\n         * \n         * @param f the function we are integrating over\n         * @param y0 the starting value (the initial value or the previous step's result)\n         * @param h the step size\n         * \n         * @return the computation of one runge kutta step\n         */\n        template<typename Function>\n        Step iteration(Function &&f, Step &y0, const double h){\n            \n            // initialize current step as previous step\n            Step y1 = y0;\n\n            // temporary vector to store the increments\n            std::vector<Step> increments;\n            \n            // calculate an increment per loop iteration\n            for(unsigned int i = 0; i < size; i++){\n\n                Step increment = y0;\n                // second loop to account for dependency of current increments on previous increments\n                for(unsigned int k = 0; k < i; k++){\n                    increment += h*A(i,k) * increments[k];\n                }\n\n                // store the increment                \n                increments.push_back(f(increment));\n            }\n\n            // now we add the increments with correct weights to y0 which we already copied over to y1\n            for(unsigned int i = 0; i < size; i++){\n                y1 += h*b(i) *increments[i];\n            }\n\n            return y1;\n\n        }\n\n\n        const Eigen::MatrixXd A;\n        const Eigen::VectorXd b;\n        unsigned int size;\n};\n\n\n\n\n\n\n\n\n\n\n\n\ntemplate <typename Step> class ImplicitRungeKuttaIntegrator {\n\n    public:\n        ImplicitRungeKuttaIntegrator(const Eigen::MatrixXd &A, const Eigen::VectorXd &b) : A(A),b(b),size(A.cols()){\n        }\n\n\n        /**\n         * The solve methods applies an implicit Runge Kutta method to a given ODE\n         * \n         * @param f the function we are integrating over\n         * @param the Jacobian of f, needed for finding 0 (newton method) to solve for stages.\n         * @param time the time interval we want to integrate over\n         * @param y0 the initial state of the system\n         * @param steps the number of integration steps we would like to make (number of steps equals number of runge kutta method evaluations)\n         * \n         * @return a std::vector of states, one for every integration step performed. The first step will be the supplied y0.\n         */\n        template<typename Function, typename Jacobian>\n        std::vector<Step> solve(Function &&f, Jacobian && J, double time, const Step &y0, unsigned int steps){\n\n            std::vector<Step> stepsVector;\n            \n            // as advertised the first position will be our initial state\n            stepsVector.push_back(y0);\n\n            // knowing the total time and number of steps allows us to calculate the time we integrate over every step\n            double h = time / steps;\n\n            // now we call the solver \"steps\" times to do the actual integration\n            for(unsigned int i = 0; i < steps; i++){\n                // integrate and directly add to our list\n                stepsVector.push_back(iteration(f,stepsVector.back(),h));\n            }\n            \n            return stepsVector;\n\n\n        }\n\n    private:\n        /**\n         * This function computes on single runge kutta step and returns its result. This method uses \n         * \n         * @param f the function we are integrating over\n         * @param y0 the starting value (the initial value or the previous step's result)\n         * @param h the step size\n         * \n         * @return the computation of one runge kutta step\n         */\n        template<typename Function, typename Jacobian>\n        Step iteration(Function &&f, Jacobian && J, Step &y0, const double h){\n            \n            throw \"not yet implemented\";\n            // TODO \n\n        }\n\n\n    private:\n        const Eigen::MatrixXd A;\n        const Eigen::VectorXd b;\n        unsigned int size;\n};\n\n\n// a collection of optimization methods needed for implicit runge-kutta methods\nnamespace OptimizationMethods{\n\n    /**\n     * Takes a function f, its derivative J as well as a starting point x0 and finds the root x' with f(x') = 0\n     * Source: Adapted from 'C++ code 8.4.4.5' of the book https://www.sam.math.ethz.ch/~grsam/NCSE19/NumCSE_Lecture_Document.pdf\n     * \n     * @param f the function whose root we want to find\n     * @param J the jacobian of f\n     * @param x0 the starting value for the newton iteration\n     * @param reltol if the difference between two iterations is smaller than rtol*x', with x' a likely root, we stop the iteration\n     * @param abstol if the difference between two iterations is smaller than abstol we stop the iteration \n     * \n     * @exception if the function does not converge an error will be thrown\n     * \n     * \n     * @return the root of f (the value x where f(x) = 0)\n     * \n     */\n    template<typename Step, typename Function, typename Jacobian>\n    Step dampedNewton(Function &&f, Jacobian &&J, Step x0, double reltol = 1e-7, double abstol=1e-8){\n\n        // first we check the dimensionality of the function\n        uint32_t n = x0.size();\n        Step correction(n), tentativeCorrection(n);\n        Step x(n);\n        Step xTemp(n);\n        double correctionNorm, tentativeCorrectionNorm;\n        \n        // convergence variables\n        double lambda = 1.0;\n        double lmin = 1E-3;\n\n        do {\n            // calculate the difference to the next iterate\n            auto jacobianLUFactorized = J(x).lu();\n            correction = jacobianLUFactorized.solve(f(x));\n            correctionNorm = correction.norm();\n\n            do {\n                // reduction of damping factor\n                lambda /= 2;\n                // check for non convergence\n                if(lambda < lmin){\n                    throw \"No convergence\";\n                }\n                // tentative next iterate\n                xTemp = x-lambda*correction;\n                tentativeCorrection = jacobianLUFactorized.solve(f(xTemp));\n                tentativeCorrectionNorm = tentativeCorrection.norm();\n            } while(tentativeCorrectionNorm > (1-lambda/2)*correctionNorm);\n            // we accept the new step\n            x = xTemp;\n            // we somewhat reduce the damping\n            lambda = std::min(2*lambda,1.0);\n        } while((tentativeCorrectionNorm > reltol*x.norm()) && tentativeCorrectionNorm > abstol);\n    }\n}\n\n\n\n\n\n\n\n\n#endif\n", "meta": {"hexsha": "58aea6c3b3197676d6c6bb917e14ea4cfd15db82", "size": 8648, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/rk_implementer.hpp", "max_stars_repo_name": "davidrzs/Runge-Kutta-ODE-Solver", "max_stars_repo_head_hexsha": "d6295007e78ae390ff95e2c25e4bcc906ce9624e", "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/rk_implementer.hpp", "max_issues_repo_name": "davidrzs/Runge-Kutta-ODE-Solver", "max_issues_repo_head_hexsha": "d6295007e78ae390ff95e2c25e4bcc906ce9624e", "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/rk_implementer.hpp", "max_forks_repo_name": "davidrzs/Runge-Kutta-ODE-Solver", "max_forks_repo_head_hexsha": "d6295007e78ae390ff95e2c25e4bcc906ce9624e", "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.4541832669, "max_line_length": 211, "alphanum_fraction": 0.5915818686, "num_tokens": 1881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.885631470799559, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.7134932225174321}}
{"text": "#include \"matrix_add_subtract.h\"\n#include \"common/pixel_benchmark.h\"\n\n#include <opencv2/opencv.hpp>\n#include <Eigen/Dense>\n\nstatic void matrix_add_f32_opencv(float* mA, float* mB, float* mC, size_t M, size_t N)\n{\n    cv::Size size;\n    size.height = M;\n    size.width = N;\n    cv::Mat matA = cv::Mat(size, CV_32FC1, mA);\n    cv::Mat matB = cv::Mat(size, CV_32FC1, mB);\n    cv::Mat matC = cv::Mat(size, CV_32FC1, mC);\n    cv::add(matA, matB, matC);\n}\n\nstatic void matrix_add_f32_eigen(float* mA, float* mB, float* mC, size_t M, size_t N)\n{\n    Eigen::Map<Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>> eA(mA, M, N);\n    Eigen::Map<Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>> eB(mB, M, N);\n    Eigen::Map<Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>> eC(mC, M, N);\n    eC = eA + eB;\n}\n\n//----------------------------------------------------------------------\n\nstatic void matrix_subtract_f32_opencv(float* mA, float* mB, float* mC, size_t M, size_t N)\n{\n    cv::Size size;\n    size.height = M;\n    size.width = N;\n    cv::Mat matA = cv::Mat(size, CV_32FC1, mA);\n    cv::Mat matB = cv::Mat(size, CV_32FC1, mB);\n    cv::Mat matC = cv::Mat(size, CV_32FC1, mC);\n    cv::subtract(matA, matB, matC);\n}\n\nstatic void matrix_subtract_f32_eigen(float* mA, float* mB, float* mC, size_t M, size_t N)\n{\n    Eigen::Map<Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>> eA(mA, M, N);\n    Eigen::Map<Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>> eB(mB, M, N);\n    Eigen::Map<Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>> eC(mC, M, N);\n    eC = eA - eB;\n}\n\nstatic void matrix_add_f32_test()\n{\n    cv::Mat image = cv::imread(\"river_bank2.png\");\n    std::vector<cv::Mat> channels;\n    cv::split(image, channels);\n    cv::Mat b_channels = channels[0];\n    cv::Mat g_channels = channels[1];\n    cv::Mat r_channels = channels[2];\n\n    b_channels.convertTo(b_channels, CV_32FC1);\n    g_channels.convertTo(g_channels, CV_32FC1);\n    r_channels.convertTo(r_channels, CV_32FC1);\n\n    cv::Size size = image.size();\n    size_t height = size.height; // M\n    size_t width = size.width; // N\n    printf(\"image info: height=%zu, width=%zu\\n\", height, width);\n\n    float* mA = (float*)b_channels.data;\n    float* mB = (float*)g_channels.data;\n\n    size_t buf_size = sizeof(float)*height*width;\n    float* mC_opencv = (float*)malloc(buf_size);\n    float* mC_eigen = (float*)malloc(buf_size);\n    float* mC_naive = (float*)malloc(buf_size);\n    float* mC_asimd = (float*)malloc(buf_size);\n    double t_start, t_cost;\n\n    t_start = pixel_get_current_time();\n    matrix_add_f32_eigen(mA, mB, mC_eigen, height, width);\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"matrix_add_f32, eigen, time cost %.2lf ms\\n\", t_cost);\n\n    t_start = pixel_get_current_time();\n    matrix_add_f32_opencv(mA, mB, mC_opencv, height, width);\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"matrix_add_f32, opencv, time cost %.2lf ms\\n\", t_cost);\n\n    t_start = pixel_get_current_time();\n    matrix_add_f32_naive(mA, mB, mC_naive, height, width);\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"matrix_add_f32, naive,  time cost %.2lf ms\\n\", t_cost);\n\n    t_start = pixel_get_current_time();\n    matrix_add_f32_asimd(mA, mB, mC_asimd, height, width);\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"matrix_add_f32, asimd,  time cost %.2lf ms\\n\", t_cost);\n\n    // validate result, check if they are match\n    int mis_opencv = 0;\n    int mis_eigen = 0;\n    int mis_asimd = 0;\n    size_t len = height * width;\n    for (size_t i=0; i<len; i++) {\n        if (mC_naive[i]!=mC_opencv[i]) {\n            mis_opencv ++;\n        }\n\n        if (mC_naive[i]!=mC_eigen[i]) {\n            mis_eigen ++;\n        }\n\n        if (mC_naive[i]!=mC_asimd[i]) {\n            mis_asimd ++;\n        }\n    }\n    printf(\"mis_opencv=%d, mis_eigen=%d, mis_asimd=%d\\n\", mis_opencv, mis_eigen, mis_asimd);\n\n}\n\nstatic void matrix_subtract_f32_test()\n{\n    cv::Mat image = cv::imread(\"river_bank2.png\");\n    std::vector<cv::Mat> channels;\n    cv::split(image, channels);\n    cv::Mat b_channels = channels[0];\n    cv::Mat g_channels = channels[1];\n    cv::Mat r_channels = channels[2];\n\n    b_channels.convertTo(b_channels, CV_32FC1);\n    g_channels.convertTo(g_channels, CV_32FC1);\n    r_channels.convertTo(r_channels, CV_32FC1);\n\n    cv::Size size = image.size();\n    size_t height = size.height; // M\n    size_t width = size.width; // N\n    printf(\"image info: height=%zu, width=%zu\\n\", height, width);\n\n    float* mA = (float*)b_channels.data;\n    float* mB = (float*)g_channels.data;\n\n    size_t buf_size = sizeof(float)*height*width;\n    float* mC_opencv = (float*)malloc(buf_size);\n    float* mC_eigen = (float*)malloc(buf_size);\n    float* mC_naive = (float*)malloc(buf_size);\n    float* mC_asimd = (float*)malloc(buf_size);\n    double t_start, t_cost;\n\n    t_start = pixel_get_current_time();\n    matrix_subtract_f32_eigen(mA, mB, mC_eigen, height, width);\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"matrix_subtract_f32, eigen, time cost %.2lf ms\\n\", t_cost);\n\n    t_start = pixel_get_current_time();\n    matrix_subtract_f32_opencv(mA, mB, mC_opencv, height, width);\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"matrix_subtract_f32, opencv, time cost %.2lf ms\\n\", t_cost);\n\n    t_start = pixel_get_current_time();\n    matrix_subtract_f32_naive(mA, mB, mC_naive, height, width);\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"matrix_subtract_f32, naive,  time cost %.2lf ms\\n\", t_cost);\n\n    t_start = pixel_get_current_time();\n    matrix_subtract_f32_asimd(mA, mB, mC_asimd, height, width);\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"matrix_subtract_f32, asimd,  time cost %.2lf ms\\n\", t_cost);\n\n    // validate result, check if they are match\n    int mis_opencv = 0;\n    int mis_eigen = 0;\n    int mis_asimd = 0;\n    size_t len = height * width;\n    for (size_t i=0; i<len; i++) {\n        if (mC_naive[i]!=mC_opencv[i]) {\n            mis_opencv ++;\n        }\n\n        if (mC_naive[i]!=mC_eigen[i]) {\n            mis_eigen ++;\n        }\n\n        if (mC_naive[i]!=mC_asimd[i]) {\n            mis_asimd ++;\n        }\n    }\n    printf(\"mis_opencv=%d, mis_eigen=%d, mis_asimd=%d\\n\", mis_opencv, mis_eigen, mis_asimd);\n\n}\n\n\nint main() {\n\n    matrix_add_f32_test();\n    matrix_subtract_f32_test();\n\n    return 0;\n}", "meta": {"hexsha": "8ab189a7a6eb4dd8cc9a617b1291c001aa8542e2", "size": 6488, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "matcalc/matrix_add_subtract_test.cpp", "max_stars_repo_name": "zchrissirhcz/pixel", "max_stars_repo_head_hexsha": "6bfe4b2f2b80de64c7de4b6d8735de8000b7dc3a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 38.0, "max_stars_repo_stars_event_min_datetime": "2020-12-23T16:37:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T13:46:04.000Z", "max_issues_repo_path": "matcalc/matrix_add_subtract_test.cpp", "max_issues_repo_name": "zchrissirhcz/pixel", "max_issues_repo_head_hexsha": "6bfe4b2f2b80de64c7de4b6d8735de8000b7dc3a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-01-31T16:04:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T13:58:11.000Z", "max_forks_repo_path": "matcalc/matrix_add_subtract_test.cpp", "max_forks_repo_name": "zchrissirhcz/pixel", "max_forks_repo_head_hexsha": "6bfe4b2f2b80de64c7de4b6d8735de8000b7dc3a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-11-23T09:33:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-15T08:13:56.000Z", "avg_line_length": 33.4432989691, "max_line_length": 99, "alphanum_fraction": 0.6407213317, "num_tokens": 2005, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225575, "lm_q2_score": 0.8354835309589074, "lm_q1q2_score": 0.713430054391284}}
{"text": "#include <mona/utility.hpp>\n#include <mona/targets/png.hpp>\n#include <mona/axes3.hpp>\n#include <mona/surface_mesh.hpp>\n\n#include <armadillo>\n\n\nauto f(double x, double y)\n{\n    return (2*x*x + y*y) * std::exp(1 - x*x -y*y);\n};\n\n\ntemplate <typename F>\nauto get_surface(F f)\n{\n    arma::fvec line = mona::linspace(-2, 2, 50);\n    auto [x, y] = mona::meshgrid(line, line);\n    auto z = mona::apply(f, x, y);\n\n    auto mesh = mona::surface_mesh(x, y, z);\n\n    return mesh;\n}\n\n\nint main()\n{\n    auto png  = mona::png(800, 600);\n    auto axes = mona::axes3({-4, 4}, {-4, 4}, {-4, 4}, 5);\n    auto surf = get_surface(f);\n\n    axes.submit(surf);\n    png.save(axes, \"image.png\");\n}", "meta": {"hexsha": "35c6fb362d945000c992ec9906f05feb808e35e7", "size": 671, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/save_to_png/main.cpp", "max_stars_repo_name": "Eleobert/mona", "max_stars_repo_head_hexsha": "079e70b190b0850cf2579c1b0872da87f2706d80", "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": "examples/save_to_png/main.cpp", "max_issues_repo_name": "Eleobert/mona", "max_issues_repo_head_hexsha": "079e70b190b0850cf2579c1b0872da87f2706d80", "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": "examples/save_to_png/main.cpp", "max_forks_repo_name": "Eleobert/mona", "max_forks_repo_head_hexsha": "079e70b190b0850cf2579c1b0872da87f2706d80", "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.6388888889, "max_line_length": 58, "alphanum_fraction": 0.5856929955, "num_tokens": 232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951625409307, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.7133955353436745}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include \"ReferenceModel.hpp\"\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(void)\n{\n    cout << \"Started\" << endl;\n    ReferenceModel_Config_t config_model_z;\n    // Reference model\n    config_model_z.A        = MatrixXd::Zero(2,2);\n    config_model_z.B        = MatrixXd::Zero(2,1);\n    config_model_z.states0  = VectorXd::Zero(2);\n    config_model_z.dt       = 1.0/200.0;\n    config_model_z.A(0,0)   =  0.0;\n    config_model_z.A(0,1)   =  1.0;\n    config_model_z.A(1,0)   = -5.416;\n    config_model_z.A(1,1)   = -7.027;\n    config_model_z.B(0,0)   = -0.1145;\n    config_model_z.B(1,0)   =  6.273;\n\n    cout << config_model_z.A;\n\n    ReferenceModel model;\n    model.initialize(config_model_z);\n\n    for(int i=0; i<1000; i++)\n    {\n        if (i >= 200)\n        {\n            VectorXd inputs = VectorXd::Zero(1);\n            inputs(0) = -0.5;\n            model.update(inputs);\n        }\n        else\n            model.update(VectorXd::Zero(1));\n        \n        VectorXd outputs;\n        model.get_outputs(outputs);\n        \n        cout << i << \",\" << outputs(0) << endl;\n        \n    }\n    return 0;\n}\n", "meta": {"hexsha": "3e14e097746b326cd348110af2cb01fc6769336b", "size": 1156, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "crazyflie_mrac_controllers/test/unittest_ReferenceModel.cpp", "max_stars_repo_name": "fjctp/crazyflie_mrac_ros", "max_stars_repo_head_hexsha": "d43df1832860addd0ff7fbad391c7871cb3c6577", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-10-09T03:17:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-24T06:00:12.000Z", "max_issues_repo_path": "crazyflie_mrac_controllers/test/unittest_ReferenceModel.cpp", "max_issues_repo_name": "fjctp/crazyflie_mrac_ros", "max_issues_repo_head_hexsha": "d43df1832860addd0ff7fbad391c7871cb3c6577", "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": "crazyflie_mrac_controllers/test/unittest_ReferenceModel.cpp", "max_forks_repo_name": "fjctp/crazyflie_mrac_ros", "max_forks_repo_head_hexsha": "d43df1832860addd0ff7fbad391c7871cb3c6577", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-24T22:48:29.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-24T22:48:29.000Z", "avg_line_length": 24.0833333333, "max_line_length": 50, "alphanum_fraction": 0.5501730104, "num_tokens": 346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632996617212, "lm_q2_score": 0.7690802423634961, "lm_q1q2_score": 0.713216791262848}}
{"text": "#include <cmath>\n#include <memory>\n\n#include <Eigen/Geometry>\n\n#include \"rclcpp/rclcpp.hpp\"\n#include \"std_msgs/msg/float64.hpp\"\n#include \"sensor_msgs/msg/imu.hpp\"\n\nusing namespace std::chrono_literals;\nusing std::placeholders::_1;\n\ndouble normaliseAngle(double x)\n{\n  x = fmod(x + M_PI, 2*M_PI);\n  if (x < 0)\n    x += 2*M_PI;\n  return x - M_PI;\n}\n\nEigen::Vector3d ToEulerAngles(Eigen::Quaterniond q)\n{\n  Eigen::Vector3d angles;\n\n  // roll (x-axis rotation)\n  double sinr_cosp = 2 * (q.w() * q.x() + q.y() * q.z());\n  double cosr_cosp = 1 - 2 * (q.x() * q.x() + q.y() * q.y());\n  angles(0) = std::atan2(sinr_cosp, cosr_cosp);\n\n  // pitch (y-axis rotation)\n  double sinp = 2 * (q.w() * q.y() - q.z() * q.x());\n  if (std::abs(sinp) >= 1)\n    angles(1) = std::copysign(M_PI / 2, sinp); // use 90 degrees if out of range\n  else\n    angles(1) = std::asin(sinp);\n\n  // yaw (z-axis rotation)\n  double siny_cosp = 2 * (q.w() * q.z() + q.x() * q.y());\n  double cosy_cosp = 1 - 2 * (q.y() * q.y() + q.z() * q.z());\n  angles(2) = std::atan2(siny_cosp, cosy_cosp);\n\n  return angles;\n}\n\nclass Imu2rpy : public rclcpp::Node\n{\npublic:\n  Imu2rpy()\n      : Node(\"imu_to_rpy\")\n  {\n    imu_sub_ = this->create_subscription<sensor_msgs::msg::Imu>(\n        \"imu\", 10, std::bind(&Imu2rpy::imu_callback, this, _1));\n\n    roll_publisher_ = this->create_publisher<std_msgs::msg::Float64>(\"roll\", 10);\n    pitch_publisher_ = this->create_publisher<std_msgs::msg::Float64>(\"pitch\", 10);\n    yaw_publisher_ = this->create_publisher<std_msgs::msg::Float64>(\"yaw\", 10);\n\n    roll_rate_publisher_ = this->create_publisher<std_msgs::msg::Float64>(\"roll_rate\", 10);\n    pitch_rate_publisher_ = this->create_publisher<std_msgs::msg::Float64>(\"pitch_rate\", 10);\n    yaw_rate_publisher_ = this->create_publisher<std_msgs::msg::Float64>(\"yaw_rate\", 10);\n  }\n\nprivate:\n\n  void imu_callback(const sensor_msgs::msg::Imu::SharedPtr msg)\n  {\n    Eigen::Quaterniond q(msg->orientation.w, msg->orientation.x, msg->orientation.y, msg->orientation.z);\n    //auto euler = q.toRotationMatrix().eulerAngles(2, 1, 0);\n    auto euler = ToEulerAngles(q);\n\n    double roll = euler(0);\n    double pitch = euler(1);\t\n    double yaw = euler(2);\n\n    //std::string message1 = \"w=\" + std::to_string(q.w()) + \", x= \" + std::to_string(q.x()) +\n    //  \", y= \" + std::to_string(q.y()) + \", z= \" + std::to_string(q.z());\n    //RCLCPP_INFO(this->get_logger(), \"Incoming quaternion '%s'\", message1.c_str());\n\n    //std::string message2 = \"roll=\" + std::to_string(roll) + \", pitch= \" + std::to_string(pitch) + \", yaw= \" + std::to_string(yaw);\n    //RCLCPP_INFO(this->get_logger(), \"Converted euler angles '%s'\", message2.c_str());\n\n    //Eigen::Quaterniond q2 = Eigen::AngleAxisd(roll, Eigen::Vector3d::UnitX()) *\n    //  Eigen::AngleAxisd(pitch, Eigen::Vector3d::UnitY()) *\n    //  Eigen::AngleAxisd(yaw, Eigen::Vector3d::UnitZ());\n\n    //std::string message3 = \"w=\" + std::to_string(q2.w()) + \", x= \" + std::to_string(q2.x()) +\n    //  \", y= \" + std::to_string(q2.y()) + \", z= \" + std::to_string(q2.z());\n    //RCLCPP_INFO(this->get_logger(), \"Converted quaternion '%s'\\n\", message3.c_str());\n\n    auto roll_msg = std_msgs::msg::Float64();\n    roll_msg.data = roll;\n\n    auto pitch_msg = std_msgs::msg::Float64();\n    pitch_msg.data = pitch;\n\n    auto yaw_msg = std_msgs::msg::Float64();\n    yaw_msg.data = yaw;\n\n    auto roll_rate_msg = std_msgs::msg::Float64();\n    roll_rate_msg.data = msg->angular_velocity.x;\n\n    auto pitch_rate_msg = std_msgs::msg::Float64();\n    pitch_rate_msg.data = msg->angular_velocity.y;\n\n    auto yaw_rate_msg = std_msgs::msg::Float64();\n    yaw_rate_msg.data = msg->angular_velocity.z;\n\n    roll_publisher_->publish(roll_msg);\n    pitch_publisher_->publish(pitch_msg);\n    yaw_publisher_->publish(yaw_msg);\n    roll_rate_publisher_->publish(roll_rate_msg);\n    pitch_rate_publisher_->publish(pitch_rate_msg);\n    yaw_rate_publisher_->publish(yaw_rate_msg);\n  }\n\n  rclcpp::Subscription<sensor_msgs::msg::Imu>::SharedPtr imu_sub_;\n  rclcpp::Publisher<std_msgs::msg::Float64>::SharedPtr roll_publisher_;\n  rclcpp::Publisher<std_msgs::msg::Float64>::SharedPtr pitch_publisher_;\n  rclcpp::Publisher<std_msgs::msg::Float64>::SharedPtr yaw_publisher_;\n  rclcpp::Publisher<std_msgs::msg::Float64>::SharedPtr roll_rate_publisher_;\n  rclcpp::Publisher<std_msgs::msg::Float64>::SharedPtr pitch_rate_publisher_;\n  rclcpp::Publisher<std_msgs::msg::Float64>::SharedPtr yaw_rate_publisher_;\n};\n\nint main(int argc, char * argv[])\n{\n  rclcpp::init(argc, argv);\n  rclcpp::spin(std::make_shared<Imu2rpy>());\n  rclcpp::shutdown();\n  return 0;\n}\n", "meta": {"hexsha": "3f09b1fbbb3392f0c69b6d58d7dfe3ea0b08070c", "size": 4593, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "imu_rpy/src/imu_rpy_node.cpp", "max_stars_repo_name": "bdholt1/rpi-quadcopter", "max_stars_repo_head_hexsha": "b39449f3f5e930e822c56df83367970374be9fc6", "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": "imu_rpy/src/imu_rpy_node.cpp", "max_issues_repo_name": "bdholt1/rpi-quadcopter", "max_issues_repo_head_hexsha": "b39449f3f5e930e822c56df83367970374be9fc6", "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": "imu_rpy/src/imu_rpy_node.cpp", "max_forks_repo_name": "bdholt1/rpi-quadcopter", "max_forks_repo_head_hexsha": "b39449f3f5e930e822c56df83367970374be9fc6", "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": 34.7954545455, "max_line_length": 132, "alphanum_fraction": 0.6544741999, "num_tokens": 1395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797003640646, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.7131461584393698}}
{"text": "/**\n * @file categorical.hpp\n * @author Vahid Bastani\n *\n * implementation of categorical (multinomial) distribution\n */\n#ifndef SSMPACK_DISTRIBUTION_CATEGORICAL_HPP\n#define SSMPACK_DISTRIBUTION_CATEGORICAL_HPP\n\n#include \"ssmkit/random/generator.hpp\"\n\n#include <armadillo>\n\nnamespace ssmkit {\nnamespace distribution {\n\n/** Categorical (multinomial) distribution\n * \n * \\f{equation}{p(x|\\mathbf{p}) = \\mathcal{Cat}(\\mathbf{p})\\f}\n * where \\f$\\mathbf{p} = [p_0, \\cdots, p_N]^T\\f$ and \\f$p(x=i|\\mathbf{p}) = p_i\\f$\n */\nclass Categorical {\n  //! Type of the parameter vector \\f$\\mathbf{p}\\f$.\n  using TParameterVar = arma::vec;\n  //! Type of the random variable \\f$x\\f$.\n  using TValueType = unsigned int;\n\n private:\n //! The parameter vector \\f$\\mathbf{p}\\f$.\n TParameterVar param_;\n //! Cumulative distribution function. \n TParameterVar cdf_;\n //! Core random number distribution.\n std::uniform_real_distribution<double> uniform_;\n //! Length of the parameter vector \\f$N+1\\f$.\n TValueType max_;\n\n public:\n  //! Default constructor \\f$\\mathbf{p}=[1.0]\\f$.\n  Categorical() : Categorical(arma::ones<arma::vec>(1)) {}\n  /** Constructor\n   * @param parameter The parameter vector \\f$\\mathbf{p}\\f$.\n   * @pre The sum of the elements of \\p parameter should be 1.0.\n   */\n  Categorical(TParameterVar parameters)\n      : param_(std::move(parameters)) {calcCDF(); calcMax();}\n  //! Return a random variable from the distribution.\n  TValueType random() {\n    double rv = uniform_(random::Generator::get().getGenerator());\n    for (TValueType i = 0; i < max_; ++i)\n      if (rv < cdf_(i))\n        return i;\n\n    return 0; // this line never get reached\n  }\n  //! Return likelihood of the given random variable\n  double likelihood(const TValueType &rv) {\n    return param_(rv);\n  }\n\n  /** Change parameters of the distribution\n   * @param parameter The parameter vector \\f$\\mathbf{p}\\f$.\n   * @pre The sum of the elements of \\p parameter should be 1.0.\n   */\n  Categorical &parameterize(const TParameterVar & param){\n    param_ = param;\n    calcCDF();\n    calcMax();\n    return *this;\n  }\n\n  private:\n   void calcCDF() { cdf_ = arma::cumsum(param_); }\n   void calcMax() { max_ = param_.n_rows; }\n};\n\n} // namespace ssmkit\n} // namespace distribution\n\n#endif //SSMPACK_DISTRIBUTION_CATEGORICAL_HPP\n", "meta": {"hexsha": "05b312ac6a289ce02c10557cf69918fcde6afd97", "size": 2283, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/ssmkit/distribution/categorical.hpp", "max_stars_repo_name": "vahid-bastani/ssmpack", "max_stars_repo_head_hexsha": "68aed98b1c661a7d1c9e5610656de57f6a967532", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-07-08T09:18:49.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-10T06:46:55.000Z", "max_issues_repo_path": "src/ssmkit/distribution/categorical.hpp", "max_issues_repo_name": "vahidbas/ssmkit", "max_issues_repo_head_hexsha": "68aed98b1c661a7d1c9e5610656de57f6a967532", "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/ssmkit/distribution/categorical.hpp", "max_forks_repo_name": "vahidbas/ssmkit", "max_forks_repo_head_hexsha": "68aed98b1c661a7d1c9e5610656de57f6a967532", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-01-03T17:46:08.000Z", "max_forks_repo_forks_event_max_datetime": "2018-01-03T17:46:08.000Z", "avg_line_length": 28.1851851852, "max_line_length": 82, "alphanum_fraction": 0.6763031099, "num_tokens": 648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.7931059609645724, "lm_q1q2_score": 0.7130985282312117}}
{"text": "\n#pragma once\n\n#include \"numeric/dense_matrix.hpp\"\n#include <Eigen/Geometry>\n\n/// \\file jacobian_determinant.hpp\n\nnamespace neon\n{\nnamespace detail\n{\ntemplate <typename matrix_type>\n[[nodiscard]] auto jacobian_determinant(matrix_type const& jacobian)\n{\n    return jacobian.determinant();\n}\n\n[[nodiscard]] inline auto jacobian_determinant(matrix32 const& jacobian)\n{\n    return jacobian.col(0).cross(jacobian.col(1)).norm();\n}\n\n[[nodiscard]] inline auto jacobian_determinant(matrix31 const& jacobian) { return jacobian.norm(); }\n}\n\n/**\n * Compute the Jacobian determinant for a volume or surface mapping.  In three\n * dimensions it performs the following operation:\n * \\f{align*}{\n *     j &= \\det \\begin{bmatrix}\n *             \\frac{\\partial x}{\\partial \\xi} & \\frac{\\partial x}{\\partial \\eta} & \\frac{\\partial\n * x}{\\partial \\zeta} \\\\\n *             \\frac{\\partial y}{\\partial \\xi} & \\frac{\\partial y}{\\partial \\eta} & \\frac{\\partial\n * y}{\\partial \\zeta} \\\\ \\frac{\\partial z}{\\partial \\xi} & \\frac{\\partial z}{\\partial \\eta} &\n * \\frac{\\partial z}{\\partial \\zeta} \\end{bmatrix} \\f}\n *\n * However the determinant for non-square Jacobian is not defined.  When there\n * is a mapping from \\f$ \\mathbb{R}^3 \\f$ to \\f$ \\mathbb{R}^2 \\f$ the Jacobian\n * `determinant' can be computed by\n * \\f{align*}{\n *     j &= || \\mathbf{x}_{,\\mathbf{\\xi}} \\times \\mathbf{x}_{,\\mathbf{\\eta}} ||\n * \\f}\n * where the Jacobian is given by the non-square matrix\n * \\f{align*}{\n *    & \\begin{bmatrix}\n *          \\frac{\\partial x}{\\partial \\xi} & \\frac{\\partial x}{\\partial \\eta} \\\\\n *          \\frac{\\partial y}{\\partial \\xi} & \\frac{\\partial y}{\\partial \\eta} \\\\\n *          \\frac{\\partial z}{\\partial \\xi} & \\frac{\\partial z}{\\partial \\eta}\n *      \\end{bmatrix}\n * \\f}\n * This is useful when the surface is described by a two dimensional\n * element but there are only three dimensional coordinates \\cite Anton1998.\n */\ntemplate <typename matrix_expression>\n[[nodiscard]] inline auto jacobian_determinant(matrix_expression const& jacobian)\n{\n    return detail::jacobian_determinant(jacobian.eval());\n}\n}\n", "meta": {"hexsha": "b892b5a4ef0a2341a43a99c7f47a972a9bec0b92", "size": 2085, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/math/jacobian_determinant.hpp", "max_stars_repo_name": "annierhea/neon", "max_stars_repo_head_hexsha": "4eb51a06bda6bbf32c54fff8f39c9e02d429cfd1", "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/jacobian_determinant.hpp", "max_issues_repo_name": "annierhea/neon", "max_issues_repo_head_hexsha": "4eb51a06bda6bbf32c54fff8f39c9e02d429cfd1", "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/jacobian_determinant.hpp", "max_forks_repo_name": "annierhea/neon", "max_forks_repo_head_hexsha": "4eb51a06bda6bbf32c54fff8f39c9e02d429cfd1", "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.1803278689, "max_line_length": 100, "alphanum_fraction": 0.660911271, "num_tokens": 597, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026505426832, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.7130192323865943}}
{"text": "#define BOOST_TEST_MODULE test SPH_2D\n#include <boost/test/included/unit_test.hpp>\n#include <boost/test/tools/floating_point_comparison.hpp>\n#include <boost/test/parameterized_test.hpp>\n#include <boost/bind.hpp>\n\n#include \"SPH_2D.h\"\n#include \"file_writer.h\"\n\nusing namespace boost::unit_test;\nnamespace tt=boost::test_tools;\n\nSPH_main domain;\n\n/* \n * Spline Functions Tests\n */\nBOOST_AUTO_TEST_SUITE(TestSplineFunctions, * description(\"Testsing Cubic Spline Functions\"));\n\nBOOST_AUTO_TEST_CASE(TestCubicSplineLess,  * description(\"Distance between 0 and 1\"))\n{\n    domain.h = 1.;\n    double dn[2] = { 0.5 , 0. };\n    double tres = domain.cubic_spline(dn);\n    double res = 10.0 * (1.0 - 1.5 * 1/4 + 0.75 * 1/8) / (7.0 * M_PI);\n    BOOST_TEST(tres == res, tt::tolerance(0.0001));\n}\n\nBOOST_AUTO_TEST_CASE(TestCubicSplineGreater, * description(\"Distance between 1 and 2\"))\n{\n    domain.h = 1.;\n    double dn[2] = {1, 0};\n    double tres = domain.cubic_spline(dn);\n    double res = 10  * 0.25 / (7 * M_PI);\n    BOOST_TEST(tres == res, tt::tolerance(0.0001));\n}\n\nBOOST_AUTO_TEST_CASE(TestCubicSplineOutsite, * description(\"Distance outside the spline\"))\n{\n    domain.h = 1.;\n    double dn[2] = {2, 1};\n    double tres = domain.cubic_spline(dn);\n    double res = 0;\n    BOOST_TEST(tres == res, tt::tolerance(0.0001));\n}\n\nBOOST_AUTO_TEST_CASE(TestCubicSplineFirstLess, \\\n* description(\"First derivative of distance between 0 and 1\"))\n{\n    domain.h = 1.;\n    double dn[2] = {0.5, 0};\n    double tres = domain.cubic_spline_first_derivative(dn);\n    double res = 10 * (-3 * 0.5 + 2.25 * 1/4) / (7 * M_PI);\n    BOOST_TEST(tres == res, tt::tolerance(0.0001));\n}\n\nBOOST_AUTO_TEST_CASE(TestCubicSplineFirstGreater, \\\n* description(\"First derivative of distance between 1 and 2\"))\n{\n    domain.h = 1.;\n    double dn[2] = {1, 0};\n    double tres = domain.cubic_spline_first_derivative(dn);\n    double res = -10 * 0.75 / (7 * M_PI);\n    BOOST_TEST(tres == res, tt::tolerance(0.0001));\n}\n\nBOOST_AUTO_TEST_CASE(TestCubicSplineFirstOutside, \\\n* description(\"First derivative of distance outside the spline\"))\n{\n    domain.h = 1.;\n    double dn[2] = {2., 1.};\n    double tres = domain.cubic_spline_first_derivative(dn);\n    double res = 0;\n    BOOST_TEST(tres == res, tt::tolerance(0.0001));\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n\n\n/*\n * Gradient Function Tests\n */\n\nBOOST_AUTO_TEST_SUITE(TestGradient, * description(\"Testing the Gradient Update Function\"));\n\nBOOST_AUTO_TEST_CASE(TestGradientLess, * description(\"Distance between 0 and 1\"))\n{\n    SPH_particle* p1 = new SPH_particle();\n    SPH_particle* p2 = new SPH_particle();\n    \n    domain.h = 1.;\n    domain.mass = 1.;\n    domain.mu = 1.;\n    \n    p1->v[0] = 1.;\n    p1->v[1] = 0.;\n    p1->rho = 1.;\n    p1->P = 1.;\n    p1->a[0] = 0.;\n    p1->a[1] = 0.;\n    p1->D = 0.;\n    \n    p2->v[0] = 0.;\n    p2->v[1] = 0.;\n    p2->rho = 1.;\n    p2->P = 1.;\n    p1->a[0] = 0.;\n    p1->a[1] = 0.;\n    \n    \n    double dn[2] = {0.5 , 0};\n    \n    domain.update_gradients(dn, p1, p2);\n    \n    double res = (10 * (-3 * 0.5 + 2.25 * 1/4) / (7 * M_PI));\n    \n    BOOST_TEST(2 * res == p1->a[0], tt::tolerance(0.0001));\n    BOOST_TEST(res == p1->D, tt::tolerance(0.0001));\n    BOOST_TEST(0 == p1->a[1], tt::tolerance(0.0001));\n    \n    delete p1;\n    delete p2;\n    \n    // Need to check a and D\n}\n\nBOOST_AUTO_TEST_CASE(TestGradientGreater, * description(\"Distance between 1 and 2\"))\n{\n    SPH_particle* p1 = new SPH_particle();\n    SPH_particle* p2 = new SPH_particle();\n    \n    domain.h = 1.;\n    domain.mass = 1.;\n    domain.mu = 1.;\n    \n    p1->v[0] = 1.;\n    p1->v[1] = 1.;\n    p1->rho = 1.;\n    p1->P = 1.;\n    p1->a[0] = 0.;\n    p1->a[1] = 0.;\n    p1->D = 0.;\n    \n    p2->v[0] = 0.;\n    p2->v[1] = 0.;\n    p2->rho = 1.;\n    p2->P = 1.;\n    p1->a[0] = 0.;\n    p1->a[1] = 0.;\n    \n    \n    double dn[2] = {1 , 0};\n    \n    domain.update_gradients(dn, p1, p2);\n    \n    double res = -10 * 0.75 / (7 * M_PI);\n    \n    BOOST_TEST(2 * res == p1->a[1], tt::tolerance(0.0001));\n    BOOST_TEST(res == p1->D, tt::tolerance(0.0001));\n    BOOST_TEST(0 == p1->a[0], tt::tolerance(0.0001));\n    \n    delete p1;\n    delete p2;\n    // Need to check a and D\n}\n\nBOOST_AUTO_TEST_CASE(TestGradinetOutside, * description(\"Distance outside the spline\"))\n{\n    SPH_particle* p1 = new SPH_particle();\n    SPH_particle* p2 = new SPH_particle();\n    \n    domain.h = 1.;\n    domain.mass = 1.;\n    domain.mu = 1.;\n    \n    p1->v[0] = 1.;\n    p1->v[1] = 0.;\n    p1->rho = 1.;\n    p1->P = 1.;\n    p1->a[0] = 0.;\n    p1->a[1] = 0.;\n    p1->D = 0.;\n    \n    p2->v[0] = 0.;\n    p2->v[1] = 0.;\n    p2->rho = 1.;\n    p2->P = 1.;\n    p1->a[0] = 0.;\n    p1->a[1] = 0.;\n    \n    \n    double dn[2] = {2 , 1};\n    \n    domain.update_gradients(dn, p1, p2);\n    \n    BOOST_TEST(0 == p1->a[0], tt::tolerance(0.0001));\n    BOOST_TEST(0 == p1->D, tt::tolerance(0.0001));\n    BOOST_TEST(0 == p1->a[1], tt::tolerance(0.0001));\n    \n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "133902d3416a4b1a6b31d585818a4b90ab6b28f4", "size": 4941, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "acse-4-sph-ness-solution/tests/test_SPH_2D.cpp", "max_stars_repo_name": "Ping-ChenTsai417/Smooth-Particle-Hydrodynamic-Solver-acse4", "max_stars_repo_head_hexsha": "07881458abce12c75f81a833f7132d1db6144ac5", "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": "acse-4-sph-ness-solution/tests/test_SPH_2D.cpp", "max_issues_repo_name": "Ping-ChenTsai417/Smooth-Particle-Hydrodynamic-Solver-acse4", "max_issues_repo_head_hexsha": "07881458abce12c75f81a833f7132d1db6144ac5", "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": "acse-4-sph-ness-solution/tests/test_SPH_2D.cpp", "max_forks_repo_name": "Ping-ChenTsai417/Smooth-Particle-Hydrodynamic-Solver-acse4", "max_forks_repo_head_hexsha": "07881458abce12c75f81a833f7132d1db6144ac5", "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.3399014778, "max_line_length": 93, "alphanum_fraction": 0.5778182554, "num_tokens": 1776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582632076909, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.7130042572189252}}
{"text": "#pragma once\n\n#include <armadillo>\n#include <iostream>\n#include <unordered_map>\n#include <cmath>\n#include <Eigen/Dense>\n// using Eigen::ArrayXi;\nusing namespace std;\n// using namespace arma;\nusing ArrayXL = Eigen::Array<int64_t, Eigen::Dynamic, 1>; \n\n\nstruct shannonEntropy {\n    \n    typedef unordered_map<uint64_t, size_t> histoMap;\n//    typedef unordered_map<int, double> probMap;\n\n    static shannonEntropy::histoMap calcDistribution(const ArrayXL &seq) {\n        shannonEntropy::histoMap histo;\n        for (const uint64_t &v: seq) {\n            shannonEntropy::histoMap::iterator it = histo.find(v);\n            if (it == histo.end()) {\n                histo.insert(std::make_pair(v, 1));\n            }else{\n                it->second = it->second + 1;\n            }\n        }\n        return histo;\n    }\n    \n    static double calcProbability(const shannonEntropy::histoMap &histo, const ArrayXL &seq) {\n        double scale = 1.0 / seq.size();\n        double H=0;\n        for(auto v: histo) {\n            double prob = v.second * scale;\n            H = H - (prob * log2(prob));\n        }\n        return H;\n    }\n    \n    static double calc(const ArrayXL &seq) {\n        shannonEntropy::histoMap histo = shannonEntropy::calcDistribution(seq);\n//        for(auto v: histo) {\n//            cout << v.first << \": \" << v.second << endl;\n//        }\n        double prob = shannonEntropy::calcProbability(histo, seq);\n        return prob;\n    }\n};\n", "meta": {"hexsha": "17436c950b90d39911887fc57f58adc2076b0c0f", "size": 1450, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "shannonEntropy.hpp", "max_stars_repo_name": "chriskiefer/libcccrt", "max_stars_repo_head_hexsha": "e05edc8ed65cecc5515ccb5469e4c73fc4549231", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-03-19T23:16:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-19T03:20:15.000Z", "max_issues_repo_path": "shannonEntropy.hpp", "max_issues_repo_name": "chriskiefer/libcccrt", "max_issues_repo_head_hexsha": "e05edc8ed65cecc5515ccb5469e4c73fc4549231", "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": "shannonEntropy.hpp", "max_forks_repo_name": "chriskiefer/libcccrt", "max_forks_repo_head_hexsha": "e05edc8ed65cecc5515ccb5469e4c73fc4549231", "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.431372549, "max_line_length": 94, "alphanum_fraction": 0.5786206897, "num_tokens": 358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206686206199, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.7129956380304304}}
{"text": "#pragma once\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n#include <vector>\n\n#include \"stiffness_matrix.hpp\"\n\n//! Sparse Matrix type. Makes using this type easier.\ntypedef Eigen::SparseMatrix<double> SparseMatrix;\n\n//! Used for filling the sparse matrix.\ntypedef Eigen::Triplet<double> Triplet;\n\n//----------------AssembleMatrixBegin----------------\n//! Assemble the stiffness matrix\n//! for the linear system\n//!\n//! @param[out] A will at the end contain the Galerkin matrix\n//! @param[in] vertices a list of triangle vertices\n//! @param[in] triangles a list of triangles\ntemplate<class Matrix>\nvoid assembleStiffnessMatrix(Matrix& A, const Eigen::MatrixXd& vertices,\n                            const Eigen::MatrixXi& triangles)\n{\n    \n    const int numberOfElements = triangles.rows();\n    A.resize(vertices.rows(), vertices.rows());\n    \n    std::vector<Triplet> triplets;\n\n    triplets.reserve(numberOfElements * 3 * 3);\n    //// ANCSE_START_TEMPLATE\n    for (int i = 0; i < numberOfElements; ++i) {\n        auto& indexSet = triangles.row(i);\n\n        const auto& a = vertices.row(indexSet(0));\n        const auto& b = vertices.row(indexSet(1));\n        const auto& c = vertices.row(indexSet(2));\n\n        Eigen::Matrix3d stiffnessMatrix;\n        computeStiffnessMatrix(stiffnessMatrix, a, b, c);\n\n        for (int n = 0; n < 3; ++n) {\n            for (int m = 0; m < 3; ++m) {\n                auto triplet = Triplet(indexSet(n), indexSet(m), stiffnessMatrix(n, m));\n                triplets.push_back(triplet);\n            }\n        }\n    }\n    //// ANCSE_END_TEMPLATE\n    A.setFromTriplets(triplets.begin(), triplets.end());\n}\n//----------------AssembleMatrixEnd----------------\n", "meta": {"hexsha": "6219f2fa2f7e011a1b4818e5d044c8f621c1704d", "size": 1687, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "series0_solution/2d-poissonlFEM/stiffness_matrix_assembly.hpp", "max_stars_repo_name": "BeatHubmann/19H-AdvNCSE", "max_stars_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-05T22:38:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-05T22:38:47.000Z", "max_issues_repo_path": "series0_solution/2d-poissonlFEM/stiffness_matrix_assembly.hpp", "max_issues_repo_name": "BeatHubmann/19H-AdvNCSE", "max_issues_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "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": "series0_solution/2d-poissonlFEM/stiffness_matrix_assembly.hpp", "max_forks_repo_name": "BeatHubmann/19H-AdvNCSE", "max_forks_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-08T20:43:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-08T20:43:27.000Z", "avg_line_length": 31.2407407407, "max_line_length": 88, "alphanum_fraction": 0.6152934203, "num_tokens": 403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206738932333, "lm_q2_score": 0.7905303162021596, "lm_q1q2_score": 0.7129956355220826}}
{"text": "#include <boost/multiprecision/cpp_int.hpp>\r\n#include <cmath>\r\n#include <iostream>\r\n#include <string>\r\n\r\nusing namespace std;\r\nusing boost::multiprecision::cpp_int;\r\n\r\n/*\r\nWe need to find the n-digit integers that are also an n'th power. i.e. a 3 digit number that is also a third power.\r\nSo the integers we need to find are.. 10 ^ (n - 1) <= x ^ n < 10 ^ n;\r\n\r\nOr in other words if the function L gets length of an integer then we need:\r\nL(x ^ n) = n.\r\n\r\nIf our base is x then the maximum it can be is 9 and lowest it can be is 1.\r\nThen we just need to get maximum value of n, which will be given by taking the log and solving for n >.\r\nFor x = 9, largest possible n = 22, so we have our upperlimits.\r\n*/\r\n\r\nint digitCount(cpp_int n) {\r\n\tint digits = 0;\r\n\twhile(n) {\r\n\t\tn /= 10;\r\n\t\tdigits++;\r\n\t}\r\n\treturn digits;\r\n}\r\n\r\nint main(int argc, char *argv[]) {\r\n\tint result = 0;\r\n\tfor(int x = 1; x < 10; x++) {\r\n\t\tfor(int n = 1; n < 22; n++) {\r\n\t\t\tif(digitCount(boost::multiprecision::pow((cpp_int)x, n)) == n) {\r\n\t\t\t\tresult++;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tcout << result << endl;\r\n\treturn 0;\r\n}", "meta": {"hexsha": "7d4cf20997bedde9cd54359990792c7a498bb07d", "size": 1077, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Solutions/51-100/63/Solution.cpp", "max_stars_repo_name": "kitegi/Edmonton", "max_stars_repo_head_hexsha": "774c9b2f72e7b2c6a3bc1b3329ef227ef39adf9d", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-07-16T13:30:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-16T18:17:40.000Z", "max_issues_repo_path": "Solutions/51-100/63/Solution.cpp", "max_issues_repo_name": "kitegi/Edmonton", "max_issues_repo_head_hexsha": "774c9b2f72e7b2c6a3bc1b3329ef227ef39adf9d", "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": "Solutions/51-100/63/Solution.cpp", "max_forks_repo_name": "kitegi/Edmonton", "max_forks_repo_head_hexsha": "774c9b2f72e7b2c6a3bc1b3329ef227ef39adf9d", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-16T22:56:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-16T22:56:07.000Z", "avg_line_length": 26.2682926829, "max_line_length": 116, "alphanum_fraction": 0.6248839369, "num_tokens": 316, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897525789547, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.7129251790571937}}
{"text": "//\n//  EuropeanOption.cpp\n//  VI.3 Option Pricing\n//\n//  Created by Zhehao Li on 2020/4/27.\n//  Copyright \u00a9 2020 Zhehao Li. All rights reserved.\n//\n\n#include \"EuropeanOption.hpp\"\n#include <boost/math/distributions/normal.hpp>\n#include <iostream>\n#include <cmath>\n\n/* Private Memeber Functions */\ndouble EuropeanOption::CallPrice(double U) const{                   // U is the price of underlying assets\n    double tmp = sig * sqrt(T);\n    double d1 = ( log(U / K) + (b + (sig * sig) * 0.5 ) * T ) / tmp;\n    double d2 = d1 - tmp;\n\n    boost::math::normal_distribution<double> stdNormal(0.0, 1.0);   // Create a normal dstn object\n    \n    return ( U * exp((b - r) * T) * cdf(stdNormal, d1) ) - ( K * exp(- r * T) * cdf(stdNormal, d2) );\n}\n\ndouble EuropeanOption::PutPrice(double U) const{\n    double tmp = sig * sqrt(T);\n    double d1 = ( log(U / K) + (b + (sig * sig) * 0.5 ) * T ) / tmp;\n    double d2 = d1 - tmp;\n    \n    boost::math::normal_distribution<double> stdNormal(0.0, 1.0);   // Create a normal dstn object\n\n    return ( K * exp(- r * T) * cdf(stdNormal, -d2) ) - ( U * exp((b - r) * T) * cdf(stdNormal, -d1) );\n}\n\ndouble EuropeanOption::CallDelta(double U) const{\n    double tmp = sig * sqrt(T);\n    double d1 = ( log(U / K) + (b + (sig * sig) * 0.5 ) * T ) / tmp;\n\n    boost::math::normal_distribution<double> stdNormal(0.0, 1.0);   // Create a normal dstn object\n    \n    return exp((b - r) * T) * cdf(stdNormal, d1);\n}\n\ndouble EuropeanOption::PutDelta(double U) const{\n    double tmp = sig * sqrt(T);\n    double d1 = ( log(U / K) + (b + (sig * sig) * 0.5 ) * T ) / tmp;\n    \n    boost::math::normal_distribution<double> stdNormal(0.0, 1.0);   // Create a normal dstn object\n\n    return exp((b - r) * T) * ( cdf(stdNormal, d1) - 1.0 );\n}\n\n\n/* Public Memeber Functions */\n// Default constructor\nEuropeanOption::EuropeanOption() : r(0.05), sig(0.2), K(110.0), T(0.5), b(0.05), optType(\"C\") {}\n\n// Copy constructor\nEuropeanOption::EuropeanOption(const EuropeanOption & option2) : r(option2.r), sig(option2.sig), K(option2.K), T(option2.T), b(option2.b), optType(option2.optType) {}\n\n// Constructor with values\nEuropeanOption::EuropeanOption(const std::string & optionType) : optType(optionType) {\n    if (optType == \"c\"){\n        optType = \"C\";\n    }\n}\n\n// Destructor\nEuropeanOption::~EuropeanOption() {}\n\n// Assignment Operators\nEuropeanOption & EuropeanOption::operator=(const EuropeanOption & option2) {\n    if (this == &option2) {\n        return *this;\n    }\n    else{\n        r   = option2.r;\n        sig = option2.sig;\n        K   = option2.K;\n        T   = option2.T;\n        b   = option2.b;\n        optType = option2.optType;\n        \n        return *this;\n    }\n}\n\n// Accessing functions\ndouble EuropeanOption::Price(double U) const{\n    if (optType == \"C\") {\n        std::cout << \"Call Price..\";\n        return CallPrice(U);\n    }\n    else{\n        std::cout << \"Put Price..\";\n        return PutPrice(U);\n    }\n}\n\ndouble EuropeanOption::Delta(double U) const{\n    if (optType == \"C\") {\n        std::cout << \"Call Delta..\";\n        return CallDelta(U);\n    }\n    else{\n        std::cout << \"Put Delta..\";\n        return PutDelta(U);\n    }\n}\n\n// Modifier functions\nvoid EuropeanOption::toggle(){\n    if (optType == \"C\") {\n        optType = \"P\";\n    }\n    else{\n        optType = \"C\";\n    }\n}\n", "meta": {"hexsha": "99e1c3a5392f73477082f211aad9037e1c749065", "size": 3314, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Level_9/VI.3 Option Pricing/VI.3 Option Pricing/EuropeanOption.cpp", "max_stars_repo_name": "ZhehaoLi9705/QuantNet_CPP", "max_stars_repo_head_hexsha": "a889f4656e757842f4163b0cda7e098cc6ad1193", "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": "Level_9/VI.3 Option Pricing/VI.3 Option Pricing/EuropeanOption.cpp", "max_issues_repo_name": "ZhehaoLi9705/QuantNet_CPP", "max_issues_repo_head_hexsha": "a889f4656e757842f4163b0cda7e098cc6ad1193", "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": "Level_9/VI.3 Option Pricing/VI.3 Option Pricing/EuropeanOption.cpp", "max_forks_repo_name": "ZhehaoLi9705/QuantNet_CPP", "max_forks_repo_head_hexsha": "a889f4656e757842f4163b0cda7e098cc6ad1193", "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.6166666667, "max_line_length": 166, "alphanum_fraction": 0.5766445383, "num_tokens": 1006, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308110294983, "lm_q2_score": 0.7634837527911056, "lm_q1q2_score": 0.7126592585756467}}
{"text": "// Boost.Geometry\r\n// QuickBook Example\r\n// Copyright (c) 2018, Oracle and/or its affiliates\r\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//[discrete_frechet_distance\r\n//` Calculate Similarity between two geometries as the discrete frechet distance between them.\r\n\r\n#include <iostream>\r\n\r\n#include <boost/geometry.hpp>\r\n#include <boost/geometry/geometries/point_xy.hpp>\r\n#include <boost/geometry/geometries/linestring.hpp>\r\n\r\nint main()\r\n{\r\n    typedef boost::geometry::model::d2::point_xy<double> point_type;\r\n    typedef boost::geometry::model::linestring<point_type> linestring_type;\r\n\r\n    linestring_type ls1, ls2;\r\n    boost::geometry::read_wkt(\"LINESTRING(0 0,1 1,1 2,2 1,2 2)\", ls1);\r\n    boost::geometry::read_wkt(\"LINESTRING(1 0,0 1,1 1,2 1,3 1)\", ls2);\r\n\r\n    double res = boost::geometry::discrete_frechet_distance(ls1, ls2);\r\n\r\n    std::cout << \"Discrete Frechet Distance: \" << res << std::endl;\r\n\r\n    return 0;\r\n}\r\n\r\n//]\r\n\r\n//[discrete_frechet_distance_output\r\n/*`\r\nOutput:\r\n[pre\r\nDiscrete Frechet Distance:  1.41421\r\n]\r\n*/\r\n//]\r\n", "meta": {"hexsha": "ee44a0d642fa5e257a0814c0fc574d623f6c0b7a", "size": 1265, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/libs/geometry/doc/src/examples/algorithms/discrete_frechet_distance.cpp", "max_stars_repo_name": "Jackarain/tinyrpc", "max_stars_repo_head_hexsha": "07060e3466776aa992df8574ded6c1616a1a31af", "max_stars_repo_licenses": ["BSL-1.0"], "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": "third_party/boost/libs/geometry/doc/src/examples/algorithms/discrete_frechet_distance.cpp", "max_issues_repo_name": "avplayer/cxxrpc", "max_issues_repo_head_hexsha": "7049b4079fac78b3828e68f787d04d699ce52f6d", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "third_party/boost/libs/geometry/doc/src/examples/algorithms/discrete_frechet_distance.cpp", "max_forks_repo_name": "avplayer/cxxrpc", "max_forks_repo_head_hexsha": "7049b4079fac78b3828e68f787d04d699ce52f6d", "max_forks_repo_licenses": ["BSL-1.0"], "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": 28.75, "max_line_length": 95, "alphanum_fraction": 0.7019762846, "num_tokens": 351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.8289388104343893, "lm_q1q2_score": 0.7126086467212561}}
{"text": "//------------------------------------------------------------------------------\n// \\file Search_tests.cpp\n//------------------------------------------------------------------------------\n#include \"Algorithms/BinarySearch.h\"\n#include \"Algorithms/BubbleSort.h\"\n#include \"Algorithms/MergeSort.h\"\n#include \"Algorithms/QuickSort.h\"\n\n#include <array>\n#include <boost/test/unit_test.hpp>\n#include <deque>\n#include <forward_list>\n#include <list>\n#include <string>\n#include <vector>\n\nusing Algorithms::Search::Details::binary_search_iteration;\nusing Algorithms::Search::Details::calculate_midpoint;\nusing Algorithms::Search::Details::compare_partition;\nusing Algorithms::Search::binary_search;\nusing Algorithms::Search::binary_search_inclusive;\nusing Algorithms::Search::square_root;\nusing std::size_t;\n\nBOOST_AUTO_TEST_SUITE(Algorithms)\nBOOST_AUTO_TEST_SUITE(Search_tests)\nBOOST_AUTO_TEST_SUITE(Binary_Search_tests)\n\nBOOST_AUTO_TEST_SUITE(Details_tests)\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(DemonstrateCalculateMidpoint)\n{\n  std::size_t r {5};\n  std::size_t l {3};\n  \n  // Don't design code that has to static cast a size_t into an int.\n  //const long long L {r - l + 1};\n\n  //BOOST_TEST(L == -1);\n  {\n    const auto result = calculate_midpoint(r, l);\n    BOOST_TEST(!result.has_value());\n  }\n  {\n    const auto result = calculate_midpoint(l, r);\n    BOOST_TEST(result.has_value());\n    BOOST_TEST(result.value() == 4);\n  }\n  {\n    size_t r {7};\n    size_t l {4};\n\n    const auto result = calculate_midpoint(l, r);\n    BOOST_TEST(result.has_value());\n    BOOST_TEST(result.value() == 5);\n  }\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(DemonstrateComparePartition)\n{\n  {\n    const auto result = compare_partition(11, 11, 3, 0, 6);\n    BOOST_TEST(static_cast<bool>(result));\n    BOOST_TEST(result.value().first);\n    BOOST_TEST(result.value().second.first == 3);\n    BOOST_TEST(result.value().second.second == 3);\n  }\n  {\n    const auto result = compare_partition(11, 10, 3, 0, 6);\n    BOOST_TEST(static_cast<bool>(result));\n    BOOST_TEST(!result.value().first);\n    BOOST_TEST(result.value().second.first == 0);\n    BOOST_TEST(result.value().second.second == 2);\n  }\n  {\n    const auto result = compare_partition(11, 12, 3, 0, 6);\n    BOOST_TEST(static_cast<bool>(result));\n    BOOST_TEST(!result.value().first);\n    BOOST_TEST(result.value().second.first == 4);\n    BOOST_TEST(result.value().second.second == 6);\n  }\n  {\n    const auto result = compare_partition(1, 0, 0, 0, 1);\n    BOOST_TEST(!static_cast<bool>(result));\n  }\n  {\n    const auto result = compare_partition(1, 2, 0, 0, 1);\n    BOOST_TEST(result.has_value());\n    BOOST_TEST(!result.value().first);\n    BOOST_TEST(result.value().second.first == 1);\n    BOOST_TEST(result.value().second.second == 1);\n  }\n  {\n    const auto result = compare_partition(29, 30, 6, 6, 6);\n    BOOST_TEST(!result.has_value());\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END() // Details_tests\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(DemonstrateBinarySearch)\n{ \n  std::vector<int> sorted_vector {1, 3, 9, 11, 15, 19, 29};\n  {\n    const auto result = binary_search(sorted_vector, 25);\n    BOOST_TEST(!result.has_value());\n  }\n  {\n    const auto result = binary_search(sorted_vector, -1);\n    BOOST_TEST(!result.has_value());\n  }\n  {\n    const auto result = binary_search(sorted_vector, 1);\n    BOOST_TEST(result.has_value());\n    BOOST_TEST(result.value() == 0);\n  }\n  {\n    const auto result = binary_search(sorted_vector, 3);\n    BOOST_TEST(result.has_value());\n    BOOST_TEST(result.value() == 1);\n  }\n  {\n    const auto result = binary_search(sorted_vector, 19);\n    BOOST_TEST(result.has_value());\n    BOOST_TEST(result.value() == 5);\n  }\n  {\n    const auto result = binary_search(sorted_vector, 29);\n    BOOST_TEST(result.has_value());\n    BOOST_TEST(result.value() == 6);\n  }\n}\n\n// cf. https://web2.qatar.cmu.edu/~mhhammou/15122-s16/lectures/06-binsearch.pdf\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(SearchOnSortedIntArray)\n{ \n  int A[] {5, 7, 11, 19, 34, 42, 65, 65, 89, 123};\n  constexpr int N {10};\n\n  {\n    const auto result = binary_search(5, A, N);\n    BOOST_TEST(*result == 0);\n  }\n  {\n    const auto result = binary_search(123, A, N);\n    BOOST_TEST(*result == N - 1);\n  }\n  {\n    const auto result = binary_search(4, A, N);\n    BOOST_TEST(!result.has_value());\n  }\n  {\n    const auto result = binary_search(124, A, N);\n    BOOST_TEST(!result.has_value());\n  }\n  {\n    const auto result = binary_search(18, A, N);\n    BOOST_TEST(!result.has_value());\n  }\n  {\n    const auto result = binary_search(19, A, N);\n    BOOST_TEST(*result == 3);\n  }\n  {\n    const auto result = binary_search(65, A, N);\n    BOOST_TEST(*result == 7);\n  }\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(SameResultsWithBinarySearchInclusive)\n{ \n  std::vector<int> a {5, 7, 11, 19, 34, 42, 65, 65, 89, 123};\n\n  {\n    const auto result = binary_search_inclusive(a, 5);\n    BOOST_TEST(*result == 0);\n  }\n  {\n    const auto result = binary_search_inclusive(a, 123);\n    BOOST_TEST(*result == a.size() - 1);\n  }\n  {\n    const auto result = binary_search_inclusive(a, 4);\n    BOOST_TEST(!result.has_value());\n  }\n  {\n    const auto result = binary_search_inclusive(a, 124);\n    BOOST_TEST(!result.has_value());\n  }\n  {\n    const auto result = binary_search_inclusive(a, 18);\n    BOOST_TEST(!result.has_value());\n  }\n  {\n    const auto result = binary_search_inclusive(a, 19);\n    BOOST_TEST(*result == 3);\n  }\n  {\n    const auto result = binary_search_inclusive(a, 65);\n    BOOST_TEST(*result == 7);\n  }\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(SquareRootSearchesForAnswerInSearchSpace)\n{\n  BOOST_TEST(square_root(4) == 2);\n  BOOST_TEST(square_root(8) == 2);\n  BOOST_TEST(square_root(3) == 1);\n  BOOST_TEST(square_root(2) == 1);\n  BOOST_TEST(square_root(1024) == 32);\n}\n\nBOOST_AUTO_TEST_SUITE_END() // Binary_Search_tests\nBOOST_AUTO_TEST_SUITE_END() // Search_tests\nBOOST_AUTO_TEST_SUITE_END() // Algorithms", "meta": {"hexsha": "2612a7ff2f18f5bca2b0879d347d012561a964b4", "size": 6770, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Voltron/Source/UnitTests/Algorithms/Search_tests.cpp", "max_stars_repo_name": "ernestyalumni/HrdwCCppCUDA", "max_stars_repo_head_hexsha": "17ed937dea06431a4d5ca103f993ea69a6918734", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-02-09T19:44:51.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-09T19:44:51.000Z", "max_issues_repo_path": "Voltron/Source/UnitTests/Algorithms/Search_tests.cpp", "max_issues_repo_name": "ernestyalumni/HrdwCCppCUDA", "max_issues_repo_head_hexsha": "17ed937dea06431a4d5ca103f993ea69a6918734", "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": "Voltron/Source/UnitTests/Algorithms/Search_tests.cpp", "max_forks_repo_name": "ernestyalumni/HrdwCCppCUDA", "max_forks_repo_head_hexsha": "17ed937dea06431a4d5ca103f993ea69a6918734", "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.6929824561, "max_line_length": 80, "alphanum_fraction": 0.5598227474, "num_tokens": 1573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190938, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.7126086407605037}}
{"text": "/* test_lognormal.cpp\r\n *\r\n * Copyright Steven Watanabe 2011\r\n * Distributed under the Boost Software License, Version 1.0. (See\r\n * accompanying file LICENSE_1_0.txt or copy at\r\n * http://www.boost.org/LICENSE_1_0.txt)\r\n *\r\n * $Id: test_lognormal.cpp 71018 2011-04-05 21:27:52Z steven_watanabe $\r\n *\r\n */\r\n\r\n#include <boost/random/lognormal_distribution.hpp>\r\n#include <boost/random/uniform_real.hpp>\r\n#include <boost/math/distributions/lognormal.hpp>\r\n\r\n#define BOOST_RANDOM_DISTRIBUTION boost::random::lognormal_distribution<>\r\n#define BOOST_RANDOM_DISTRIBUTION_NAME lognormal\r\n#define BOOST_MATH_DISTRIBUTION boost::math::lognormal\r\n#define BOOST_RANDOM_ARG1_TYPE double\r\n#define BOOST_RANDOM_ARG1_NAME m\r\n#define BOOST_RANDOM_ARG1_DEFAULT 10.0\r\n#define BOOST_RANDOM_ARG1_DISTRIBUTION(n) boost::uniform_real<>(-n, n)\r\n#define BOOST_RANDOM_ARG2_TYPE double\r\n#define BOOST_RANDOM_ARG2_NAME s\r\n#define BOOST_RANDOM_ARG2_DEFAULT 10.0\r\n#define BOOST_RANDOM_ARG2_DISTRIBUTION(n) boost::uniform_real<>(0.0001, n)\r\n\r\n#include \"test_real_distribution.ipp\"\r\n", "meta": {"hexsha": "a162e8aaae7784a8bf8f3f95cf92ebc18069b6da", "size": 1052, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/random/test/test_lognormal.cpp", "max_stars_repo_name": "jmuskaan72/Boost", "max_stars_repo_head_hexsha": "047e36c01841a8cd6a5c74d4e3034da46e327bc1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "libs/random/test/test_lognormal.cpp", "max_issues_repo_name": "xiaoliang2121/Boost", "max_issues_repo_head_hexsha": "fc90c3fde129c62565c023f091eddc4a7ed9902b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-03-19T08:23:23.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-24T07:48:47.000Z", "max_forks_repo_path": "libs/random/test/test_lognormal.cpp", "max_forks_repo_name": "xiaoliang2121/Boost", "max_forks_repo_head_hexsha": "fc90c3fde129c62565c023f091eddc4a7ed9902b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 36.275862069, "max_line_length": 75, "alphanum_fraction": 0.7899239544, "num_tokens": 264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. Yes\n2. Yes", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.8872045877523148, "lm_q1q2_score": 0.7125794768902864}}
{"text": "#ifndef INCLUDE_SWIFT_VIO_VECTOR_NORMALIZATION_JACOBIAN_HPP_\n#define INCLUDE_SWIFT_VIO_VECTOR_NORMALIZATION_JACOBIAN_HPP_\n\n#include <glog/logging.h>\n#include <Eigen/Dense>\n\nnamespace swift_vio {\nclass VectorNormalizationJacobian\n{\npublic:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n  VectorNormalizationJacobian(const Eigen::Vector3d& vecIn) : vecIn_(vecIn) {\n\n  }\n\n  template<typename MatrixType>\n  void dxi_dvec(MatrixType* j) const {\n    normalizationJacobian(vecIn_, j);\n  }\n\n  Eigen::Vector3d normalized() const {\n    return vecIn_.normalized();\n  }\n\n  template<typename MatrixType>\n  static void normalizationJacobian(const Eigen::Vector3d& vecIn, MatrixType* j) {\n    double norm = vecIn.norm();\n    CHECK_GT(norm, 1e-6);\n    double invNorm = 1.0 / norm;\n    double invNorm3 = invNorm * invNorm * invNorm;\n    *j = Eigen::Matrix3d::Identity() * invNorm - vecIn * vecIn.transpose() * invNorm3;\n  }\n\nprivate:\n  Eigen::Vector3d vecIn_; // vector before normalization\n\n};\n} // namespace swift_vio\n#endif // INCLUDE_SWIFT_VIO_VECTOR_NORMALIZATION_JACOBIAN_HPP_\n", "meta": {"hexsha": "1fe5e25b69b04188a1ffba552d1b67c51d1bb08d", "size": 1054, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "okvis_ceres/include/swift_vio/VectorNormalizationJacobian.hpp", "max_stars_repo_name": "wbl1997/okvis", "max_stars_repo_head_hexsha": "65e30d6ab25380d65c96c665485148e2ab55e93e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-26T15:31:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T15:31:53.000Z", "max_issues_repo_path": "okvis_ceres/include/swift_vio/VectorNormalizationJacobian.hpp", "max_issues_repo_name": "wbl1997/okvis", "max_issues_repo_head_hexsha": "65e30d6ab25380d65c96c665485148e2ab55e93e", "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": "okvis_ceres/include/swift_vio/VectorNormalizationJacobian.hpp", "max_forks_repo_name": "wbl1997/okvis", "max_forks_repo_head_hexsha": "65e30d6ab25380d65c96c665485148e2ab55e93e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-08-01T16:49:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-14T09:00:03.000Z", "avg_line_length": 26.35, "max_line_length": 86, "alphanum_fraction": 0.7523719165, "num_tokens": 288, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7125761583474679}}
{"text": "#include \"AKS.hpp\"\n\n#include \"AKSCoefficient.hpp\"\n#include \"AKSPolynomial.hpp\"\n#include \"GMPWrappers.hpp\"\n\n#include <mpfr.h>\n#include <NTL/ZZ.h>\n#include <NTL/RR.h>\n#include <NTL/ZZ_pE.h>\n#include <NTL/ZZ_pEX.h>\n\n#include <cassert>\n#include <cmath>\n\nnamespace tfg::aks\n{\nnamespace steps\n{\nnamespace\n{\n\nauto isOrderBiggerThan(mpz_class const& n, std::size_t r, std::size_t threshold) -> bool\n{\n    auto temp = 1_mpz;\n\n    for (auto i = std::size_t{1}; i <= threshold; ++i)\n    {\n        temp *= n;\n        temp %= r;\n\n        if (temp == 1)\n        {\n            return false;\n        }\n    }\n\n    return true;\n}\n\nauto phi(std::size_t n) -> std::size_t\n{\n    auto const top = static_cast<std::size_t>(std::sqrt(n));\n    auto result = n;\n\n    for (auto p = std::size_t{2}; p <= top; ++p)\n    {\n        if (n % p == 0)\n        {\n            while (n % p == 0)\n            {\n                n /= p;\n            }\n\n            result -= result / p;\n        }\n    }\n\n    if (n > 1)\n    {\n        result -= result / n; // NOLINT\n    }\n\n    return result;\n}\n\nauto calculateUpperBound(mpz_class const& n, std::size_t r) -> std::size_t\n{\n    // log_2(n)\n    mpfr_t result;\n    mpfr_init_set_z(result, n.get_mpz_t(), MPFR_RNDU); // NOLINT\n    mpfr_log2(result, result, MPFR_RNDU);              // NOLINT\n    \n    // sqrt(phi(r))\n    mpfr_t sqrtPhiR;\n    mpfr_init_set_ui(sqrtPhiR, phi(r), MPFR_RNDU); // NOLINT\n    mpfr_sqrt(sqrtPhiR, sqrtPhiR, MPFR_RNDU);      // NOLINT\n\n    // log_2(n) * sqrt(phi(r))\n    mpfr_mul(result, result, sqrtPhiR, MPFR_RNDU); // NOLINT\n\n    // Return floor(log_2(n) * sqrt(phi(r)))\n    return mpfr_get_ui(result, MPFR_RNDD); // NOLINT\n}\n\n} // namespace unnamed\n\nauto step1(mpz_class const& n) -> bool\n{\n    return gmp::isPerfectPower(n);\n}\n\nauto step2(mpz_class const& n) -> std::size_t\n{\n    auto const threshold = [&n]\n    {\n        // Use MPFR to calculate a more accurate threshold using floating point\n        // computations. We round towards +infinity for a more conservative\n        // threshold.\n        mpfr_t thresholdMPFR;\n        mpfr_init_set_z(thresholdMPFR, n.get_mpz_t(), MPFR_RNDU); // NOLINT\n        mpfr_log2(thresholdMPFR, thresholdMPFR, MPFR_RNDU);       // NOLINT\n        mpfr_sqr(thresholdMPFR, thresholdMPFR, MPFR_RNDU);        // NOLINT\n\n        // Return the result from MPFR as an unsigned long (this threshold is\n        // unlikely to be bigger that 32-bits long, let alone 64-bits).\n        // Round towards -infinity to get the floored value\n        return mpfr_get_ui(thresholdMPFR, MPFR_RNDD); // NOLINT\n    }();\n\n    // r = log^2(n) + 2 is the first r such that ord_r(n) can be higher than\n    // log^2(n).\n    //\n    // If r <= log^2(n) + 1, then ord(r) <= phi(r) < r - 1 <= log^2(n)\n    for (auto r = threshold + 2;; ++r)\n    {\n        if (isOrderBiggerThan(n, r, threshold))\n        {\n            return r;\n        }\n    }\n}\n\nauto step3(mpz_class const& n, std::size_t r) -> bool\n{\n    for (auto a = std::size_t{2}; a <= r; ++a)\n    {\n        auto const result = gmp::gcd(a, n);\n\n        if (1 < result && result < n)\n        {\n            return true;\n        }\n    }\n\n    return false;\n}\n\nauto step4(mpz_class const& n, std::size_t r) -> bool\n{\n    return n <= r;\n}\n\nnamespace impl\n{\n\nauto step5Direct(mpz_class const& n, std::size_t r) -> bool\n{\n    // First we calculate the upper bound of the loop\n    auto const top = calculateUpperBound(n, r);\n\n    // Prepare the environment to work mod(X^r - 1, n)\n    detail::AKSCoefficient::setModule(n);\n    detail::AKSPolynomial::setModuleDegree(r);\n\n    // We create both polynomials outside the loop to avoid reallocations.\n    auto lhs = detail::AKSPolynomial{};\n    auto rhs = detail::AKSPolynomial{};\n\n    // We are also going to create a temporary polynomial to avoid even more\n    // reallocations.\n    auto temp = detail::AKSPolynomial{0_mpz, 1_mpz};\n\n    // X^n mod(X^r - 1, n) instead of X^n + a mod(X^r - 1, n) so it doesn't\n    // depend on a, therefore calculating it only once.\n    temp.pow(detail::AKSCoefficient::getModule(), rhs);\n\n    for (auto a = std::size_t{1}; a <= top; ++a)\n    {\n        // (X + a)^n - a mod(X^r - 1, n)\n        temp.setCoefficient(0, mpz_class{a});\n        temp.pow(detail::AKSCoefficient::getModule(), lhs);\n        lhs -= mpz_class{a};\n\n        if (lhs != rhs)\n        {\n            return true;\n        }\n    }\n\n    return false;\n}\n\nauto step5NTL(mpz_class const& n, std::size_t r) -> bool\n{\n    // First we calculate the upper bound of the loop\n    auto const top = calculateUpperBound(n, r);\n    // Convert GMP's integer to NTL's integer and set ring to Z_n\n    auto const nNTL = NTL::conv<NTL::ZZ>(n.get_str().c_str());\n    NTL::ZZ_p::init(nNTL);\n\n    // Define the polynomial module X^r - 1\n    auto const module = NTL::ZZ_pXModulus{NTL::ZZ_pX{static_cast<long>(r), 1} - 1};\n    // Define X^n mod X^r - 1\n    auto const rhs = [&nNTL, &module]\n    {\n        auto result = NTL::ZZ_pX{1, 1};\n        NTL::PowerMod(result, result, nNTL, module);\n\n        return result;\n    }();\n\n    for (auto a = std::size_t{1}; a <= top; ++a)\n    {\n        // (X + a)^n - a mod(X^r - 1, n)\n        auto lhs = NTL::ZZ_pX{1, 1};\n        lhs += static_cast<long>(a);\n        NTL::PowerMod(lhs, lhs, nNTL, module);\n        lhs -= static_cast<long>(a);\n\n        if ((lhs != rhs) != 0)\n        {\n            return true;\n        }\n    }\n\n    return false;\n}\n\n} // namespace impl\n\nauto step5(mpz_class const& n, std::size_t r) -> bool\n{\n    return impl::step5NTL(n, r);\n}\n\nauto step6() -> bool\n{\n    return true;\n}\n\n} // namespace steps\n\nauto isPrime(mpz_class const &n) -> bool\n{\n    // Step 1: Check if n is a perfect power\n    if (steps::step1(n))\n    {\n        return false;\n    }\n\n    // Step 2: Find smallest r such that ord_r(n) > log^2(n)\n    auto const r = steps::step2(n);\n\n    // Step 3: Check if 1 < (a, n) < n for some a <= r\n    if (steps::step3(n, r))\n    {\n        return false;\n    }\n\n    // Step 4: Check if n <= r\n    if (steps::step4(n, r))\n    {\n        return true;\n    }\n\n    // Step 5: Check if the polynomial identities are not satisfied\n    if (steps::step5(n, r))\n    {\n        return false;\n    }\n\n    // Step 6: If we reach this point, the number is prime.\n    return steps::step6();\n}\n\n} // namespace tfg::aks", "meta": {"hexsha": "4d1a25c010f9d3116094465c0c2eaf27970676a9", "size": 6265, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Software/src/AKS.cpp", "max_stars_repo_name": "fgallegosalido/TFG", "max_stars_repo_head_hexsha": "0432a99442f5fcffd2b1ddfa7ba340f49609f290", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-11-25T09:58:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T22:57:27.000Z", "max_issues_repo_path": "Software/src/AKS.cpp", "max_issues_repo_name": "fgallegosalido/TFG", "max_issues_repo_head_hexsha": "0432a99442f5fcffd2b1ddfa7ba340f49609f290", "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": "Software/src/AKS.cpp", "max_forks_repo_name": "fgallegosalido/TFG", "max_forks_repo_head_hexsha": "0432a99442f5fcffd2b1ddfa7ba340f49609f290", "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.4644194757, "max_line_length": 88, "alphanum_fraction": 0.5639265762, "num_tokens": 1922, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.7853085909370422, "lm_q1q2_score": 0.7125200820966693}}
{"text": "#include \"KolmogorovSmirnov.hxx\"\n#include <boost/format.hpp>\n#include <cmath>\n#include <iostream>\n\nstd::vector<float> KolmogorovSmirnov::cdf(const std::vector<int> & S, int & N)\n{\n  std::vector<float> ret; \n\n  N = 0;\n  for(int i = 0; i < S.size(); i++) {\n    N += S[i]; \n  }\n\n  float fscale = 1.0 / ((float) N); \n\n  float cdf = 0.0;   \n  for(int i = 0; i < S.size(); i++) {\n    cdf += ((float) S[i]) * fscale; \n    ret.push_back(cdf); \n  }\n\n  return ret; \n}\n\nbool KolmogorovSmirnov::test(float alpha, \n\t\t\t     const std::vector<int> & S, \n\t\t\t     const std::vector<int> & X) \n{\n  int N, M; \n  std::vector<float> Scdf = cdf(S, N);\n  std::vector<float> Xcdf = cdf(X, M);\n  \n  float max_sep = 0.0; \n  for(int i = 0; i < S.size(); i++) {\n    float sep = fabs(Scdf[i] - Xcdf[i]);\n    max_sep = (max_sep > sep) ? max_sep : sep; \n  }\n\n  // now is the difference significant? \n  float n = (float) N;\n  float m = (float) M; \n\n  float calpha = sqrt(-0.5 * log(alpha / 2.0));\n  \n  float Dmin = calpha * sqrt((n + m) / (n*m));\n\n  std::cerr << boost::format(\"Dnm = %f n = %f m = %f calpha = %f Dmin = %f\\n\")\n    % max_sep % n % m % calpha % Dmin; \n\n  return max_sep  > Dmin; \n}\n", "meta": {"hexsha": "cc7fe0fe249045a868f03dcbc890db118861c536", "size": 1165, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/KolmogorovSmirnov.cxx", "max_stars_repo_name": "kb1vc/WSPRLog", "max_stars_repo_head_hexsha": "0c0121f9050a249905c3e72f2520479d60acba7c", "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/KolmogorovSmirnov.cxx", "max_issues_repo_name": "kb1vc/WSPRLog", "max_issues_repo_head_hexsha": "0c0121f9050a249905c3e72f2520479d60acba7c", "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/KolmogorovSmirnov.cxx", "max_forks_repo_name": "kb1vc/WSPRLog", "max_forks_repo_head_hexsha": "0c0121f9050a249905c3e72f2520479d60acba7c", "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": 21.9811320755, "max_line_length": 78, "alphanum_fraction": 0.5407725322, "num_tokens": 435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.7125200775377502}}
{"text": "/**\n * @file    Projection.h\n * @brief   3D single-view projection functions\n * @author  Jing Dong\n * @date    Oct 11, 2018\n */\n\n#include <minisam/geometry/CalibBundler.h>\n#include <minisam/geometry/projection.h>\n\n#include <Eigen/Core>\n#include <sophus/se3.hpp>\n\nnamespace minisam {\n\nnamespace {\n// 3x3 skew symmetric matrix from a Vector3d\nEigen::Matrix3d skewSymmetric(const Eigen::Vector3d& v) {\n  Eigen::Matrix3d m;\n  // clang-format off\n  m <<  0.0,  -v(2),  v(1), \n        v(2),  0.0,  -v(0),  \n       -v(1),  v(0),  0.0;\n  // clang-format on\n  return m;\n}\n}  // namespace\n\n/* ************************************************************************** */\nvoid transform2sensorJacobians(const Sophus::SE3d& pose,\n                               const Eigen::Vector3d& pw,\n                               Eigen::Matrix<double, 3, 6>& J_pose,\n                               Eigen::Matrix<double, 3, 3>& J_pw) {\n  Eigen::Vector3d pc = transform2sensor(pose, pw);\n  J_pose << -Eigen::Matrix3d::Identity(), skewSymmetric(pc);\n  J_pw = pose.so3().inverse().matrix();\n}\n\n/* ************************************************************************** */\nvoid transform2worldJacobians(const Sophus::SE3d& pose,\n                              const Eigen::Vector3d& ps,\n                              Eigen::Matrix<double, 3, 6>& J_pose,\n                              Eigen::Matrix<double, 3, 3>& J_ps) {\n  Eigen::Matrix3d R = pose.so3().matrix();\n  J_pose << R, R * skewSymmetric(-ps);\n  J_ps = R;\n}\n\n/* ************************************************************************** */\nvoid transform2imageJacobians(const Sophus::SE3d& pose,\n                              const Eigen::Vector3d& pw,\n                              Eigen::Matrix<double, 2, 6>& J_pose,\n                              Eigen::Matrix<double, 2, 3>& J_pw) {\n  // see gtsam/geometry/CalibratedCamera.cpp\n  Eigen::Vector3d ps = transform2sensor(pose, pw);\n  Eigen::Matrix3d Rt = pose.so3().inverse().matrix();\n  const double u = ps(0) / ps(2);\n  const double v = ps(1) / ps(2);\n  const double d = 1.0 / ps(2);\n  const double uv = u * v;\n  const double uu = u * u;\n  const double vv = v * v;\n  // clang-format off\n  J_pose << -d,   0,   d*u,   uv,   -1-uu,  v,\n            0,   -d,   d*v,   1+vv, -uv,   -u;\n  J_pw << Rt(0, 0)-u*Rt(2, 0), Rt(0, 1)-u*Rt(2, 1), Rt(0, 2)-u*Rt(2, 2),\n          Rt(1, 0)-v*Rt(2, 0), Rt(1, 1)-v*Rt(2, 1), Rt(1, 2)-v*Rt(2, 2);\n  // clang-format on\n  J_pw *= d;\n}\n\n/* ************************************************************************** */\nEigen::Vector2d projectBundler(const Sophus::SE3d& pose,\n                               const CalibBundler& calib,\n                               const Eigen::Vector3d& pw) {\n  Eigen::Vector3d pc = pose * pw;\n  double invz = 1.0 / pc(2);\n  Eigen::Vector2d pi(-pc(0) * invz, -pc(1) * invz);\n  return calib.project(pi);\n}\n\n/* ************************************************************************** */\nvoid projectBundlerJacobians(const Sophus::SE3d& pose,\n                             const CalibBundler& calib,\n                             const Eigen::Vector3d& pw,\n                             Eigen::Matrix<double, 2, 6>& J_pose,\n                             Eigen::Matrix<double, 2, 3>& J_calib,\n                             Eigen::Matrix<double, 2, 3>& J_pw) {\n  Eigen::Vector3d pc = pose * pw;\n  double invz = 1.0 / pc(2);\n  double invz2 = invz * invz;\n  Eigen::Vector2d pi(-pc(0) * invz, -pc(1) * invz);\n\n  Eigen::Matrix<double, 2, 2> J_pi;\n  calib.projectJacobians(pi, J_calib, J_pi);\n\n  Eigen::Matrix<double, 2, 3> J_pc;\n  // clang-format off\n  J_pc << -invz*J_pi(0,0), -invz*J_pi(0,1), (pc(0)*J_pi(0,0) + pc(1)*J_pi(0,1)) * invz2,\n          -invz*J_pi(1,0), -invz*J_pi(1,1), (pc(0)*J_pi(1,0) + pc(1)*J_pi(1,1)) * invz2;\n  // clang-format on\n\n  Eigen::Matrix3d R = pose.so3().matrix();\n  Eigen::Matrix<double, 2, 3> J_pc_R = J_pc * R;\n  J_pose << J_pc_R,\n      J_pc_R * skewSymmetric(-pw);  // J_pc_pose << R, R * skew_symmetric(-pw);\n  J_pw = J_pc_R;                    // J_pc_pw = R\n}\n\n}  // namespace minisam\n", "meta": {"hexsha": "2c0087da8a382c67b62636e14377797ef98fb421", "size": 4055, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "minisam/geometry/projection.cpp", "max_stars_repo_name": "versatran01/minisam", "max_stars_repo_head_hexsha": "b3840d2629551fdfa287df8aac2e7956873d2b0e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 338.0, "max_stars_repo_stars_event_min_datetime": "2019-09-03T10:44:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:12:08.000Z", "max_issues_repo_path": "minisam/geometry/projection.cpp", "max_issues_repo_name": "bhsphd/minisam", "max_issues_repo_head_hexsha": "ef84796fa11ac6e5e4d4aa9d60d9b94a99a973fb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 23.0, "max_issues_repo_issues_event_min_datetime": "2019-09-26T09:00:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-04T06:04:02.000Z", "max_forks_repo_path": "minisam/geometry/projection.cpp", "max_forks_repo_name": "bhsphd/minisam", "max_forks_repo_head_hexsha": "ef84796fa11ac6e5e4d4aa9d60d9b94a99a973fb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 87.0, "max_forks_repo_forks_event_min_datetime": "2019-09-04T05:17:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T09:47:23.000Z", "avg_line_length": 36.5315315315, "max_line_length": 88, "alphanum_fraction": 0.4818742293, "num_tokens": 1262, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391579526935, "lm_q2_score": 0.7718435030872967, "lm_q1q2_score": 0.7124417771609555}}
{"text": "#ifndef ZSVM_JACOBI_COORDINATES_HPP_INCLUDED\n#define ZSVM_JACOBI_COORDINATES_HPP_INCLUDED\n\n// C++ standard library headers\n#include <cstddef> // for std::size_t\n#include <vector>\n\n// Eigen linear algebra library headers\n#include <Eigen/Core>\n\nnamespace jaco {\n\n    template <typename T>\n    Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>\n    transformation_matrix(const std::vector<T> &masses) {\n        const std::size_t n = masses.size();\n        std::vector<T> mass_sums(n);\n        if (n > 0) { mass_sums[0] = masses[0]; }\n        for (std::size_t i = 1; i < n; ++i) {\n            mass_sums[i] = mass_sums[i - 1] + masses[i];\n        }\n        Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> u(n, n);\n        for (std::size_t i = 0; i < n; ++i) {\n            for (std::size_t j = 0; j < n; ++j) {\n                if (i >= j) {\n                    u(i, j) = masses[j] / mass_sums[i];\n                } else if (i == j - 1) {\n                    u(i, j) = -1;\n                } else {\n                    u(i, j) = 0;\n                }\n            }\n        }\n        return u;\n    }\n\n    template <typename T>\n    Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>\n    transformation_matrix_inverse(const std::vector<T> &masses) {\n        const std::size_t n = masses.size();\n        std::vector<T> mass_sums(n);\n        if (n > 0) { mass_sums[0] = masses[0]; }\n        for (std::size_t i = 1; i < n; ++i) {\n            mass_sums[i] = mass_sums[i - 1] + masses[i];\n        }\n        Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> v(n, n);\n        for (std::size_t i = 0; i < n; ++i) {\n            for (std::size_t j = 0; j < n; ++j) {\n                if (j + 1 == n) {\n                    v(i, j) = 1;\n                } else if (i <= j) {\n                    v(i, j) = masses[j + 1] / mass_sums[j + 1];\n                } else if (i == j + 1) {\n                    v(i, j) = -mass_sums[j] / mass_sums[i];\n                } else {\n                    v(i, j) = 0;\n                }\n            }\n        }\n        return v;\n    }\n\n    template <typename T>\n    Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>\n    inverse_mass_matrix(const std::vector<T> &masses) {\n        const std::size_t n = masses.size();\n        const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> u =\n                transformation_matrix(masses);\n        Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> inverse_masses(n, n);\n        for (std::size_t i = 0; i < n; ++i) {\n            for (std::size_t j = 0; j < n; ++j) {\n                if (i == j) {\n                    inverse_masses(i, j) = 1 / masses[i];\n                } else {\n                    inverse_masses(i, j) = 0;\n                }\n            }\n        }\n        return u * inverse_masses * u.transpose();\n    }\n\n    template <typename T>\n    Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>\n    reduced_inverse_mass_matrix(const std::vector<T> &masses) {\n        const std::size_t n = masses.size();\n        if (n == 0) {\n            throw std::invalid_argument(\n                    \"jaco::reduced_inverse_mass_matrix \"\n                    \"received empty vector of masses\");\n        }\n        const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> m =\n                inverse_mass_matrix(masses);\n        Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> r(n - 1, n - 1);\n        for (std::size_t i = 0; i < n - 1; ++i) {\n            for (std::size_t j = 0; j < n - 1; ++j) {\n                r(i, j) = m(i, j);\n            }\n        }\n        return r;\n    }\n\n    template <typename T>\n    Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>\n    pairwise_weights(const std::vector<T> &masses) {\n        const std::size_t n = masses.size();\n        if (n == 0) {\n            throw std::invalid_argument(\n                    \"jaco::pairwise_weights received empty vector of masses\");\n        }\n        const std::size_t num_pairs = n * (n - 1) / 2;\n        const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> v =\n                transformation_matrix_inverse(masses);\n        Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> w(n - 1, num_pairs);\n        for (std::size_t i = 0, k = 0; i < n - 1; ++i) {\n            for (std::size_t j = i + 1; j < n; ++j, ++k) {\n                for (std::size_t m = 0; m < n - 1; ++m) {\n                    w(m, k) = v(i, m) - v(j, m);\n                }\n            }\n        }\n        return w;\n    }\n\n    template <typename T>\n    std::vector<Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>>\n    permutation_matrices(\n            const std::vector<T> &masses,\n            const std::vector<std::vector<std::size_t>> &permutations) {\n        const std::size_t n = masses.size();\n        if (n == 0) {\n            throw std::invalid_argument(\n                    \"jaco::permutation_matrices received \"\n                    \"empty vector of masses\");\n        }\n        const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> u =\n                transformation_matrix(masses);\n        const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> v =\n                transformation_matrix_inverse(masses);\n        std::vector<Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>> result;\n        for (const auto &permutation : permutations) {\n            Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> w(n, n);\n            for (std::size_t i = 0; i < n; ++i) {\n                for (std::size_t j = 0; j < n; ++j) {\n                    w(i, j) = v(permutation[i], j);\n                }\n            }\n            const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> x = u * w;\n            result.emplace_back(n - 1, n - 1);\n            for (std::size_t i = 0; i < n - 1; ++i) {\n                for (std::size_t j = 0; j < n - 1; ++j) {\n                    result.back()(i, j) = x(i, j);\n                }\n            }\n        }\n        return result;\n    }\n\n} // namespace jaco\n\n#endif // ZSVM_JACOBI_COORDINATES_HPP_INCLUDED\n", "meta": {"hexsha": "b024afde3e39353bc40e22474f920323f9e5a51d", "size": 5897, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "JacobiCoordinates.hpp", "max_stars_repo_name": "dzhang314/zsvm", "max_stars_repo_head_hexsha": "cf7155627e446e095b5888f828ea879378834eaa", "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": "JacobiCoordinates.hpp", "max_issues_repo_name": "dzhang314/zsvm", "max_issues_repo_head_hexsha": "cf7155627e446e095b5888f828ea879378834eaa", "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": "JacobiCoordinates.hpp", "max_forks_repo_name": "dzhang314/zsvm", "max_forks_repo_head_hexsha": "cf7155627e446e095b5888f828ea879378834eaa", "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.6273291925, "max_line_length": 78, "alphanum_fraction": 0.4754960149, "num_tokens": 1633, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037221561135, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.7124018911380324}}
{"text": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union\u2019s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n\n#include \"../util/AlgorithmUtils.hpp\"\n#include \"../util/FluidEigenMappings.hpp\"\n#include \"../../data/FluidIndex.hpp\"\n#include <Eigen/Core>\n#include <cassert>\n#include <cmath>\n\nnamespace fluid {\nnamespace algorithm {\n\nclass MelBands\n{\npublic:\n  MelBands(index maxBands, index maxFFT)\n      : mFiltersStorage(maxBands, maxFFT / 2 + 1)\n  {}\n\n  /*static inline double mel2hz(double x) {\n      return 700.0 * (exp(x / 1127.01048) - 1.0);\n    }*/\n\n  static inline double hz2mel(double x)\n  {\n    return 1127.01048 * std::log(x / 700.0 + 1.0);\n  }\n\n  void init(double lo, double hi, index nBands, index nBins, double sampleRate,\n            index windowSize)\n  {\n\n    using namespace Eigen;\n    assert(hi > lo);\n    assert(nBands > 1);\n    mScale1 = 1.0 / (windowSize / 4.0); // scale to original amplitude\n    index fftSize = 2 * (nBins - 1);\n    mScale2 = 1.0 / (2.0 * double(fftSize) / windowSize);\n    ArrayXd melFreqs = ArrayXd::LinSpaced(nBands + 2, hz2mel(lo), hz2mel(hi));\n    melFreqs = 700.0 * ((melFreqs / 1127.01048).exp() - 1.0);\n    mFilters = mFiltersStorage.block(0, 0, nBands, nBins);\n    mFilters.setZero();\n    ArrayXd fftFreqs = ArrayXd::LinSpaced(nBins, 0, sampleRate / 2.0);\n    ArrayXd melD =\n        (melFreqs.segment(0, nBands + 1) - melFreqs.segment(1, nBands + 1))\n            .abs();\n    ArrayXXd ramps = melFreqs.replicate(1, nBins);\n    ramps.rowwise() -= fftFreqs.transpose();\n    for (index i = 0; i < nBands; i++)\n    {\n      ArrayXd lower = -ramps.row(i) / melD(i);\n      ArrayXd upper = ramps.row(i + 2) / melD(i + 1);\n      mFilters.row(i) = lower.min(upper).max(0);\n    }\n  }\n\n  void processFrame(const RealVectorView in, RealVectorView out, bool magNorm,\n                    bool usePower, bool logOutput)\n  {\n    using namespace Eigen;\n\n    ArrayXd frame = _impl::asEigen<Eigen::Array>(in);\n    if (magNorm) frame = frame * mScale1;\n    ArrayXd result;\n    if (usePower) { result = (mFilters * frame.square().matrix()).array(); }\n    else\n    {\n      result = (mFilters * frame.matrix()).array();\n    }\n    if (magNorm)\n    {\n      double energy = frame.sum() * mScale2;\n      result = result * energy / std::max(epsilon, result.sum());\n    }\n\n    if (logOutput) result = 20 * result.max(epsilon).log10();\n    out = _impl::asFluid(result);\n  }\n\n  double mScale1{1.0};\n  double mScale2{1.0};\n\n  Eigen::MatrixXd mFilters;\n  Eigen::MatrixXd mFiltersStorage;\n};\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "e709698d5e271bfb0af08ff52924d4550da12f86", "size": 2859, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/public/MelBands.hpp", "max_stars_repo_name": "chriskiefer/flucoma-core", "max_stars_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2020-05-11T15:42:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T01:51:36.000Z", "max_issues_repo_path": "include/algorithms/public/MelBands.hpp", "max_issues_repo_name": "chriskiefer/flucoma-core", "max_issues_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 90.0, "max_issues_repo_issues_event_min_datetime": "2020-05-13T20:25:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T18:05:35.000Z", "max_forks_repo_path": "include/algorithms/public/MelBands.hpp", "max_forks_repo_name": "chriskiefer/flucoma-core", "max_forks_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2020-05-11T15:15:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-15T12:15:36.000Z", "avg_line_length": 29.1734693878, "max_line_length": 79, "alphanum_fraction": 0.6435816719, "num_tokens": 855, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037262250327, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.712401889364647}}
{"text": "/*!\n * \\file QuadraticCurve.hpp\n * \\author Jun Yoshida\n * \\copyright (c) 2019 Jun Yoshida.\n * The project is released under the MIT License.\n * \\date Descember 9, 2019: created\n */\n\n#pragma once\n\n#include <memory>\n#include <array>\n#include <vector>\n#include <Eigen/Dense>\n\n#include \"AffHypPlane.hpp\"\n#include \"Bezier.hpp\"\n\n/*!\n * The class represents a quadratic curve on the Euclidean plane R^2.\n */\nclass QuadraticCurve\n{\nprivate:\n    Eigen::Matrix3d m_M;\n\npublic:\n    static constexpr double threshold = 10e-14;\n\n    //! Constructor, which accepts the coefficients of the associated quadratic form; namely,\n    //! ax^2+by^2+cz^2+dxy+exz+fyz\n    QuadraticCurve(double a, double b, double c, double d, double e, double f);\n\n    QuadraticCurve(QuadraticCurve const &) = default;\n    QuadraticCurve(QuadraticCurve &&) = default;\n\n    ~QuadraticCurve() = default;\n\n    //! Evaluate the defining function; i.e. q(x,y,1) for the associated quadratic form q.\n    double evaluate(double x0, double y0) const\n    {\n        Eigen::Vector3d v{x0, y0, 1.0};\n\n        return v.adjoint()*m_M*v;\n    }\n\n    //! Generate an affine line tangent to the curve q(x,y,1)=q(x0,y0,1).\n    AffHypPlane<2> tangent(double x0, double y0) const\n    {\n        Eigen::Vector2d df = m_M.block<2,3>(0,0) * Eigen::Vector3d(x0, y0, 1.0);\n        return AffHypPlane<2>(df, Eigen::Vector2d(x0, y0));\n    }\n\n    AffHypPlane<2> tangent(Eigen::Vector2d const &p) const\n    {\n        return tangent(p(0), p(1));\n    }\n\n    //! Compute the curvature vector at a given point (x0,y0).\n    Eigen::Vector2d curvature(double x0, double y0) const;\n\n    Eigen::Vector2d curvature(Eigen::Vector2d const &p) const\n    {\n        return curvature(p(0),p(1));\n    }\n\n    /*! If the curve is hyperbolic, compute an affine line such that\n     * - it divides the plain into two components each of which contains one of the two connected component of the hyperbola;\n     * - the curve is invariant under the reflection associated to the line.\n     * If the curve is not hyperbolic, i.e. it is elliptic, parabolic, or degenerate, then nullptr is returned.\n     */\n    std::unique_ptr<AffHypPlane<2> > divAxis() const;\n\n    //! Compute the parameter t (0<=t<=1) at which the segment (1-t)p0 + t p1 intersects with the curve.\n    std::vector<double> intersectParams(Eigen::Vector2d const &p0, Eigen::Vector2d const &p1);\n\n    //! Compute the parameter t (0<=t<=1) at which the segment (1-t)(x0,y0)+t(x1,y1) intersects with the curve.\n    std::vector<double> intersectParams(double x0, double y0, double x1, double y1)\n    {\n        return intersectParams(Eigen::Vector2d(x0,y0), Eigen::Vector2d(x1,y1));\n    }\n\n    /*! Approximate the intersection with a given triangle by cubic Bezier curves.\n     * \\param p The array of vertices that span a triangle.\n     * \\return The pair of\n     * - the set of Bezier curves each of which approximates a connected component of the intersection;\n     * - the flag indicating if the returned list is reliable.\n     */\n    auto onTriangle(std::array<Eigen::Vector2d,3> const& p)\n        -> std::pair<std::vector<Bezier<Eigen::Vector2d,3> >,bool>;\n};\n", "meta": {"hexsha": "0c81b76b15590e60fdffdd41514b13cf31516532", "size": 3130, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/math/QuadraticCurve.hpp", "max_stars_repo_name": "Junology/bord2", "max_stars_repo_head_hexsha": "0068885144032d4a8e30c6f2c5898918d00b1d8f", "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/QuadraticCurve.hpp", "max_issues_repo_name": "Junology/bord2", "max_issues_repo_head_hexsha": "0068885144032d4a8e30c6f2c5898918d00b1d8f", "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/QuadraticCurve.hpp", "max_forks_repo_name": "Junology/bord2", "max_forks_repo_head_hexsha": "0068885144032d4a8e30c6f2c5898918d00b1d8f", "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.0217391304, "max_line_length": 125, "alphanum_fraction": 0.6686900958, "num_tokens": 886, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.919642533380189, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.7123398209421749}}
{"text": "/**\n * @ file norms.cc\n * @ brief NPDE homework PointEvaluationRhs code\n * @ author Christian Mitsch, Liaowang Huang (refactoring)\n * @ date 22/03/2019, 06/01/2020 (refactoring)\n * @ copyright Developed at ETH Zurich\n */\n\n#include \"pointevaluationrhs_norms.h\"\n\n#include <cmath>\n\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n\n#include <lf/assemble/assemble.h>\n#include <lf/base/base.h>\n#include <lf/geometry/geometry.h>\n#include <lf/mesh/mesh.h>\n#include <lf/quad/quad.h>\n#include <lf/uscalfe/uscalfe.h>\n\nnamespace PointEvaluationRhs {\n\n/* SAM_LISTING_BEGIN_1 */\ndouble computeL2normLinearFE(const lf::assemble::DofHandler &dofh,\n                             const Eigen::VectorXd &mu) {\n  double result = 0.0;\n#if SOLUTION\n  int N_dofs = dofh.NumDofs();\n  lf::assemble::COOMatrix<double> mass_matrix(N_dofs, N_dofs);\n  MassLocalMatrixAssembler my_mat_provider{};\n  lf::assemble::AssembleMatrixLocally(0, dofh, dofh, my_mat_provider,\n                                      mass_matrix);\n  const Eigen::SparseMatrix<double> mass_mat = mass_matrix.makeSparse();\n  result = std::sqrt(mu.dot(mass_mat * mu));\n#else\n  //====================\n  // Your code goes here\n  //====================\n#endif\n  return result;\n}\n/* SAM_LISTING_END_1 */\n\n/* SAM_LISTING_BEGIN_2 */\ndouble computeH1seminormLinearFE(const lf::assemble::DofHandler &dofh,\n                                 const Eigen::VectorXd &mu) {\n  // calculate stiffness matrix by using the already existing local assembler\n  // LinearFELaplaceElementMatrix\n  double result = 0.0;\n#if SOLUTION\n  int N_dofs = dofh.NumDofs();\n  lf::assemble::COOMatrix<double> stiffness_matrix(N_dofs, N_dofs);\n  lf::uscalfe::LinearFELaplaceElementMatrix my_mat_provider{};\n  lf::assemble::AssembleMatrixLocally(0, dofh, dofh, my_mat_provider,\n                                      stiffness_matrix);\n  const Eigen::SparseMatrix<double> stiffness_mat =\n      stiffness_matrix.makeSparse();\n  result = std::sqrt(mu.dot(stiffness_mat * mu));\n#else\n  //====================\n  // Your code goes here\n  //====================\n#endif\n  return result;\n}\n/* SAM_LISTING_END_2 */\n\nEigen::MatrixXd MassLocalMatrixAssembler::Eval(const lf::mesh::Entity &entity) {\n  Eigen::MatrixXd result;\n#if SOLUTION\n  lf::geometry::Geometry *geo_ptr = entity.Geometry();\n  double volume = lf::geometry::Volume(*geo_ptr);\n\n  if (lf::base::RefEl::kTria() == entity.RefEl()) {\n    result.resize(3, 3);\n    result.setZero();\n    // See Lemma 2.7.5.5 for the derivation of these entries\n    double diag = volume / 6.0;\n    double non_diag = volume / 12.0;\n    result << diag, non_diag, non_diag, non_diag, diag, non_diag, non_diag,\n        non_diag, diag;\n  } else if (lf::base::RefEl::kQuad() == entity.RefEl()) {\n    result.resize(4, 4);\n    result.setZero();\n\n    // use quad rule to evaluate all possible combinations of products of\n    // basis functions\n    lf::uscalfe::FeLagrangeO1Quad<double> quad_element{};\n    lf::quad::QuadRule my_quad_rule = lf::quad::make_QuadQR_P4O4();\n\n    // Evaluate the basis functions on the quadrature points\n    Eigen::MatrixXd point_eval =\n        quad_element.EvalReferenceShapeFunctions(my_quad_rule.Points());\n\n    // Evaluate the integration element at the quadrature points\n    Eigen::MatrixXd int_el_eval =\n        geo_ptr->IntegrationElement(my_quad_rule.Points());\n\n    // weigh each point according to its weight in the quadrature formula and\n    // according to its integration element\n    Eigen::MatrixXd point_eval_weighted = point_eval *\n                                          my_quad_rule.Weights().asDiagonal() *\n                                          int_el_eval.asDiagonal();\n\n    // This product gives us the result of the quadrature rule for all\n    // possible combinations of basis functions\n    result = point_eval.transpose() * point_eval_weighted;\n  } else {\n    LF_ASSERT_MSG(false,\n                  \"Function only defined for triangular or quadrilateral cells\")\n  }\n#else\n  //====================\n  // Your code goes here\n  //====================\n#endif\n  return result;\n}\n\n}  // namespace PointEvaluationRhs\n", "meta": {"hexsha": "74dc71eb1de6b95ec32e7687af7aa9d020f88ec2", "size": 4089, "ext": "cc", "lang": "C++", "max_stars_repo_path": "developers/PointEvaluationRhs/mastersolution/pointevaluationrhs_norms.cc", "max_stars_repo_name": "padomu/NPDECODES", "max_stars_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "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": "developers/PointEvaluationRhs/mastersolution/pointevaluationrhs_norms.cc", "max_issues_repo_name": "padomu/NPDECODES", "max_issues_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "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": "developers/PointEvaluationRhs/mastersolution/pointevaluationrhs_norms.cc", "max_forks_repo_name": "padomu/NPDECODES", "max_forks_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "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.243902439, "max_line_length": 80, "alphanum_fraction": 0.6549278552, "num_tokens": 1012, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.7122105107466873}}
{"text": "/* test_uniform_on_sphere.cpp\r\n *\r\n * Copyright Steven Watanabe 2011\r\n * Distributed under the Boost Software License, Version 1.0. (See\r\n * accompanying file LICENSE_1_0.txt or copy at\r\n * http://www.boost.org/LICENSE_1_0.txt)\r\n *\r\n * $Id$\r\n *\r\n */\r\n\r\n#include <boost/random/uniform_on_sphere.hpp>\r\n#include <boost/random/uniform_int.hpp>\r\n#include <boost/math/distributions/uniform.hpp>\r\n#include <cmath>\r\n\r\nclass uniform_on_sphere_test {\r\npublic:\r\n    typedef double result_type;\r\n    uniform_on_sphere_test(int dims, int x, int y)\r\n        : impl(dims), idx1(x), idx2(y) {}\r\n    template<class Engine>\r\n    result_type operator()(Engine& rng) {\r\n        const boost::random::uniform_on_sphere<>::result_type& tmp = impl(rng);\r\n        // This should be uniformly distributed in [-pi,pi)\r\n        return std::atan2(tmp[idx1], tmp[idx2]);\r\n    }\r\nprivate:\r\n    boost::random::uniform_on_sphere<> impl;\r\n    int idx1, idx2;\r\n};\r\n\r\nstatic const double pi = 3.14159265358979323846;\r\n\r\n#define BOOST_RANDOM_DISTRIBUTION uniform_on_sphere_test\r\n#define BOOST_RANDOM_DISTRIBUTION_NAME uniform_on_sphere\r\n#define BOOST_MATH_DISTRIBUTION boost::math::uniform\r\n#define BOOST_RANDOM_ARG1_TYPE double\r\n#define BOOST_RANDOM_ARG1_NAME n\r\n#define BOOST_RANDOM_ARG1_DEFAULT 6\r\n#define BOOST_RANDOM_ARG1_DISTRIBUTION(n) boost::uniform_int<>(2, n)\r\n#define BOOST_RANDOM_DISTRIBUTION_INIT (n, 0, n-1)\r\n#define BOOST_MATH_DISTRIBUTION_INIT (-pi, pi)\r\n\r\n#include \"test_real_distribution.ipp\"\r\n", "meta": {"hexsha": "1edcb842fcd781a6594746a484c98e10b0ee2fee", "size": 1475, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/random/test/test_uniform_on_sphere.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/random/test/test_uniform_on_sphere.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/random/test/test_uniform_on_sphere.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": 32.0652173913, "max_line_length": 80, "alphanum_fraction": 0.7274576271, "num_tokens": 360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460332, "lm_q2_score": 0.8056321843145405, "lm_q1q2_score": 0.7122104975729142}}
{"text": "// lu_decomposition.cpp example program comparing float vs posit LU decomposition algorithms\n//\n// Copyright (C) 2017-2020 Stillwater Supercomputing, Inc.\n//\n// This file is part of the HPRBLAS project, which is released under an MIT Open Source license.\n\n#include \"common.hpp\"\n// configure the posit number system behavior\n#define POSIT_ROUNDING_ERROR_FREE_IO_FORMAT 0\n// configure the HPR-BLAS behavior\n#define HPRBLAS_TRACE_ROUNDING_EVENTS 1\n#include <hprblas>\n#include <mtl_extensions.hpp>\n// matrix generators\n#include <generators/matrix_generators.hpp>\n#include <utils/print_utils.hpp>\n\ntemplate<typename Matrix, typename Vector>\nvoid CroutCycle(Matrix& A, Vector& x, const Vector& b)\n{\n\tusing namespace sw::hprblas;\n\n\tassert(num_cols(A) == size(b));\n\tsize_t N = size(b);\n\tusing Scalar = typename mtl::Collection<Matrix>::value_type;\n\tmtl::dense2D< Scalar > LU(N, N);\n\n\tstd::cout << \"----------------- Crout cycle ------------------------\\n\";\n\tusing namespace std::chrono;\n\tsteady_clock::time_point t1 = steady_clock::now();\n\tCrout(A, LU);\n\tsteady_clock::time_point t2 = steady_clock::now();\n\tduration<double> time_span = duration_cast<duration<double>>(t2 - t1);\n\tdouble elapsed = time_span.count();\n\tstd::cout << \"Crout took \" << elapsed << \" seconds.\" << std::endl;\n\tstd::cout << \"Performance \" << (uint32_t)(N*N*N / (1000 * elapsed)) << \" KOPS/s\" << std::endl;\n\tSolveCrout(LU, b, x);\n\tprintMatrix(std::cout, \"Crout LU\", LU);\n\tprintVector(std::cout, \"Crout Solution\", x);\n}\n\ntemplate<size_t nbits, size_t es, size_t capacity = 10>\nvoid CroutCycle(mtl::dense2D< sw::unum::posit<nbits, es> >& A, mtl::dense_vector< sw::unum::posit<nbits, es> >& x, mtl::dense_vector< sw::unum::posit<nbits, es> >& b)\n{\n\tusing namespace sw::hprblas;\n\n\tassert(num_cols(A) == size(b));\n\tsize_t N = size(b);\n\tmtl::dense2D< sw::unum::posit<nbits, es> > LU(N, N);\n\n\tstd::cout << \"----------------- Crout cycle ------------------------\\n\";\n\tusing namespace std::chrono;\n\tsteady_clock::time_point t1 = steady_clock::now();\n\tCrout(A, LU);\n\tsteady_clock::time_point t2 = steady_clock::now();\n\tduration<double> time_span = duration_cast<duration<double>>(t2 - t1);\n\tdouble elapsed = time_span.count();\n\tstd::cout << \"Crout took \" << elapsed << \" seconds.\" << std::endl;\n\tstd::cout << \"Performance \" << (uint32_t)(N*N*N / (1000 * elapsed)) << \" KOPS/s\" << std::endl;\n\tSolveCrout(LU, b, x);\n\tprintMatrix(std::cout, \"Crout LU\", LU);\n\tprintVector(std::cout, \"Crout Solution\", x);\n}\n\ntemplate<size_t nbits, size_t es, size_t capacity = 10>\nvoid CroutFDPCycle(mtl::dense2D< sw::unum::posit<nbits, es> >& A, mtl::dense_vector< sw::unum::posit<nbits, es> >& x, mtl::dense_vector< sw::unum::posit<nbits, es> >& b)\n{\n\tusing namespace sw::hprblas;\n\n\tassert(num_cols(A) == size(b));\n\tsize_t N = size(b);\n\tmtl::dense2D< sw::unum::posit<nbits, es> > LU(N, N);\n\n\tstd::cout << \"----------------- Crout FDP cycle --------------------\\n\";\n\tusing namespace std::chrono;\n\tsteady_clock::time_point t1 = steady_clock::now();\n\tCroutFDP(A, LU);\n\tsteady_clock::time_point t2 = steady_clock::now();\n\tduration<double> time_span = duration_cast<duration<double>>(t2 - t1);\n\tdouble elapsed = time_span.count();\n\tstd::cout << \"Crout with FDP took \" << elapsed << \" seconds.\" << std::endl;\n\tstd::cout << \"Performance \" << (uint32_t)(N*N*N / (1000 * elapsed)) << \" KOPS/s\" << std::endl;\n\tSolveCroutFDP(LU, b, x);\n\tprintMatrix(std::cout, \"Crout FDP LU\", LU);\n\tprintVector(std::cout, \"Crout FDP Solution\", x);\n}\n\ntemplate<size_t nbits, size_t es, size_t capacity = 10>\nvoid ComparePositDecompositions(std::vector< sw::unum::posit<nbits, es> >& A, std::vector< sw::unum::posit<nbits, es> >& x, std::vector< sw::unum::posit<nbits, es> >& b) {\n\tsize_t d = b.size();\n\tassert(A.size() == d*d);\n\tusing namespace sw::hprblas;\n\tstd::vector< sw::unum::posit<nbits, es> > LU(d*d);\n\n\t{\n\t\tusing namespace std::chrono;\n\t\tsteady_clock::time_point t1 = steady_clock::now();\n\t\tCrout(A, LU);\n\t\tsteady_clock::time_point t2 = steady_clock::now();\n\t\tduration<double> time_span = duration_cast<duration<double>>(t2 - t1);\n\t\tdouble elapsed = time_span.count();\n\t\tstd::cout << \"Crout took \" << elapsed << \" seconds.\" << std::endl;\n\t\tstd::cout << \"Performance \" << (uint32_t)(d*d*d / (1000 * elapsed)) << \" KOPS/s\" << std::endl;\n\n\t\tSolveCrout(LU, b, x);\n\t\tprintMatrix(std::cout, \"Crout LU\", LU);\n\t\tprintVector(std::cout, \"Solution\", x);\n\t}\n\n\tstd::cout << std::endl;\n#if 0\n\t{\n\t\tusing namespace std::chrono;\n\t\tsteady_clock::time_point t1 = steady_clock::now();\n\t\tDoolittleFDP(A, LU);\n\t\tsteady_clock::time_point t2 = steady_clock::now();\n\t\tduration<double> time_span = duration_cast<duration<double>>(t2 - t1);\n\t\tdouble elapsed = time_span.count();\n\t\tstd::cout << \"Doolittle took \" << elapsed << \" seconds.\" << std::endl;\n\t\tstd::cout << \"Performance \" << (uint32_t)(d*d*d / (1000 * elapsed)) << \" KOPS/s\" << std::endl;\n\t\tSolveDoolittle(LU, b, x);\n\t\tprintMatrix(std::cout, \"Doolittle LU\", LU);\n\t\tprintVector(std::cout, \"Solution\", x);\n\t}\n\n\n\tstd::cout << std::endl;\n\n\t{\n\t\tusing namespace std::chrono;\n\t\tsteady_clock::time_point t1 = steady_clock::now();\n\t\tCholeskyFDP(A, LU);\n\t\tsteady_clock::time_point t2 = steady_clock::now();\n\t\tduration<double> time_span = duration_cast<duration<double>>(t2 - t1);\n\t\tdouble elapsed = time_span.count();\n\t\tstd::cout << \"Cholesky took \" << elapsed << \" seconds.\" << std::endl;\n\t\tstd::cout << \"Performance \" << (uint32_t)(d*d*d / (1000 * elapsed)) << \" KOPS/s\" << std::endl;\n\t\tSolveCholesky(LU, b, x);\n\t\tprintMatrix(std::cout, \"Cholesky LU\", LU);\n\t\tprintVector(std::cout, \"Solution\", x);\n\t}\n#endif\n}\n\n#if 0\ntemplate<typename Scalar>\nvoid RandomMatrix() {\n\tusing namespace std;\n\tmtl::dense_vector<Scalar> x(5), b(5), xprime(5);\n\tmtl::dense2D<Scalar> A(5, 5);\n\tmtl::mat::uniform_rand(A, -1.0, 1.0);\n\n\tx = 1.0;\n\tb = A * x;\n\tcout << endl;\n\tprintMatrix(cout, \"Matrix A(5x5):\\n\", A);\n\tcout << endl;\n\tcout << endl;\n\tprintVector(cout, \"RHS    b(5)  :\\n\", b);\n\tcout << endl;\n\tCroutCycle<nbits, es, capacity>(A, xprime, b);\n\tprintVector(cout, \"RHS    x(5)  :\\n\", xprime);\n\tcout << endl;\n\tCroutFDPCycle<nbits, es, capacity>(A, xprime, b);\n\tprintVector(cout, \"RHS    x(5)  :\\n\", xprime);\n}\n#endif\n\ntemplate<typename Ty>\nvoid CompareIEEEDecompositions(std::vector<Ty>& A, std::vector<Ty>& x, std::vector<Ty>& b) {\n\tsize_t d = b.size();\n\tassert(A.size() == d*d);\n\tusing namespace sw::hprblas;\n\tstd::vector<Ty> LU(d*d);\n\n\t{\n\t\tusing namespace std::chrono;\n\t\tsteady_clock::time_point t1 = steady_clock::now();\n\t\tCrout(A, LU);\n\t\tsteady_clock::time_point t2 = steady_clock::now();\n\t\tduration<double> time_span = duration_cast<duration<double>>(t2 - t1);\n\t\tdouble elapsed = time_span.count();\n\t\tstd::cout << \"Crout took \" << elapsed << \" seconds.\" << std::endl;\n\t\tstd::cout << \"Performance \" << (uint32_t)(d*d*d / (1000 * elapsed)) << \" KOPS/s\" << std::endl;\n\n\t\tSolveCrout(LU, b, x);\n\t\tprintMatrix(std::cout, \"Crout LU\", LU);\n\t\tprintVector(std::cout, \"Solution\", x);\n\t}\n\n\n\tstd::cout << std::endl;\n\n\t{\n\t\tusing namespace std::chrono;\n\t\tsteady_clock::time_point t1 = steady_clock::now();\n\t\tDoolittle(A, LU);\n\t\tsteady_clock::time_point t2 = steady_clock::now();\n\t\tduration<double> time_span = duration_cast<duration<double>>(t2 - t1);\n\t\tdouble elapsed = time_span.count();\n\t\tstd::cout << \"Doolittle took \" << elapsed << \" seconds.\" << std::endl;\n\t\tstd::cout << \"Performance \" << (uint32_t)(d*d*d / (1000 * elapsed)) << \" KOPS/s\" << std::endl;\n\t\tSolveCrout(LU, b, x);\n\t\tprintMatrix(std::cout, \"Doolittle LU\", LU);\n\t\tprintVector(std::cout, \"Solution\", x);\n\n\t\tSolveDoolittle(LU, b, x);\n\t\tprintMatrix(std::cout, \"Doolittle LU\", LU);\n\t\tprintVector(std::cout, \"Solution\", x);\n\t}\n\n\n\tstd::cout << std::endl;\n\n\t{\n\t\tusing namespace std::chrono;\n\t\tsteady_clock::time_point t1 = steady_clock::now();\n\t\tCholesky(A, LU);\n\t\tsteady_clock::time_point t2 = steady_clock::now();\n\t\tduration<double> time_span = duration_cast<duration<double>>(t2 - t1);\n\t\tdouble elapsed = time_span.count();\n\t\tstd::cout << \"Cholesky took \" << elapsed << \" seconds.\" << std::endl;\n\t\tstd::cout << \"Performance \" << (uint32_t)(d*d*d / (1000 * elapsed)) << \" KOPS/s\" << std::endl;\n\t\tSolveCrout(LU, b, x);\n\t\tprintMatrix(std::cout, \"Cholesky LU\", LU);\n\t\tprintVector(std::cout, \"Solution\", x);\n\n\t\tSolveCholesky(LU, b, x);\n\t\tprintMatrix(std::cout, \"Cholesky LU\", LU);\n\t\tprintVector(std::cout, \"Solution\", x);\n\t}\n}\n\n// trace 1 + eps configurations: TODO does this make sense for non-posit numbers?\ntemplate<typename Scalar>\nvoid TraceDeltas() {\n\tusing namespace std;\n\tusing namespace sw::unum;\n\tScalar eps = std::numeric_limits<Scalar>::epsilon();\n\tcout << \"       eps : \" << posit_format(eps) << \" \" << eps << endl;\n\n\tScalar epsplus;\n\tfor (auto i : { 0,1,2,4,8,16,32,64 }) {\n\t\tepsplus = Scalar(1.0) + Scalar(i) * eps;\n\t\tcout << \"1 + \" << setw(2) << i << \"*eps : \" << posit_format(epsplus) << \" \" << epsplus << endl;\n\t}\n\tfor (auto i : { 0,1,2,4,8,16,32,64 }) {\n\t\tepsplus = Scalar(1.0) + Scalar(i) * eps;\n\t\tcout << setw(2) << i << \"*(1 + eps) : \" << posit_format((1 + i)*epsplus) << \" \" << (1 + i)*epsplus << endl;\n\t}\n}\n\n// generate an A matrix that has an exact factorization solution\ntemplate<typename Matrix>\nvoid GenerateSystemOfLinearEquations(unsigned N, Matrix& L, Matrix& U, Matrix& A) {\n\tusing namespace sw::hprblas;\n\tfill_L(L);\n\tfill_U(U);\n\tA = L * U;\n}\n\ntemplate<typename Scalar>\nvoid GenerateAndSolveSystemOfLinearEquations(size_t N)\n{\n\tusing namespace std;\n\tusing namespace sw::unum;\n\tusing namespace mtl;\n\tusing namespace sw::hprblas;\n\n\tdense2D<Scalar> U(N, N), L(N, N), A(N, N);\n\tfill_U(U);\n\tfill_L(L);\n\n\t// show the different eps bits that we need to organize to avoid rounding error\n\t// cout << \"minpos     : \" << posit_format(minpos<nbits, es>()) << \" \" << minpos<nbits, es>() << endl;\n\t// TraceDeltas<Scalar>();\n\n\t// We want to solve the system Ax=b\n\tA = L*U;   // construct the A matrix to solve\n\tprintMatrix(cout, \"A = LU\", A);\n\tcout << endl;\n\n\t// define a difficult solution\n\tScalar eps = std::numeric_limits<Scalar>::epsilon();\n\t// let's pick one that doesn't generate rounding errors in the A * x operator\n\tScalar epsplus = Scalar(1.0) + Scalar(16) * eps;\n\n\tdense_vector<Scalar> x(N), b(N);\n\tx = epsplus;\n\tb = A * x;   // construct the right hand side\n\tprintVector(cout, \"x\", x);\n\tprintVector(cout, \"b\", b);\n\tcout << endl;\n\tdense_vector<Scalar> xprime(N);\n\tCroutCycle(A, b);\n\tcout << endl;\n}\n\ntemplate<size_t nbits, size_t es>\nvoid GenerateAndSolveSystemOfLinearEquations(size_t N)\n{\n\tusing namespace std;\n\tusing namespace sw::unum;\n\tusing namespace mtl;\n\tusing namespace sw::hprblas;\n\n\tusing Scalar = posit<nbits, es>;\n\tdense2D<Scalar> U(N, N), L(N, N), A(N, N);\n\tfill_U(U);\n\tfill_L(L);\n\n\t// show the different eps bits that we need to organize to avoid rounding error\n\t// cout << \"minpos     : \" << posit_format(minpos<nbits, es>()) << \" \" << minpos<nbits, es>() << endl;\n\t// TraceDeltas<Scalar>();\n\n\t// We want to solve the system Ax=b\n\tmatmul(A, L, U);   // construct the A matrix to solve\n\tprintMatrix(cout, \"A = LU\", A);\n\tcout << endl;\n\n\t// define a difficult solution\n\tScalar eps = std::numeric_limits<Scalar>::epsilon();\n\t// let's pick one that doesn't generate rounding errors in the A * x operator\n\tScalar epsplus = Scalar(1.0) + Scalar(16) * eps;\n\n\tdense_vector<Scalar> x(N), b(N);\n\tx = epsplus;\n\tmatvec(A, x, b);   // construct the right hand side\n\tprintVector(cout, \"x\", x);\n\tprintVector(cout, \"b\", b);\n\tcout << endl;\n\n\tCroutCycle(A, b);\n\tcout << endl;\n\tCroutFDPCycle(A, b);\n}\n\n\nint main(int argc, char** argv)\ntry {\n\tusing namespace std;\n\tusing namespace mtl;\n\tusing namespace sw::unum;\n\tusing namespace sw::hprblas;\n\n\t// a 32-bit float and a <27,1> posit have the same number of significand bits around 1.0\n\tconstexpr size_t nbits = 16;\n\tconstexpr size_t es = 1;\n\tconstexpr size_t capacity = 10;\n\tconstexpr size_t N = 5;\n\n\t//using Scalar = posit<nbits, es>;\n\t//\n\t//GenerateAndSolveSystemOfLinearEquations<Scalar>(N);\n\t//GenerateAndSolveSystemOfLinearEquations<float>(N);\n\n\t{\n\t\tusing Real = double;\n\t\tcout << \"Crout LU for type: \" << typeid(Real).name() << endl;\n\t\tdense2D<Real> U(N, N), L(N, N), A(N, N);\n\t\tGenerateSystemOfLinearEquations(N, L, U, A);\n\t\tprintMatrix(cout, \"L\", L);\n\t\tprintMatrix(cout, \"U\", U);\n\t\tprintMatrix(cout, \"A = LU\", A);\n\n\t\tdense_vector<Real> x(N), y(N), b(N);\n\t\ty = Real(1.0);\n\t\tb = A * y;   // construct the right hand side with rounding error\n//\t\tx = A / b;\n\t\tCroutCycle(A, x, b);\n\t\tcout << endl;\n\t}\n\n\t{\n\t\tusing Real = posit<32,2>;\n\t\tcout << \"Crout LU for type: \" << typeid(Real).name() << endl;\n\t\tdense2D<Real> U(N, N), L(N, N), A(N, N);\n\t\tGenerateSystemOfLinearEquations(N, L, U, A);\n\t\tprintMatrix(cout, \"L\", L);\n\t\tprintMatrix(cout, \"U\", U);\n\t\tprintMatrix(cout, \"A = LU\", A);\n\n\t\tdense_vector<Real> x(N), y(N), b(N);\n\t\ty = Real(1.0);\n\t\tb = A * y;   // construct the right hand side with rounding error\n//\t\tx = A / b;\n\t\tCroutFDPCycle(A, x, b);\n\t\tcout << endl;\n\t}\n\n#if 0\n\tcout << \"LinearSolve regular dot product\" << endl;\n\tCompareIEEEDecompositions(Aieee, xieee, bieee);\n\tcout << endl << \">>>>>>>>>>>>>>>>\" << endl;\n\tcout << \"LinearSolve fused-dot product\" << endl;\n\tComparePositDecompositions(Aposit, xposit, bposit);\n#endif\n\n\n\treturn EXIT_SUCCESS;\n}\ncatch (char const* msg) {\n\tstd::cerr << msg << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (const posit_arithmetic_exception& err) {\n\tstd::cerr << \"Uncaught posit arithmetic exception: \" << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (const quire_exception& err) {\n\tstd::cerr << \"Uncaught quire exception: \" << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (const posit_internal_exception& err) {\n\tstd::cerr << \"Uncaught posit internal exception: \" << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (std::runtime_error& err) {\n\tstd::cerr << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (...) {\n\tstd::cerr << \"Caught unknown exception\" << std::endl;\n\treturn EXIT_FAILURE;\n}\n", "meta": {"hexsha": "556981ee194fac9bd7f49a80198d7728457ac62f", "size": 13804, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "blas/L3/lu_decomposition.cpp", "max_stars_repo_name": "fossabot/hpr-blas", "max_stars_repo_head_hexsha": "dad4656f556ea62abddbf3ddbb712d6b77fe7e91", "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": "blas/L3/lu_decomposition.cpp", "max_issues_repo_name": "fossabot/hpr-blas", "max_issues_repo_head_hexsha": "dad4656f556ea62abddbf3ddbb712d6b77fe7e91", "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": "blas/L3/lu_decomposition.cpp", "max_forks_repo_name": "fossabot/hpr-blas", "max_forks_repo_head_hexsha": "dad4656f556ea62abddbf3ddbb712d6b77fe7e91", "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.4037558685, "max_line_length": 171, "alphanum_fraction": 0.6468414952, "num_tokens": 4282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460333, "lm_q2_score": 0.8056321796478255, "lm_q1q2_score": 0.712210493447355}}
{"text": "#include \"SDOT/Distances/RectangularQuadrature.h\"\n#include \"SDOT/Distances/LineQuadrature.h\"\n\n#include <Eigen/Core>\n#include \"SDOT/Assert.h\"\n\nusing namespace sdot::distances;\n\n\nstd::pair<Eigen::Matrix2Xd, Eigen::VectorXd> RectangularQuadrature::Get(unsigned int degree)\n{\n  // Get the 1d scalar points and weights\n  Eigen::VectorXd pts1d, wts1d;\n  std::tie(pts1d, wts1d) = LineQuadrature::Get(degree);\n\n  const int N1 = pts1d.size();\n  int ind;\n\n  Eigen::Matrix2Xd pts(2,N1*N1);\n  Eigen::VectorXd wts(N1*N1);\n  for(int xind=0; xind<N1; ++xind){\n    for(int yind=0; yind<N1; ++yind){\n      ind = yind + xind*N1;\n      pts(0,ind) = pts1d(xind);\n      pts(1,ind) = pts1d(yind);\n      wts(ind) = wts1d(xind)*wts1d(yind);\n    }\n  }\n\n  return std::make_pair(pts,wts);\n}\n", "meta": {"hexsha": "cc858d591e9d48b8a5ae62eba20262f8ae5fe9b9", "size": 764, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Distances/RectangularQuadrature.cpp", "max_stars_repo_name": "mparno/sdot2d", "max_stars_repo_head_hexsha": "f632824fc4f0285eab6de911cca8932f69ece705", "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/Distances/RectangularQuadrature.cpp", "max_issues_repo_name": "mparno/sdot2d", "max_issues_repo_head_hexsha": "f632824fc4f0285eab6de911cca8932f69ece705", "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/Distances/RectangularQuadrature.cpp", "max_forks_repo_name": "mparno/sdot2d", "max_forks_repo_head_hexsha": "f632824fc4f0285eab6de911cca8932f69ece705", "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.875, "max_line_length": 92, "alphanum_fraction": 0.6636125654, "num_tokens": 272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392695254318, "lm_q2_score": 0.8056321796478255, "lm_q1q2_score": 0.7122104836020451}}
{"text": "#include \"nlmatode.h\"\n\n#include <Eigen/Core>\n#include <Eigen/LU>\n#include <cmath>\n#include <iostream>\n#include <limits>\n\n// Supplies class Ode45\n#include \"../../../lecturecodes/Ode45/ode45.h\"\n// Supplied auxiliary function for linear regression\n#include \"../../../lecturecodes/helperfiles/polyfit.h\"\n\nnamespace NLMatODE {\n\n/* SAM_LISTING_BEGIN_1 */\nEigen::MatrixXd matode(const Eigen::MatrixXd &Y0, double T) {\n  // Use the Ode45 class to find an approximation\n  // of the matrix IVP $Y' = -(Y-Y')*Y$ at time $T$\n  Eigen::MatrixXd YT;\n  // Define the RHS\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 = 1e-10;\n  O.options.rtol = 1e-8;\n\n  // Return only matrix at $T$, (solution is vector\n  // of pairs $(y(t_k), t_k)$ for each step k\n  YT = O.solve(Y0, T).back().first;\n  return YT;\n}\n/* SAM_LISTING_END_1 */\n\n/* SAM_LISTING_BEGIN_2 */\nbool checkinvariant(const Eigen::MatrixXd &M, double T) {\n  // Check if $Y'*Y$ is preserved at the time $T$ by matode.\n  Eigen::MatrixXd N = matode(M, T);\n\n  if ((N.transpose() * N - M.transpose() * M).norm() <\n      10 * std::numeric_limits<double>::epsilon() * M.norm()) {\n    return true;\n  }\n\n  return false;\n}\n/* SAM_LISTING_END_2 */\n\n/* SAM_LISTING_BEGIN_3 */\ndouble cvgDiscreteGradientMethod() {\n  // Compute the fitted convergence rate of the Discrete\n  // gradient method. Also tabulate the values M and the errors.\n  double conv_rate = 0;\n  double T = 1.0;\n  // initial value\n  Eigen::MatrixXd Y0 = Eigen::MatrixXd::Zero(5, 5);\n  Y0(4, 0) = 1;\n  for (unsigned int i = 0; i < 4; ++i) {\n    Y0(i, i + 1) = 1;\n  }\n  // reference solution\n  Eigen::MatrixXd Y_ex = matode(Y0, T);\n\n  // define the rhs\n  auto F = [](const Eigen::MatrixXd &M) { return -(M - M.transpose()) * M; };\n\n  Eigen::MatrixXd I = Eigen::MatrixXd::Identity(5, 5);\n  Eigen::ArrayXd MM(8);\n  Eigen::ArrayXd err(8);\n\n  std::cout << \"Error for equidistant steps:\" << std::endl;\n  std::cout << \"M\"\n            << \"\\t\"\n            << \"Error\" << std::endl;\n  for (unsigned int i = 0; i < 8; ++i) {\n    unsigned int M = 10 * std::pow(2, i);\n    double h = T / M;\n    MM(i) = M;\n    Eigen::MatrixXd Y = Y0;\n    for (unsigned int j = 0; j < M; ++j) {\n      Eigen::MatrixXd Ystar = Y + 0.5 * h * F(Y);\n\n      Eigen::MatrixXd Yinc = 0.5 * h * (Ystar - Ystar.transpose());\n      Y = (I + Yinc).lu().solve((I - Yinc) * Y);\n    }\n    err(i) = (Y - Y_ex).norm();\n    std::cout << M << \"\\t\" << err(i) << std::endl;\n  }\n\n  // compute fitted rate\n  Eigen::VectorXd coeffs = polyfit(MM.log(), err.log(), 1);\n  conv_rate = -coeffs(0);\n  return conv_rate;\n}\n/* SAM_LISTING_END_3 */\n\n}  // namespace NLMatODE\n", "meta": {"hexsha": "7fd038f462f5b42fed034f9157f82300d934a7f6", "size": 2699, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/NLMatODE/mastersolution/nlmatode.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": "homeworks/NLMatODE/mastersolution/nlmatode.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": "homeworks/NLMatODE/mastersolution/nlmatode.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": 27.2626262626, "max_line_length": 77, "alphanum_fraction": 0.5987402742, "num_tokens": 871, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.8438950966654774, "lm_q1q2_score": 0.7121589391457886}}
{"text": "/*! \\file demo_FP_compare.cpp\n   \\brief Demonstrate features of floating-point comparisons to find if values are close to each other,\n    or are too small to be significantly different from zero.\n\n  \\author Paul A. Bristow\n*/\n\n//  Copyright Paul A. Bristow 2008, 2009, 2020\n\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#include <iostream>\n // using std::cout;\n  using std::endl;\n  using std::dec;\n  using std::hex;\n  using std::boolalpha;\n#include <iomanip>\n // using std::setprecision;\n // using std::setw;\n#include <string>\n  //using std::string;\n#include <limits>\n  //using std::numeric_limits;\n\n#include <boost/svg_plot/detail/fp_compare.hpp>\n\nint main()\n{\n  std::cout << \"Demo FP compare\";\n\n#if defined(__FILE__) && defined(__TIMESTAMP__)\n  std::cout << \"  \" << __FILE__ << ' ' << __TIMESTAMP__ ;\n#  ifdef _MSC_FULL_VER\n  std::cout << ' '<< _MSC_FULL_VER;\n#  endif\n#endif\n  std::cout << boolalpha << endl;\n\n  {\n  // Check if a floating-point value is very close to zero, or exactly zero.\n  // Sort of operator ~= (if such a thing was possible)\n\n  // Use the default type double and the default small value 2 * min_value.\n  smallest<> t_def; // double is default FP type.\n  std::cout << t_def.size() << std::endl; // 4.45015e-308\n  std::cout << \"t(0) \" << t_def(0) << std::endl; // true -  is *integer* zero.\n  std::cout << \"t(0.) \" << t_def(0.) << std::endl; // true = really is zero.\n\n  // Specify a default float value.\n  smallest<float> tf;\n  std::cout << \"smallest<float> tf size = \" << tf.size() << std::endl; // smallest<float> tf small = 2.35099e-038\n  std::cout << \" tf(1e-38F) \" << tf(1e-38F) << std::endl; // Smaller than float min_value, so expect true ~= zero.\n  std::cout << \" tf(9.e-38F) \" << tf(9.e-38F) << std::endl; // Larger than float min_value, so expect false != zero.\n\n  // Specify a chosen small float value of 1e-10.\n  smallest<float> tf10(1e-10F); // Note value must be a float - to match.\n  std::cout << \"smallest<float> tf10(1e-10); = \" << tf10.size() << std::endl; // smallest<float> tf10(1e-10); = 1e-010\n\n  std::cout << \" tf10(1e-11F) \" << tf10(1e-11F) << std::endl; // Smaller than float 1e-10, so expect true ~= zero.\n  std::cout << \" tf10(tf10(9.e-9F) \" << tf10(9.e-9F) << std::endl; // Larger than float 1e-10, so expect false != zero.\n\n  // Use convenience typdef for double and 2 * (std::numeric_limits<double>::min())\n  // typedef smallest<double> tiny;\n\n  tiny tn;\n  std::cout  << \"tiny tn.size() = \" << tn.size() << std::endl; // 4.45015e-308\n  std::cout<< \"tn(0)  \" << tn(0) << std::endl; // true\n\n  smallest<double> z;\n  std::cout << z.size() << std::endl;\n  std::cout << z(1e-308) << std::endl;\n\n  tiny zz; // typedef smallest<double> tiny;\n  std::cout << zz.size() << std::endl;\n  std::cout << zz(1e-308) << std::endl;\n\n  constexpr double v = (std::numeric_limits<double>::min)();\n  if (zz(v))\n  {\n    std::cout << v << \" is tiny.\" << std::endl;\n  }\n  tiny z0(0);\n  std::cout << zz.size() << std::endl;\n\n  tiny z00(0.);\n  std::cout << zz.size() << std::endl;\n\n\n  close_to<> is_near_100eps(std::numeric_limits<double>::epsilon(), FPC_WEAK);\n\n  std::cout << is_near_100eps(1., 1 + 90 * std::numeric_limits<double>::epsilon() ) << std::endl;\n  std::cout << is_near_100eps(1., 1 + 110 * std::numeric_limits<double>::epsilon() ) << std::endl;\n\n  }\n\n  {   // Compare two floating-point values for being close enough to be considered 'equal'.\n// Demonstrate use of close-to to check close enough to meet tolerance.\n\n  // Use default tolerance\n  // This is twice numeric_limits min,\n  // which should allow for a few bits difference from computations.\n\n  // Specific type float, and both tolerance and strength specified.\n  close_to<float> t1(1e-15F, FPC_WEAK);\n  std::cout << \"close_to() t1.size() \" << t1.size() << ' ' << (t1.strength() == 0 ? \"strong \" : \"weak\" )  << std::endl; //  1e-015 weak\n  close_to<float> tdf; // default tolerance = 2 *epsilon and strength = strong\n  std::cout << \"close_to<float> tdf.size() = \"  << tdf.size() << ' ' << (tdf.strength() == 0 ? \"strong \" : \"weak\" ) << std::endl; //  2.38419e-007 strong\n\n  // Use the default type double and the default tolerance value 2 * epsilon.\n  close_to<double> tds(1e-14, FPC_STRONG); // default strength = strong\n  std::cout << \"close_to<double> tds.size() = \"  << tds.size() << ' ' << (tds.strength() == 0 ? \"strong \" : \"weak\" ) << std::endl;\n  close_to<double> tdw(1e-14, FPC_WEAK); // default strength = strong\n  std::cout << \"close_to<double> tdw.size() = \"  << tdw.size() << ' ' << (tdw.strength() == 0 ? \"strong \" : \"weak\" ) << std::endl;\n  close_to<double> tdd; // default tolerance = 2 *epsilon and strength = strong\n  std::cout << \"close_to<double> tdd.size() = \"  << tdd.size() << ' ' << (tdd.strength() == 0 ? \"strong \" : \"weak\" ) << std::endl;\n  close_to<double> tdds(1e-14); // specific tolerance but use default strength = strong\n  std::cout << \"close_to<double> tdds.size() = \"  << tdds.size() << ' ' << (tdds.strength() == 0 ? \"strong \" : \"weak\" ) << std::endl;\n\n  close_to<> t; //\n  std::cout << \"close_to<double> t.size() = \"  << t.size() << ' ' << (t.strength() == 0 ? \"strong \" : \"weak\" ) << std::endl;\n  std::cout << \"close_to<double> tdd.size() = \"  << tdd.size() << ' ' << (tdd.strength() == 0 ? \"strong \" : \"weak\" ) << std::endl;\n\n  // neareq\n  // Use nearby the convenience typedef for close_to<double>\n  neareq neq;\n  std::cout << \"neq(0) \" << neq(0, FPC_STRONG) << std::endl; // true -  is *integer* zero.\n  std::cout << \"neq(0.) \" << neq(0., FPC_STRONG) << std::endl; // true = really is zero.\n  std::cout << \"neq(1 * (std::numeric_limits<double>::min)()) \" << neq(1 * (std::numeric_limits<double>::min)(), 2 * (std::numeric_limits<double>::min)()) << std::endl; // true\n\n  neareq neqd(1 * (std::numeric_limits<double>::min)()); // Specify tolerance & rely on default strong requirement.\n  std::cout << neqd.size()  << neqd.size() << ' ' << (neqd.strength() == 0 ? \"strong \" : \"weak\" ) << std::endl;\n  neareq neqdw(1 * (std::numeric_limits<double>::min)(), FPC_WEAK); // Both tolerance strength specified.\n  std::cout << neqdw.size()  << neqdw.size() << ' ' << (neqdw.strength() == 0 ? \"strong \" : \"weak\" ) << std::endl;\n\n  std::cout << neq(1e-308, 1.1e-308) << std::endl;\n  std::cout << neq(1e-308, 1.0000000000000001e-308) << std::endl;\n\n  close_to<> is_near_100eps(100 * std::numeric_limits<double>::epsilon(), FPC_WEAK);\n  // Set a tolerance of 100 epsilon ~= 1e-14\n\n  std::cout << is_near_100eps(1., 1. + 90 * std::numeric_limits<double>::epsilon() ) << std::endl; // true\n  std::cout << is_near_100eps(1., 1. + 110 * std::numeric_limits<double>::epsilon() ) << std::endl; // false\n }\n  return 0;\n}  // int main()\n\n\n/*\n\nOutput:\n\nAutorun \"j:\\Cpp\\SVG\\Debug\\demo_fp_compare.exe\nDemo FP compare  i:\\boost-sandbox\\SOC\\2007\\visualization\\libs\\svg_plot\\example\\demo_FP_compare.cpp Wed Mar 25 12:57:38 2009 150021022\n4.45015e-308\nt(0) true\nt(0.) true\nsmallest<float> tf size = 2.35099e-038\n tf(1e-38F) true\n tf(9.e-38F) false\nsmallest<float> tf10(1e-10); = 1e-010\n tf10(1e-11F) true\n tf10(tf10(9.e-9F) false\ntiny tn.size() = 4.45015e-308\ntn(0)  true\n4.45015e-308\ntrue\n4.45015e-308\ntrue\n2.22507e-308 is tiny.\n4.45015e-308\n4.45015e-308\nfalse\nfalse\nclose_to() t1.size() 1e-015 weak\nclose_to<float> tdf.size() = 2.38419e-007 strong\nclose_to<double> tds.size() = 1e-014 strong\nclose_to<double> tdw.size() = 1e-014 weak\nclose_to<double> tdd.size() = 4.44089e-016 strong\nclose_to<double> tdds.size() = 1e-014 strong\nclose_to<double> t.size() = 4.44089e-016 strong\nclose_to<double> tdd.size() = 4.44089e-016 strong\nneq(0) true\nneq(0.) true\nneq(1 * (numeric_limits<double>::min)()) false\n2.22507e-3082.22507e-308 strong\n2.22507e-3082.22507e-308 weak\nfalse\ntrue\ntrue\nfalse\n\n*/\n\n\n\n", "meta": {"hexsha": "7e1982bf7ad0ee996a39feb141be00aac8bf72ab", "size": 7820, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/demo_FP_compare.cpp", "max_stars_repo_name": "pabristow/svg_plot", "max_stars_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2016-03-09T03:23:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T14:02:07.000Z", "max_issues_repo_path": "example/demo_FP_compare.cpp", "max_issues_repo_name": "pabristow/svg_plot", "max_issues_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2018-03-05T14:39:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-22T09:00:33.000Z", "max_forks_repo_path": "example/demo_FP_compare.cpp", "max_forks_repo_name": "pabristow/svg_plot", "max_forks_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2016-11-04T14:36:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-17T08:12:03.000Z", "avg_line_length": 39.2964824121, "max_line_length": 176, "alphanum_fraction": 0.6278772379, "num_tokens": 2666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.8499711737573762, "lm_q1q2_score": 0.7119528302877157}}
{"text": "/*\n * NOTE: This solution is based on https://www.reddit.com/r/adventofcode/comments/3xflz8/day_19_solutions/cy4etju/\n *\n * Conceptually, to get the minimum steps from molecule \"e\" to the medicine, we need to go backwards and\n * start with the medicine. The medicine is composed of output molecules, each for which there's an input\n * molecule. So we keep replacing each molecule in the medicine with its input until there's only molecule\n * \"e\" left.\n *\n * Looking at the input, there are a couple observations we can make:\n *\n * a) There are only two kinds of replacements (\"|\" denotes multiple replacements for the same input):\n * 1. X => XX\n * 2. X => X Rn X Ar | X Rn X Y X Ar | X Rn X Y X Y X Ar\n *\n * b) Following observation a), Rn Y Ar is equivalent to ( , )\n * - X => X(X) | X(X,X) | X(X,X,X)\n *\n * c) When you have a molecule of type XX, that is, none of Rn, Y or Ar, you can apply the first production (see a)),\n * i.e. reverse the replacement like this:\n * - XX => X\n *\n * When you have a molecule of type X(X) | X(X,X) | X(X,X,X), you can apply the second production (see a)), i.e.\n * reverse the replacement like this:\n * - X(X) | X(X,X) | X(X,X,X) => X\n *\n * Applying a production counts as one step.\n *\n * d) Repeatedly applying XX => X until there's only one molecule left takes `count(X) - 1` steps\n * - ABCDE => XCDE => XDE => XE => X\n *\n * This example produces `count(`ABCDE`) - 1` = `5 - 1` = 4 steps.\n *\n * Applying X(X) => X is similar, but `()` must be taken into account, since it increases the count.\n * This is expressed by expanding the formula: `count(`X(X)`) - count(no. of parentheses) - 1` steps. Example:\n * - A(B(C(D(E)))) => A(B(C(X))) => A(B(X)) => A(X) => X\n *\n * count(`A(B(C(D(E))))`) = 13\n * count(`(((())))`) = 8\n *\n * Result: 13 - 8 - 1 = 4 steps\n *\n * Applying X(X,X) | X(X,X,X) => X adds another variable to the count formula, the comma `,`, representing molecule Y.\n * As you can observe, each comma adds two molecules `,X` to the output. Taking this into account, we can write\n * the final formula as follows:\n *\n * `count(`X(X,X)`) - count(parentheses) - 2*count(commas) - 1` steps.\n *\n * - X(X,X) => X is expressed as `6 - 2 - 2 - 1 = 1 step`\n * - X(X,X,X) => X is expressed as `8 - 2 - 4 - 1 = 1 step`\n */\n#include <array>\n#include <iostream>\n#include <string_view>\n\n#include \"input.hpp\"\n\nconstexpr auto NEWLINE = '\\n';\nconstexpr auto UPPERCASE_ALPHABET = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\nconstexpr auto parse_stats(std::string_view input) {\n\n  auto med_size = 0;\n\n  auto pos = input.rfind(NEWLINE) + 1;\n\n  while(pos != input.npos) {\n    auto next = input.find_first_of(UPPERCASE_ALPHABET, (pos + 1));\n    ++med_size;\n    pos = next;\n  }\n\n  return med_size;\n}\n\nconstexpr auto MED_SIZE = parse_stats(puzzle_input);\n\nusing Medicine = std::array<std::string_view, MED_SIZE>;\n\n/*\n * Molecules always start with an uppercase letter. If we represent the medicine\n * as a sequence of separate molecules, it becomes easier to use the count formula\n * described above later on.\n */\n#include <boost/range/irange.hpp>\nauto parse_medicine(std::string_view input) {\n\n  auto medicine = Medicine{};\n\n  input.remove_prefix(input.rfind(NEWLINE) + 1);\n\n  for(const auto i : boost::irange(MED_SIZE)) {\n    const auto pos = input.find_first_of(UPPERCASE_ALPHABET, 1);\n    medicine[i] = input.substr(0, pos);\n    input.remove_prefix(pos);\n  }\n\n  return medicine;\n}\n\nauto min_steps(const Medicine& medicine) {\n\n  auto num_steps = 0;\n\n  constexpr auto Rn = \"Rn\";\n  constexpr auto Ar = \"Ar\";\n  constexpr auto Y  = \"Y\";\n\n  for(auto molecule : medicine) {\n    /*\n     * This is the application of the formula described above:\n     *\n     * min_steps = `count(`X(X,X)`) - count(parentheses) - 2*count(commas) - 1` steps\n     *\n     * - Rn and Ar are parentheses\n     * - Y is a comma\n     */\n    num_steps += 1 - ((molecule == Rn) or (molecule == Ar)) - (2 * (molecule == Y));\n  }\n\n  return (num_steps - 1);\n}\n\nauto solution(std::string_view input) {\n\n  const auto& medicine = parse_medicine(input);\n\n  return min_steps(medicine);\n}\n\nint main() {\n\n  std::cout << solution(puzzle_input) << std::endl;\n\n}\n", "meta": {"hexsha": "08fa9c068df169ae3c7b29362e1dc6e34f7549c5", "size": 4125, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Day 19 Part 2/main_v2.cpp", "max_stars_repo_name": "Miroslav-Cetojevic/aoc-2015", "max_stars_repo_head_hexsha": "2807fcd3fc684843ae4222b25af6fd086fac77f5", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-19T20:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-19T20:19:18.000Z", "max_issues_repo_path": "Day 19 Part 2/main_v2.cpp", "max_issues_repo_name": "Miroslav-Cetojevic/aoc-2015", "max_issues_repo_head_hexsha": "2807fcd3fc684843ae4222b25af6fd086fac77f5", "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": "Day 19 Part 2/main_v2.cpp", "max_forks_repo_name": "Miroslav-Cetojevic/aoc-2015", "max_forks_repo_head_hexsha": "2807fcd3fc684843ae4222b25af6fd086fac77f5", "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": 30.5555555556, "max_line_length": 118, "alphanum_fraction": 0.6448484848, "num_tokens": 1201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583695, "lm_q2_score": 0.837619959279793, "lm_q1q2_score": 0.711952827909873}}
{"text": "//\n//  Copyright (c) 2018, Cem Bassoy, cem.bassoy@gmail.com\n//  Copyright (c) 2019, Amit Singh, amitsingh19975@gmail.com\n//\n//  Distributed under the Boost Software License, Version 1.0. (See\n//  accompanying file LICENSE_1_0.txt or copy at\n//  http://www.boost.org/LICENSE_1_0.txt)\n//\n//  The authors gratefully acknowledge the support of\n//  Google and Fraunhofer IOSB, Ettlingen, Germany\n//\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/tensor.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <iostream>\n\nvoid multiply_tensors_with_dynamic_order()\n{\n    namespace ublas = boost::numeric::ublas;\n\n    using layout = ublas::layout::first_order;\n    using value  = float; // std::complex<double>;\n    using tensor = ublas::tensor_dynamic<value,layout>;\n    using matrix = ublas::matrix<value,layout>;\n    using vector = ublas::vector<value>;\n    using shape  = typename tensor::extents_type;\n    constexpr auto ones = ublas::ones<value,layout>{};\n\n    // Tensor-Vector-Multiplications - Including Transposition\n    try {\n\n        auto n = shape{3,4,2};\n        auto A = tensor(n,2);\n        auto q = 0u; // contraction mode\n\n        // C1(j,k) = T2(j,k) + A(i,j,k)*T1(i);\n        q = 1u;\n        tensor C1 = matrix(n[1],n[2],2) + ublas::prod(A,vector(n[q-1],1),q);\n\n        // C2(i,k) = A(i,j,k)*T1(j) + 4;\n        q = 2u;\n        tensor C2 = ublas::prod(A,vector(n[q-1],1),q) + 4;\n\n        // C3() = A(i,j,k)*T1(i)*T2(j)*T2(k);  \n        tensor C3 = ublas::prod(ublas::prod(ublas::prod(A,vector(n[0],1),1),vector(n[1],1),1),vector(n[2],1),1);\n\n        // C4(i,j) = A(k,i,j)*T1(k) + 4;\n        q = 1u;\n        tensor C4 = ublas::prod(trans(A,{2,3,1}),vector(n[2],1),q) + 4;\n\n\n        // formatted output\n        std::cout << \"% --------------------------- \" << std::endl;\n        std::cout << \"% --------------------------- \" << std::endl << std::endl;\n        std::cout << \"% C1(j,k) = T2(j,k) + A(i,j,k)*T1(i);\" << std::endl << std::endl;\n        std::cout << \"C1=\" << C1 << \";\" << std::endl << std::endl;\n\n        // formatted output\n        std::cout << \"% --------------------------- \" << std::endl;\n        std::cout << \"% --------------------------- \" << std::endl << std::endl;\n        std::cout << \"% C2(i,k) = A(i,j,k)*T1(j) + 4;\" << std::endl << std::endl;\n        std::cout << \"C2=\" << C2 << \";\" << std::endl << std::endl;\n\n        // formatted output\n        std::cout << \"% --------------------------- \" << std::endl;\n        std::cout << \"% --------------------------- \" << std::endl << std::endl;\n        std::cout << \"% C3() = A(i,j,k)*T1(i)*T2(j)*T2(k);\" << std::endl << std::endl;\n        std::cout << \"C3()=\" << C3(0) << \";\" << std::endl << std::endl;\n\n        // formatted output\n        std::cout << \"% --------------------------- \" << std::endl;\n        std::cout << \"% --------------------------- \" << std::endl << std::endl;\n        std::cout << \"% C4(i,j) = A(k,i,j)*T1(k) + 4;\" << std::endl << std::endl;\n        std::cout << \"C4=\" << C4 << \";\" << std::endl << std::endl;\n\n    }  catch (const std::exception& e) {\n      std::cerr << \"Cought exception \" << e.what();\n      std::cerr << \"in the main function of multiply-tensor-product-function.\" << std::endl;\n    }\n\n\n\n    // Tensor-Matrix-Multiplications - Including Transposition\n    try {\n\n        auto n = shape{3,4,2};\n        tensor A = 2*ones(n);//tensor\n        auto m = 5u;\n        auto q = 0u; // contraction mode\n\n        // C1(l,j,k) = T2(l,j,k) + A(i,j,k)*T1(l,i);\n        q = 1u;\n        tensor C1 = 2*ones(m,n[1],n[2]) + ublas::prod(A,matrix(m,n[q-1],1),q);\n\n        // C2(i,l,k) = A(i,j,k)*T1(l,j) + 4;\n        q = 2u;\n        tensor C2 = ublas::prod(A,matrix(m,n[q-1],1),q) + 4;\n\n        // C3(i,l1,l2) = A(i,j,k)*T1(l1,j)*T2(l2,k);\n        q = 3u;\n        tensor C3 = ublas::prod(ublas::prod(A,matrix(m+1,n[q-2],1),q-1),matrix(m+2,n[q-1],1),q);\n\n        // C4(i,l1,l2) = A(i,j,k)*T2(l2,k)*T1(l1,j);\n        tensor C4 = ublas::prod(ublas::prod(A,matrix(m+2,n[q-1],1),q),matrix(m+1,n[q-2],1),q-1);\n\n        // C5(i,k,l) = A(i,k,j)*T1(l,j) + 4;\n        q = 3u;\n        tensor C5 = ublas::prod(trans(A,{1,3,2}),matrix(m,n[1],1),q) + 4;\n\n        // formatted output\n        std::cout << \"% --------------------------- \" << std::endl;\n        std::cout << \"% --------------------------- \" << std::endl << std::endl;\n        std::cout << \"% C1(l,j,k) = T2(l,j,k) + A(i,j,k)*T1(l,i);\" << std::endl << std::endl;\n        std::cout << \"C1=\" << C1 << \";\" << std::endl << std::endl;\n\n        // formatted output\n        std::cout << \"% --------------------------- \" << std::endl;\n        std::cout << \"% --------------------------- \" << std::endl << std::endl;\n        std::cout << \"% C2(i,l,k) = A(i,j,k)*T1(l,j) + 4;\" << std::endl << std::endl;\n        std::cout << \"C2=\" << C2 << \";\" << std::endl << std::endl;\n\n        // formatted output\n        std::cout << \"% --------------------------- \" << std::endl;\n        std::cout << \"% --------------------------- \" << std::endl << std::endl;\n        std::cout << \"% C3(i,l1,l2) = A(i,j,k)*T1(l1,j)*T2(l2,k);\" << std::endl << std::endl;\n        std::cout << \"C3=\" << C3 << \";\" << std::endl << std::endl;\n\n        // formatted output\n        std::cout << \"% --------------------------- \" << std::endl;\n        std::cout << \"% --------------------------- \" << std::endl << std::endl;\n        std::cout << \"% C4(i,l1,l2) = A(i,j,k)*T2(l2,k)*T1(l1,j);\" << std::endl << std::endl;\n        std::cout << \"C4=\" << C4 << \";\" << std::endl << std::endl;\n        std::cout << \"% C3 and C4 should have the same values, true? \" << std::boolalpha << (C3 == C4) << \"!\" << std::endl;\n\n\n        // formatted output\n        std::cout << \"% --------------------------- \" << std::endl;\n        std::cout << \"% --------------------------- \" << std::endl << std::endl;\n        std::cout << \"% C5(i,k,l) = A(i,k,j)*T1(l,j) + 4;\" << std::endl << std::endl;\n        std::cout << \"C5=\" << C5 << \";\" << std::endl << std::endl;\n    } catch (const std::exception& e) {\n      std::cerr << \"Cought exception \" << e.what();\n      std::cerr << \"in the multiply_tensors_with_dynamic_order function of multiply-tensor-product-function.\" << std::endl;\n    }\n\n\n\n\n\n    // Tensor-Tensor-Multiplications Including Transposition\n    try {\n\n        using perm_t = std::vector<std::size_t>;\n\n        auto na = shape{3,4,5};\n        auto nb = shape{4,6,3,2};\n        tensor A = 2*ones(na); //tensor(na,2);\n        tensor B = 3*ones(nb); //tensor(nb,3);\n\n\n        // C1(j,l) = T(j,l) + A(i,j,k)*A(i,j,l) + 5;\n        tensor C1 = 2*ones(na[2],na[2]) + ublas::prod(A,A,perm_t{1,2}) + 5;\n\n        // formatted output\n        std::cout << \"% --------------------------- \" << std::endl;\n        std::cout << \"% --------------------------- \" << std::endl << std::endl;\n        std::cout << \"% C1(k,l) = T(k,l) + A(i,j,k)*A(i,j,l) + 5;\" << std::endl << std::endl;\n        std::cout << \"C1=\" << C1 << \";\" << std::endl << std::endl;\n\n\n        // C2(k,l,m) = T(k,l,m) + A(i,j,k)*B(j,l,i,m) + 5;\n        tensor C2 = 2*ones(na[2],nb[1],nb[3]) + ublas::prod(A,B,perm_t{1,2},perm_t{3,1}) + 5;\n\n        // formatted output\n        std::cout << \"% --------------------------- \" << std::endl;\n        std::cout << \"% --------------------------- \" << std::endl << std::endl;\n        std::cout << \"%  C2(k,l,m) = T(k,l,m) + A(i,j,k)*B(j,l,i,m) + 5;\" << std::endl << std::endl;\n        std::cout << \"C2=\" << C2 << \";\" << std::endl << std::endl;\n\n\n        // C3(k,l,m) = T(k,l,m) + A(i,j,k)*trans(B(j,l,i,m),{2,3,1,4})+ 5;\n        tensor C3 = 2*ones(na[2],nb[1],nb[3]) + ublas::prod(A,trans(B,{2,3,1,4}),perm_t{1,2}) + 5;\n\n        // formatted output\n        std::cout << \"% --------------------------- \" << std::endl;\n        std::cout << \"% --------------------------- \" << std::endl << std::endl;\n        std::cout << \"%  C3(k,l,m) = T(k,l,m) + A(i,j,k)*trans(B(j,l,i,m),{2,3,1,4})+ 5;\" << std::endl << std::endl;\n        std::cout << \"C3=\" << C3 << \";\" << std::endl << std::endl;\n\n    } catch (const std::exception& e) {\n      std::cerr << \"Cought exception \" << e.what();\n      std::cerr << \"in the main function of multiply-tensor-product-function.\" << std::endl;\n    }\n}\n\n\nvoid multiply_tensors_with_static_order()\n{\n    namespace ublas = boost::numeric::ublas;\n\n    using layout  = ublas::layout::first_order;\n    using value   = float; // std::complex<double>;\n    using matrix  = ublas::matrix<value,layout>;\n    using vector  = ublas::vector<value>;\n    using tensor2 = ublas::tensor_static_rank<value,2>;\n    using tensor3 = ublas::tensor_static_rank<value,3>;\n    using tensor4 = ublas::tensor_static_rank<value,4>;\n    using shape2  = typename tensor2::extents_type;\n    using shape3  = typename tensor3::extents_type;\n    using shape4  = typename tensor4::extents_type;\n\n    constexpr auto ones = ublas::ones_static_rank<value,layout>{};\n\n    // Tensor-Vector-Multiplications - Including Transposition\n    // dynamic_extents with static rank\n    try {\n\n        auto n = shape3{3,4,2};\n        tensor3 A = 2*ones(n);\n        auto q = 0U; // contraction mode\n\n        // C1(j,k) = T2(j,k) + A(i,j,k)*T1(i);\n        q = 1U;\n        tensor2 C1 = matrix(n[1],n[2],2) + ublas::prod(A,vector(n[q-1],1),q);\n\n        // C2(i,k) = A(i,j,k)*T1(j) + 4;\n        q = 2U;\n        tensor2 C2 = ublas::prod(A,vector(n[q-1],1),q) + 4;\n\n        // C3() = A(i,j,k)*T1(i)*T2(j)*T2(k);  \n        tensor2 C3 = ublas::prod(ublas::prod(ublas::prod(A,vector(n[0],1),1),vector(n[1],1),1),vector(n[2],1),1);\n\n\n        // formatted output\n        std::cout << \"% --------------------------- \" << std::endl;\n        std::cout << \"% --------------------------- \" << std::endl << std::endl;\n        std::cout << \"% C1(j,k) = T2(j,k) + A(i,j,k)*T1(i);\" << std::endl << std::endl;\n        std::cout << \"C1=\" << C1 << \";\" << std::endl << std::endl;\n\n        // formatted output\n        std::cout << \"% --------------------------- \" << std::endl;\n        std::cout << \"% --------------------------- \" << std::endl << std::endl;\n        std::cout << \"% C2(i,k) = A(i,j,k)*T1(j) + 4;\" << std::endl << std::endl;\n        std::cout << \"C2=\" << C2 << \";\" << std::endl << std::endl;\n\n        // formatted output\n        std::cout << \"% --------------------------- \" << std::endl;\n        std::cout << \"% --------------------------- \" << std::endl << std::endl;\n        std::cout << \"% C3() = A(i,j,k)*T1(i)*T2(j)*T2(k);\" << std::endl << std::endl;\n        std::cout << \"C3()=\" << C3(0) << \";\" << std::endl << std::endl;\n\n    } catch (const std::exception& e) {\n      std::cerr << \"Cought exception \" << e.what();\n      std::cerr << \"in the main function of multiply-tensor-product-function.\" << std::endl;\n    }\n\n    // Tensor-Matrix-Multiplications - Including Transposition\n    // dynamic_extents with static rank\n    try {\n\n        auto n = shape3{3,4,2};\n        tensor3 A = 2*ones(n);\n        auto m = 5U;\n        auto q = 0U; // contraction mode\n\n        // C1(l,j,k) = T2(l,j,k) + A(i,j,k)*T1(l,i);\n        q = 1U;\n        tensor3 C1 = 2*ones(m,n[1],n[2]) + ublas::prod(A,matrix(m,n[q-1],1),q);\n\n        // C2(i,l,k) = A(i,j,k)*T1(l,j) + 4;\n        q = 2U;\n        tensor3 C2 = ublas::prod(A,matrix(m,n[q-1],1),q) + 4 ;\n\n        // C3(i,l1,l2) = A(i,j,k)*T1(l1,j)*T2(l2,k);\n        q = 3U;\n        tensor3 C3 = ublas::prod(ublas::prod(A,matrix(m+1,n[q-2],1),q-1),matrix(m+2,n[q-1],1),q) ;\n\n        // C4(i,l1,l2) = A(i,j,k)*T2(l2,k)*T1(l1,j);\n        tensor3 C4 = ublas::prod(ublas::prod(A,matrix(m+2,n[q-1],1),q),matrix(m+1,n[q-2],1),q-1) ;\n\n        // formatted output\n        std::cout << \"% --------------------------- \" << std::endl;\n        std::cout << \"% --------------------------- \" << std::endl << std::endl;\n        std::cout << \"% C1(l,j,k) = T2(l,j,k) + A(i,j,k)*T1(l,i);\" << std::endl << std::endl;\n        std::cout << \"C1=\" << C1 << \";\" << std::endl << std::endl;\n\n        // formatted output\n        std::cout << \"% --------------------------- \" << std::endl;\n        std::cout << \"% --------------------------- \" << std::endl << std::endl;\n        std::cout << \"% C2(i,l,k) = A(i,j,k)*T1(l,j) + 4;\" << std::endl << std::endl;\n        std::cout << \"C2=\" << C2 << \";\" << std::endl << std::endl;\n\n        // formatted output\n        std::cout << \"% --------------------------- \" << std::endl;\n        std::cout << \"% --------------------------- \" << std::endl << std::endl;\n        std::cout << \"% C3(i,l1,l2) = A(i,j,k)*T1(l1,j)*T2(l2,k);\" << std::endl << std::endl;\n        std::cout << \"C3=\" << C3 << \";\" << std::endl << std::endl;\n\n        // formatted output\n        std::cout << \"% --------------------------- \" << std::endl;\n        std::cout << \"% --------------------------- \" << std::endl << std::endl;\n        std::cout << \"% C4(i,l1,l2) = A(i,j,k)*T2(l2,k)*T1(l1,j);\" << std::endl << std::endl;\n        std::cout << \"C4=\" << C4 << \";\" << std::endl << std::endl;\n        //std::cout << \"% C3 and C4 should have the same values, true? \" << std::boolalpha << (C3 == C4) << \"!\" << std::endl;\n\n    } catch (const std::exception& e) {\n      std::cerr << \"Cought exception \" << e.what();\n      std::cerr << \"in the main function of multiply-tensor-product-function.\" << std::endl;\n    }\n\n    // Tensor-Tensor-Multiplications Including Transposition\n    // dynamic_extents with static rank\n    try {\n\n        using perm_t = std::array<std::size_t,2>;\n\n        auto na = shape3{3,4,5};\n        auto nb = shape4{4,6,3,2};\n        auto nc = shape2{5,5};\n        tensor3 A = 2*ones(na);\n        tensor4 B = 3*ones(nb);\n        tensor2 C = 2*ones(nc);\n\n        // C1(j,l) = T(j,l) + A(i,j,k)*A(i,j,l) + 5;\n        // Right now there exist no tensor other than dynamic_extents with \n        // dynamic rank so every tensor times tensor operator automatically\n        // to dynamic tensor\n        auto C1 = C + ublas::prod(A,A,perm_t{1,2}) + 5;\n        std::cout << \"% --------------------------- \" << std::endl;\n        std::cout << \"% --------------------------- \" << std::endl << std::endl;\n        std::cout << \"% C1(k,l) = T(k,l) + A(i,j,k)*A(i,j,l) + 5;\" << std::endl << std::endl;\n        std::cout << \"C1=\" << tensor2(C1) << \";\" << std::endl << std::endl;\n\n\n        // C2(k,l,m) = T(k,l,m) + A(i,j,k)*B(j,l,i,m) + 5;\n        // Similar Problem as above\n        tensor3 C2 = 2*ones(na[2],nb[1],nb[3]) + ublas::prod(A,B,perm_t{1,2},perm_t{3,1}) + 5;\n        std::cout << \"% --------------------------- \" << std::endl;\n        std::cout << \"% --------------------------- \" << std::endl << std::endl;\n        std::cout << \"%  C2(k,l,m) = T(k,l,m) + A(i,j,k)*B(j,l,i,m) + 5;\" << std::endl << std::endl;\n        std::cout << \"C2=\" << C2 << \";\" << std::endl << std::endl;\n\n         // C3(k,l,m) = T(k,l,m) + A(i,j,k)*trans(B(j,l,i,m),{2,3,1,4})+ 5;\n         // Similar Problem as above\n         tensor3 C3 = 2*ones(na[2],nb[1],nb[3]) + ublas::prod(A,trans(B,{2,3,1,4}),perm_t{1,2}) + 5;\n         std::cout << \"% --------------------------- \" << std::endl;\n         std::cout << \"% --------------------------- \" << std::endl << std::endl;\n         std::cout << \"%  C3(k,l,m) = T(k,l,m) + A(i,j,k)*trans(B(j,l,i,m),{2,3,1,4})+ 5;\" << std::endl << std::endl;\n         std::cout << \"C3=\" << C3 << \";\" << std::endl << std::endl;\n\n    } catch (const std::exception& e) {\n      std::cerr << \"Cought exception \" << e.what();\n      std::cerr << \"in the multiply_tensors_with_static_order function of multiply-tensor-product-function.\" << std::endl;\n      throw;\n    }\n}\n\nint main()\n{\n  try {\n    multiply_tensors_with_dynamic_order();\n    multiply_tensors_with_static_order();\n  } catch (const std::exception& e) {\n    std::cerr << \"Cought exception \" << e.what();\n    std::cerr << \"in the main function of multiply-tensor-product-function.\" << std::endl;\n  }\n}\n\n\n", "meta": {"hexsha": "bd2adb34af70a443a52f5f1fc32579da306f4b7b", "size": 15747, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/tensor/multiply_tensors_product_function.cpp", "max_stars_repo_name": "samd2/ublas", "max_stars_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 96.0, "max_stars_repo_stars_event_min_datetime": "2015-01-23T10:15:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T18:31:02.000Z", "max_issues_repo_path": "examples/tensor/multiply_tensors_product_function.cpp", "max_issues_repo_name": "samd2/ublas", "max_issues_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 105.0, "max_issues_repo_issues_event_min_datetime": "2015-01-14T09:01:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-05T06:10:39.000Z", "max_forks_repo_path": "examples/tensor/multiply_tensors_product_function.cpp", "max_forks_repo_name": "samd2/ublas", "max_forks_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 157.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T13:35:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T11:12:27.000Z", "avg_line_length": 42.4447439353, "max_line_length": 125, "alphanum_fraction": 0.4515145742, "num_tokens": 5102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533051062237, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.711912963739223}}
{"text": "#include <iostream>\n#include <Eigen/Eigen>\n\nint main() {\n    // Create Random Matrix\n    std::cout << \"Initialize Matrices with random values\" << std::endl;\n    Eigen::MatrixXd matrix = Eigen::MatrixXd::Random(3,3);      // Declare matrix and initialize with random values.\n    std::cout << matrix << std::endl;\n    // Matrix Transpose\n    std::cout << \"Matrix transpose :\" << std::endl;\n    Eigen::MatrixXd matrix_transpose = matrix.transpose();\n    std::cout << matrix_transpose << std::endl;\n    // Matrix Inverse\n    std::cout << \"Matrix inverse :\" << std::endl;\n    Eigen::MatrixXd matrix_inverse = matrix.inverse();\n    std::cout << matrix_inverse << std::endl;\n}\n\n", "meta": {"hexsha": "c92d5bdd7bc1021c211a40f3aa2895e727a202f6", "size": 671, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example-04/example_four.cpp", "max_stars_repo_name": "JuliusDiestra/eigen-examples", "max_stars_repo_head_hexsha": "6b43b9390058d1ae747e3cb3ae94db1751976fe8", "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": "example-04/example_four.cpp", "max_issues_repo_name": "JuliusDiestra/eigen-examples", "max_issues_repo_head_hexsha": "6b43b9390058d1ae747e3cb3ae94db1751976fe8", "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": "example-04/example_four.cpp", "max_forks_repo_name": "JuliusDiestra/eigen-examples", "max_forks_repo_head_hexsha": "6b43b9390058d1ae747e3cb3ae94db1751976fe8", "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.3157894737, "max_line_length": 116, "alphanum_fraction": 0.6453055142, "num_tokens": 162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533069832973, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.7119129601542538}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n\nusing namespace Eigen;\nusing namespace std;\nint main() {\n  Vector3d v(1, 2, 3);\n  Vector3d w(0, 1, 2);\n\n  cout << \"Dot product: \" << v.dot(w) << endl;\n  double dp = v.adjoint() * w; // automatic conversion of the inner product to a scalar\n  cout << \"Dot product via a matrix product: \" << dp << endl;\n  cout << \"Cross product:\\n\" << v.cross(w) << endl;\n}\n", "meta": {"hexsha": "83dff8ac884cd7bd8e9cb8301169943978d900af", "size": 399, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/Eigen-3.3/doc/examples/tut_arithmetic_dot_cross.cpp", "max_stars_repo_name": "chen0510566/CarND-Path-Planning-Project", "max_stars_repo_head_hexsha": "4652e5c459980252e4ab72a0fd687341f3245466", "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/Eigen-3.3/doc/examples/tut_arithmetic_dot_cross.cpp", "max_issues_repo_name": "chen0510566/CarND-Path-Planning-Project", "max_issues_repo_head_hexsha": "4652e5c459980252e4ab72a0fd687341f3245466", "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": "include/Eigen-3.3/doc/examples/tut_arithmetic_dot_cross.cpp", "max_forks_repo_name": "chen0510566/CarND-Path-Planning-Project", "max_forks_repo_head_hexsha": "4652e5c459980252e4ab72a0fd687341f3245466", "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.6, "max_line_length": 87, "alphanum_fraction": 0.6240601504, "num_tokens": 123, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.8128673269042767, "lm_q1q2_score": 0.7118986361090685}}
{"text": "//\n// Created by rdelfin on 4/20/16.\n//\n\n#pragma once\n\n#include <Eigen/Dense>\n\nclass Derivative {\npublic:\n    Derivative(int x, int y);\n\n    Eigen::MatrixXd dx(const Eigen::MatrixXd&, double deltaX);\n    Eigen::MatrixXd dy(const Eigen::MatrixXd&, double deltaY);\n\n    ~Derivative();\nprivate:\n\n    Eigen::MatrixXd dxLT;\n    Eigen::MatrixXd dyLT;\n};\n", "meta": {"hexsha": "920ece8fb18b2764566f818a6f951ac980bafb1e", "size": 348, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/heat-equation-calc/include/heat-equation-calc/Derivative.hpp", "max_stars_repo_name": "rdelfin/heat-simulation", "max_stars_repo_head_hexsha": "0f178c0934c88ee6071afbe42efcb7dc49fd4461", "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": "src/heat-equation-calc/include/heat-equation-calc/Derivative.hpp", "max_issues_repo_name": "rdelfin/heat-simulation", "max_issues_repo_head_hexsha": "0f178c0934c88ee6071afbe42efcb7dc49fd4461", "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": "src/heat-equation-calc/include/heat-equation-calc/Derivative.hpp", "max_forks_repo_name": "rdelfin/heat-simulation", "max_forks_repo_head_hexsha": "0f178c0934c88ee6071afbe42efcb7dc49fd4461", "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": 15.8181818182, "max_line_length": 62, "alphanum_fraction": 0.6609195402, "num_tokens": 88, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.8128673178375735, "lm_q1q2_score": 0.7118986281685677}}
{"text": "#include \"internal.h\"\n#include <Eigen/LU>\n#include <Eigen/SVD>\n#include <Eigen/QR>\n\n\ndouble cnInvert(const CnMat *srcarr, CnMat *dstarr, enum cnInvertMethod method) {\n\tauto src = CONVERT_TO_EIGEN_PTR(srcarr);\n\tauto dst = CONVERT_TO_EIGEN_PTR(dstarr);\n\n\tassert(srcarr->rows == dstarr->cols);\n\tassert(srcarr->cols == dstarr->rows);\n\n\tEIGEN_RUNTIME_SET_IS_MALLOC_ALLOWED(false);\n\tif (method == CN_INVERT_METHOD_LU) {\n\t\tassert(srcarr->rows == srcarr->cols);\n\t\tdst.noalias() = src.inverse();\n\t} else {\n\t\tdst.noalias() = src.completeOrthogonalDecomposition().pseudoInverse();\n\t}\n\treturn 0;\n}\n\nextern \"C\" int cnSolve(const CnMat *_Aarr, const CnMat *_Barr, CnMat *_xarr, enum cnInvertMethod method) {\n\tauto Aarr = CONVERT_TO_EIGEN_PTR(_Aarr);\n\tauto Barr = CONVERT_TO_EIGEN_PTR(_Barr);\n\tauto xarr = CONVERT_TO_EIGEN_PTR(_xarr);\n\n\tif (method == CN_INVERT_METHOD_LU) {\n\t\txarr.noalias() = Aarr.partialPivLu().solve(Barr);\n\t} else if (method == CN_INVERT_METHOD_QR) {\n\t\txarr.noalias() = Aarr.colPivHouseholderQr().solve(Barr);\n\t} else {\n\t\tEIGEN_RUNTIME_SET_IS_MALLOC_ALLOWED(true);\n\t\tauto cnd = Aarr.jacobiSvd(\n\t\t\tEigen::ComputeFullU |\n\t\t\tEigen::ComputeFullV); \n\t\tEIGEN_RUNTIME_SET_IS_MALLOC_ALLOWED(false);\n\t\txarr.noalias() = cnd.solve(Barr);\n\t}\n\treturn 0;\n}\n\nextern \"C\" void cnSVD(CnMat *aarr, CnMat *warr, CnMat *uarr, CnMat *varr, enum cnSVDFlags flags) {\n\tauto aarrEigen = CONVERT_TO_EIGEN_PTR(aarr);\n\tauto warrEigen = CONVERT_TO_EIGEN_PTR(warr);\n\n\tint options = 0;\n\tif (uarr)\n\t\toptions |= Eigen::ComputeFullU;\n\tif (varr)\n\t\toptions |= Eigen::ComputeFullV;\n\tEIGEN_RUNTIME_SET_IS_MALLOC_ALLOWED(true);\n\tauto cnd = aarrEigen.jacobiSvd(options);\n\tEIGEN_RUNTIME_SET_IS_MALLOC_ALLOWED(false);\n\n\tif (warrEigen.cols() == 1) {\n\t\twarrEigen.noalias() = cnd.singularValues();\n\t} else if (warrEigen.rows() == 1) {\n\t\twarrEigen.noalias() = cnd.singularValues().transpose();\n\t} else {\n\t\twarrEigen.diagonal().noalias() = cnd.singularValues();\n\t}\n\n\tif (uarr) {\n\t\tauto uarrEigen = CONVERT_TO_EIGEN_PTR(uarr);\n\t\tif (flags & CN_SVD_U_T)\n\t\t\tuarrEigen.noalias() = cnd.matrixU().transpose();\n\t\telse\n\t\t\tuarrEigen.noalias() = cnd.matrixU();\n\t}\n\n\tif (varr) {\n\t\tauto varrEigen = CONVERT_TO_EIGEN_PTR(varr);\n\t\tif (flags & CN_SVD_V_T)\n\t\t\tvarrEigen.noalias() = cnd.matrixV().transpose();\n\t\telse\n\t\t\tvarrEigen.noalias() = cnd.matrixV();\n\t}\n}\n", "meta": {"hexsha": "895acd2eabf19161d041f24728a8cb207fc99416", "size": 2302, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/eigen/svd.cpp", "max_stars_repo_name": "cntools/cnmatrix", "max_stars_repo_head_hexsha": "5936c62511305227fbd59b2d5a43aaf89ec3a0b6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-26T12:48:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T12:48:16.000Z", "max_issues_repo_path": "src/eigen/svd.cpp", "max_issues_repo_name": "cntools/cnmatrix", "max_issues_repo_head_hexsha": "5936c62511305227fbd59b2d5a43aaf89ec3a0b6", "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/eigen/svd.cpp", "max_forks_repo_name": "cntools/cnmatrix", "max_forks_repo_head_hexsha": "5936c62511305227fbd59b2d5a43aaf89ec3a0b6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2022-02-06T23:10:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T12:48:20.000Z", "avg_line_length": 28.4197530864, "max_line_length": 106, "alphanum_fraction": 0.7124239791, "num_tokens": 740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.7981867777396212, "lm_q1q2_score": 0.711831784710704}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n\nusing namespace std;\nusing namespace Eigen;\nint main()\n{\n  MatrixXf mat(2,4);\n  mat << 1, 2, 6, 9,\n         3, 1, 7, 2;\n  \n  MatrixXf::Index   maxIndex;\n  float maxNorm = mat.colwise().sum().maxCoeff(&maxIndex);\n  \n  std::cout << \"Maximum sum at position \" << maxIndex << std::endl;\n\n  std::cout << \"The corresponding vector is: \" << std::endl;\n  std::cout << mat.col( maxIndex ) << std::endl;\n  std::cout << \"And its sum is is: \" << maxNorm << std::endl;\n}\n", "meta": {"hexsha": "049c747b08525ad25925474b3687bcf8027a373c", "size": 502, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Eigen-3.3/doc/examples/Tutorial_ReductionsVisitorsBroadcasting_maxnorm.cpp", "max_stars_repo_name": "shareq2005/CarND-MPC-Project", "max_stars_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3457.0, "max_stars_repo_stars_event_min_datetime": "2018-06-09T15:36:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-01T22:09:25.000Z", "max_issues_repo_path": "src/Eigen-3.3/doc/examples/Tutorial_ReductionsVisitorsBroadcasting_maxnorm.cpp", "max_issues_repo_name": "shareq2005/CarND-MPC-Project", "max_issues_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 851.0, "max_issues_repo_issues_event_min_datetime": "2017-11-27T15:09:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:26:38.000Z", "max_forks_repo_path": "src/Eigen-3.3/doc/examples/Tutorial_ReductionsVisitorsBroadcasting_maxnorm.cpp", "max_forks_repo_name": "shareq2005/CarND-MPC-Project", "max_forks_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1380.0, "max_forks_repo_forks_event_min_datetime": "2017-06-12T23:58:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:52:48.000Z", "avg_line_length": 23.9047619048, "max_line_length": 67, "alphanum_fraction": 0.6035856574, "num_tokens": 163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.8080672227971211, "lm_q1q2_score": 0.7117432435924368}}
{"text": "/**\n * @file\n * @brief NPDE homework TestQuadratureRules\n * @author Erick Schulz, Liaowang Huang (refactoring)\n * @date 08/03/2019, 22/02/2020 (refactoring)\n * @copyright Developed at ETH Zurich\n */\n\n#include \"testquadraturerules.h\"\n\n#include <lf/base/base.h>\n#include <lf/quad/quad.h>\n\n#include <Eigen/Core>\n#include <cassert>\n#include <cmath>\n\nnamespace TestQuadratureRules {\n\ndouble factorial(int i) { return std::tgamma(i + 1); }\n\n/* SAM_LISTING_BEGIN_1 */\nbool testQuadOrderTria(const lf::quad::QuadRule &quad_rule,\n                       unsigned int order) {\n  bool order_isExact = true;  // return variable\n#if SOLUTION\n  double my_epsilon = 1e-12;\n  // Retrieve the passed quadrature rule's reference element\n  const lf::base::RefEl ref_element = quad_rule.RefEl();\n  // Check that the passed reference element is triangular\n  assert(ref_element == lf::base::RefElType::kTria);\n  // A quadrature rule involves quadrature nodes and weights defined so that\n  // the weighted sum of the value of a function at these points approximates\n  // the integral of that function.\n  const Eigen::VectorXd weights = quad_rule.Weights();\n  const Eigen::MatrixXd points = quad_rule.Points();  // (x,y) points\n  const Eigen::VectorXd x_coords = points.row(0);\n  const Eigen::VectorXd y_coords = points.row(1);\n  // A quadrature rule over a two dimensional domain is of order k if it can\n  // integrate exactly all bivariate polynomials of order k-1. The collection of\n  // such polynomials is spanned by the set of homogeneous polynomials of order\n  // strictly less than k, i.e. by the polynomials of the form\n  /* p_IJ(x,y) = (x^I)(y^J), I+J < k: */\n  auto eval_p_IJ = [&x_coords, &y_coords](int I, int J) -> Eigen::VectorXd {\n    return x_coords.array().pow(I) * y_coords.array().pow(J);\n  }; /* evaluates p_IJ at all points (x,y) as defined by quad_rule */\n\n  /* Compare analytical value and quadrature sum for all p_IJ, I+J < k */\n  double exact_integral;  // analytical value of the integral\n  double quad_rule_sum;   // weighted sum used for approximating the integral\n  for (int I = 0; I < order; I++) {\n    for (int J = 0; J < order - I; J++) {\n      exact_integral = factorial(I) * factorial(J) / factorial(I + J + 2);\n      quad_rule_sum = eval_p_IJ(I, J).dot(weights);\n\n      // Check if the difference bewteen the results is within tolerance\n      order_isExact = fabs(exact_integral - quad_rule_sum) <=\n                      fabs(exact_integral) * my_epsilon;\n      if (!order_isExact) {\n        return order_isExact;\n      }\n    }\n  }\n#else\n  //====================\n  // Your code goes here\n  //====================\n#endif\n  return order_isExact;\n}\n/* SAM_LISTING_END_1 */\n\n/* SAM_LISTING_BEGIN_2 */\nbool testQuadOrderQuad(const lf::quad::QuadRule &quad_rule,\n                       unsigned int order) {\n  bool order_isExact = true;  // return variable\n\n#if SOLUTION\n  double my_epsilon = 1e-12;\n  // Retrieve the passed quadrature rule's reference element\n  const lf::base::RefEl ref_element = quad_rule.RefEl();\n  // Check that the passed reference element is triangular\n  assert(ref_element == lf::base::RefElType::kQuad);\n  // A quadrature rule consists of quadrature nodes and weights defined so that\n  // the weighted sum of the value of a function at these points approximates\n  // the integral of that function.\n  const Eigen::VectorXd weights = quad_rule.Weights();\n  const Eigen::MatrixXd points = quad_rule.Points();  // (x,y) points\n  const Eigen::VectorXd x_coords = points.row(0);\n  const Eigen::VectorXd y_coords = points.row(1);\n  // A quadrature rule over a two dimensional domain is of order k if it can\n  // integrate exactly all bivariate polynomials of order k-1. The collection of\n  // such polynomials is spanned by the set of homogeneous polynomials of order\n  // strictly less than k, i.e. by the polynomials of the form\n  /* p_IJ(x,y) = (1-x)^I(y^J), I,J < k: */\n  auto eval_p_IJ = [&x_coords, &y_coords](int I, int J) -> Eigen::VectorXd {\n    return x_coords.array().pow(I) * y_coords.array().pow(J);\n  }; /* evaluates p_IJ at all points (x,y) as defined by quad_rule */\n\n  /* Compare the analytical value and the quadrature sum for all p_IJ, I+J < k\n   */\n  double exact_integral;  // analytical value of the integral\n  double quad_rule_sum;   // weighted sum used for approximating the integral\n  for (int I = 0; I < order; I++) {\n    for (int J = 0; J < order; J++) {\n      exact_integral = 1.0 / ((I + 1.0) * (J + 1.0));\n      quad_rule_sum = eval_p_IJ(I, J).dot(weights);\n\n      // Check if the difference bewteen the results is within tolerance\n      order_isExact = fabs(exact_integral - quad_rule_sum) <=\n                      fabs(exact_integral) * my_epsilon;\n      if (!order_isExact) {\n        return order_isExact;\n      }\n    }\n  }\n#else\n  //====================\n  // Your code goes here\n  //====================\n#endif\n  return order_isExact;\n}\n/* SAM_LISTING_END_2 */\n\n/* SAM_LISTING_BEGIN_3 */\nunsigned int calcQuadOrder(const lf::quad::QuadRule &quad_rule) {\n  unsigned int maximal_order = quad_rule.Order();\n\n#if SOLUTION\n  // Retrieve the passed quadrature rule's reference element\n  const lf::base::RefEl ref_element = quad_rule.RefEl();\n\n  if (ref_element == lf::base::RefElType::kTria) {\n    assert(testQuadOrderTria(quad_rule, maximal_order));\n    while (testQuadOrderTria(quad_rule, maximal_order + 1)) {\n      maximal_order++;\n    }\n  }\n\n  if (ref_element == lf::base::RefElType::kQuad) {\n    assert(testQuadOrderQuad(quad_rule, maximal_order));\n    while (testQuadOrderQuad(quad_rule, maximal_order + 1)) {\n      maximal_order++;\n    }\n  }\n#else\n  //====================\n  // Your code goes here\n  //====================\n#endif\n  return maximal_order;\n}\n/* SAM_LISTING_END_3 */\n\n}  // namespace TestQuadratureRules\n", "meta": {"hexsha": "16cce398f35a5a00e7f376a5940150140001d5d8", "size": 5778, "ext": "cc", "lang": "C++", "max_stars_repo_path": "developers/TestQuadratureRules/mastersolution/testquadraturerules.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": "developers/TestQuadratureRules/mastersolution/testquadraturerules.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": "developers/TestQuadratureRules/mastersolution/testquadraturerules.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": 36.8025477707, "max_line_length": 80, "alphanum_fraction": 0.6668397369, "num_tokens": 1536, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942041005327, "lm_q2_score": 0.787931188173138, "lm_q1q2_score": 0.7117336755068417}}
{"text": "\n#include <stdio.h>\n#include <iostream>\n\n#ifdef NDEBUG\n#define EIGEN_NO_DEBUG\n#endif\n\n#include \"main.h\"\n#include <unsupported/Eigen/LevenbergMarquardt>\n#include <unsupported/Eigen/SparseExtra>\n\n#include <Eigen/Eigen>\n#include \"unsupported/Eigen/src/SparseExtra/BlockSparseQR.h\"\n#include \"unsupported/Eigen/src/SparseExtra/BlockDiagonalSparseQR.h\"\n\n// This disables some useless Warnings on MSVC.\n// It is intended to be done for this test only.\n#include <Eigen/src/Core/util/DisableStupidWarnings.h>\n\nconst size_t NUM_SAMPLE_POINTS =\n#ifdef NDEBUG\n500000;\n#else\n50000;\n#endif\n\ntemplate <typename _Scalar>\nstruct EllipseFitting : SparseFunctor<_Scalar, int>\n{\n    // Class data: 2xN matrix with each column a 2D point\n    Matrix2Xd ellipsePoints;\n\n    // Number of parameters in the model, to which will be added\n    // one latent variable per point.\n    static const int nParamsModel = 5;\n\n    // Constructor initializes points, and tells the base class how many parameters there are in total\n    EllipseFitting(const Matrix2Xd& points ):\n      SparseFunctor<_Scalar, int>(nParamsModel + points.cols(), points.cols()*2),\n      ellipsePoints(points) \n    {\n    }\n\n    // Functor functions\n    int operator()(const InputType& uv, ValueType& fvec) const {\n      // Ellipse parameters are the last 5 entries\n      auto params = uv.tail(nParamsModel);\n      double a = params[0];\n      double b = params[1];\n      double x0 = params[2];\n      double y0 = params[3];\n      double r = params[4];\n\n      // Correspondences (t values) are the first N\n      for (int i = 0; i < ellipsePoints.cols(); i++) {\n        double t = uv(i);\n        double x = a*cos(t)*cos(r) - b*sin(t)*sin(r) + x0;\n        double y = a*cos(t)*sin(r) + b*sin(t)*cos(r) + y0;\n        fvec(2 * i + 0) = ellipsePoints(0, i) - x;\n        fvec(2 * i + 1) = ellipsePoints(1, i) - y;\n      }\n\n      return 0;\n    }\n\n    // Functor jacobian\n    int df(const InputType& uv, JacobianType& fjac) {\n        // X_i - (a*cos(t_i) + x0)\n        // Y_i - (b*sin(t_i) + y0)\n        int npoints = ellipsePoints.cols();\n        auto params = uv.tail(nParamsModel);\n        double a = params[0];\n        double b = params[1];\n        double r = params[4];\n\n        TripletArray<JacobianType::Scalar> triplets(npoints * 2 * 5); // npoints * rows_per_point * nonzeros_per_row\n        for(int i=0; i<npoints; i++) {\n            double t = uv(i);\n            triplets.add(2 * i, i,             +a*cos(r)*sin(t) + b*sin(r)*cos(t));\n            triplets.add(2 * i, npoints + 0,   -cos(t)*cos(r));\n            triplets.add(2 * i, npoints + 1,   +sin(t)*sin(r));\n            triplets.add(2 * i, npoints + 2,   -1);\n            triplets.add(2 * i, npoints + 4,   +a*cos(t)*sin(r) + b*sin(t)*cos(r));\n\n            triplets.add(2 * i + 1, i,             +a*sin(r)*sin(t) - b*cos(r)*cos(t));\n            triplets.add(2 * i + 1, npoints + 0,   -cos(t)*sin(r));\n            triplets.add(2 * i + 1, npoints + 1,   -sin(t)*cos(r));\n            triplets.add(2 * i + 1, npoints + 3,   -1);\n            triplets.add(2 * i + 1, npoints + 4,   -a*cos(t)*cos(r) + b*sin(t)*sin(r));\n        }\n\n        fjac.setFromTriplets(triplets.begin(), triplets.end());\n        return 0;\n    }\n\n    // For generic Jacobian, one might use this Dense QR solver.\n    typedef SparseQR<JacobianType, COLAMDOrdering<int> > GeneralQRSolver;\n\n    // But for optimal performance, declare QRSolver that understands the sparsity structure.\n    // Here it's block-diagonal LHS with dense RHS\n    //\n    // J1 = [J11   0   0 ... 0\n    //         0 J12   0 ... 0\n    //                   ...\n    //         0   0   0 ... J1N];\n    // And \n    // J = [J1 J2];\n\n    // QR for J1 subblocks is 2x1\n    typedef ColPivHouseholderQR<Matrix<Scalar, 2, 1> > DenseQRSolver2x1;\n\n    // QR for J1 is block diagonal\n    typedef BlockDiagonalSparseQR<JacobianType, DenseQRSolver2x1> LeftSuperBlockSolver;\n    \n    // QR for J1'J2 is general dense (faster than general sparse by about 1.5x for n=500K)\n    typedef ColPivHouseholderQR<Matrix<Scalar, Dynamic, Dynamic> > RightSuperBlockSolver;\n\n    // QR for J is concatenation of the above.\n    typedef BlockSparseQR<JacobianType, LeftSuperBlockSolver, RightSuperBlockSolver> SchurlikeQRSolver;  \n    \n    typedef SchurlikeQRSolver QRSolver;\n\n    // And tell the algorithm how to set the QR parameters.\n    void initQRSolver(GeneralQRSolver &qr) {}\n\n    void initQRSolver(SchurlikeQRSolver &qr) {\n        // set block size\n        qr.getLeftSolver().setSparseBlockParams(2, 1);\n        qr.setBlockParams(ellipsePoints.cols());\n    }\n};\n\n\nvoid ellipseFitting()\n{\n\n  //eigen_assert(false);\n\n  // _CrtSetDbgFlag(_CRTDBG_CHECK_ALWAYS_DF);\n\n  if (1) {\n    // Check fast QR\n    Matrix<double, 5, 2> A;\n    A << 12, 3, -5, 17, -7, 132, 1.0, 1.1, -3.1, 4.7;\n    ColPivHouseholderQR<Matrix<double, 5, 2> > qr(A);\n\n    MatrixXd R = qr.matrixR().template triangularView<Upper>();\n\n    Matrix<double, 5, 5> Q = qr.matrixQ();\n    std::cout << \"A=\\n\" << A << std::endl;\n    std::cout << \"AP=\\n\" << A * qr.colsPermutation() << std::endl;\n    //std::cout << \"QR=\\n\" << qr.matrixQ() * qr.matrixR().template triangularView<Upper>() << std::endl;\n    std::cout << \"Q=\\n\" << Q << std::endl;\n    std::cout << \"R=\\n\" << R << std::endl;\n    std::cout << \"QR=\\n\" << Q * R << std::endl;\n    VERIFY_IS_APPROX(Q * R, A * qr.colsPermutation());\n  }\n\n\n    // ELLIPSE PARAMETERS\n    double a, b, x0, y0, r;\n    a = 7.5;\n    b = 2;\n    x0 = 17.;\n    y0 = 23.;\n    r = 0.23;\n\n    std::cout << \"GROUND TRUTH   \" << \" \";\n    std::cout << \"a=\" << a << \"\\t\";\n    std::cout << \"b=\" << b << \"\\t\";\n    std::cout << \"x0=\" << x0 << \"\\t\";\n    std::cout << \"y0=\" << y0 << \"\\t\";\n    std::cout << \"r=\" << r*180./EIGEN_PI << \"\\t\";\n    std::cout << std::endl;\n\n    // CREATE DATA SAMPLES\n    \n    int nDataPoints = NUM_SAMPLE_POINTS;\n    Matrix2Xd ellipsePoints;\n    ellipsePoints.resize(2, nDataPoints);\n    double incr = 1.3*EIGEN_PI / double(nDataPoints);\n    for(int i=0; i<nDataPoints; i++) {\n        double t = double(i)*incr;\n        ellipsePoints(0, i) = x0 + a*cos(t)*cos(r) - b*sin(t)*sin(r);\n        ellipsePoints(1, i) = y0 + a*cos(t)*sin(r) + b*sin(t)*cos(r);\n    }\n\n    // INITIAL PARAMS\n    EllipseFitting<double>::InputType params;\n    params.resize(EllipseFitting<double>::nParamsModel+nDataPoints);\n    double minX, minY, maxX, maxY;\n    minX = maxX = ellipsePoints(0,0);\n    minY = maxY = ellipsePoints(1,0);\n    for(int i=0; i<ellipsePoints.cols(); i++) {\n        minX = (std::min)(minX, ellipsePoints(0,i));\n        maxX = (std::max)(maxX, ellipsePoints(0,i));\n        minY = (std::min)(minY, ellipsePoints(1,i));\n        maxY = (std::max)(maxY, ellipsePoints(1,i));\n    }\n    params(ellipsePoints.cols()) = 0.5*(maxX - minX);\n    params(ellipsePoints.cols()+1) = 0.5*(maxY - minY);\n    params(ellipsePoints.cols()+2) = 0.5*(maxX + minX);\n    params(ellipsePoints.cols()+3) = 0.5*(maxY + minY);\n    params(ellipsePoints.cols()+4) = 0;\n    for(int i=0; i<ellipsePoints.cols(); i++) {\n        params(i) = double(i)*incr;\n    }\n\n    std::cout << \"INITIALIZATION\" << \" \";\n    std::cout << \"a=\" << params(ellipsePoints.cols()) << \"\\t\";\n    std::cout << \"b=\" << params(ellipsePoints.cols() + 1) << \"\\t\";\n    std::cout << \"x0=\" << params(ellipsePoints.cols() + 2) << \"\\t\";\n    std::cout << \"y0=\" << params(ellipsePoints.cols() + 3) << \"\\t\";\n    std::cout << \"r=\" << params(ellipsePoints.cols() + 4)*180. / EIGEN_PI << \"\\t\";\n    std::cout << std::endl << std::endl;\n\n    typedef EllipseFitting<double> Functor;\n    Functor functor(ellipsePoints);\n    Eigen::LevenbergMarquardt< Functor > lm(functor);\n    lm.setVerbose(true);\n\n    Eigen::LevenbergMarquardtSpace::Status info = lm.minimize(params);\n\n    std::cout << \"END[\" << info << \"]\";\n    std::cout << \"a=\" << params(ellipsePoints.cols()) << \"\\t\";\n    std::cout << \"b=\" << params(ellipsePoints.cols()+1) << \"\\t\";\n    std::cout << \"x0=\" << params(ellipsePoints.cols()+2) << \"\\t\";\n    std::cout << \"y0=\" << params(ellipsePoints.cols()+3) << \"\\t\";\n    std::cout << \"r=\" << params(ellipsePoints.cols()+4)*180./EIGEN_PI << \"\\t\";\n    std::cout << std::endl << std::endl;\n\n    // check parameters ambiguity before test result\n    // a should be bigger than b\n    if( fabs(params(ellipsePoints.cols()+1)) > fabs(params(ellipsePoints.cols())) ) {\n       std::swap( params(ellipsePoints.cols()), params(ellipsePoints.cols()+1) );\n       params(ellipsePoints.cols()+4) -= 0.5*EIGEN_PI;\n    }\n    // a and b should be positive\n    if(params(ellipsePoints.cols())<0 ) {\n       params(ellipsePoints.cols()) *= -1.;\n       params(ellipsePoints.cols()+1) *= -1.;\n       params(ellipsePoints.cols()+4) += EIGEN_PI;\n    }\n    // fix rotation angle range\n    while( params(ellipsePoints.cols()+4) < 0 ) params(ellipsePoints.cols()+4) += 2.*EIGEN_PI;\n    while( params(ellipsePoints.cols()+4) > EIGEN_PI ) params(ellipsePoints.cols()+4) -= EIGEN_PI;\n\n\n    eigen_assert( fabs(a - params(ellipsePoints.cols())) < 0.00001 );\n    eigen_assert( fabs(b - params(ellipsePoints.cols()+1)) < 0.00001 );\n    eigen_assert( fabs(x0 - params(ellipsePoints.cols()+2)) < 0.00001 );\n    eigen_assert( fabs(y0 - params(ellipsePoints.cols()+3)) < 0.00001 );\n    eigen_assert( fabs(r - params(ellipsePoints.cols()+4)) < 0.00001 );\n\n\n\n}\n\n\nvoid test_ellipse_fitting()\n{\n    CALL_SUBTEST(ellipseFitting());\n}\n", "meta": {"hexsha": "c48ea079d474cef69f609f38fbaf5021d5abed92", "size": 9318, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "eigen_pr/unsupported/test/ellipse_fitting.cpp", "max_stars_repo_name": "pmkalshetti/parametric_sphere_fitting", "max_stars_repo_head_hexsha": "1d86a18a997ecbc6ab4234c9550db1cc6c707b42", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-10-26T07:50:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T00:41:14.000Z", "max_issues_repo_path": "eigen_pr/unsupported/test/ellipse_fitting.cpp", "max_issues_repo_name": "pmkalshetti/parametric_sphere_fitting", "max_issues_repo_head_hexsha": "1d86a18a997ecbc6ab4234c9550db1cc6c707b42", "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": "eigen_pr/unsupported/test/ellipse_fitting.cpp", "max_forks_repo_name": "pmkalshetti/parametric_sphere_fitting", "max_forks_repo_head_hexsha": "1d86a18a997ecbc6ab4234c9550db1cc6c707b42", "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.1622641509, "max_line_length": 116, "alphanum_fraction": 0.5896115046, "num_tokens": 2880, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436153333645, "lm_q2_score": 0.7799928900257126, "lm_q1q2_score": 0.711693712202654}}
{"text": "\r\n/*\r\n\tkstatboost\r\n\tVer. k09.01\r\n\t\r\n\tWritten by Koji Yamamoto\r\n\tCopyright (C) 2020-2021 Koji Yamamoto\r\n\tIn using this, please read the document which states terms of use.\r\n\t\r\n\tStatistical Computations using Boost\r\n\tPlus, Random Number from Distrbution using Boost \r\n\t\r\n*/\r\n\r\n\r\n/* ********** Preprocessor Directives ********** */\r\n\r\n#ifndef kstatboost_cpp_include_guard\r\n#define kstatboost_cpp_include_guard\r\n\r\n#include <vector>\r\n#include <functional>\r\n\r\n#include <k09/krand01.cpp> \r\n\r\n#include <boost/math/statistics/univariate_statistics.hpp>\r\n#include <boost/math/statistics/bivariate_statistics.hpp>\r\n#include <boost/math/distributions/beta.hpp>\r\n\r\n\r\n/* ********** Using Directives ********** */\r\n\r\n//using namespace std;\r\n\r\n\r\n/* ********** Type Declarations: enum, class, etc. ********** */\r\n\r\n\r\n/* ********** Function Declarations ********** */\r\n\r\ndouble unbiasedVarBoost( const std::vector <double> &); \r\ndouble corrBoost( const std::vector <double> &, const std::vector <double> &); \r\n\r\nstd::function <double(double)>\r\ngetBetaQ(\r\n\tdouble, double\r\n);\r\n\r\nvoid \r\ngetBetaRandomVec(\r\n\tstd::vector <double> &, RandomNumberEngine &, int, double, double\r\n);\r\n\r\n\r\n/* ********** Type Definitions: enum, class, etc. ********** */\r\n\r\n\r\n/* ********** Global Variables ********** */\r\n\r\n\r\n/* ********** Definitions of Static Member Variables ********** */\r\n\r\n\r\n/* ********** Function Definitions ********** */\r\n\r\n\r\ndouble unbiasedVarBoost( const std::vector <double> &vec0)\r\n{\r\n\r\n\t// sample_variance() returns unbiased variance in estimation from sample \r\n\tdouble sigma_sq = boost::math::statistics::sample_variance( vec0);\r\n\treturn sigma_sq;\r\n\r\n}\r\n\r\n\r\n// corrBoost()\u306b\u3064\u3044\u3066\u3001\u30b3\u30f3\u30d1\u30a4\u30eb\u6642\u306b\u8b66\u544a\u304c\u51fa\u3066\u304f\u308b\u306e\u3067\u3001\u3053\u308c\u3092\u6291\u5236\u3057\u3066\u304a\u304f\u3002\r\n// \u8b66\u544a\u306e\u8da3\u65e8\u306f\u578b\u5909\u63db\u306b\u3088\u3063\u3066\u7cbe\u5ea6\u304c\u843d\u3061\u308b\u53ef\u80fd\u6027\u3092\u6307\u6458\u3057\u305f\u3082\u306e\u3089\u3057\u3044\u3002\r\n// \u5b9f\u969b\u306b\u306f\u3001boost\\math\\statistics\\bivariate_statictics.hpp\u306e\r\n// correlation_coefficient_seq_impl( )\u306e\u5b9a\u7fa9\u3067\u3001\u6574\u6570\u3092\u6d6e\u52d5\u5c0f\u6570\u70b9\u306b\u30ad\u30e3\u30b9\u30c8\u3057\u3066\u3044\u306a\u3044\u304b\u3089\u3002\r\n// \u2192Github\u3067\u30d7\u30eb\u30ea\u30af\u3092\u6295\u3052\u305f\u3002\r\n\r\n#if defined(_MSC_VER) && _MSC_VER >= 1400 \r\n#pragma warning(push) \r\n#pragma warning(disable:4244) \r\n#endif \r\n\r\ndouble corrBoost( const std::vector <double> &xvec, const std::vector <double> &yvec)\r\n{\r\n\r\n\tdouble ret = boost::math::statistics::correlation_coefficient( xvec, yvec);\r\n\treturn ret;\r\n\r\n}\r\n\r\n#if defined(_MSC_VER) && _MSC_VER >= 1400 \r\n#pragma warning(pop) \r\n#endif \r\n\r\n\r\n// returns quatile function (inverse distribution function)\r\n// of targeted Beta dist. with specific mean and variance \r\nstd::function <double(double)> getBetaQ( double mean0, double var0)\r\n{\r\n\r\n\tusing boost::math::beta_distribution;\r\n\t\r\n\tdouble alpha = beta_distribution<>::find_alpha( mean0, var0);\r\n\tdouble beta = beta_distribution<>::find_beta( mean0, var0);\r\n\r\n\tbeta_distribution<> mybeta( alpha, beta);\r\n\r\n\tauto ret =\r\n\t\t[=]( double p) -> double \r\n\t\t{\r\n\t\t\treturn quantile( mybeta, p);\r\n\t\t};\r\n\t\r\n\treturn ret;\r\n\r\n}\r\n\r\n// returns vector of random numbers from targeted Beta distribution \r\nvoid\r\ngetBetaRandomVec(\r\n\tstd::vector <double> &ret,\r\n\tRandomNumberEngine &rne,\r\n\tint len,\r\n\tdouble mean0,\r\n\tdouble var0\r\n)\r\n{\r\n\r\n\tret.clear();\r\n\r\n\tauto qfunc = getBetaQ( mean0, var0);\r\n\t\r\n\tret = rne.getDistRandomVec( len, qfunc);\r\n\r\n}\r\n\r\n\r\n/* ********** Definitions of Member Functions ********** */\r\n\r\n\r\n\r\n\r\n#endif /* kstatboost_cpp_include_guard */\r\n", "meta": {"hexsha": "01e8010c29b68963af0bbd44cdac776a3b07e2e4", "size": 3205, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "k09/kstatboost01.cpp", "max_stars_repo_name": "kojiynet/koli", "max_stars_repo_head_hexsha": "681f9c1b1a291a36e1f0eee43c45b37567d2661e", "max_stars_repo_licenses": ["BSL-1.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": "k09/kstatboost01.cpp", "max_issues_repo_name": "kojiynet/koli", "max_issues_repo_head_hexsha": "681f9c1b1a291a36e1f0eee43c45b37567d2661e", "max_issues_repo_licenses": ["BSL-1.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": "k09/kstatboost01.cpp", "max_forks_repo_name": "kojiynet/koli", "max_forks_repo_head_hexsha": "681f9c1b1a291a36e1f0eee43c45b37567d2661e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.5100671141, "max_line_length": 86, "alphanum_fraction": 0.6514820593, "num_tokens": 839, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248225478307, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.711587730150361}}
{"text": "#include<NTL/ZZ_p.h>\n#include <NTL/ZZ.h>\n#include<NTL/ZZ_pXFactoring.h>\n#include<NTL/vector.h>\nusing namespace std;\nusing namespace NTL;\n\nint main()\n{\n\n   ZZ n1,n2,p1,p2,q,f,n_cpy; \n\n   long L = 512*4;\n\n   GenGermainPrime(p1,L,800);\n   GenGermainPrime(p2,L,800);\n   GenGermainPrime(q1,L,800);\n   GenGermainPrime(q2,L,800);\n   n1 = p1*q1;\n   n2 = p2*q2;\n\n   cout <<\"P1=\"<< p1 << \"\\n\";\n   cout <<\"P2=\"<< p2 << \"\\n\";\n   cout <<\"Q1=\"<< q1 << \"\\n\";\n   cout <<\"Q2=\"<< q2 << \"\\n\";\n   cout <<\"N1=\"<< n1 << \"\\n\";\n   cout <<\"N2=\"<< n2 << \"\\n\";\n   //~ ZZ d;\n   //~ GCD(d, n1,n2);\n   //~ cout <<\"\\n\\nGCD=\"<< d << \"\\n\";\n   //~ if(d == 1){\n\t   //~ cout <<\"GCD is correct\"<< \"\\n\";\n\t   //~ }\n   return 0;\n}\n\n\n\n", "meta": {"hexsha": "27ea50c86f1477d7b0c83378f1908e8a77d40b2a", "size": 694, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Generate_random_modulii.cpp", "max_stars_repo_name": "dheerajmpai/python", "max_stars_repo_head_hexsha": "733c331ce4fb35cc136170218115e8bb4a61134e", "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": "Generate_random_modulii.cpp", "max_issues_repo_name": "dheerajmpai/python", "max_issues_repo_head_hexsha": "733c331ce4fb35cc136170218115e8bb4a61134e", "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": "Generate_random_modulii.cpp", "max_forks_repo_name": "dheerajmpai/python", "max_forks_repo_head_hexsha": "733c331ce4fb35cc136170218115e8bb4a61134e", "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": 17.7948717949, "max_line_length": 39, "alphanum_fraction": 0.4855907781, "num_tokens": 269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248157222396, "lm_q2_score": 0.7577943822145998, "lm_q1q2_score": 0.711587730114413}}
{"text": "#pragma once\n#include <cmath>\n#include <iostream>\n#include <exception>\n\n#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\n\nusing Eigen::ArrayXd;\nusing Eigen::MatrixXcd;\nusing Eigen::MatrixXd;\nusing Eigen::Vector3d;\n\nnamespace GPU\n{\n    class Matrix : public MatrixXd\n    {\n    public:\n        void fromGpu(double *gpu_rep, unsigned row, unsigned col, size_t pitch);\n        double *toGpu(size_t *pitch) const;\n        int toGpu(double** p, size_t *pitch, size_t offset, size_t batch_size,\n                  bool iscol) const;\n    };\n\n    struct gpu_closest_matrix_params\n    {\n        const Matrix &p;\n        const Matrix &m;\n        Matrix &y;\n    };\n\n    struct gpu_err_compute_params\n    {\n        const Matrix &Y;\n        Matrix &p;\n        bool s;\n        const Matrix sr;\n        const Matrix &t;\n    };\n\n    class ICP\n    {\n    public:\n        ICP(Matrix m_, Matrix p_, int max_iter_)\n            : m{m_},\n              p{p_},\n              new_p{p_},\n              np{(unsigned int)p_.cols()},\n              nm{(unsigned int)m_.cols()},\n              dim{3},\n              max_iter{max_iter_}\n        {\n            this->s = 1.;\n            this->r = {Matrix::Identity(m_.rows(), m_.rows())};\n            this->t = {Matrix::Zero(m_.rows(), 1)};\n        }\n\n        struct gpu_closest_matrix_params get_closest_matrix_params(Matrix &Y)\n        {\n            struct gpu_closest_matrix_params cmp\n                {\n                    new_p, m, Y\n                };\n            return cmp;\n        }\n        struct gpu_err_compute_params get_err_compute_params(Matrix &Y, bool s)\n        {\n            struct gpu_err_compute_params cmp\n                {\n                    Y, new_p, s, s*r, t\n                };\n            return cmp;\n        }\n\n        double getDim() {return dim;}\n        double getNp() {return np;}\n\n        ~ICP()\n        {\n        }\n\n        void find_corresponding_naive();\n        void find_corresponding_opti();\n        Matrix compute_y_naive();\n        double find_alignment(Matrix y);\n\n    public:\n        Matrix new_p;\n\n    private:\n        double s;\n        Matrix t;\n        Matrix r;\n\n        Matrix m;\n        Matrix p;\n\n        unsigned int np;\n        unsigned int nm;\n        unsigned int dim;\n\n        int max_iter;\n        const double threshold = 1e-5;\n    };\n} // namespace GPU\n\n\n// Compute wrapper functions\n\nvoid compute_Y_w_opti(const GPU::Matrix &m, const GPU::Matrix &pi, GPU::Matrix &Y);\nint compute_distance_w_naive(const GPU::Matrix &m, const GPU::Matrix &pi);\ndouble compute_err_w(const GPU::Matrix &Y, GPU::Matrix &p, bool in_place,\n                     const GPU::Matrix &sr, const GPU::Matrix &t);\n\nGPU::Matrix substract_col_w(const GPU::Matrix &M, const GPU::Matrix &m);\nvoid y_p_norm_w(const GPU::Matrix &y, const GPU::Matrix &p, size_t size_arr, double &d_caps, double &sp);\n", "meta": {"hexsha": "bfc235b763164d5993733117a900a61276e5b6db", "size": 2838, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/GPU/gpu.hh", "max_stars_repo_name": "yassram/iterative-closest-point", "max_stars_repo_head_hexsha": "11ed48b5a3885c20ea99f4265c9c8bae2752ef86", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-03-04T08:53:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T16:36:13.000Z", "max_issues_repo_path": "src/GPU/gpu.hh", "max_issues_repo_name": "yassram/iterative-closest-point", "max_issues_repo_head_hexsha": "11ed48b5a3885c20ea99f4265c9c8bae2752ef86", "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/GPU/gpu.hh", "max_forks_repo_name": "yassram/iterative-closest-point", "max_forks_repo_head_hexsha": "11ed48b5a3885c20ea99f4265c9c8bae2752ef86", "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.2564102564, "max_line_length": 105, "alphanum_fraction": 0.5465116279, "num_tokens": 685, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218348550491, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.7115793834256398}}
{"text": "/**\n *  @file eigen_vector_operations.cpp\n *  @author Maximilian Harr <maximilian.harr@daimler.com>\n *  @date 13.07.2017\n *\n *  @brief Eigen vector computations\n *\n *\n *\n *          Coding Standard:\n *          wiki.ros.org/CppStyleGuide\n *          https://google.github.io/styleguide/cppguide.html\n *\n *\n *  @bug\n *\n *\n *  @todo\n *\n *\n */\n\n// PRAGMA\n\n// SYSTEM INCLUDES\n#include <iostream>  /* Header that defines the standard input/output stream objects */\n#include <cstdlib>  /* Header that defines several general purpose functions */\n#include <string>\n#include <Eigen/Dense>  /* template library for linear algebra http://eigen.tuxfamily.org */\n#include <math.h> /* Defines M_PI for pi value */\n#include <Eigen/Eigenvalues> \n#include <Eigen/Geometry>\n\n// PROJECT INCLUDES\n\n// LOCAL INCLUDES\n\n// FORWARD REFERENCES\n\n// FUNCTION PROTOTYPES\nvoid ProjectVector(Eigen::VectorXd vec_a, Eigen::VectorXd vec_b, \n  Eigen::VectorXd& vec_parallel, Eigen::VectorXd& vec_perpendicular );\n\nvoid ProjectVectorAbsolute(Eigen::VectorXd vec_a, Eigen::VectorXd vec_b, \n  double& parallel, double& perpendicular );\n\nvoid ProjectVectorAbsolute(Eigen::Vector2d vec_a, Eigen::Vector2d vec_b, \n  double& parallel, double& perpendicular );\n\n// GLOBAL VARIABLES\n\n\n//// MAIN //////////////////////////////////////////////////////////////////////////////////////////\nint main(int argc, char* argv[])\n{\n  \n  Eigen::VectorXd vec_a(3), vec_b(3);\n\n  Eigen::VectorXd vec_parallel(3), vec_perpendicular(3);\n  double parallel, perpendicular;\n\n  /* Project b on a */\n  vec_a << 2, 0, 0;\n  vec_b << 1, 1, 0;\n  ProjectVector(vec_a, vec_b, vec_parallel, vec_perpendicular);\n  vec_b << -1, 1, 0;\n  ProjectVector(vec_a, vec_b, vec_parallel, vec_perpendicular);\n  vec_b << -1, -1, 0;\n  ProjectVector(vec_a, vec_b, vec_parallel, vec_perpendicular);\n  vec_b << 1, -1, 0;\n  ProjectVector(vec_a, vec_b, vec_parallel, vec_perpendicular);\n  vec_b << 1, 0, 0;\n  ProjectVector(vec_a, vec_b, vec_parallel, vec_perpendicular);\n  vec_b << 0, 0, 1;\n  ProjectVector(vec_a, vec_b, vec_parallel, vec_perpendicular);\n\n  std::cout << \"---------- 3d vector rotation in x,y ----------\" << std::endl;\n  Eigen::Vector2d vec_a3, vec_b3;\n  vec_a3 << 2, 0;\n  vec_b3 << 1, 1;\n  ProjectVectorAbsolute(vec_a3, vec_b3, parallel, perpendicular);\n  vec_b3 << -1, 1;\n  ProjectVectorAbsolute(vec_a3, vec_b3, parallel, perpendicular);\n  vec_b3 << -1, -1;\n  ProjectVectorAbsolute(vec_a3, vec_b3, parallel, perpendicular);\n  vec_b3 << 1, -1;\n  ProjectVectorAbsolute(vec_a3, vec_b3, parallel, perpendicular);\n\n  return 0;\n\n}\n\n\n//// FUNCTION DEFINITIONS //////////////////////////////////////////////////////////////////////////\n\nvoid ProjectVector(Eigen::VectorXd vec_a, Eigen::VectorXd vec_b, \n  Eigen::VectorXd& vec_parallel, Eigen::VectorXd& vec_perpendicular ){\n  \n  double parallel, perpendicular;\n  ProjectVectorAbsolute(vec_a, vec_b, parallel, perpendicular);\n\n  vec_parallel = vec_a;\n  vec_parallel.normalize();\n  vec_parallel = parallel*vec_parallel;\n\n  vec_perpendicular = vec_b-vec_parallel;\n  vec_perpendicular.normalize();\n  vec_perpendicular = perpendicular*vec_perpendicular;\n\n  std::cout << \"vec_b            : \\n\" << vec_b << std::endl;\n  std::cout << \"vec_parallel     : \\n\" << vec_parallel << std::endl;\n  std::cout << \"vec_perpendicular: \\n\" << vec_perpendicular << std::endl;\n\n}\n\nvoid ProjectVectorAbsolute(Eigen::VectorXd vec_a, Eigen::VectorXd vec_b, \n  double& parallel, double& perpendicular ){\n  \n  // Warning: there is no check whether perpendicular portion is left/right use Vector2d function\n\n  /* rotation from a to b (Kosinussatz) */\n  double phi = acos( vec_a.dot(vec_b)/ (vec_a.norm()*vec_b.norm()) );\n\n  parallel = cos(phi)*vec_b.norm();\n  perpendicular = sin(phi)*vec_b.norm();\n  std::cout << std::endl << \"---------------\" << std::endl;\n  std::cout << \"phi          : \" << phi << std::endl;\n  std::cout << \"parallel     : \" << parallel << std::endl;\n  std::cout << \"perpendicular: \" << perpendicular << std::endl;\n  \n}\n\nvoid ProjectVectorAbsolute(Eigen::Vector2d vec_a2, Eigen::Vector2d vec_b2, \n  double& parallel, double& perpendicular ){\n\n  Eigen::Vector3d vec_a, vec_b;\n  vec_a << vec_a2[0], vec_a2[1], 0;\n  vec_b << vec_b2[0], vec_b2[1], 0;\n\n  /* rotation from a to b (Kosinussatz) */\n  double phi = acos( vec_a.dot(vec_b) / (vec_a.norm()*vec_b.norm()) );\n\n  Eigen::Vector3d cross_product = vec_a.cross(vec_b);\n  double sign = 1;\n  if( cross_product[2] < 0) {sign = -1;}\n\n  parallel = cos(phi)*vec_b.norm();\n  perpendicular = sign*sin(phi)*vec_b.norm();\n  std::cout << std::endl << \"---------------\" << std::endl;\n  std::cout << \"phi          : \" << phi << std::endl;\n  std::cout << \"parallel     : \" << parallel << std::endl;\n  std::cout << \"perpendicular: \" << perpendicular << std::endl;\n\n}", "meta": {"hexsha": "d079f1813a1dcf0f833270b1873bc6ab6e66ed09", "size": 4762, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/cpp_libs/src/eigen_vector_operations.cpp", "max_stars_repo_name": "maximilianharr/code_snippets", "max_stars_repo_head_hexsha": "8b271e6fa9174e24200e88be59e417abd5f2f59a", "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": "cpp/cpp_libs/src/eigen_vector_operations.cpp", "max_issues_repo_name": "maximilianharr/code_snippets", "max_issues_repo_head_hexsha": "8b271e6fa9174e24200e88be59e417abd5f2f59a", "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": "cpp/cpp_libs/src/eigen_vector_operations.cpp", "max_forks_repo_name": "maximilianharr/code_snippets", "max_forks_repo_head_hexsha": "8b271e6fa9174e24200e88be59e417abd5f2f59a", "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": 30.9220779221, "max_line_length": 100, "alphanum_fraction": 0.6453170937, "num_tokens": 1312, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299632771662, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.7115760746051164}}
{"text": "/*\r\n * Copyright Nick Thompson, 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 shows to to numerically integrate a periodic function using the adaptive_trapezoidal routine provided by boost.\r\n */\r\n\r\n#include <iostream>\r\n#include <cmath>\r\n#include <limits>\r\n#include <boost/math/quadrature/trapezoidal.hpp>\r\n\r\nint main()\r\n{\r\n    using boost::math::constants::two_pi;\r\n    using boost::math::constants::third;\r\n    using boost::math::quadrature::trapezoidal;\r\n    // This function has an analytic form for its integral over a period: 2pi/3.\r\n    auto f = [](double x) { return 1/(5 - 4*cos(x)); };\r\n\r\n    double Q = trapezoidal(f, (double) 0, two_pi<double>());\r\n\r\n    std::cout << std::setprecision(std::numeric_limits<double>::digits10);\r\n    std::cout << \"The adaptive trapezoidal rule gives the integral of our function as \" << Q << \"\\n\";\r\n    std::cout << \"The exact result is                                                 \" << two_pi<double>()*third<double>() << \"\\n\";\r\n\r\n}\r\n", "meta": {"hexsha": "86067d62b8800df4bdcf31af5e30745bfa6984e5", "size": 1151, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/math/example/trapezoidal_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/trapezoidal_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-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/math/example/trapezoidal_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.3666666667, "max_line_length": 133, "alphanum_fraction": 0.6446568202, "num_tokens": 284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299488452012, "lm_q2_score": 0.7690802317779601, "lm_q1q2_score": 0.7115760635057775}}
{"text": "/*\n * MIT License\n * \n * Copyright (c) 2018 Forrest\n * \n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n*/\n#ifndef CUBIC_SPLINE_H\n#define CUBIC_SPLINE_H\n\n#include <Eigen/Eigen>\n#include <algorithm>\n#include <array>\n#include <iostream>\n#include <stdexcept>\n#include <string>\n#include <vector>\n\nstatic std::vector<double> vec_diff(const std::vector<double> & input)\n{\n  std::vector<double> output;\n  for (unsigned int i = 1; i < input.size(); i++) {\n    output.push_back(input[i] - input[i - 1]);\n  }\n  return output;\n}\n\nstatic std::vector<double> cum_sum(const std::vector<double> & input)\n{\n  std::vector<double> output;\n  double temp = 0;\n  for (unsigned int i = 0; i < input.size(); i++) {\n    temp += input[i];\n    output.push_back(temp);\n  }\n  return output;\n}\n\nclass Spline\n{\npublic:\n  std::vector<double> x;\n  std::vector<double> y;\n  int nx;\n  std::vector<double> h;\n  std::vector<double> a;\n  std::vector<double> b;\n  std::vector<double> c;\n  // Eigen::VectorXf c;\n  std::vector<double> d;\n\n  Spline(){};\n  // d_i * (x-x_i)^3 + c_i * (x-x_i)^2 + b_i * (x-x_i) + a_i\n  Spline(const std::vector<double> & x_, const std::vector<double> & y_)\n  : x(x_), y(y_), nx(x_.size()), h(vec_diff(x_)), a(y_)\n  {\n    Eigen::MatrixXd A = calc_A();\n    Eigen::VectorXd B = calc_B();\n    Eigen::VectorXd c_eigen = A.colPivHouseholderQr().solve(B);\n    double * c_pointer = c_eigen.data();\n    c.assign(c_pointer, c_pointer + c_eigen.rows());\n\n    for (int i = 0; i < nx - 1; i++) {\n      d.push_back((c[i + 1] - c[i]) / (3.0 * h[i]));\n      b.push_back((a[i + 1] - a[i]) / h[i] - h[i] * (c[i + 1] + 2 * c[i]) / 3.0);\n    }\n  };\n\n  double calc(double t)\n  {\n    if (t < x.front() || t > x.back()) {\n      std::cout << \"Dangerous\" << std::endl;\n      std::cout << t << std::endl;\n      throw std::invalid_argument(\"received value out of the pre-defined range\");\n    }\n    int seg_id = bisect(t, 0, nx);\n    double dx = t - x[seg_id];\n    return a[seg_id] + b[seg_id] * dx + c[seg_id] * dx * dx + d[seg_id] * dx * dx * dx;\n  }\n\n  double calc(double t, double s)\n  {\n    if (t < 0 || t > s) {\n      std::cout << \"Dangerous\" << std::endl;\n      std::cout << t << std::endl;\n      throw std::invalid_argument(\"received value out of the pre-defined range\");\n    }\n    int seg_id = bisect(t, 0, nx);\n    double dx = t - x[seg_id];\n    return a[seg_id] + b[seg_id] * dx + c[seg_id] * dx * dx + d[seg_id] * dx * dx * dx;\n  }\n\n  double calc_d(double t)\n  {\n    if (t < x.front() || t > x.back()) {\n      std::cout << \"Dangerous\" << std::endl;\n      std::cout << t << std::endl;\n      throw std::invalid_argument(\"received value out of the pre-defined range\");\n    }\n    int seg_id = bisect(t, 0, nx - 1);\n    double dx = t - x[seg_id];\n    return b[seg_id] + 2 * c[seg_id] * dx + 3 * d[seg_id] * dx * dx;\n  }\n\n  double calc_d(double t, double s)\n  {\n    if (t < 0 || t > s) {\n      std::cout << \"Dangerous\" << std::endl;\n      std::cout << t << std::endl;\n      throw std::invalid_argument(\"received value out of the pre-defined range\");\n    }\n    int seg_id = bisect(t, 0, nx - 1);\n    double dx = t - x[seg_id];\n    return b[seg_id] + 2 * c[seg_id] * dx + 3 * d[seg_id] * dx * dx;\n  }\n\n  double calc_dd(double t)\n  {\n    if (t < x.front() || t > x.back()) {\n      std::cout << \"Dangerous\" << std::endl;\n      std::cout << t << std::endl;\n      throw std::invalid_argument(\"received value out of the pre-defined range\");\n    }\n    int seg_id = bisect(t, 0, nx);\n    double dx = t - x[seg_id];\n    return 2 * c[seg_id] + 6 * d[seg_id] * dx;\n  }\n\n  double calc_dd(double t, double s)\n  {\n    if (t < 0.0 || t > s) {\n      std::cout << \"Dangerous\" << std::endl;\n      std::cout << t << std::endl;\n      throw std::invalid_argument(\"received value out of the pre-defined range\");\n    }\n    int seg_id = bisect(t, 0, nx);\n    double dx = t - x[seg_id];\n    return 2 * c[seg_id] + 6 * d[seg_id] * dx;\n  }\n\nprivate:\n  Eigen::MatrixXd calc_A()\n  {\n    Eigen::MatrixXd A = Eigen::MatrixXd::Zero(nx, nx);\n    A(0, 0) = 1;\n    for (int i = 0; i < nx - 1; i++) {\n      if (i != nx - 2) {\n        A(i + 1, i + 1) = 2 * (h[i] + h[i + 1]);\n      }\n      A(i + 1, i) = h[i];\n      A(i, i + 1) = h[i];\n    }\n    A(0, 1) = 0.0;\n    A(nx - 1, nx - 2) = 0.0;\n    A(nx - 1, nx - 1) = 1.0;\n    return A;\n  };\n  Eigen::VectorXd calc_B()\n  {\n    Eigen::VectorXd B = Eigen::VectorXd::Zero(nx);\n    for (int i = 0; i < nx - 2; i++) {\n      B(i + 1) = 3.0 * (a[i + 2] - a[i + 1]) / h[i + 1] - 3.0 * (a[i + 1] - a[i]) / h[i];\n    }\n    return B;\n  };\n\n  int bisect(double t, int start, int end)\n  {\n    int mid = (start + end) / 2;\n    if (t == x[mid] || end - start <= 1) {\n      return mid;\n    } else if (t > x[mid]) {\n      return bisect(t, mid, end);\n    } else {\n      return bisect(t, start, mid);\n    }\n  }\n};\n\nclass Spline2D\n{\npublic:\n  Spline sx;\n  Spline sy;\n  std::vector<double> s;\n\n  Spline2D(const std::vector<double> & x, const std::vector<double> & y)\n  {\n    s = calc_s(x, y);\n    sx = Spline(s, x);\n    sy = Spline(s, y);\n    max_s_value_ = *std::max_element(s.begin(), s.end());\n  };\n\n  std::array<double, 2> calc_position(double s_t)\n  {\n    double x = sx.calc(s_t, max_s_value_);\n    double y = sy.calc(s_t, max_s_value_);\n    return {{x, y}};\n  };\n\n  double calc_curvature(double s_t)\n  {\n    double dx = sx.calc_d(s_t, max_s_value_);\n    double ddx = sx.calc_dd(s_t, max_s_value_);\n    double dy = sy.calc_d(s_t, max_s_value_);\n    double ddy = sy.calc_dd(s_t, max_s_value_);\n    return (ddy * dx - ddx * dy) / (dx * dx + dy * dy);\n  };\n\n  double calc_yaw(double s_t)\n  {\n    double dx = sx.calc_d(s_t, max_s_value_);\n    double dy = sy.calc_d(s_t, max_s_value_);\n    return std::atan2(dy, dx);\n  };\n\nprivate:\n  std::vector<double> calc_s(const std::vector<double> & x, const std::vector<double> & y)\n  {\n    std::vector<double> ds;\n    std::vector<double> out_s{0};\n    std::vector<double> dx = vec_diff(x);\n    std::vector<double> dy = vec_diff(y);\n\n    for (unsigned int i = 0; i < dx.size(); i++) {\n      ds.push_back(std::sqrt(dx[i] * dx[i] + dy[i] * dy[i]));\n    }\n\n    std::vector<double> cum_ds = cum_sum(ds);\n    out_s.insert(out_s.end(), cum_ds.begin(), cum_ds.end());\n    return out_s;\n  };\n  double max_s_value_;\n};\n\nclass Spline3D\n{\npublic:\n  Spline sx;\n  Spline sy;\n  Spline sv;\n  std::vector<double> s;\n\n  Spline3D(\n    const std::vector<double> & x, const std::vector<double> & y, const std::vector<double> & v)\n  {\n    s = calc_s(x, y);\n    sx = Spline(s, x);\n    sy = Spline(s, y);\n    sv = Spline(s, v);\n    max_s_value_ = *std::max_element(s.begin(), s.end());\n  };\n\n  std::array<double, 3> calc_trajectory_point(double s_t)\n  {\n    double x = sx.calc(s_t, max_s_value_);\n    double y = sy.calc(s_t, max_s_value_);\n    double v = sv.calc(s_t, max_s_value_);\n    return {{x, y, v}};\n  };\n\n  double calc_curvature(double s_t)\n  {\n    double dx = sx.calc_d(s_t, max_s_value_);\n    double ddx = sx.calc_dd(s_t, max_s_value_);\n    double dy = sy.calc_d(s_t, max_s_value_);\n    double ddy = sy.calc_dd(s_t, max_s_value_);\n    return (ddy * dx - ddx * dy) / (dx * dx + dy * dy);\n  };\n\n  double calc_yaw(double s_t)\n  {\n    double dx = sx.calc_d(s_t, max_s_value_);\n    double dy = sy.calc_d(s_t, max_s_value_);\n    return std::atan2(dy, dx);\n  };\n\nprivate:\n  std::vector<double> calc_s(const std::vector<double> & x, const std::vector<double> & y)\n  {\n    std::vector<double> ds;\n    std::vector<double> out_s{0};\n    std::vector<double> dx = vec_diff(x);\n    std::vector<double> dy = vec_diff(y);\n\n    for (unsigned int i = 0; i < dx.size(); i++) {\n      ds.push_back(std::sqrt(dx[i] * dx[i] + dy[i] * dy[i]));\n    }\n\n    std::vector<double> cum_ds = cum_sum(ds);\n    out_s.insert(out_s.end(), cum_ds.begin(), cum_ds.end());\n    return out_s;\n  };\n  double max_s_value_;\n};\n\nclass Spline4D\n{\npublic:\n  Spline sx;\n  Spline sy;\n  Spline sz;\n  Spline sv;\n  std::vector<double> s;\n\n  Spline4D(\n    const std::vector<double> & x, const std::vector<double> & y, const std::vector<double> & z,\n    const std::vector<double> & v)\n  {\n    s = calc_s(x, y);\n    sx = Spline(s, x);\n    sy = Spline(s, y);\n    sz = Spline(s, z);\n    sv = Spline(s, v);\n    max_s_value_ = *std::max_element(s.begin(), s.end());\n  };\n\n  std::array<double, 4> calc_trajectory_point(double s_t)\n  {\n    double x = sx.calc(s_t, max_s_value_);\n    double y = sy.calc(s_t, max_s_value_);\n    double z = sz.calc(s_t, max_s_value_);\n    double v = sv.calc(s_t, max_s_value_);\n    return {{x, y, z, v}};\n  };\n\n  double calc_curvature(double s_t)\n  {\n    double dx = sx.calc_d(s_t, max_s_value_);\n    double ddx = sx.calc_dd(s_t, max_s_value_);\n    double dy = sy.calc_d(s_t, max_s_value_);\n    double ddy = sy.calc_dd(s_t, max_s_value_);\n    return (ddy * dx - ddx * dy) / (dx * dx + dy * dy);\n  };\n\n  double calc_yaw(double s_t)\n  {\n    double dx = sx.calc_d(s_t, max_s_value_);\n    double dy = sy.calc_d(s_t, max_s_value_);\n    return std::atan2(dy, dx);\n  };\n\nprivate:\n  std::vector<double> calc_s(const std::vector<double> & x, const std::vector<double> & y)\n  {\n    std::vector<double> ds;\n    std::vector<double> out_s{0};\n    std::vector<double> dx = vec_diff(x);\n    std::vector<double> dy = vec_diff(y);\n\n    for (unsigned int i = 0; i < dx.size(); i++) {\n      ds.push_back(std::sqrt(dx[i] * dx[i] + dy[i] * dy[i]));\n    }\n\n    std::vector<double> cum_ds = cum_sum(ds);\n    out_s.insert(out_s.end(), cum_ds.begin(), cum_ds.end());\n    return out_s;\n  };\n  double max_s_value_;\n};\n\n#endif  // CUBIC_SPLINE_H\n", "meta": {"hexsha": "a3c139cb3f71e7120af426b1b5023c5eb20233ae", "size": 10495, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "planning/scenario_planning/lane_driving/behavior_planning/behavior_velocity_planner/include/utilization/interpolation/cubic_spline.hpp", "max_stars_repo_name": "sgermanserrano/Pilot.Auto", "max_stars_repo_head_hexsha": "0f3dee10dd4c22fddbee44662bd520e5a6d87ef7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-18T01:32:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-18T01:32:41.000Z", "max_issues_repo_path": "planning/scenario_planning/lane_driving/behavior_planning/behavior_velocity_planner/include/utilization/interpolation/cubic_spline.hpp", "max_issues_repo_name": "sgermanserrano/Pilot.Auto", "max_issues_repo_head_hexsha": "0f3dee10dd4c22fddbee44662bd520e5a6d87ef7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2021-08-09T14:15:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-19T07:56:14.000Z", "max_forks_repo_path": "planning/scenario_planning/lane_driving/behavior_planning/behavior_velocity_planner/include/utilization/interpolation/cubic_spline.hpp", "max_forks_repo_name": "sgermanserrano/Pilot.Auto", "max_forks_repo_head_hexsha": "0f3dee10dd4c22fddbee44662bd520e5a6d87ef7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-06-21T11:58:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T08:25:54.000Z", "avg_line_length": 27.6184210526, "max_line_length": 96, "alphanum_fraction": 0.5860886136, "num_tokens": 3354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600902, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.7114815886830856}}
{"text": "// Copyright 2019, Collabora, Ltd.\n// Copyright 2016, Sensics, Inc.\n// SPDX-License-Identifier: Apache-2.0\n/*!\n * @file\n * @brief  Base implementations for math library.\n * @author Ryan Pavlik <ryan.pavlik@collabora.com>\n * @ingroup aux_math\n *\n * Based in part on inc/osvr/Util/EigenQuatExponentialMap.h in OSVR-Core\n */\n\n#include \"math/m_api.h\"\n#include \"math/m_eigen_interop.hpp\"\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include <assert.h>\n\n\n// anonymous namespace for internal types\nnamespace {\ntemplate <typename Scalar> struct FourthRootMachineEps;\ntemplate <> struct FourthRootMachineEps<double>\n{\n\t/// machine epsilon is 1e-53, so fourth root is roughly 1e-13\n\tstatic double\n\tget()\n\t{\n\t\treturn 1.e-13;\n\t}\n};\ntemplate <> struct FourthRootMachineEps<float>\n{\n\t/// machine epsilon is 1e-24, so fourth root is 1e-6\n\tstatic float\n\tget()\n\t{\n\t\treturn 1.e-6f;\n\t}\n};\n/// Computes the \"historical\" (un-normalized) sinc(Theta)\n/// (sine(theta)/theta for theta != 0, defined as the limit value of 0\n/// at theta = 0)\ntemplate <typename Scalar>\ninline Scalar\nsinc(Scalar theta)\n{\n\t/// fourth root of machine epsilon is recommended cutoff for taylor\n\t/// series expansion vs. direct computation per\n\t/// Grassia, F. S. (1998). Practical Parameterization of Rotations\n\t/// Using the Exponential Map. Journal of Graphics Tools, 3(3),\n\t/// 29-48. http://doi.org/10.1080/10867651.1998.10487493\n\tScalar ret;\n\tif (theta < FourthRootMachineEps<Scalar>::get()) {\n\t\t// taylor series expansion.\n\t\tret = Scalar(1.f) - theta * theta / Scalar(6.f);\n\t\treturn ret;\n\t}\n\t// direct computation.\n\tret = std::sin(theta) / theta;\n\treturn ret;\n}\n\n/// fully-templated free function for quaternion expontiation\ntemplate <typename Derived>\ninline Eigen::Quaternion<typename Derived::Scalar>\nquat_exp(Eigen::MatrixBase<Derived> const &vec)\n{\n\tEIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Derived, 3);\n\tusing Scalar = typename Derived::Scalar;\n\t/// Implementation inspired by\n\t/// Grassia, F. S. (1998). Practical Parameterization of Rotations\n\t/// Using the Exponential Map. Journal of Graphics Tools, 3(3),\n\t/// 29\u201348. http://doi.org/10.1080/10867651.1998.10487493\n\t///\n\t/// However, that work introduced a factor of 1/2 which I could not\n\t/// derive from the definition of quaternion exponentiation and\n\t/// whose absence thus distinguishes this implementation. Without\n\t/// that factor of 1/2, the exp and ln functions successfully\n\t/// round-trip and match other implementations.\n\tScalar theta = vec.norm();\n\tScalar vecscale = sinc(theta);\n\tEigen::Quaternion<Scalar> ret;\n\tret.vec() = vecscale * vec;\n\tret.w() = std::cos(theta);\n\treturn ret.normalized();\n}\n\n/// Taylor series expansion of theta over sin(theta), aka cosecant, for\n/// use near 0 when you want continuity and validity at 0.\ntemplate <typename Scalar>\ninline Scalar\ncscTaylorExpansion(Scalar theta)\n{\n\treturn Scalar(1) +\n\t       // theta ^ 2 / 6\n\t       (theta * theta) / Scalar(6) +\n\t       // 7 theta^4 / 360\n\t       (Scalar(7) * theta * theta * theta * theta) / Scalar(360) +\n\t       // 31 theta^6/15120\n\t       (Scalar(31) * theta * theta * theta * theta * theta * theta) /\n\t           Scalar(15120);\n}\n\n/// fully-templated free function for quaternion log map.\n///\n/// Assumes a unit quaternion.\ntemplate <typename Scalar>\ninline Eigen::Matrix<Scalar, 3, 1>\nquat_ln(Eigen::Quaternion<Scalar> const &quat)\n{\n\t// ln q = ( (phi)/(norm of vec) vec, ln(norm of quat))\n\t// When we assume a unit quaternion, ln(norm of quat) = 0\n\t// so then we just scale the vector part by phi/sin(phi) to get the\n\t// result (i.e., ln(qv, qw) = (phi/sin(phi)) * qv )\n\tScalar vecnorm = quat.vec().norm();\n\n\t// \"best for numerical stability\" vs asin or acos\n\tScalar phi = std::atan2(vecnorm, quat.w());\n\n\t// Here is where we compute the coefficient to scale the vector part\n\t// by, which is nominally phi / std::sin(phi).\n\t// When the angle approaches zero, we compute the coefficient\n\t// differently, since it gets a bit like sinc in that we want it\n\t// continuous but 0 is undefined.\n\tScalar phiOverSin = vecnorm < 1e-4 ? cscTaylorExpansion<Scalar>(phi)\n\t                                   : (phi / std::sin(phi));\n\treturn quat.vec() * phiOverSin;\n}\n\n} // namespace\n\nextern \"C\" void\nmath_quat_integrate_velocity(const struct xrt_quat *quat,\n                             const struct xrt_vec3 *ang_vel,\n                             const float dt,\n                             struct xrt_quat *result)\n{\n\tassert(quat != NULL);\n\tassert(ang_vel != NULL);\n\tassert(result != NULL);\n\tassert(dt != 0);\n\n\n\tEigen::Quaternionf q = map_quat(*quat);\n\tEigen::Quaternionf incremental_rotation =\n\t    quat_exp(map_vec3(*ang_vel) * dt * 0.5f).normalized();\n\tmap_quat(*result) = q * incremental_rotation;\n}\n\nextern \"C\" void\nmath_quat_finite_difference(const struct xrt_quat *quat0,\n                            const struct xrt_quat *quat1,\n                            const float dt,\n                            struct xrt_vec3 *out_ang_vel)\n{\n\tassert(quat0 != NULL);\n\tassert(quat1 != NULL);\n\tassert(out_ang_vel != NULL);\n\tassert(dt != 0);\n\n\n\tEigen::Quaternionf inc_quat =\n\t    map_quat(*quat1) * map_quat(*quat0).conjugate();\n\tmap_vec3(*out_ang_vel) = 2.f * quat_ln(inc_quat);\n}\n", "meta": {"hexsha": "d52850d50c8061d55b94ae6beee4e9ea1f0d8cff", "size": 5187, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/xrt/auxiliary/math/m_quatexpmap.cpp", "max_stars_repo_name": "ltstein/monado_integration", "max_stars_repo_head_hexsha": "4e5348e3dbf3bb9584eec9a761488274a7deddbd", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-10-31T14:32:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-31T14:32:59.000Z", "max_issues_repo_path": "src/xrt/auxiliary/math/m_quatexpmap.cpp", "max_issues_repo_name": "patchedsoul/monado", "max_issues_repo_head_hexsha": "e6edaa9caf72d4caf1ea5968674d23845c7b975d", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-09-08T18:32:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-22T00:13:29.000Z", "max_forks_repo_path": "src/xrt/auxiliary/math/m_quatexpmap.cpp", "max_forks_repo_name": "patchedsoul/monado", "max_forks_repo_head_hexsha": "e6edaa9caf72d4caf1ea5968674d23845c7b975d", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-01-31T01:19:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T22:32:31.000Z", "avg_line_length": 30.6923076923, "max_line_length": 72, "alphanum_fraction": 0.6712936187, "num_tokens": 1411, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480252950991, "lm_q2_score": 0.7745833841649232, "lm_q1q2_score": 0.7114395426194333}}
{"text": "#include <iostream>\n#include <cassert>\n#include <cmath>\n\n#include <Eigen/Dense>\n\n#include <cannon/log/registry.hpp>\n\nusing namespace Eigen;\n\nusing namespace cannon::log;\n\n/*!\n * There are exactly ten ways of selecting three from five, 12345:\n *\n *   123, 124, 125, 134, 135, 145, 234, 245, 345\n *\n * In combinatorics, we use the notation, 5c3 = 10.\n *\n * In generall, ncr = n! / r!*(n - r)!, where r <= n.\n *\n * It is not until n = 23 that a value exceeds one-million: 23c10 = 1144066.\n *\n * How many, not necessarily distinct, values of ncr for 1 <= n <= 100, are\n * greater than one-million.\n */\n\nunsigned int compute_num_combinations_over_million() {\n  unsigned int num_greater = 0;\n  MatrixXd pascal = MatrixXd::Zero(101, 101);\n  pascal.col(0) = VectorXd::Ones(101);\n\n  for (unsigned int n = 1; n <= 100; ++n) {\n    for (unsigned int r = 1; r <= n; ++r) {\n      pascal(n, r) = pascal(n - 1, r) + pascal(n - 1, r -1);\n\n      if (pascal(n, r) > 1000000) {\n        pascal(n, r) = 1000000;\n        ++num_greater;\n      }\n    }\n  }\n\n  return num_greater;\n}\n\nint main(int argc, char **argv) {\n  std::cout << compute_num_combinations_over_million() << std::endl;\n}\n", "meta": {"hexsha": "443b379fcbca38a530dad9aa387b0ae77c3ea458", "size": 1162, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scripts/project_euler/euler_problem_53.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_53.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_53.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": 23.24, "max_line_length": 76, "alphanum_fraction": 0.6187607573, "num_tokens": 380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802395624257, "lm_q2_score": 0.774583389368527, "lm_q1q2_score": 0.7114395370282803}}
{"text": "// combination_iterator.hpp\n//\n// Produces all k-combinations of the universe {0,...,n-1} in\n// lexicographical order. The algorithm is a tuned-up version\n// of a simple generation method (\"Algorithm T\") described in:\n//\n//   Knuth, Donald E.\n//   The Art of Computer Programming, Volume 4A: Combinatorial Algorithms,\n//   Part 1. Pearson Education Inc., 2011.\n\n#ifndef COMBINATION_ITERATOR_HPP\n#define COMBINATION_ITERATOR_HPP\n\n// This code was produced by Juho Lauri (euler314).\n\n#include <cassert>\n#include <cstdint>\n#include <numeric>\n#include <vector>\n\n#include <boost/iterator/iterator_facade.hpp>\n\ntemplate <typename T>\nclass combination_iterator\n    : public boost::iterator_facade<combination_iterator<T>, const std::vector<T>&, boost::forward_traversal_tag>\n{\npublic:\n    combination_iterator() : comb_() {}\n\n    explicit combination_iterator(T n, T k)\n        : end_(false), n_(n), k_(k), comb_(k)\n    {\n        assert(k != 0 && n_ > k);\n        std::iota(comb_.begin(), comb_.end(), 0);\n        assert(!end_);\n    }\n\nprivate:\n    friend class boost::iterator_core_access;\n\n    void increment()\n    {\n        std::int64_t j = k_ - 1;\n\n        for (const T end = n_ - k_; j >= 0 && comb_[j] >= end + j; --j) {}\n\n        if (j < 0)\n        {\n            assert(comb_.front() == n_ - k_);\n            end_ = true;\n            return;\n        }\n\n        ++comb_[j];\n\n        for (const std::int64_t end = k_ - 1; j < end; ++j)\n        {\n            comb_[j + 1] = comb_[j] + 1;\n        }\n    }\n\n    bool equal(const combination_iterator& other) const\n    {\n        return end_ == other.end_;\n    }\n\n    const std::vector<T>& dereference() const { return comb_; }\n\n    bool end_{true};\n    const int n_{0};\n    const int k_{0};\n    std::vector<T> comb_;\n};\n\ntemplate <typename T>\nclass combination_iterator_minimax_order\n    : public boost::iterator_facade<combination_iterator_minimax_order<T>,\n                                    const std::vector<T>&,\n                                    boost::forward_traversal_tag>\n{\npublic:\n    combination_iterator_minimax_order() : comb_() {}\n\n    explicit combination_iterator_minimax_order(T n, T k)\n        : end_(false), n_(n), k_(k), hint_(k), comb_(k)\n    {\n        assert(k != 0 && n_ > k);\n        std::iota(comb_.begin(), comb_.end(), 0);\n        assert(!end_);\n    }\n\nprivate:\n    friend class boost::iterator_core_access;\n\n    void increment()\n    {\n        // The following code was copied from the discreture library:\n        // http://github.com/mraggi/discreture\n        if (k_ == 0)\n            return;\n\n        if (hint_ > 0)\n        {\n            --hint_;\n            ++comb_[hint_];\n            return;\n        }\n\n        T i = 0;\n        for (const T last = comb_.size() - 1;\n             (i < last) && (comb_[i] + 1 == comb_[i + 1]);\n             ++i)\n        {\n            comb_[i] = i;\n        }\n\n        ++comb_[i];\n\n        if (comb_[i] == n_)\n            end_ = true;\n        else\n            hint_ = i;\n    }\n\n    bool equal(const combination_iterator_minimax_order& other) const\n    {\n        return end_ == other.end_;\n    }\n\n    const std::vector<T>& dereference() const { return comb_; }\n\n    bool end_{true};\n    const int n_{0};\n    const int k_{0};\n    int hint_{};\n    std::vector<T> comb_;\n};\n\n#endif\n", "meta": {"hexsha": "5989188298aa2530aadb30e08f08d27579ea45cc", "size": 3285, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "benchmarks/external/euler314_combination_iterator.hpp", "max_stars_repo_name": "remz1337/discreture", "max_stars_repo_head_hexsha": "f15227a3e5c4faf04621bc9b2adad937aee06898", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 53.0, "max_stars_repo_stars_event_min_datetime": "2016-08-25T07:40:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T09:27:31.000Z", "max_issues_repo_path": "benchmarks/external/euler314_combination_iterator.hpp", "max_issues_repo_name": "remz1337/discreture", "max_issues_repo_head_hexsha": "f15227a3e5c4faf04621bc9b2adad937aee06898", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2018-01-08T20:43:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-29T19:11:39.000Z", "max_forks_repo_path": "benchmarks/external/euler314_combination_iterator.hpp", "max_forks_repo_name": "remz1337/discreture", "max_forks_repo_head_hexsha": "f15227a3e5c4faf04621bc9b2adad937aee06898", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2018-03-12T05:42:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T23:18:32.000Z", "avg_line_length": 23.4642857143, "max_line_length": 113, "alphanum_fraction": 0.5525114155, "num_tokens": 865, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.8311430436757313, "lm_q1q2_score": 0.7113347333354796}}
{"text": "#include <Eigen/Core>\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <mathtoolbox/gaussian-process-regression.hpp>\n#include <random>\n#include <string>\n#include <timer.hpp>\n#include <vector>\n\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\n\nnamespace\n{\n    std::random_device                     seed;\n    std::default_random_engine             engine(seed());\n    std::uniform_real_distribution<double> uniform_dist(0.0, 1.0);\n    std::normal_distribution<double>       normal_dist(0.0, 1.0);\n\n    double CalculateFunction(double x) { return x * std::sin(10.0 * x); }\n} // namespace\n\nint main(int argc, char** argv)\n{\n    // Set a output directory path\n    const std::string output_directory_path = (argc < 2) ? \".\" : argv[1];\n\n    // Define the scene setting\n    constexpr int    number_of_samples = 20;\n    constexpr double noise_intensity   = 0.010;\n\n    // Generate (and export) scattered data\n    std::ofstream scattered_data_stream(output_directory_path + \"/scattered_data.csv\");\n    scattered_data_stream << \"x,y\" << std::endl;\n    MatrixXd X(1, number_of_samples);\n    VectorXd y(number_of_samples);\n    for (int i = 0; i < number_of_samples; ++i)\n    {\n        X(0, i) = uniform_dist(engine);\n        y(i)    = CalculateFunction(X(0, i)) + noise_intensity * normal_dist(engine);\n\n        scattered_data_stream << X(0, i) << \",\" << y(i) << std::endl;\n    }\n    scattered_data_stream.close();\n\n    // Define the kernel type\n    const auto kernel_type = mathtoolbox::GaussianProcessRegressor::KernelType::ArdMatern52;\n\n    // Instantiate the interpolation object\n    mathtoolbox::GaussianProcessRegressor regressor(X, y, kernel_type);\n\n    // Perform hyperparameter estimation\n    const Eigen::Vector2d default_kernel_hyperparams{0.50, 0.50};\n    {\n        timer::Timer t(\"maximum likelihood estimation\");\n        regressor.PerformMaximumLikelihood(default_kernel_hyperparams, 0.010);\n    }\n\n    // Define constants for export\n    constexpr int    resolution       = 200;\n    constexpr double percentile_point = 1.95996398454005423552;\n\n    // Calculate (and export) predictive distribution\n    std::ofstream estimated_data_stream(output_directory_path + \"/estimated_data.csv\");\n    estimated_data_stream << \"x,mean,standard deviation,95-percent upper,95-percent lower\" << std::endl;\n    for (int i = 0; i <= resolution; ++i)\n    {\n        const double x = (1.0 / static_cast<double>(resolution)) * i;\n        const double y = regressor.PredictMean(VectorXd::Constant(1, x));\n        const double s = regressor.PredictStdev(VectorXd::Constant(1, x));\n\n        estimated_data_stream << x << \",\" << y << \",\" << s << \",\" << y + percentile_point * s << \",\"\n                              << y - percentile_point * s << std::endl;\n    }\n    estimated_data_stream.close();\n\n    return 0;\n}\n", "meta": {"hexsha": "fc8aab48431653869903480038b1400235348c9b", "size": 2805, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/gaussian-process-regression/main.cpp", "max_stars_repo_name": "yuki-koyama/mathtoolbox", "max_stars_repo_head_hexsha": "eb7449c3c489f465849a74405e72aff016a296f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 195.0, "max_stars_repo_stars_event_min_datetime": "2018-04-28T16:12:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:52:56.000Z", "max_issues_repo_path": "examples/gaussian-process-regression/main.cpp", "max_issues_repo_name": "amazing89/mathtoolbox", "max_issues_repo_head_hexsha": "8904bb06ced2ac501594f9574ef1ba3454b8e38e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 52.0, "max_issues_repo_issues_event_min_datetime": "2018-04-15T01:24:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-02T09:14:23.000Z", "max_forks_repo_path": "examples/gaussian-process-regression/main.cpp", "max_forks_repo_name": "amazing89/mathtoolbox", "max_forks_repo_head_hexsha": "8904bb06ced2ac501594f9574ef1ba3454b8e38e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 21.0, "max_forks_repo_forks_event_min_datetime": "2018-06-05T04:11:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T13:28:12.000Z", "avg_line_length": 35.0625, "max_line_length": 104, "alphanum_fraction": 0.6573975045, "num_tokens": 689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314858927011, "lm_q2_score": 0.8031738034238807, "lm_q1q2_score": 0.7113160089563837}}
{"text": "\n///////////////////////////////////////////////////////////////////////////////\n//  Copyright 2014 Anton Bikineev\n//  Copyright 2014 Christopher Kormanyos\n//  Copyright 2014 John Maddock\n//  Copyright 2014 Paul Bristow\n//  Distributed under the Boost\n//  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#ifndef BOOST_HYPERGEOMETRIC_1F1_RECURRENCE_HPP_\n#define BOOST_HYPERGEOMETRIC_1F1_RECURRENCE_HPP_\n\n#include <boost/math/special_functions/modf.hpp>\n#include <boost/math/special_functions/next.hpp>\n\n#include <boost/math/tools/recurrence.hpp>\n#include <boost/math/special_functions/detail/hypergeometric_pFq_checked_series.hpp>\n\n  namespace boost { namespace math { namespace detail {\n\n  // forward declaration for initial values\n  template <class T, class Policy>\n  inline T hypergeometric_1F1_imp(const T& a, const T& b, const T& z, const Policy& pol);\n\n  template <class T, class Policy>\n  inline T hypergeometric_1F1_imp(const T& a, const T& b, const T& z, const Policy& pol, int& log_scaling);\n\n  template <class T>\n  struct hypergeometric_1F1_recurrence_a_coefficients\n  {\n    typedef boost::math::tuple<T, T, T> result_type;\n\n    hypergeometric_1F1_recurrence_a_coefficients(const T& a, const T& b, const T& z):\n    a(a), b(b), z(z)\n    {\n    }\n\n    result_type operator()(boost::intmax_t i) const\n    {\n      const T ai = a + i;\n\n      const T an = b - ai;\n      const T bn = (2 * ai - b + z);\n      const T cn = -ai;\n\n      return boost::math::make_tuple(an, bn, cn);\n    }\n\n  private:\n    const T a, b, z;\n    hypergeometric_1F1_recurrence_a_coefficients operator=(const hypergeometric_1F1_recurrence_a_coefficients&);\n  };\n\n  template <class T>\n  struct hypergeometric_1F1_recurrence_b_coefficients\n  {\n    typedef boost::math::tuple<T, T, T> result_type;\n\n    hypergeometric_1F1_recurrence_b_coefficients(const T& a, const T& b, const T& z):\n    a(a), b(b), z(z)\n    {\n    }\n\n    result_type operator()(boost::intmax_t i) const\n    {\n      const T bi = b + i;\n\n      const T an = bi * (bi - 1);\n      const T bn = bi * (1 - bi - z);\n      const T cn = z * (bi - a);\n\n      return boost::math::make_tuple(an, bn, cn);\n    }\n\n  private:\n    const T a, b, z;\n    hypergeometric_1F1_recurrence_b_coefficients& operator=(const hypergeometric_1F1_recurrence_b_coefficients&);\n  };\n  //\n  // for use when we're recursing to a small b:\n  //\n  template <class T>\n  struct hypergeometric_1F1_recurrence_small_b_coefficients\n  {\n     typedef boost::math::tuple<T, T, T> result_type;\n\n     hypergeometric_1F1_recurrence_small_b_coefficients(const T& a, const T& b, const T& z, int N) :\n        a(a), b(b), z(z), N(N)\n     {\n     }\n\n     result_type operator()(boost::intmax_t i) const\n     {\n        const T bi = b + (i + N);\n        const T bi_minus_1 = b + (i + N - 1);\n\n        const T an = bi * bi_minus_1;\n        const T bn = bi * (-bi_minus_1 - z);\n        const T cn = z * (bi - a);\n\n        return boost::math::make_tuple(an, bn, cn);\n     }\n\n  private:\n     hypergeometric_1F1_recurrence_small_b_coefficients operator=(const hypergeometric_1F1_recurrence_small_b_coefficients&);\n     const T a, b, z;\n     int N;\n  };\n\n  template <class T>\n  struct hypergeometric_1F1_recurrence_a_and_b_coefficients\n  {\n    typedef boost::math::tuple<T, T, T> result_type;\n\n    hypergeometric_1F1_recurrence_a_and_b_coefficients(const T& a, const T& b, const T& z, int offset = 0):\n    a(a), b(b), z(z), offset(offset)\n    {\n    }\n\n    result_type operator()(boost::intmax_t i) const\n    {\n      const T ai = a + (offset + i);\n      const T bi = b + (offset + i);\n\n      const T an = bi * (b + (offset + i - 1));\n      const T bn = bi * (z - (b + (offset + i - 1)));\n      const T cn = -ai * z;\n\n      return boost::math::make_tuple(an, bn, cn);\n    }\n\n  private:\n    const T a, b, z;\n    int offset;\n    hypergeometric_1F1_recurrence_a_and_b_coefficients operator=(const hypergeometric_1F1_recurrence_a_and_b_coefficients&);\n  };\n#if 0\n  //\n  // These next few recurrence relations are archived for future reference, some of them are novel, though all\n  // are trivially derived from the existing well known relations:\n  //\n  // Recurrence relation for double-stepping on both a and b:\n  // - b(b-1)(b-2) / (2-b+z) M(a-2,b-2,z) + [b(a-1)z / (2-b+z) + b(1-b+z) + abz(b+1) /(b+1)(z-b)] M(a,b,z) - a(a+1)z^2 / (b+1)(z-b) M(a+2,b+2,z)\n  //\n  template <class T>\n  struct hypergeometric_1F1_recurrence_2a_and_2b_coefficients\n  {\n     typedef boost::math::tuple<T, T, T> result_type;\n\n     hypergeometric_1F1_recurrence_2a_and_2b_coefficients(const T& a, const T& b, const T& z, int offset = 0) :\n        a(a), b(b), z(z), offset(offset)\n     {\n     }\n\n     result_type operator()(boost::intmax_t i) const\n     {\n        i *= 2;\n        const T ai = a + (offset + i);\n        const T bi = b + (offset + i);\n\n        const T an = -bi * (b + (offset + i - 1)) * (b + (offset + i - 2)) / (-(b + (offset + i - 2)) + z);\n        const T bn = bi * (a + (offset + i - 1)) * z / (z - (b + (offset + i - 2)))\n           + bi * (z - (b + (offset + i - 1)))\n           + ai * bi * z * (b + (offset + i + 1)) / ((b + (offset + i + 1)) * (z - bi));\n        const T cn = -ai * (a + (offset + i + 1)) * z * z / ((b + (offset + i + 1)) * (z - bi));\n\n        return boost::math::make_tuple(an, bn, cn);\n     }\n\n  private:\n     const T a, b, z;\n     int offset;\n     hypergeometric_1F1_recurrence_2a_and_2b_coefficients operator=(const hypergeometric_1F1_recurrence_2a_and_2b_coefficients&);\n  };\n\n  //\n  // Recurrence relation for double-stepping on a:\n  // -(b-a)(1 + b - a)/(2a-2-b+z)M(a-2,b,z)  + [(b-a)(a-1)/(2a-2-b+z) + (2a-b+z) + a(b-a-1)/(2a+2-b+z)]M(a,b,z)   -a(a+1)/(2a+2-b+z)M(a+2,b,z)\n  //\n  template <class T>\n  struct hypergeometric_1F1_recurrence_2a_coefficients\n  {\n     typedef boost::math::tuple<T, T, T> result_type;\n\n     hypergeometric_1F1_recurrence_2a_coefficients(const T& a, const T& b, const T& z, int offset = 0) :\n        a(a), b(b), z(z), offset(offset)\n     {\n     }\n\n     result_type operator()(boost::intmax_t i) const\n     {\n        i *= 2;\n        const T ai = a + (offset + i);\n        // -(b-a)(1 + b - a)/(2a-2-b+z)\n        const T an = -(b - ai) * (b - (a + (offset + i - 1))) / (2 * (a + (offset + i - 1)) - b + z);\n        const T bn = (b - ai) * (a + (offset + i - 1)) / (2 * (a + (offset + i - 1)) - b + z) + (2 * ai - b + z) + ai * (b - (a + (offset + i + 1))) / (2 * (a + (offset + i + 1)) - b + z);\n        const T cn = -ai * (a + (offset + i + 1)) / (2 * (a + (offset + i + 1)) - b + z);\n\n        return boost::math::make_tuple(an, bn, cn);\n     }\n\n  private:\n     const T a, b, z;\n     int offset;\n     hypergeometric_1F1_recurrence_2a_coefficients operator=(const hypergeometric_1F1_recurrence_2a_coefficients&);\n  };\n\n  //\n  // Recurrence relation for double-stepping on b:\n  // b(b-1)^2(b-2)/((1-b)(2-b-z)) M(a,b-2,z)  + [zb(b-1)(b-1-a)/((1-b)(2-b-z)) + b(1-b-z) + z(b-a)(b+1)b/((b+1)(b+z)) ] M(a,b,z) + z^2(b-a)(b+1-a)/((b+1)(b+z)) M(a,b+2,z)\n  //\n  template <class T>\n  struct hypergeometric_1F1_recurrence_2b_coefficients\n  {\n     typedef boost::math::tuple<T, T, T> result_type;\n\n     hypergeometric_1F1_recurrence_2b_coefficients(const T& a, const T& b, const T& z, int offset = 0) :\n        a(a), b(b), z(z), offset(offset)\n     {\n     }\n\n     result_type operator()(boost::intmax_t i) const\n     {\n        i *= 2;\n        const T bi = b + (offset + i);\n        const T bi_m1 = b + (offset + i - 1);\n        const T bi_p1 = b + (offset + i + 1);\n        const T bi_m2 = b + (offset + i - 2);\n\n        const T an = bi * (bi_m1) * (bi_m1) * (bi_m2) / (-bi_m1 * (-bi_m2 - z));\n        const T bn = z * bi * bi_m1 * (bi_m1 - a) / (-bi_m1 * (-bi_m2 - z)) + bi * (-bi_m1 - z) + z * (bi - a) * bi_p1 * bi / (bi_p1 * (bi + z));\n        const T cn = z * z * (bi - a) * (bi_p1 - a) / (bi_p1 * (bi + z));\n\n        return boost::math::make_tuple(an, bn, cn);\n     }\n\n  private:\n     const T a, b, z;\n     int offset;\n     hypergeometric_1F1_recurrence_2b_coefficients operator=(const hypergeometric_1F1_recurrence_2b_coefficients&);\n  };\n\n  //\n  // Recurrence relation for a+ b-:\n  // -z(b-a)(a-1-b)/(b(a-1+z)) M(a-1,b+1,z) + [(b-a)(a-1)b/(b(a-1+z)) + (2a-b+z) + a(b-a-1)/(a+z)] M(a,b,z) + a(1-b)/(a+z) M(a+1,b-1,z)\n  //\n  // This is potentially the most useful of these novel recurrences.\n  //              -                                      -                  +        -                           +\n  template <class T>\n  struct hypergeometric_1F1_recurrence_a_plus_b_minus_coefficients\n  {\n     typedef boost::math::tuple<T, T, T> result_type;\n\n     hypergeometric_1F1_recurrence_a_plus_b_minus_coefficients(const T& a, const T& b, const T& z, int offset = 0) :\n        a(a), b(b), z(z), offset(offset)\n     {\n     }\n\n     result_type operator()(boost::intmax_t i) const\n     {\n        const T ai = a + (offset + i);\n        const T bi = b - (offset + i);\n\n        const T an = -z * (bi - ai) * (ai - 1 - bi) / (bi * (ai - 1 + z));\n        const T bn = z * ((-1 / (ai + z) - 1 / (ai + z - 1)) * (bi + z - 1) + 3) + bi - 1;\n        const T cn = ai * (1 - bi) / (ai + z);\n\n        return boost::math::make_tuple(an, bn, cn);\n     }\n\n  private:\n     const T a, b, z;\n     int offset;\n     hypergeometric_1F1_recurrence_a_plus_b_minus_coefficients operator=(const hypergeometric_1F1_recurrence_a_plus_b_minus_coefficients&);\n  };\n#endif\n\n  template <class T, class Policy>\n  inline T hypergeometric_1F1_backward_recurrence_for_negative_a(const T& a, const T& b, const T& z, const Policy& pol, const char* function, int& log_scaling)\n  {\n    BOOST_MATH_STD_USING // modf, frexp, fabs, pow\n\n    boost::intmax_t integer_part = 0;\n    T ak = modf(a, &integer_part);\n    //\n    // We need ak-1 positive to avoid infinite recursion below:\n    //\n    if (0 != ak)\n    {\n       ak += 2;\n       integer_part -= 2;\n    }\n\n    if (-integer_part > static_cast<boost::intmax_t>(policies::get_max_series_iterations<Policy>()))\n       return policies::raise_evaluation_error<T>(function, \"1F1 arguments sit in a range with a so negative that we have no evaluation method, got a = %1%\", std::numeric_limits<T>::quiet_NaN(), pol);\n\n    T first, second;\n    if(ak == 0)\n    { \n       first = 1;\n       ak -= 1;\n       second = 1 - z / b;\n    }\n    else\n    {\n       int scaling1(0), scaling2(0);\n       first = detail::hypergeometric_1F1_imp(ak, b, z, pol, scaling1);\n       ak -= 1;\n       second = detail::hypergeometric_1F1_imp(ak, b, z, pol, scaling2);\n       if (scaling1 != scaling2)\n       {\n          second *= exp(T(scaling2 - scaling1));\n       }\n       log_scaling += scaling1;\n    }\n    ++integer_part;\n\n    detail::hypergeometric_1F1_recurrence_a_coefficients<T> s(ak, b, z);\n\n    return tools::apply_recurrence_relation_backward(s,\n                                                     static_cast<unsigned int>(std::abs(integer_part)),\n                                                     first,\n                                                     second, &log_scaling);\n  }\n\n\n  template <class T, class Policy>\n  T hypergeometric_1F1_backwards_recursion_on_b_for_negative_a(const T& a, const T& b, const T& z, const Policy& pol, const char*, int& log_scaling)\n  {\n     using std::swap;\n     BOOST_MATH_STD_USING // modf, frexp, fabs, pow\n     //\n     // We compute \n     //\n     // M[a + a_shift, b + b_shift; z] \n     //\n     // and recurse backwards on a and b down to\n     //\n     // M[a, b, z]\n     //\n     // With a + a_shift > 1 and b + b_shift > z\n     // \n     // There are 3 distinct regions to ensure stability during the recursions:\n     //\n     // a > 0         :  stable for backwards on a\n     // a < 0, b > 0  :  stable for backwards on a and b\n     // a < 0, b < 0  :  stable for backwards on b (as long as |b| is small). \n     // \n     // We could simplify things by ignoring the middle region, but it's more efficient\n     // to recurse on a and b together when we can.\n     //\n\n     BOOST_ASSERT(a < -1); // Not tested nor taken for -1 < a < 0\n\n     int b_shift = itrunc(z - b) + 2;\n\n     int a_shift = itrunc(-a);\n     if (a + a_shift != 0)\n     {\n        a_shift += 2;\n     }\n     //\n     // If the shifts are so large that we would throw an evaluation_error, try the series instead,\n     // even though this will almost certainly throw as well:\n     //\n     if (b_shift > static_cast<boost::intmax_t>(boost::math::policies::get_max_series_iterations<Policy>()))\n        return hypergeometric_1F1_checked_series_impl(a, b, z, pol, log_scaling);\n\n     if (a_shift > static_cast<boost::intmax_t>(boost::math::policies::get_max_series_iterations<Policy>()))\n        return hypergeometric_1F1_checked_series_impl(a, b, z, pol, log_scaling);\n\n     int a_b_shift = b < 0 ? itrunc(b + b_shift) : b_shift;   // The max we can shift on a and b together\n     int leading_a_shift = (std::min)(3, a_shift);        // Just enough to make a negative\n     if (a_b_shift > a_shift - 3)\n     {\n        a_b_shift = a_shift < 3 ? 0 : a_shift - 3;\n     }\n     else\n     {\n        // Need to ensure that leading_a_shift is large enough that a will reach it's target\n        // after the first 2 phases (-,0) and (-,-) are over:\n        leading_a_shift = a_shift - a_b_shift;\n     }\n     int trailing_b_shift = b_shift - a_b_shift;\n     if (a_b_shift < 5)\n     {\n        // Might as well do things in two steps rather than 3:\n        if (a_b_shift > 0)\n        {\n           leading_a_shift += a_b_shift;\n           trailing_b_shift += a_b_shift;\n        }\n        a_b_shift = 0;\n        --leading_a_shift;\n     }\n\n     BOOST_ASSERT(leading_a_shift > 1);\n     BOOST_ASSERT(a_b_shift + leading_a_shift + (a_b_shift == 0 ? 1 : 0) == a_shift);\n     BOOST_ASSERT(a_b_shift + trailing_b_shift == b_shift);\n\n     if ((trailing_b_shift == 0) && (fabs(b) < 0.5) && a_b_shift)\n     {\n        // Better to have the final recursion on b alone, otherwise we lose precision when b is very small:\n        int diff = (std::min)(a_b_shift, 3);\n        a_b_shift -= diff;\n        leading_a_shift += diff;\n        trailing_b_shift += diff;\n     }\n\n     T first, second;\n     int scale1(0), scale2(0);\n     first = boost::math::detail::hypergeometric_1F1_imp(T(a + a_shift), T(b + b_shift), z, pol, scale1);\n     //\n     // It would be good to compute \"second\" from first and the ratio - unfortunately we are right on the cusp\n     // recursion on a switching from stable backwards to stable forwards behaviour and so this is not possible here.\n     //\n     second = boost::math::detail::hypergeometric_1F1_imp(T(a + a_shift - 1), T(b + b_shift), z, pol, scale2);\n     if (scale1 != scale2)\n        second *= exp(T(scale2 - scale1));\n     log_scaling += scale1;\n\n     //\n     // Now we have [a + a_shift, b + b_shift, z] and [a + a_shift - 1, b + b_shift, z]\n     // and want to recurse until [a + a_shift - leading_a_shift, b + b_shift, z] and [a + a_shift - leadng_a_shift - 1, b + b_shift, z]\n     // which is leading_a_shift -1 steps.\n     //\n     second = boost::math::tools::apply_recurrence_relation_backward(\n        hypergeometric_1F1_recurrence_a_coefficients<T>(a + a_shift - 1, b + b_shift, z), \n        leading_a_shift, first, second, &log_scaling, &first);\n\n     if (a_b_shift)\n     {\n        //\n        // Now we need to switch to an a+b shift so that we have:\n        // [a + a_shift - leading_a_shift, b + b_shift, z] and [a + a_shift - leadng_a_shift - 1, b + b_shift - 1, z]\n        // A&S 13.4.3 gives us what we need:\n        //\n        {\n           // local a's and b's:\n           T la = a + a_shift - leading_a_shift - 1;\n           T lb = b + b_shift;\n           second = ((1 + la - lb) * second - la * first) / (1 - lb);\n        }\n        //\n        // Now apply a_b_shift - 1 recursions to get down to\n        // [a + 1, b + trailing_b_shift + 1, z] and [a, b + trailing_b_shift, z]\n        //\n        second = boost::math::tools::apply_recurrence_relation_backward(\n           hypergeometric_1F1_recurrence_a_and_b_coefficients<T>(a, b + b_shift - a_b_shift, z, a_b_shift - 1),\n           a_b_shift - 1, first, second, &log_scaling, &first);\n        //\n        // Now we need to switch to a b shift, a different application of A&S 13.4.3\n        // will get us there, we leave \"second\" where it is, and move \"first\" sideways:\n        //\n        {\n           T lb = b + trailing_b_shift + 1;\n           first = (second * (lb - 1) - a * first) / -(1 + a - lb);\n        }\n     }\n     else\n     {\n        //\n        // We have M[a+1, b+b_shift, z] and M[a, b+b_shift, z] and need M[a, b+b_shift-1, z] for\n        // recursion on b: A&S 13.4.3 gives us what we need.\n        //\n        T third = -(second * (1 + a - b - b_shift) - first * a) / (b + b_shift - 1);\n        swap(first, second);\n        swap(second, third);\n        --trailing_b_shift;\n     }\n     //\n     // Finish off by applying trailing_b_shift recursions:\n     //\n     if (trailing_b_shift)\n     {\n        second = boost::math::tools::apply_recurrence_relation_backward(\n           hypergeometric_1F1_recurrence_small_b_coefficients<T>(a, b, z, trailing_b_shift), \n           trailing_b_shift, first, second, &log_scaling);\n     }\n     return second;\n  }\n\n\n\n  } } } // namespaces\n\n#endif // BOOST_HYPERGEOMETRIC_1F1_RECURRENCE_HPP_\n", "meta": {"hexsha": "edf5926ef42638b761d3596d60cd6373b95fd7a3", "size": 17295, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/lib/include/boost/math/special_functions/detail/hypergeometric_1F1_recurrence.hpp", "max_stars_repo_name": "mamil/demo", "max_stars_repo_head_hexsha": "32240d95b80175549e6a1904699363ce672a1591", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 101.0, "max_stars_repo_stars_event_min_datetime": "2019-02-12T12:53:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T14:14:38.000Z", "max_issues_repo_path": "boost/lib/include/boost/math/special_functions/detail/hypergeometric_1F1_recurrence.hpp", "max_issues_repo_name": "mamil/demo", "max_issues_repo_head_hexsha": "32240d95b80175549e6a1904699363ce672a1591", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 157.0, "max_issues_repo_issues_event_min_datetime": "2019-02-06T05:04:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:50:28.000Z", "max_forks_repo_path": "boost/lib/include/boost/math/special_functions/detail/hypergeometric_1F1_recurrence.hpp", "max_forks_repo_name": "mamil/demo", "max_forks_repo_head_hexsha": "32240d95b80175549e6a1904699363ce672a1591", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 28.0, "max_forks_repo_forks_event_min_datetime": "2020-02-27T14:07:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T07:53:36.000Z", "avg_line_length": 35.3680981595, "max_line_length": 200, "alphanum_fraction": 0.575484244, "num_tokens": 5413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314768368161, "lm_q2_score": 0.8031737869342623, "lm_q1q2_score": 0.7113159870792091}}
{"text": "#include <armadillo>\n#include \"GEFE_utility.h\"\n\n// Demonstration.\nint main() {\n    const arma::mat H(\"-0.2414 0.3160; 0.3160 -0.8649\");\n    const arma::vec ii(\"0 1\");\n    const arma::vec gefe_eigvecs = getEigenvectorFromEigenvalues(H, ii, /*column j=*/0);\n    printf(\"\\ngefe:\\n\");\n    gefe_eigvecs.print(); //    0.1488\n                          //    0.8512\n\n    arma::vec arma_eigvals;\n    arma::mat arma_eigvecs;\n    arma::eig_sym(arma_eigvals, arma_eigvecs, H);\n\n    printf(\"\\narma::eig_sym:\\n\");\n    arma_eigvecs = arma::square(arma_eigvecs);\n    arma_eigvecs.col(0).print(); //    0.1488\n                                         //    0.8512\n}\n\n", "meta": {"hexsha": "e9d8caf7b0516565757ebc4ca675f0d4d7cdf721", "size": 651, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/main.cpp", "max_stars_repo_name": "cgyurgyik/eigenvectors-from-eigenvalues", "max_stars_repo_head_hexsha": "53ccbc879ddf9784a12a1635334dd3a9108efa23", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-19T03:18:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-19T03:18:41.000Z", "max_issues_repo_path": "cpp/main.cpp", "max_issues_repo_name": "cgyurgyik/eigenvectors-from-eigenvalues", "max_issues_repo_head_hexsha": "53ccbc879ddf9784a12a1635334dd3a9108efa23", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-11-16T01:39:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-19T16:12:16.000Z", "max_forks_repo_path": "cpp/main.cpp", "max_forks_repo_name": "cgyurgyik/EigenvectorsFromEigenvalues", "max_forks_repo_head_hexsha": "53ccbc879ddf9784a12a1635334dd3a9108efa23", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-19T03:18:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-19T03:18:44.000Z", "avg_line_length": 28.3043478261, "max_line_length": 88, "alphanum_fraction": 0.5622119816, "num_tokens": 216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314624993576759, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.711156494619286}}
{"text": "#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n\n#include <CGAL/Delaunay_triangulation_on_sphere_2.h>\n#include <CGAL/Projection_on_sphere_traits_3.h>\n\n#include <boost/iterator/transform_iterator.hpp>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel          K;\n\ntypedef CGAL::Projection_on_sphere_traits_3<K>                       Traits;\ntypedef CGAL::Delaunay_triangulation_on_sphere_2<Traits>             DToS2;\n\ntypedef Traits::Point_3                                              Point_3;\n\nint main(int, char**)\n{\n  std::vector<Point_3> points;\n  points.emplace_back( 3,  1,  1);\n  points.emplace_back(-8,  1,  1);\n  points.emplace_back( 1,  2,  1);\n  points.emplace_back( 1, -2,  1);\n  points.emplace_back( 1,  1, 10);\n\n  Traits traits(Point_3(1,1,1)); // radius is 1 by default\n  DToS2 dtos(traits);\n\n  Traits::Construct_point_on_sphere_2 cst = traits.construct_point_on_sphere_2_object();\n\n  for(const auto& pt : points)\n  {\n    std::cout << \"----- Inserting (\" << pt\n              << \") at squared distance \" << CGAL::squared_distance(pt, traits.center())\n              << \" from the center of the sphere\" << std::endl;\n    dtos.insert(cst(pt));\n\n    std::cout << \"The triangulation now has dimension: \" << dtos.dimension() << \" and\\n\";\n    std::cout << dtos.number_of_vertices() << \" vertices\" << std::endl;\n    std::cout << dtos.number_of_edges() << \" edges\" << std::endl;\n    std::cout << dtos.number_of_faces() << \" solid faces\" << std::endl;\n    std::cout << dtos.number_of_ghost_faces() << \" ghost faces\" << std::endl;\n  }\n\n  CGAL::IO::write_OFF(\"result.off\", dtos, CGAL::parameters::stream_precision(17));\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "814c36b7089c185e55e0321d11f49e041148ffc7", "size": 1676, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Triangulation_on_sphere_2/examples/Triangulation_on_sphere_2/triang_on_sphere_proj.cpp", "max_stars_repo_name": "ffteja/cgal", "max_stars_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 3227.0, "max_stars_repo_stars_event_min_datetime": "2015-03-05T00:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:20:35.000Z", "max_issues_repo_path": "Triangulation_on_sphere_2/examples/Triangulation_on_sphere_2/triang_on_sphere_proj.cpp", "max_issues_repo_name": "ffteja/cgal", "max_issues_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 5574.0, "max_issues_repo_issues_event_min_datetime": "2015-03-05T00:01:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:08:11.000Z", "max_forks_repo_path": "Triangulation_on_sphere_2/examples/Triangulation_on_sphere_2/triang_on_sphere_proj.cpp", "max_forks_repo_name": "ffteja/cgal", "max_forks_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1274.0, "max_forks_repo_forks_event_min_datetime": "2015-03-05T00:01:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:47:56.000Z", "avg_line_length": 35.6595744681, "max_line_length": 89, "alphanum_fraction": 0.6485680191, "num_tokens": 472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009642742805, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.7111523972388945}}
{"text": "#include <pa/stages/ftle_map_generator.hpp>\n\n#include <Eigen/Dense>\n#include <tbb/tbb.h>\n\nnamespace pa\n{\nftle_map_generator::ftle_map_generator(partitioner* partitioner, mode mode) : partitioner_(partitioner), mode_(mode)\n{\n\n}\n\nvoid                          ftle_map_generator::set_flow_map(vector_field* flow_map   )\n{\n  flow_map_ = flow_map;\n}\nvoid                          ftle_map_generator::set_time    (scalar        time       )\n{\n  time_ = time;\n}\n\nstd::unique_ptr<scalar_field> ftle_map_generator::generate    ()\n{\n  auto ftle_map = std::make_unique<scalar_field>();\n  ftle_map->data.resize(boost::extents\n   [flow_map_->data.shape()[0]]\n   [flow_map_->data.shape()[1]]\n   [flow_map_->data.shape()[2]]);\n  ftle_map->offset  = flow_map_->offset ;\n  ftle_map->size    = flow_map_->size   ;\n  ftle_map->spacing = flow_map_->spacing;\n\n  auto gradient = flow_map_->gradient();\n  tbb::parallel_for(tbb::blocked_range3d<std::size_t>(0, gradient->data.shape()[0], 0, gradient->data.shape()[1], 0, gradient->data.shape()[2]), \n    [&] (const tbb::blocked_range3d<std::size_t>& index) {\n    for (auto x = index.pages().begin(), x_end = index.pages().end(); x < x_end; ++x) {\n    for (auto y = index.rows ().begin(), y_end = index.rows ().end(); y < y_end; ++y) {\n    for (auto z = index.cols ().begin(), z_end = index.cols ().end(); z < z_end; ++z) {\n      // Compute the spectral norm (Left Cauchy-Green tensor).\n      matrix3 spectral_norm = gradient->data[x][y][z].transpose().eval() * gradient->data[x][y][z];\n\n      // Compute eigenvalues and eigenvectors.\n      Eigen::SelfAdjointEigenSolver<matrix3> solver(spectral_norm);\n      auto eigenvalues  = solver.eigenvalues ();\n      auto eigenvectors = solver.eigenvectors();\n\n      // Compute FTLE.\n      pa::scalar value;\n      if (mode_ == mode::regular)\n        value = std::log(std::sqrt(eigenvalues.maxCoeff())) / std::abs(time_);\n      else if (mode_ == mode::fractional_anisotropy)\n        value = std::sqrt(0.5) * \n                std::sqrt(std::pow(eigenvalues[0] - eigenvalues[1], 2) + std::pow(eigenvalues[1] - eigenvalues[2], 2) + std::pow(eigenvalues[2] - eigenvalues[0], 2)) /\n                std::sqrt(std::pow(eigenvalues[0], 2) + std::pow(eigenvalues[1], 2) + std::pow(eigenvalues[2], 2));\n\n      ftle_map->data[x][y][z] = value;\n  }}}});\n\n  return ftle_map;\n}\n}", "meta": {"hexsha": "12282fdc4982394e56148cb8a8b4d5bb3a375a97", "size": 2331, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pa/source/stages/ftle_map_generator.cpp", "max_stars_repo_name": "acdemiralp/pars", "max_stars_repo_head_hexsha": "e78876de860a4cd2751e3a4e314e2a42a10ea10d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-03-12T18:20:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T12:04:14.000Z", "max_issues_repo_path": "pa/source/stages/ftle_map_generator.cpp", "max_issues_repo_name": "acdemiralp/pars", "max_issues_repo_head_hexsha": "e78876de860a4cd2751e3a4e314e2a42a10ea10d", "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": "pa/source/stages/ftle_map_generator.cpp", "max_forks_repo_name": "acdemiralp/pars", "max_forks_repo_head_hexsha": "e78876de860a4cd2751e3a4e314e2a42a10ea10d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-18T14:35:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-18T14:35:49.000Z", "avg_line_length": 38.2131147541, "max_line_length": 167, "alphanum_fraction": 0.6254826255, "num_tokens": 680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009503523291, "lm_q2_score": 0.7772998508568417, "lm_q1q2_score": 0.7111523722576482}}
{"text": "/*\n    mvee.cpp\n    Desc: minimum volume ellipsoid method\n    @author Chris Larson, Cornell University\n    @date (2017)\n    @version 1.0\n*/\n\n#include <iostream>\n#include <stdio.h>\n#include <stdlib.h>\n#include <fstream>\n#include <algorithm>\n#include <exception>\n#include <string>\n#include <map>\n#include <cmath>\n#include <vector>\n#include <Eigen/Dense>\n#include \"boost/chrono.hpp\"\n#include \"mvee.hpp\"\n#include \"utils.hpp\"\n\nusing namespace std;\nusing namespace Eigen;\nusing namespace mvee;\n\n\nMvee::Mvee() {}\n\n\nvoid Mvee::decompose(MatrixXd& A, VectorXd& s, MatrixXd& U, MatrixXd& V)\n{\n    JacobiSVD<MatrixXd> SVD(A, ComputeThinU | ComputeThinV);\n    s = SVD.singularValues();\n    V = SVD.matrixV();\n    U = SVD.matrixU();\n}\n\n\n/*\n    Khachiyan's ellipsoid method\n    @param X: matrix of data (n x d)\n    @param eps: approximation error (default: 0.001)\n    @param lmcoeff: Levenberg-Marquardt coefficient \n                    used for inverting ill-condditioned\n                    matrices. (default: 1e-8)\n    Ref: Khachiyan (1979)\n*/\nvoid Mvee::khachiyan(MatrixXd& data, double eps, double lmcoeff)\n{\n    // Khachiyan's algorithm\n    auto t0 = chrono::system_clock::now();    \n    iters = 0; \n    long double err = INFINITY; \n    double alpha;\n    int n = data.rows();\n    int d = data.cols();\n    MatrixXd X = data.transpose();\n    MatrixXd Q(X.rows() + 1, X.cols());\n    Q.row(0) = X.row(0);\n    Q.row(1) = X.row(1);\n    Q.row(2).setOnes();\n    VectorXd u = (1 / (double) n) * VectorXd::Ones(n);\n    VectorXd uhat = u;\n    MatrixXd G(d + 1, d + 1);\n    MatrixXd noiseye = MatrixXd::Identity(G.rows(), G.cols()) * lmcoeff;\n    VectorXd g(n);\n    double m; int i;\n    while (err > eps)\n    {\n        G = Q * u.asDiagonal() * Q.transpose() + noiseye;\n        g = (Q.transpose() * G.inverse() * Q).diagonal();\n        m = g.maxCoeff();\n        i = findIdx(g, m);\n        alpha = (m - d - 1) / ((d + 1) * (m - 1));\n        uhat = (1 - alpha) * u;\n        uhat(i) += alpha;\n        err = (uhat - u).norm();\n        u = uhat;\n        iters++;\n    }\n    time = chrono::duration<double>(\n        chrono::system_clock::now() - t0\n    ).count();\n    \n    // Decompose US^2U^T\n    MatrixXd E = (1 / (double) d) * (\n        X * u.asDiagonal() * X.transpose()\n        - (X * u) * (X * u).transpose()\n    ).inverse();\n    VectorXd x = X * u;\n    VectorXd s(d);\n    MatrixXd V(d, d);\n    MatrixXd U(d, d);\n    decompose(E, s, U, V);\n\n    // Cache result\n    _centroid = toStdVec(x, [](double z) { return z; });\n    _radii    = toStdVec(s, [](double z) { return 1 / sqrt(z); });\n    _pose     = toStdMat(V, [](double z) { return z; });\n}\n\n\n/*\n    Computes minimum volume ellipse enclosing data in file (path/to/file.csv)\n    @param file:string path to .csv file containing data\n    @param delim:char delimiter character\n    @param eps:double approximation error (default: 0.001)\n*/\nvoid Mvee::compute(string file, char delim, double eps, double lmcoeff)\n{\n    MatrixXd D = readCSV(file, delim);\n    khachiyan(D, eps, lmcoeff);\n}\n\n\n/*\n    Computes minimum volume ellipse enclosing data\n    @param data:vector<vector<double>> data (n x d)\n    @param delim:char delimiter character\n    @param eps:double approximation error (default: 0.001)\n*/\nvoid Mvee::compute(vector<vector<double>>& data, double eps, double lmcoeff)\n{\n    int rows = data.size();\n    int cols = data[0].size();\n    MatrixXd D(rows, cols);\n    for (int i=0; i<rows; i++)\n    {\n        for (int j=0; j<cols; j++)\n        {\n            D(i, j) = data[i][j];\n        }\n    }\n    khachiyan(D, eps, lmcoeff);\n}\n\n\n/*\n    Computes minimum volume ellipse enclosing data in file\n    @param file:Eigen::MatrixXd data (n x d)\n    @param delim:char delimiter character\n    @param eps:double approximation error (default: 0.001)\n*/\nvoid Mvee::compute(MatrixXd& data, double eps, double lmcoeff)\n{\n    khachiyan(data, eps, lmcoeff);\n}\n\n\n/*\n    Ellipse centroid\n    @return centroid:vector<double> (d x 1)\n    Note: Invoke mveeInstance.compute() prior to retrieving \n            the ellipse parameters.\n*/\nvector<double> Mvee::centroid()\n{\n    return _centroid;\n}\n\n\n/*\n    Ellipse radii\n    @return radii:vector<double> (d x 1)\n    Note: Invoke mveeInstance.compute() prior to retrieving \n            the ellipse parameters.\n*/\nvector<double> Mvee::radii()\n{\n    return _radii;\n}\n\n\n/*\n    Ellipse pose (rotation)\n    @return pose:vector<vector<double>> (d x d)\n    Note: Invoke mveeInstance.compute() prior to retrieving \n            the ellipse parameters.\n*/\nvector<vector<double>> Mvee::pose()\n{\n    return _pose;\n}\n\n\nMvee::~Mvee() {}\n", "meta": {"hexsha": "c0987f22777344b8fc1d4700a3c72ae5068db01c", "size": 4575, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mvee.cpp", "max_stars_repo_name": "chrislarson1/MVEE", "max_stars_repo_head_hexsha": "4a6aa32f05527dcb01c89a72803f0dcfd078d082", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-09-09T02:16:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-13T12:15:23.000Z", "max_issues_repo_path": "src/mvee.cpp", "max_issues_repo_name": "chrislarson1/MVEE", "max_issues_repo_head_hexsha": "4a6aa32f05527dcb01c89a72803f0dcfd078d082", "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/mvee.cpp", "max_forks_repo_name": "chrislarson1/MVEE", "max_forks_repo_head_hexsha": "4a6aa32f05527dcb01c89a72803f0dcfd078d082", "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.2063492063, "max_line_length": 77, "alphanum_fraction": 0.5971584699, "num_tokens": 1339, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.908617906830944, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.7111411479875128}}
{"text": "/**\n * \\file boost/numeric/ublasx/operation/logspace.hpp\n *\n * \\brief Logarithmically spaced vector\n *\n * Inspired by MATLAB's logspace function.\n *\n * <hr/>\n *\n * Copyright (c) 2015, Marco Guazzone\n * \n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n */\n\n#ifndef BOOST_NUMERIC_UBLASX_OPERATION_LOGSPACE_HPP\n#define BOOST_NUMERIC_UBLASX_OPERATION_LOGSPACE_HPP\n\n\n#include <boost/numeric/ublas/exception.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublasx/operation/element_pow.hpp>\n#include <boost/numeric/ublasx/operation/linspace.hpp>\n#include <cstddef>\n\n\nnamespace boost { namespace numeric { namespace ublasx {\n\nusing namespace ::boost::numeric::ublas;\n\n/**\n * \\brief Generates a logarithmically spaced vector.\n *\n * Generates \\a n values logarithmically equally spaced between `pow(base,a)`\n * and `pow(base,b)`.\n * Note, in case \\f$a<b\\f$, generates a decreasing sequence.\n *\n * Inspired by MATLAB's logspace function.\n *\n * \\param a The starting value of the logarithmically spaced sequence.\n * \\param b The final value of the logarithmically spaced sequence.\n * \\param n The number of values to generate\n * \\param base The base of the logarithm\n * \\return A vector of logarithmically spaced values in\n *  \\f$[\\mathrm{base}^a,\\mathrm{base}^b]\\f$; if `n=1`, returns `pow(base,b)`.\n *\n * The call `logspace(a,b,n)` is equivalent to the call:\n * ```\n *    base .^ linspace(a,b,n)\n * ```\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n */\ntemplate <typename ValueT>\nBOOST_UBLAS_INLINE\nvector<ValueT> logspace(ValueT a, ValueT b, std::size_t n = 100, ValueT base = 10)\n{\n\t// pre: n > 0\n\tBOOST_UBLAS_CHECK( n > 0,\n\t\t\t\t\t   bad_argument() );\n\t// pre: base > 0\n\tBOOST_UBLAS_CHECK( base > 0,\n\t\t\t\t\t   bad_argument() );\n\n\treturn element_pow(base, linspace(a, b, n));\n}\n\n}}} // Namespace boost::numeric::ublasx\n\n\n#endif // BOOST_NUMERIC_UBLASX_OPERATION_LOGSPACE_HPP\n", "meta": {"hexsha": "e08bf433c1a08825aebbc2a98be7fb11273b403d", "size": 2059, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/ublasx/operation/logspace.hpp", "max_stars_repo_name": "comcon1/boost-ublasx", "max_stars_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_stars_repo_licenses": ["BSL-1.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": "boost/numeric/ublasx/operation/logspace.hpp", "max_issues_repo_name": "comcon1/boost-ublasx", "max_issues_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_issues_repo_licenses": ["BSL-1.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": "boost/numeric/ublasx/operation/logspace.hpp", "max_forks_repo_name": "comcon1/boost-ublasx", "max_forks_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4533333333, "max_line_length": 82, "alphanum_fraction": 0.7134531326, "num_tokens": 572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681013541611, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.711037269565083}}
{"text": "//\n//  main.cpp\n//  NE - Normal Equations (for regression problem)\n//\n//  Created by Zhalgas Baibatyr on 1/15/16.\n//  Copyright \u00a9 2016 Zhalgas Baibatyr. All rights reserved.\n//\n\n/*\n\n    DEGREE ----- the degree of a polynomial in regression function\n    N_SAMPLES -- number of training samples\n    N_FEATURES - number of given input features\n    features --- input features, including intercept term (x\u2092 = 1)\n    target ----- target (output) values\n    params ----- parameters (weights) with initial values (zeros)\n    hypothesis - hypothesis function;\n\n*/\n\n#include <armadillo>\n\nusing namespace arma;\n\nint main()\n{\n    /* Loading initial data: */\n    mat initData;\n    initData.load(\"../data/regression1\", arma_ascii);\n\n    /* Initializing constants: */\n    const uword DEGREE = 1;\n    const uword N_SAMPLES  = initData.n_rows;\n    const uword N_FEATURES = initData.n_cols - 1;\n\n    /* Transforming input data using polynomial formula: */\n    mat features(N_SAMPLES, DEGREE * N_FEATURES + 1);\n    features.col(0) = ones<vec>(N_SAMPLES);\n    for (int i = 0; i < N_FEATURES; ++i)\n    {\n        for (int j = 1; j <= DEGREE; ++j)\n        {\n            features.col(i * DEGREE + j) = pow(initData.col(i), j);\n        }\n    }\n\n    /* Preparing other data: */\n    vec target = initData.col(initData.n_cols - 1);\n    vec params = zeros<vec>(features.n_cols);\n    vec hypothesis;\n\n    wall_clock timer;\n    double elapsedTime;\n    timer.tic();\n\n    /* Normal Equations is solved here: */\n    params = (features.t() * features).i() * features.t() * target;\n    hypothesis = features * params;\n\n    /* Measuring the performance of the algorithm: */\n    elapsedTime = timer.toc();\n    printf(\"Elapsed time: %f sec.\\n\\n\", elapsedTime);\n\n    mat outputData = join_rows(initData.cols(0, initData.n_cols - 2), hypothesis);\n    outputData.save(\"outputData\", arma_ascii);\n    hypothesis.save(\"hypothesis\", arma_ascii);\n    params.save(\"params\", arma_ascii);\n\n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "92e51d73a4b285bdbb74458872c0c72768435589", "size": 1968, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Regression/NE/main.cpp", "max_stars_repo_name": "presscorp/ML", "max_stars_repo_head_hexsha": "6a77577fbeb5e5e6a80bf404504634d5d47f191b", "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": "Regression/NE/main.cpp", "max_issues_repo_name": "presscorp/ML", "max_issues_repo_head_hexsha": "6a77577fbeb5e5e6a80bf404504634d5d47f191b", "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": "Regression/NE/main.cpp", "max_forks_repo_name": "presscorp/ML", "max_forks_repo_head_hexsha": "6a77577fbeb5e5e6a80bf404504634d5d47f191b", "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.7183098592, "max_line_length": 82, "alphanum_fraction": 0.6402439024, "num_tokens": 501, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7109122924746949}}
{"text": "//////////////////////////////////////////////////////////////////////////\r\n// Author       :  Ngo Tien Dat\r\n// Email        :  dat.ngo@epfl.ch\r\n// Organization :  EPFL\r\n// Purpose      :  Linear algebra library\r\n// Date         :  15 March 2012\r\n//////////////////////////////////////////////////////////////////////////\r\n\r\n#include \"LinearAlgebraUtils.h\"\r\n#include <armadillo>\r\n\r\nusing namespace arma;\r\n\r\nmat LinearAlgebraUtils::SolveWithConstraints (const mat& A, const mat& B, const mat& Ac, const mat& Bc)\r\n{\r\n  mat P, Q;\r\n  makeLinearParam(Ac, Bc, P, Q); // Given Ac * X = Bc, we represent X = PY + Q\r\n\r\n  // Solution of the least square problem\r\n  return P * solve(A*P, B-A*Q) + Q;\r\n}\r\n\r\nvoid LinearAlgebraUtils::makeLinearParam(const mat& A, const mat& B, mat& P, mat& Q)\r\n{\r\n  int m = A.n_rows;\r\n  int n = A.n_cols;\r\n\r\n  Q = solve(A, B);\r\n\r\n  // P is an orthonormal basis for the null space of A\r\n  mat U, V;\r\n  vec s;\r\n  svd(U, s, V, A);\r\n\r\n  double tolerance = std::max(m, n) * max(s) * math::eps();\r\n\r\n  uvec c = s > tolerance;\r\n  int nR = sum(c);\r\n\r\n  if (nR <= n-1)\r\n    P = V.cols(nR, n-1);\r\n  else\r\n    P.set_size(V.n_rows, 0);\r\n}\r\n\r\nmat LinearAlgebraUtils::PseudoInverse(const mat& A, double lambda)\r\n{\r\n  int m = A.n_rows;\r\n  int n = A.n_cols;\r\n\r\n  if (m > n)\r\n  {\r\n    if (lambda > 0)\r\n    {\r\n      return solve(A.t()*A + lambda*eye(n,n), A.t());    // solve(A, B) = A \\ B\r\n    }\r\n    else\r\n    {\r\n      return solve(A.t()*A, A.t());\r\n    }\r\n  } \r\n  else\r\n  {\r\n    if (lambda > 0)\r\n    {\r\n      // We want to compute this: A' / ( A*A' + lambda*eye(n,n) )\r\n      // Using relation: A / B = (B' \\ A')'\r\n      mat B = A*A.t() + lambda*eye(m,m);    // B' = B, since B is symmetric\r\n      mat C = solve(B, A);\r\n      \r\n      return C.t();\r\n    } \r\n    else\r\n    {\r\n      // We want to compute: A' / (A*A')\r\n      return solve(A*A.t(), A);\r\n    }\r\n  }\r\n}\r\n\r\nvec LinearAlgebraUtils::LeastSquareSolve(const mat& A, const vec& b, double lambda)\r\n{\r\n  if (lambda > 0)\r\n  {\r\n    int m = A.n_rows;\r\n    int n = A.n_cols;\r\n\r\n    if (m > n)      // Over-constrained system\r\n    {\r\n      mat AtA = A.t() * A + lambda * eye(n, n);\r\n      mat Atb = A.t() * b;\r\n\r\n      return solve(AtA, Atb);\r\n    }\r\n    else if (m < n)    // Under-constrained system\r\n    {\r\n      mat AAt = A * A.t() + lambda * eye(m, m);\r\n      vec y  = solve(AAt, b);      \r\n      \r\n      return A.t() * y;\r\n    }\r\n    else        // As many unknowns as equations\r\n    {\r\n      mat AlamdaI = A + lambda * eye(m, m);\r\n      return solve(AlamdaI, b);\r\n    }\r\n  }\r\n  else \r\n  {\r\n    return solve(A, b);\r\n  }\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "a1ae334b319bf9dbc77793e52faa1a323b760f7e", "size": 2594, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Linear/LinearAlgebraUtils.cpp", "max_stars_repo_name": "alibabach/deformabletracker", "max_stars_repo_head_hexsha": "1ef5631f7d91488da27abd83b468e2668670ad9d", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2015-09-07T17:51:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-14T08:48:11.000Z", "max_issues_repo_path": "src/Linear/LinearAlgebraUtils.cpp", "max_issues_repo_name": "alibabach/deformabletracker", "max_issues_repo_head_hexsha": "1ef5631f7d91488da27abd83b468e2668670ad9d", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-12-07T07:58:19.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-07T09:26:39.000Z", "max_forks_repo_path": "src/Linear/LinearAlgebraUtils.cpp", "max_forks_repo_name": "alibabach/deformabletracker", "max_forks_repo_head_hexsha": "1ef5631f7d91488da27abd83b468e2668670ad9d", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2016-08-10T05:16:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-30T20:13:31.000Z", "avg_line_length": 21.7983193277, "max_line_length": 104, "alphanum_fraction": 0.4637625289, "num_tokens": 794, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213691605412, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.7107826980480058}}
{"text": "\n#include <Eigen/Dense>\n\n#include <ceres/ceres.h>\n#include <ceres/rotation.h>\n#include <ceres/loss_function.h>\n#include <ceres/autodiff_cost_function.h>\n\n#include <sphericalsfm/so3.h>\n\n#include <sphericalsfm/rotation_averaging.h>\n\nnamespace sphericalsfm {\n\n    struct RotationError\n    {\n        RotationError( const Eigen::Matrix3d &_meas ) : meas(_meas) { }\n        \n        template <typename T>\n        bool operator()(const T* const r0,\n                        const T* const r1,\n                        T* residuals) const\n        {\n            Eigen::Matrix<T,3,3> R, R0, R1;\n            for ( int i = 0; i < 3; i++ )\n                for ( int j = 0; j < 3; j++ )\n                    R(i,j) = T(meas(i,j));\n            ceres::AngleAxisToRotationMatrix( r0, R0.data() );\n            ceres::AngleAxisToRotationMatrix( r1, R1.data() );\n            \n            Eigen::Matrix<T,3,3> cycle = (R1 * R0.transpose()) * R.transpose();\n            ceres::RotationMatrixToAngleAxis( cycle.data(), residuals );\n\n            return true;\n        }\n        \n        Eigen::Matrix3d meas;\n    };\n\n    void optimize_rotations( std::vector<Eigen::Matrix3d> &rotations, const std::vector<RelativeRotation> &relative_rotations )\n    {\n        std::vector<Eigen::Vector3d> data(rotations.size());\n        for ( int i = 0; i < rotations.size(); i++ ) data[i] = so3ln(rotations[i]);\n        \n        ceres::Problem problem;\n        ceres::LossFunction* loss_function = new ceres::SoftLOneLoss(0.03);\n        for ( int i = 0; i < relative_rotations.size(); i++ )\n        {\n            std::cout << relative_rotations[i].index0 << \"\\n\";\n            std::cout << relative_rotations[i].index1 << \"\\n\";\n            std::cout << relative_rotations[i].R << \"\\n\";\n            RotationError *error = new RotationError(relative_rotations[i].R);\n            ceres::CostFunction* cost_function = new ceres::AutoDiffCostFunction<RotationError, 3, 3, 3>(error);\n            problem.AddResidualBlock(cost_function,\n                loss_function,\n                data[relative_rotations[i].index0].data(),\n                data[relative_rotations[i].index1].data()\n            );\n        }\n    \n        ceres::Solver::Options options;\n        options.linear_solver_type = ceres::SPARSE_NORMAL_CHOLESKY;\n        options.minimizer_progress_to_stdout = true;\n        ceres::Solver::Summary summary;\n        ceres::Solve(options, &problem, &summary);\n        std::cout << summary.FullReport() << \"\\n\";\n        if ( summary.termination_type == ceres::FAILURE )\n        {\n            std::cout << \"error: ceres failed.\\n\";\n            exit(1);\n        }\n        \n        for ( int i = 0; i < rotations.size(); i++ ) rotations[i] = so3exp(data[i]);\n    }\n\n}\n", "meta": {"hexsha": "6ec150e1a42e22c9772e3451c7e66977744b429a", "size": 2719, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/rotation_averaging.cpp", "max_stars_repo_name": "jonathanventura/spherical-sfm", "max_stars_repo_head_hexsha": "0f0dafdd66641cebcb57cdb8a87b9ce466ab36eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2020-03-26T15:07:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-04T06:27:32.000Z", "max_issues_repo_path": "src/rotation_averaging.cpp", "max_issues_repo_name": "jonathanventura/spherical-sfm", "max_issues_repo_head_hexsha": "0f0dafdd66641cebcb57cdb8a87b9ce466ab36eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-07-09T06:32:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-09T07:26:47.000Z", "max_forks_repo_path": "src/rotation_averaging.cpp", "max_forks_repo_name": "jonathanventura/spherical-sfm", "max_forks_repo_head_hexsha": "0f0dafdd66641cebcb57cdb8a87b9ce466ab36eb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-08T20:30:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T20:30:46.000Z", "avg_line_length": 35.3116883117, "max_line_length": 127, "alphanum_fraction": 0.5564545789, "num_tokens": 703, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951643678382, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.7107482916348983}}
{"text": "#include <boost/random.hpp>\n#include <cmath>\n#include <iostream>\n\n#define mean 0.0\n#define sigma 1.0\n#define EPS 0.01\n#define SAMPLES 10000000\n\nusing namespace boost::random;\nusing namespace std;\n\nint main()\n{\n\tmt19937 rng(static_cast<unsigned int>(time(0)));\n\tnormal_distribution<double> dist(mean, sigma);\n\n\tcout << \"Generating numbers...\" << endl;\n\tint meanpoints = 0;\n\tint epoints = 0;\n\tfor (int i = 0; i < SAMPLES; i++)\n\t{\n\t\tdouble rnd = dist(rng);\n\t\tif (fabs(rnd - mean) < EPS)\n\t\t\tmeanpoints++;\n\t\tif ((fabs(rnd - mean - sqrt(2) * sigma) < EPS) ||\n\t\t\t(fabs(rnd - mean + sqrt(2) * sigma) < EPS))\n\t\t\tepoints++;\n\t}\n\n\tcout << \"Expected f(mean)/f(mean+sqrt(2)*sigma): \" << M_E << endl;\n\tcout << \"Computed: \" << meanpoints * 2.0 / epoints << endl;\n\n\treturn 0;\n}\n", "meta": {"hexsha": "65271da725e87d728387b9a356b71a26b53dca2a", "size": 761, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "Cpp SOURCE CODE/Boost/Random/gauss.cxx", "max_stars_repo_name": "DevJeffersonL/OPEN-SOURCE-", "max_stars_repo_head_hexsha": "8e650337ebab7608a4bdb5106df74e17b0e0e995", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-30T06:19:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T06:19:22.000Z", "max_issues_repo_path": "Cpp SOURCE CODE/Boost/Random/gauss.cxx", "max_issues_repo_name": "DevJeffersonL/OPEN-SOURCE-CODE", "max_issues_repo_head_hexsha": "8e650337ebab7608a4bdb5106df74e17b0e0e995", "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": "Cpp SOURCE CODE/Boost/Random/gauss.cxx", "max_forks_repo_name": "DevJeffersonL/OPEN-SOURCE-CODE", "max_forks_repo_head_hexsha": "8e650337ebab7608a4bdb5106df74e17b0e0e995", "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.1388888889, "max_line_length": 67, "alphanum_fraction": 0.6268068331, "num_tokens": 237, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237605, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.7107137112060645}}
{"text": "#ifndef STAN_MATH_PRIM_FUN_CONSTANTS_HPP\n#define STAN_MATH_PRIM_FUN_CONSTANTS_HPP\n\n#include <stan/math/prim/meta.hpp>\n#include <stan/math/prim/fun/inv.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <cmath>\n#include <limits>\n\nnamespace stan {\nnamespace math {\n\n// TODO(anyone) Use constexpr when moving to C++17\n\n/**\n * Return the base of the natural logarithm.\n *\n * @return Base of natural logarithm.\n */\ninline double e() { return boost::math::constants::e<double>(); }\n\n/**\n * Return the value of pi.\n *\n * @return Pi.\n */\ninline double pi() { return boost::math::constants::pi<double>(); }\n\n/**\n * Smallest positive value.\n */\nconst double EPSILON = std::numeric_limits<double>::epsilon();\n\n/**\n * Positive infinity.\n */\nconst double INFTY = std::numeric_limits<double>::infinity();\n\n/**\n * Negative infinity.\n */\nconst double NEGATIVE_INFTY = -INFTY;\n\n/**\n * (Quiet) not-a-number value.\n */\nconst double NOT_A_NUMBER = std::numeric_limits<double>::quiet_NaN();\n\n/**\n * Twice the value of \\f$ \\pi \\f$,\n * \\f$ 2\\pi \\f$.\n */\nconst double TWO_PI = 2.0 * pi();\n\n/**\n * The natural logarithm of 0,\n * \\f$ \\log 0 \\f$.\n */\nconst double LOG_ZERO = std::log(0.0);\n\n/**\n * The natural logarithm of machine precision \\f$ \\epsilon \\f$,\n * \\f$ \\log \\epsilon \\f$.\n */\nconst double LOG_EPSILON = std::log(EPSILON);\n\n/**\n * The natural logarithm of \\f$ \\pi \\f$,\n * \\f$ \\log \\pi \\f$.\n */\nconst double LOG_PI = std::log(pi());\n\n/**\n * The natural logarithm of 0.5,\n * \\f$ \\log 0.5 \\f$.\n */\nconst double LOG_HALF = std::log(0.5);\n\n/**\n * The natural logarithm of 2,\n * \\f$ \\log 2 \\f$.\n */\nconst double LOG_TWO = std::log(2.0);\n\n/**\n * The natural logarithm of 2 plus the natural logarithm of \\f$ \\pi \\f$,\n * \\f$ \\log(2\\pi) \\f$.\n */\nconst double LOG_TWO_PI = LOG_TWO + LOG_PI;\n\n/**\n * The value of one quarter the natural logarithm of \\f$ \\pi \\f$,\n * \\f$ \\log(\\pi) / 4 \\f$.\n */\nconst double LOG_PI_OVER_FOUR = 0.25 * LOG_PI;\n\n/**\n * The natural logarithm of the square root of \\f$ \\pi \\f$,\n * \\f$ \\log(sqrt{\\pi}) \\f$.\n */\nconst double LOG_SQRT_PI = std::log(std::sqrt(pi()));\n\n/**\n * The natural logarithm of 10,\n * \\f$ \\log 10 \\f$.\n */\nconst double LOG_TEN = std::log(10.0);\n\n/**\n * The value of the square root of 2,\n * \\f$ \\sqrt{2} \\f$.\n */\nconst double SQRT_TWO = std::sqrt(2.0);\n\n/**\n * The value of the square root of \\f$ \\pi \\f$,\n * \\f$ \\sqrt{\\pi} \\f$.\n */\nconst double SQRT_PI = std::sqrt(pi());\n\n/**\n * The value of the square root of \\f$ 2\\pi \\f$,\n * \\f$ \\sqrt{2\\pi} \\f$.\n */\nconst double SQRT_TWO_PI = std::sqrt(TWO_PI);\n\n/**\n * The square root of 2 divided by the square root of \\f$ \\pi \\f$,\n * \\f$ \\sqrt{2} / \\sqrt{\\pi} \\f$.\n */\nconst double SQRT_TWO_OVER_SQRT_PI = SQRT_TWO / SQRT_PI;\n\n/**\n * The value of 1 over the square root of 2,\n * \\f$ 1 / \\sqrt{2} \\f$.\n */\nconst double INV_SQRT_TWO = inv(SQRT_TWO);\n\n/**\n * The value of 1 over the square root of \\f$ \\pi \\f$,\n * \\f$ 1 / \\sqrt{\\pi} \\f$.\n */\nconst double INV_SQRT_PI = inv(SQRT_PI);\n\n/**\n * The value of 1 over the square root of \\f$ 2\\pi \\f$,\n * \\f$ 1 / \\sqrt{2\\pi} \\f$.\n */\nconst double INV_SQRT_TWO_PI = inv(SQRT_TWO_PI);\n\n/**\n * The value of 2 over the square root of \\f$ \\pi \\f$,\n * \\f$ 2 / \\sqrt{\\pi} \\f$.\n */\nconst double TWO_OVER_SQRT_PI = 2.0 / SQRT_PI;\n\n/**\n * The value of half the natural logarithm 2,\n * \\f$ \\log(2) / 2 \\f$.\n */\nconst double HALF_LOG_TWO = 0.5 * LOG_TWO;\n\n/**\n * The value of half the natural logarithm \\f$ 2\\pi \\f$,\n * \\f$ \\log(2\\pi) / 2 \\f$.\n */\nconst double HALF_LOG_TWO_PI = 0.5 * LOG_TWO_PI;\n\n/**\n * The value of minus the natural logarithm of the square root of \\f$ 2\\pi \\f$,\n * \\f$ -\\log(\\sqrt{2\\pi}) \\f$.\n */\nconst double NEG_LOG_SQRT_TWO_PI = -std::log(SQRT_TWO_PI);\n\n/**\n * Largest rate parameter allowed in Poisson RNG\n */\nconst double POISSON_MAX_RATE = std::pow(2.0, 30);\n\n/**\n * Return positive infinity.\n *\n * @return Positive infinity.\n */\ninline double positive_infinity() { return INFTY; }\n\n/**\n * Return negative infinity.\n *\n * @return Negative infinity.\n */\ninline double negative_infinity() { return NEGATIVE_INFTY; }\n\n/**\n * Return (quiet) not-a-number.\n *\n * @return Quiet not-a-number.\n */\ninline double not_a_number() { return NOT_A_NUMBER; }\n\n/**\n * Returns the difference between 1.0 and the next value\n * representable.\n *\n * @return Minimum positive number.\n */\ninline double machine_precision() { return EPSILON; }\n\n/**\n * Returns the natural logarithm of ten.\n *\n * @return Natural logarithm of ten.\n */\ninline double log10() { return LOG_TEN; }\n\n/**\n * Returns the square root of two.\n *\n * @return Square root of two.\n */\ninline double sqrt2() { return SQRT_TWO; }\n\n}  // namespace math\n}  // namespace stan\n\n#endif\n", "meta": {"hexsha": "8300edc0730105f841d9b0aa8288727d77590a25", "size": 4647, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/fun/constants.hpp", "max_stars_repo_name": "bayesmix-dev/math", "max_stars_repo_head_hexsha": "3616f7195adc95ef8e719a2af845d61102bc9272", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-14T14:33:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-14T14:33:37.000Z", "max_issues_repo_path": "stan/math/prim/fun/constants.hpp", "max_issues_repo_name": "bayesmix-dev/math", "max_issues_repo_head_hexsha": "3616f7195adc95ef8e719a2af845d61102bc9272", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-07-23T12:45:30.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-01T20:43:03.000Z", "max_forks_repo_path": "stan/math/prim/fun/constants.hpp", "max_forks_repo_name": "bayesmix-dev/math", "max_forks_repo_head_hexsha": "3616f7195adc95ef8e719a2af845d61102bc9272", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-10T12:55:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-10T12:55:07.000Z", "avg_line_length": 20.4713656388, "max_line_length": 79, "alphanum_fraction": 0.6285775769, "num_tokens": 1473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760038, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.7107137036808827}}
{"text": "/*!\n * @file matrix_coeff.hpp\n * @brief Contains implementation of diffusion coefficient.\n * @author Konrad Simon\n * @date August 2019\n */\n\n#ifndef INCLUDE_MATRIX_COEFF_HPP_\n#define INCLUDE_MATRIX_COEFF_HPP_\n\n// Deal.ii\n#include <deal.II/base/tensor_function.h>\n\n// STL\n#include <cmath>\n#include <fstream>\n\n// My Headers\n#include \"coefficients.h\"\n\nnamespace Coefficients\n{\nusing namespace dealii;\n\n/*!\n * @class MatrixCoeff\n * @brief Diffusion coefficient.\n *\n * Class implements a matrix valued diffusion coefficient.\n * This coefficient must be positive definite.\n */\ntemplate <int dim>\nclass MatrixCoeff : public TensorFunction<2,dim>\n{\npublic:\n\tMatrixCoeff ();\n\n\tvirtual Tensor<2, dim> value(const Point<dim> &point) const override;\n\tvirtual void value_list(const std::vector<Point<dim>> &points,\n\t\t\tstd::vector<Tensor<2,dim>>  &values) const override;\n\nprivate:\n\tconst int k = 21;\n\tconst double scale_factor = 0.9999999;\n\n\tconst double alpha = PI_D/3,\n\t\t\t\tbeta = PI_D/6,\n\t\t\t\tgamma = PI_D/4;\n\tTensor<2,dim> rot;\n};\n\n\ntemplate <>\nMatrixCoeff<2>::MatrixCoeff ()\n:\nTensorFunction<2,2> ()\n{\n\trot[0][0] = cos(alpha);\n\trot[0][1] = sin(alpha);\n\trot[1][0] = -sin(alpha);\n\trot[1][1] = cos(alpha);\n}\n\n\ntemplate <>\nMatrixCoeff<3>::MatrixCoeff ()\n:\nTensorFunction<2,3> ()\n{\n\trot[0][0] = cos(alpha)*cos(gamma) - sin(alpha)*cos(beta)*sin(gamma);\n\trot[0][1] = -cos(alpha)*sin(gamma) - sin(alpha)*cos(beta)*cos(gamma);\n\trot[0][2] = sin(alpha)*sin(beta);\n\trot[1][0] = sin(alpha)*cos(gamma) + cos(alpha)*cos(beta)*sin(gamma);\n\trot[1][1] = -sin(alpha)*sin(gamma) + cos(alpha)*cos(beta)*cos(gamma);\n\trot[1][2] = -cos(alpha)*sin(beta);\n\trot[2][0] = sin(beta)*sin(gamma);\n\trot[2][1] = sin(beta)*cos(gamma);\n\trot[2][2] = cos(beta);\n}\n\n\ntemplate <int dim>\nTensor<2, dim>\nMatrixCoeff<dim>::value(const Point<dim> &p) const\n{\n\tTensor<2, dim> value;\n\tvalue.clear();\n\n\tfor (unsigned int d=0; d<dim; ++d)\n\t{\n\t\tvalue[d][d] = 1.0 * (1.0 - scale_factor*(\n\t\t\t\t0.5*sin(2*PI_D*k*p(0))\n\t\t\t\t+ 0.5*sin(2*PI_D*k*p(1))\n\t\t\t\t) ); /* Must be positive definite. */\n\t}\n\n\tvalue = rot * value * transpose (rot);\n\n\treturn value;\n}\n\n\ntemplate <int dim>\nvoid\nMatrixCoeff<dim>::value_list(const std::vector<Point<dim>> &points,\n\t\tstd::vector<Tensor<2,dim>>  &values) const\n{\n\tAssert (points.size() == values.size(),\n\t\t\tExcDimensionMismatch (points.size(), values.size()) );\n\n\tfor ( unsigned int p=0; p<points.size(); ++p)\n\t{\n\t\tvalues[p].clear();\n\n\t\tfor (unsigned int d=0; d<dim; ++d)\n\t\t{\n\t\t\tvalues[p][d][d] = 1.0 * (1.0 - scale_factor*(\n\t\t\t\t\t0.5*sin(2*PI_D*k*points[p](0))\n\t\t\t\t\t+ 0.5*sin(2*PI_D*k*points[p](1))\n\t\t\t\t\t) ); /* Must be positive definite. */\n\t\t}\n\n\t\tvalues[p] = rot * values[p] * transpose (rot);\n\t}\n}\n\n} // end namespace Coefficients\n\n#endif /* INCLUDE_MATRIX_COEFF_HPP_ */\n", "meta": {"hexsha": "ba5be4c552267abd4eac48fe087be5df7e84ee88", "size": 2739, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/matrix_coeff.hpp", "max_stars_repo_name": "konsim83/deal.ii-9.1.1_SS19_demo_elliptic_multiscale_fem", "max_stars_repo_head_hexsha": "cde9eabcbdee1271f4d36ce67d9168b65251ad32", "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/matrix_coeff.hpp", "max_issues_repo_name": "konsim83/deal.ii-9.1.1_SS19_demo_elliptic_multiscale_fem", "max_issues_repo_head_hexsha": "cde9eabcbdee1271f4d36ce67d9168b65251ad32", "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": "include/matrix_coeff.hpp", "max_forks_repo_name": "konsim83/deal.ii-9.1.1_SS19_demo_elliptic_multiscale_fem", "max_forks_repo_head_hexsha": "cde9eabcbdee1271f4d36ce67d9168b65251ad32", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-10-19T15:42:43.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-19T15:42:43.000Z", "avg_line_length": 21.0692307692, "max_line_length": 70, "alphanum_fraction": 0.6433004746, "num_tokens": 869, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797003640646, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.7107136924796822}}
{"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 <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/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\n // To stress test, set global_seed = 0, global_size = huge.\n static const constexpr size_t global_seed = 0;\n static const constexpr size_t global_size = 128;\n\ntemplate<class T>\nstd::vector<T> generate_random_vector(size_t size, size_t seed)\n{\n    if (seed == 0)\n    {\n        std::random_device rd;\n        seed = rd();\n    }\n    std::vector<T> v(size);\n\n    std::mt19937 gen(seed);\n\n    if constexpr (std::is_floating_point<T>::value)\n    {\n        std::normal_distribution<T> dis(0, 1);\n        for (size_t i = 0; i < v.size(); ++i)\n        {\n         v[i] = dis(gen);\n        }\n        return v;\n    }\n    else if constexpr (std::is_integral<T>::value)\n    {\n        // Rescaling by larger than 2 is UB!\n        std::uniform_int_distribution<T> dis(std::numeric_limits<T>::lowest()/2, (std::numeric_limits<T>::max)()/2);\n        for (size_t i = 0; i < v.size(); ++i)\n        {\n         v[i] = dis(gen);\n        }\n        return v;\n    }\n    else if constexpr (boost::is_complex<T>::value)\n    {\n        std::normal_distribution<typename T::value_type> dis(0, 1);\n        for (size_t i = 0; i < v.size(); ++i)\n        {\n            v[i] = {dis(gen), dis(gen)};\n        }\n        return v;\n    }\n    else if constexpr (boost::multiprecision::number_category<T>::value == boost::multiprecision::number_kind_complex)\n    {\n        std::normal_distribution<long double> dis(0, 1);\n        for (size_t i = 0; i < v.size(); ++i)\n        {\n            v[i] = {dis(gen), dis(gen)};\n        }\n        return v;\n    }\n    else if constexpr (boost::multiprecision::number_category<T>::value == boost::multiprecision::number_kind_floating_point)\n    {\n        std::normal_distribution<long double> dis(0, 1);\n        for (size_t i = 0; i < v.size(); ++i)\n        {\n            v[i] = dis(gen);\n        }\n        return v;\n    }\n    else\n    {\n        BOOST_ASSERT_MSG(false, \"Could not identify type for random vector generation.\");\n        return v;\n    }\n}\n\n\ntemplate<class Z>\nvoid test_integer_mean()\n{\n    double tol = 100*std::numeric_limits<double>::epsilon();\n    std::vector<Z> v{1,2,3,4,5};\n    double mu = boost::math::statistics::mean(v);\n    BOOST_TEST(abs(mu - 3) < tol);\n\n    // Work with std::array?\n    std::array<Z, 5> w{1,2,3,4,5};\n    mu = boost::math::statistics::mean(w);\n    BOOST_TEST(abs(mu - 3) < tol);\n\n    v = generate_random_vector<Z>(global_size, global_seed);\n    Z scale = 2;\n\n    double m1 = scale*boost::math::statistics::mean(v);\n    for (auto & x : v)\n    {\n        x *= scale;\n    }\n    double m2 = boost::math::statistics::mean(v);\n    BOOST_TEST(abs(m1 - m2) < tol*abs(m1));\n}\n\ntemplate<class RandomAccessContainer>\nauto naive_mean(RandomAccessContainer const & v)\n{\n    typename RandomAccessContainer::value_type sum = 0;\n    for (auto & x : v)\n    {\n        sum += x;\n    }\n    return sum/v.size();\n}\n\ntemplate<class Real>\nvoid test_mean()\n{\n    Real tol = std::numeric_limits<Real>::epsilon();\n    std::vector<Real> v{1,2,3,4,5};\n    Real mu = boost::math::statistics::mean(v.begin(), v.end());\n    BOOST_TEST(abs(mu - 3) < tol);\n\n    // Does range call work?\n    mu = boost::math::statistics::mean(v);\n    BOOST_TEST(abs(mu - 3) < tol);\n\n    // Can we successfully average only part of the vector?\n    mu = boost::math::statistics::mean(v.begin(), v.begin() + 3);\n    BOOST_TEST(abs(mu - 2) < tol);\n\n    // Does it work when we const qualify?\n    mu = boost::math::statistics::mean(v.cbegin(), v.cend());\n    BOOST_TEST(abs(mu - 3) < tol);\n\n    // Does it work for std::array?\n    std::array<Real, 7> u{1,2,3,4,5,6,7};\n    mu = boost::math::statistics::mean(u.begin(), u.end());\n    BOOST_TEST(abs(mu - 4) < 10*tol);\n\n    // Does it work for a forward iterator?\n    std::forward_list<Real> l{1,2,3,4,5,6,7};\n    mu = boost::math::statistics::mean(l.begin(), l.end());\n    BOOST_TEST(abs(mu - 4) < tol);\n\n    // Does it work with ublas vectors?\n    boost::numeric::ublas::vector<Real> w(7);\n    for (size_t i = 0; i < w.size(); ++i)\n    {\n        w[i] = i+1;\n    }\n    mu = boost::math::statistics::mean(w.cbegin(), w.cend());\n    BOOST_TEST(abs(mu - 4) < tol);\n\n    v = generate_random_vector<Real>(global_size, global_seed);\n    Real scale = 2;\n    Real m1 = scale*boost::math::statistics::mean(v);\n    for (auto & x : v)\n    {\n        x *= scale;\n    }\n    Real m2 = boost::math::statistics::mean(v);\n    BOOST_TEST(abs(m1 - m2) < tol*abs(m1));\n\n    // Stress test:\n    for (size_t i = 1; i < 30; ++i)\n    {\n        v = generate_random_vector<Real>(i, 12803);\n        auto naive_ = naive_mean(v);\n        auto higham_ = boost::math::statistics::mean(v);\n        if (abs(higham_ - naive_) >= 100*tol*abs(naive_))\n        {\n            std::cout << std::hexfloat;\n            std::cout << \"Terms = \" << v.size() << \"\\n\";\n            std::cout << \"higham = \" << higham_ << \"\\n\";\n            std::cout << \"naive_ = \" << naive_ << \"\\n\";\n        }\n        BOOST_TEST(abs(higham_ - naive_) < 100*tol*abs(naive_));\n    }\n\n}\n\ntemplate<class Complex>\nvoid test_complex_mean()\n{\n    typedef typename Complex::value_type Real;\n    Real tol = std::numeric_limits<Real>::epsilon();\n    std::vector<Complex> v{{0,1},{0,2},{0,3},{0,4},{0,5}};\n    auto mu = boost::math::statistics::mean(v.begin(), v.end());\n    BOOST_TEST(abs(mu.imag() - 3) < tol);\n    BOOST_TEST(abs(mu.real()) < tol);\n\n    // Does range work?\n    mu = boost::math::statistics::mean(v);\n    BOOST_TEST(abs(mu.imag() - 3) < tol);\n    BOOST_TEST(abs(mu.real()) < tol);\n}\n\ntemplate<class Real>\nvoid test_variance()\n{\n    Real tol = std::numeric_limits<Real>::epsilon();\n    std::vector<Real> v{1,1,1,1,1,1};\n    Real sigma_sq = boost::math::statistics::variance(v.begin(), v.end());\n    BOOST_TEST(abs(sigma_sq) < tol);\n\n    sigma_sq = boost::math::statistics::variance(v);\n    BOOST_TEST(abs(sigma_sq) < tol);\n\n    Real s_sq = boost::math::statistics::sample_variance(v);\n    BOOST_TEST(abs(s_sq) < tol);\n\n    std::vector<Real> u{1};\n    sigma_sq = boost::math::statistics::variance(u.cbegin(), u.cend());\n    BOOST_TEST(abs(sigma_sq) < tol);\n\n    std::array<Real, 8> w{0,1,0,1,0,1,0,1};\n    sigma_sq = boost::math::statistics::variance(w.begin(), w.end());\n    BOOST_TEST(abs(sigma_sq - 1.0/4.0) < tol);\n\n    sigma_sq = boost::math::statistics::variance(w);\n    BOOST_TEST(abs(sigma_sq - 1.0/4.0) < tol);\n\n    std::forward_list<Real> l{0,1,0,1,0,1,0,1};\n    sigma_sq = boost::math::statistics::variance(l.begin(), l.end());\n    BOOST_TEST(abs(sigma_sq - 1.0/4.0) < tol);\n\n    v = generate_random_vector<Real>(global_size, global_seed);\n    Real scale = 2;\n    Real m1 = scale*scale*boost::math::statistics::variance(v);\n    for (auto & x : v)\n    {\n        x *= scale;\n    }\n    Real m2 = boost::math::statistics::variance(v);\n    BOOST_TEST(abs(m1 - m2) < tol*abs(m1));\n\n    // Wikipedia example for a variance of N sided die:\n    // https://en.wikipedia.org/wiki/Variance\n    for (size_t j = 16; j < 2048; j *= 2)\n    {\n        v.resize(1024);\n        Real n = v.size();\n        for (size_t i = 0; i < v.size(); ++i)\n        {\n            v[i] = i + 1;\n        }\n\n        sigma_sq = boost::math::statistics::variance(v);\n\n        BOOST_TEST(abs(sigma_sq - (n*n-1)/Real(12)) <= tol*sigma_sq);\n    }\n\n}\n\ntemplate<class Z>\nvoid test_integer_variance()\n{\n    double tol = std::numeric_limits<double>::epsilon();\n    std::vector<Z> v{1,1,1,1,1,1};\n    double sigma_sq = boost::math::statistics::variance(v);\n    BOOST_TEST(abs(sigma_sq) < tol);\n\n    std::forward_list<Z> l{0,1,0,1,0,1,0,1};\n    sigma_sq = boost::math::statistics::variance(l.begin(), l.end());\n    BOOST_TEST(abs(sigma_sq - 1.0/4.0) < tol);\n\n    v = generate_random_vector<Z>(global_size, global_seed);\n    Z scale = 2;\n    double m1 = scale*scale*boost::math::statistics::variance(v);\n    for (auto & x : v)\n    {\n        x *= scale;\n    }\n    double m2 = boost::math::statistics::variance(v);\n    BOOST_TEST(abs(m1 - m2) < tol*abs(m1));\n}\n\ntemplate<class Z>\nvoid test_integer_skewness()\n{\n    double tol = std::numeric_limits<double>::epsilon();\n    std::vector<Z> v{1,1,1};\n    double skew = boost::math::statistics::skewness(v);\n    BOOST_TEST(abs(skew) < tol);\n\n    // Dataset is symmetric about the mean:\n    v = {1,2,3,4,5};\n    skew = boost::math::statistics::skewness(v);\n    BOOST_TEST(abs(skew) < tol);\n\n    v = {0,0,0,0,5};\n    // mu = 1, sigma^2 = 4, sigma = 2, skew = 3/2\n    skew = boost::math::statistics::skewness(v);\n    BOOST_TEST(abs(skew - 3.0/2.0) < tol);\n\n    std::forward_list<Z> v2{0,0,0,0,5};\n    skew = boost::math::statistics::skewness(v);\n    BOOST_TEST(abs(skew - 3.0/2.0) < tol);\n\n\n    v = generate_random_vector<Z>(global_size, global_seed);\n    Z scale = 2;\n    double m1 = boost::math::statistics::skewness(v);\n    for (auto & x : v)\n    {\n        x *= scale;\n    }\n    double m2 = boost::math::statistics::skewness(v);\n    BOOST_TEST(abs(m1 - m2) < tol*abs(m1));\n\n}\n\ntemplate<class Real>\nvoid test_skewness()\n{\n    Real tol = std::numeric_limits<Real>::epsilon();\n    std::vector<Real> v{1,1,1};\n    Real skew = boost::math::statistics::skewness(v);\n    BOOST_TEST(abs(skew) < tol);\n\n    // Dataset is symmetric about the mean:\n    v = {1,2,3,4,5};\n    skew = boost::math::statistics::skewness(v);\n    BOOST_TEST(abs(skew) < tol);\n\n    v = {0,0,0,0,5};\n    // mu = 1, sigma^2 = 4, sigma = 2, skew = 3/2\n    skew = boost::math::statistics::skewness(v);\n    BOOST_TEST(abs(skew - Real(3)/Real(2)) < tol);\n\n    std::array<Real, 5> w1{0,0,0,0,5};\n    skew = boost::math::statistics::skewness(w1);\n    BOOST_TEST(abs(skew - Real(3)/Real(2)) < tol);\n\n    std::forward_list<Real> w2{0,0,0,0,5};\n    skew = boost::math::statistics::skewness(w2);\n    BOOST_TEST(abs(skew - Real(3)/Real(2)) < tol);\n\n    v = generate_random_vector<Real>(global_size, global_seed);\n    Real scale = 2;\n    Real m1 = boost::math::statistics::skewness(v);\n    for (auto & x : v)\n    {\n        x *= scale;\n    }\n    Real m2 = boost::math::statistics::skewness(v);\n    BOOST_TEST(abs(m1 - m2) < tol*abs(m1));\n}\n\ntemplate<class Real>\nvoid test_kurtosis()\n{\n    Real tol = std::numeric_limits<Real>::epsilon();\n    std::vector<Real> v{1,1,1};\n    Real kurt = boost::math::statistics::kurtosis(v);\n    BOOST_TEST(abs(kurt) < tol);\n\n    v = {1,2,3,4,5};\n    // mu =1, sigma^2 = 2, kurtosis = 17/10\n    kurt = boost::math::statistics::kurtosis(v);\n    BOOST_TEST(abs(kurt - Real(17)/Real(10)) < 10*tol);\n\n    v = {0,0,0,0,5};\n    // mu = 1, sigma^2 = 4, sigma = 2, skew = 3/2, kurtosis = 13/4\n    kurt = boost::math::statistics::kurtosis(v);\n    BOOST_TEST(abs(kurt - Real(13)/Real(4)) < tol);\n\n    std::array<Real, 5> v1{0,0,0,0,5};\n    kurt = boost::math::statistics::kurtosis(v1);\n    BOOST_TEST(abs(kurt - Real(13)/Real(4)) < tol);\n\n    std::forward_list<Real> v2{0,0,0,0,5};\n    kurt = boost::math::statistics::kurtosis(v2);\n    BOOST_TEST(abs(kurt - Real(13)/Real(4)) < tol);\n\n    std::vector<Real> v3(10000);\n    std::mt19937 gen(42);\n    std::normal_distribution<long double> dis(0, 1);\n    for (size_t i = 0; i < v3.size(); ++i) {\n        v3[i] = dis(gen);\n    }\n    kurt = boost::math::statistics::kurtosis(v3);\n    BOOST_TEST(abs(kurt - 3) < 0.1);\n\n    std::uniform_real_distribution<long double> udis(-1, 3);\n    for (size_t i = 0; i < v3.size(); ++i) {\n        v3[i] = udis(gen);\n    }\n    auto excess_kurtosis = boost::math::statistics::excess_kurtosis(v3);\n    BOOST_TEST(abs(excess_kurtosis + 6.0/5.0) < 0.2);\n\n    v = generate_random_vector<Real>(global_size, global_seed);\n    Real scale = 2;\n    Real m1 = boost::math::statistics::kurtosis(v);\n    for (auto & x : v)\n    {\n        x *= scale;\n    }\n    Real m2 = boost::math::statistics::kurtosis(v);\n    BOOST_TEST(abs(m1 - m2) < tol*abs(m1));\n\n    // This test only passes when there are a large number of samples.\n    // Otherwise, the distribution doesn't generate enough outliers to give,\n    // or generates too many, giving pretty wildly different values of kurtosis on different runs.\n    // However, by kicking up the samples to 1,000,000, I got very close to 6 for the excess kurtosis on every run.\n    // The CI system, however, would die on a million long doubles.\n    //v3.resize(1000000);\n    //std::exponential_distribution<long double> edis(0.1);\n    //for (size_t i = 0; i < v3.size(); ++i) {\n    //    v3[i] = edis(gen);\n    //}\n    //excess_kurtosis = boost::math::statistics::kurtosis(v3) - 3;\n    //BOOST_TEST(abs(excess_kurtosis - 6.0) < 0.2);\n}\n\ntemplate<class Z>\nvoid test_integer_kurtosis()\n{\n    double tol = std::numeric_limits<double>::epsilon();\n    std::vector<Z> v{1,1,1};\n    double kurt = boost::math::statistics::kurtosis(v);\n    BOOST_TEST(abs(kurt) < tol);\n\n    v = {1,2,3,4,5};\n    // mu =1, sigma^2 = 2, kurtosis = 17/10\n    kurt = boost::math::statistics::kurtosis(v);\n    BOOST_TEST(abs(kurt - 17.0/10.0) < 10*tol);\n\n    v = {0,0,0,0,5};\n    // mu = 1, sigma^2 = 4, sigma = 2, skew = 3/2, kurtosis = 13/4\n    kurt = boost::math::statistics::kurtosis(v);\n    BOOST_TEST(abs(kurt - 13.0/4.0) < tol);\n\n    v = generate_random_vector<Z>(global_size, global_seed);\n    Z scale = 2;\n    double m1 = boost::math::statistics::kurtosis(v);\n    for (auto & x : v)\n    {\n        x *= scale;\n    }\n    double m2 = boost::math::statistics::kurtosis(v);\n    BOOST_TEST(abs(m1 - m2) < tol*abs(m1));\n}\n\ntemplate<class Real>\nvoid test_first_four_moments()\n{\n    Real tol = 10*std::numeric_limits<Real>::epsilon();\n    std::vector<Real> v{1,1,1};\n    auto [M1_1, M2_1, M3_1, M4_1] = boost::math::statistics::first_four_moments(v);\n    BOOST_TEST(abs(M1_1 - 1) < tol);\n    BOOST_TEST(abs(M2_1) < tol);\n    BOOST_TEST(abs(M3_1) < tol);\n    BOOST_TEST(abs(M4_1) < tol);\n\n    v = {1, 2, 3, 4, 5};\n    auto [M1_2, M2_2, M3_2, M4_2] = boost::math::statistics::first_four_moments(v);\n    BOOST_TEST(abs(M1_2 - 3) < tol);\n    BOOST_TEST(abs(M2_2 - 2) < tol);\n    BOOST_TEST(abs(M3_2) < tol);\n    BOOST_TEST(abs(M4_2 - Real(34)/Real(5)) < tol);\n}\n\ntemplate<class Real>\nvoid test_median()\n{\n    std::mt19937 g(12);\n    std::vector<Real> v{1,2,3,4,5,6,7};\n\n    Real m = boost::math::statistics::median(v.begin(), v.end());\n    BOOST_TEST_EQ(m, 4);\n\n    std::shuffle(v.begin(), v.end(), g);\n    // Does range call work?\n    m = boost::math::statistics::median(v);\n    BOOST_TEST_EQ(m, 4);\n\n    v = {1,2,3,3,4,5};\n    m = boost::math::statistics::median(v.begin(), v.end());\n    BOOST_TEST_EQ(m, 3);\n    std::shuffle(v.begin(), v.end(), g);\n    m = boost::math::statistics::median(v.begin(), v.end());\n    BOOST_TEST_EQ(m, 3);\n\n    v = {1};\n    m = boost::math::statistics::median(v.begin(), v.end());\n    BOOST_TEST_EQ(m, 1);\n\n    v = {1,1};\n    m = boost::math::statistics::median(v.begin(), v.end());\n    BOOST_TEST_EQ(m, 1);\n\n    v = {2,4};\n    m = boost::math::statistics::median(v.begin(), v.end());\n    BOOST_TEST_EQ(m, 3);\n\n    v = {1,1,1};\n    m = boost::math::statistics::median(v.begin(), v.end());\n    BOOST_TEST_EQ(m, 1);\n\n    v = {1,2,3};\n    m = boost::math::statistics::median(v.begin(), v.end());\n    BOOST_TEST_EQ(m, 2);\n    std::shuffle(v.begin(), v.end(), g);\n    m = boost::math::statistics::median(v.begin(), v.end());\n    BOOST_TEST_EQ(m, 2);\n\n    // Does it work with std::array?\n    std::array<Real, 3> w{1,2,3};\n    m = boost::math::statistics::median(w);\n    BOOST_TEST_EQ(m, 2);\n\n    // Does it work with ublas?\n    boost::numeric::ublas::vector<Real> w1(3);\n    w1[0] = 1;\n    w1[1] = 2;\n    w1[2] = 3;\n    m = boost::math::statistics::median(w);\n    BOOST_TEST_EQ(m, 2);\n}\n\ntemplate<class Real>\nvoid test_median_absolute_deviation()\n{\n    std::vector<Real> v{-1, 2, -3, 4, -5, 6, -7};\n\n    Real m = boost::math::statistics::median_absolute_deviation(v.begin(), v.end(), 0);\n    BOOST_TEST_EQ(m, 4);\n\n    std::mt19937 g(12);\n    std::shuffle(v.begin(), v.end(), g);\n    m = boost::math::statistics::median_absolute_deviation(v, 0);\n    BOOST_TEST_EQ(m, 4);\n\n    v = {1, -2, -3, 3, -4, -5};\n    m = boost::math::statistics::median_absolute_deviation(v.begin(), v.end(), 0);\n    BOOST_TEST_EQ(m, 3);\n    std::shuffle(v.begin(), v.end(), g);\n    m = boost::math::statistics::median_absolute_deviation(v.begin(), v.end(), 0);\n    BOOST_TEST_EQ(m, 3);\n\n    v = {-1};\n    m = boost::math::statistics::median_absolute_deviation(v.begin(), v.end(), 0);\n    BOOST_TEST_EQ(m, 1);\n\n    v = {-1, 1};\n    m = boost::math::statistics::median_absolute_deviation(v.begin(), v.end(), 0);\n    BOOST_TEST_EQ(m, 1);\n    // The median is zero, so coincides with the default:\n    m = boost::math::statistics::median_absolute_deviation(v.begin(), v.end());\n    BOOST_TEST_EQ(m, 1);\n\n    m = boost::math::statistics::median_absolute_deviation(v);\n    BOOST_TEST_EQ(m, 1);\n\n\n    v = {2, -4};\n    m = boost::math::statistics::median_absolute_deviation(v.begin(), v.end(), 0);\n    BOOST_TEST_EQ(m, 3);\n\n    v = {1, -1, 1};\n    m = boost::math::statistics::median_absolute_deviation(v.begin(), v.end(), 0);\n    BOOST_TEST_EQ(m, 1);\n\n    v = {1, 2, -3};\n    m = boost::math::statistics::median_absolute_deviation(v.begin(), v.end(), 0);\n    BOOST_TEST_EQ(m, 2);\n    std::shuffle(v.begin(), v.end(), g);\n    m = boost::math::statistics::median_absolute_deviation(v.begin(), v.end(), 0);\n    BOOST_TEST_EQ(m, 2);\n\n    std::array<Real, 3> w{1, 2, -3};\n    m = boost::math::statistics::median_absolute_deviation(w, 0);\n    BOOST_TEST_EQ(m, 2);\n\n    // boost.ublas vector?\n    boost::numeric::ublas::vector<Real> u(6);\n    u[0] = 1;\n    u[1] = 2;\n    u[2] = -3;\n    u[3] = 1;\n    u[4] = 2;\n    u[5] = -3;\n    m = boost::math::statistics::median_absolute_deviation(u, 0);\n    BOOST_TEST_EQ(m, 2);\n}\n\n\ntemplate<class Real>\nvoid test_sample_gini_coefficient()\n{\n    Real tol = std::numeric_limits<Real>::epsilon();\n    std::vector<Real> v{1,0,0};\n    Real gini = boost::math::statistics::sample_gini_coefficient(v.begin(), v.end());\n    BOOST_TEST(abs(gini - 1) < tol);\n\n    gini = boost::math::statistics::sample_gini_coefficient(v);\n    BOOST_TEST(abs(gini - 1) < tol);\n\n    v[0] = 1;\n    v[1] = 1;\n    v[2] = 1;\n    gini = boost::math::statistics::sample_gini_coefficient(v.begin(), v.end());\n    BOOST_TEST(abs(gini) < tol);\n\n    v[0] = 0;\n    v[1] = 0;\n    v[2] = 0;\n    gini = boost::math::statistics::sample_gini_coefficient(v.begin(), v.end());\n    BOOST_TEST(abs(gini) < tol);\n\n    std::array<Real, 3> w{0,0,0};\n    gini = boost::math::statistics::sample_gini_coefficient(w);\n    BOOST_TEST(abs(gini) < tol);\n}\n\n\ntemplate<class Real>\nvoid test_gini_coefficient()\n{\n    Real tol = std::numeric_limits<Real>::epsilon();\n    std::vector<Real> v{1,0,0};\n    Real gini = boost::math::statistics::gini_coefficient(v.begin(), v.end());\n    Real expected = Real(2)/Real(3);\n    BOOST_TEST(abs(gini - expected) < tol);\n\n    gini = boost::math::statistics::gini_coefficient(v);\n    BOOST_TEST(abs(gini - expected) < tol);\n\n    v[0] = 1;\n    v[1] = 1;\n    v[2] = 1;\n    gini = boost::math::statistics::gini_coefficient(v.begin(), v.end());\n    BOOST_TEST(abs(gini) < tol);\n\n    v[0] = 0;\n    v[1] = 0;\n    v[2] = 0;\n    gini = boost::math::statistics::gini_coefficient(v.begin(), v.end());\n    BOOST_TEST(abs(gini) < tol);\n\n    std::array<Real, 3> w{0,0,0};\n    gini = boost::math::statistics::gini_coefficient(w);\n    BOOST_TEST(abs(gini) < tol);\n\n    boost::numeric::ublas::vector<Real> w1(3);\n    w1[0] = 1;\n    w1[1] = 1;\n    w1[2] = 1;\n    gini = boost::math::statistics::gini_coefficient(w1);\n    BOOST_TEST(abs(gini) < tol);\n\n    std::mt19937 gen(18);\n    // Gini coefficient for a uniform distribution is (b-a)/(3*(b+a));\n    std::uniform_real_distribution<long double> dis(0, 3);\n    expected = (dis.b() - dis.a())/(3*(dis.b()+ dis.a()));\n    v.resize(1024);\n    for(size_t i = 0; i < v.size(); ++i)\n    {\n        v[i] = dis(gen);\n    }\n    gini = boost::math::statistics::gini_coefficient(v);\n    BOOST_TEST(abs(gini - expected) < 0.01);\n\n}\n\ntemplate<class Z>\nvoid test_integer_gini_coefficient()\n{\n    double tol = std::numeric_limits<double>::epsilon();\n    std::vector<Z> v{1,0,0};\n    double gini = boost::math::statistics::gini_coefficient(v.begin(), v.end());\n    double expected = 2.0/3.0;\n    BOOST_TEST(abs(gini - expected) < tol);\n\n    gini = boost::math::statistics::gini_coefficient(v);\n    BOOST_TEST(abs(gini - expected) < tol);\n\n    v[0] = 1;\n    v[1] = 1;\n    v[2] = 1;\n    gini = boost::math::statistics::gini_coefficient(v.begin(), v.end());\n    BOOST_TEST(abs(gini) < tol);\n\n    v[0] = 0;\n    v[1] = 0;\n    v[2] = 0;\n    gini = boost::math::statistics::gini_coefficient(v.begin(), v.end());\n    BOOST_TEST(abs(gini) < tol);\n\n    std::array<Z, 3> w{0,0,0};\n    gini = boost::math::statistics::gini_coefficient(w);\n    BOOST_TEST(abs(gini) < tol);\n\n    boost::numeric::ublas::vector<Z> w1(3);\n    w1[0] = 1;\n    w1[1] = 1;\n    w1[2] = 1;\n    gini = boost::math::statistics::gini_coefficient(w1);\n    BOOST_TEST(abs(gini) < tol);\n}\n\ntemplate<typename Real>\nvoid test_interquartile_range()\n{\n    std::mt19937 gen(486);\n    Real iqr;\n    // Taken from Wikipedia's example:\n    std::vector<Real> v{7, 7, 31, 31, 47, 75, 87, 115, 116, 119, 119, 155, 177};\n\n    // Q1 = 31, Q3 = 119, Q3 - Q1 = 88.\n    iqr = boost::math::statistics::interquartile_range(v);\n    BOOST_TEST_EQ(iqr, 88);\n\n    std::shuffle(v.begin(), v.end(), gen);\n    iqr = boost::math::statistics::interquartile_range(v);\n    BOOST_TEST_EQ(iqr, 88);\n\n    std::shuffle(v.begin(), v.end(), gen);\n    iqr = boost::math::statistics::interquartile_range(v);\n    BOOST_TEST_EQ(iqr, 88);\n\n    std::fill(v.begin(), v.end(), 1);\n    iqr = boost::math::statistics::interquartile_range(v);\n    BOOST_TEST_EQ(iqr, 0);\n\n    v = {1,2,3};\n    iqr = boost::math::statistics::interquartile_range(v);\n    BOOST_TEST_EQ(iqr, 2);\n    std::shuffle(v.begin(), v.end(), gen);\n    iqr = boost::math::statistics::interquartile_range(v);\n    BOOST_TEST_EQ(iqr, 2);\n\n    v = {0, 3, 5};\n    iqr = boost::math::statistics::interquartile_range(v);\n    BOOST_TEST_EQ(iqr, 5);\n    std::shuffle(v.begin(), v.end(), gen);\n    iqr = boost::math::statistics::interquartile_range(v);\n    BOOST_TEST_EQ(iqr, 5);\n\n    v = {1,2,3,4};\n    iqr = boost::math::statistics::interquartile_range(v);\n    BOOST_TEST_EQ(iqr, 2);\n    std::shuffle(v.begin(), v.end(), gen);\n    iqr = boost::math::statistics::interquartile_range(v);\n    BOOST_TEST_EQ(iqr, 2);\n\n    v = {1,2,3,4,5};\n    // Q1 = 1.5, Q3 = 4.5\n    iqr = boost::math::statistics::interquartile_range(v);\n    BOOST_TEST_EQ(iqr, 3);\n    std::shuffle(v.begin(), v.end(), gen);\n    iqr = boost::math::statistics::interquartile_range(v);\n    BOOST_TEST_EQ(iqr, 3);\n\n    v = {1,2,3,4,5,6};\n    // Q1 = 2, Q3 = 5\n    iqr = boost::math::statistics::interquartile_range(v);\n    BOOST_TEST_EQ(iqr, 3);\n    std::shuffle(v.begin(), v.end(), gen);\n    iqr = boost::math::statistics::interquartile_range(v);\n    BOOST_TEST_EQ(iqr, 3);\n\n    v = {1,2,3, 4, 5,6,7};\n    // Q1 = 2, Q3 = 6\n    iqr = boost::math::statistics::interquartile_range(v);\n    BOOST_TEST_EQ(iqr, 4);\n    std::shuffle(v.begin(), v.end(), gen);\n    iqr = boost::math::statistics::interquartile_range(v);\n    BOOST_TEST_EQ(iqr, 4);\n\n    v = {1,2,3,4,5,6,7,8};\n    // Q1 = 2.5, Q3 = 6.5\n    iqr = boost::math::statistics::interquartile_range(v);\n    BOOST_TEST_EQ(iqr, 4);\n    std::shuffle(v.begin(), v.end(), gen);\n    iqr = boost::math::statistics::interquartile_range(v);\n    BOOST_TEST_EQ(iqr, 4);\n\n    v = {1,2,3,4,5,6,7,8,9};\n    // Q1 = 2.5, Q3 = 7.5\n    iqr = boost::math::statistics::interquartile_range(v);\n    BOOST_TEST_EQ(iqr, 5);\n    std::shuffle(v.begin(), v.end(), gen);\n    iqr = boost::math::statistics::interquartile_range(v);\n    BOOST_TEST_EQ(iqr, 5);\n\n    v = {1,2,3,4,5,6,7,8,9,10};\n    // Q1 = 3, Q3 = 8\n    iqr = boost::math::statistics::interquartile_range(v);\n    BOOST_TEST_EQ(iqr, 5);\n    std::shuffle(v.begin(), v.end(), gen);\n    iqr = boost::math::statistics::interquartile_range(v);\n    BOOST_TEST_EQ(iqr, 5);\n\n    v = {1,2,3,4,5,6,7,8,9,10,11};\n    // Q1 = 3, Q3 = 9\n    iqr = boost::math::statistics::interquartile_range(v);\n    BOOST_TEST_EQ(iqr, 6);\n    std::shuffle(v.begin(), v.end(), gen);\n    iqr = boost::math::statistics::interquartile_range(v);\n    BOOST_TEST_EQ(iqr, 6);\n\n    v = {1,2,3,4,5,6,7,8,9,10,11,12};\n    // Q1 = 3.5, Q3 = 9.5\n    iqr = boost::math::statistics::interquartile_range(v);\n    BOOST_TEST_EQ(iqr, 6);\n    std::shuffle(v.begin(), v.end(), gen);\n    iqr = boost::math::statistics::interquartile_range(v);\n    BOOST_TEST_EQ(iqr, 6);\n}\n\nint main()\n{\n    test_mean<float>();\n    test_mean<double>();\n    test_mean<long double>();\n    test_mean<cpp_bin_float_50>();\n\n    test_integer_mean<unsigned>();\n    test_integer_mean<int>();\n\n    test_complex_mean<std::complex<float>>();\n    test_complex_mean<cpp_complex_50>();\n\n    test_variance<float>();\n    test_variance<double>();\n    test_variance<long double>();\n    test_variance<cpp_bin_float_50>();\n\n    test_integer_variance<int>();\n    test_integer_variance<unsigned>();\n\n    test_skewness<float>();\n    test_skewness<double>();\n    test_skewness<long double>();\n    test_skewness<cpp_bin_float_50>();\n\n    test_integer_skewness<int>();\n    test_integer_skewness<unsigned>();\n\n    test_first_four_moments<float>();\n    test_first_four_moments<double>();\n    test_first_four_moments<long double>();\n    test_first_four_moments<cpp_bin_float_50>();\n\n    test_kurtosis<float>();\n    test_kurtosis<double>();\n    test_kurtosis<long double>();\n    // Kinda expensive:\n    //test_kurtosis<cpp_bin_float_50>();\n\n    test_integer_kurtosis<int>();\n    test_integer_kurtosis<unsigned>();\n\n    test_median<float>();\n    test_median<double>();\n    test_median<long double>();\n    test_median<cpp_bin_float_50>();\n    test_median<int>();\n\n    test_median_absolute_deviation<float>();\n    test_median_absolute_deviation<double>();\n    test_median_absolute_deviation<long double>();\n    test_median_absolute_deviation<cpp_bin_float_50>();\n\n    test_gini_coefficient<float>();\n    test_gini_coefficient<double>();\n    test_gini_coefficient<long double>();\n    test_gini_coefficient<cpp_bin_float_50>();\n\n    test_integer_gini_coefficient<unsigned>();\n    test_integer_gini_coefficient<int>();\n\n    test_sample_gini_coefficient<float>();\n    test_sample_gini_coefficient<double>();\n    test_sample_gini_coefficient<long double>();\n    test_sample_gini_coefficient<cpp_bin_float_50>();\n\n    test_interquartile_range<double>();\n    test_interquartile_range<cpp_bin_float_50>();\n    return boost::report_errors();\n}\n", "meta": {"hexsha": "11598c7ff5985b611bb208e1af60880d15ce97eb", "size": 27505, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/math/test/univariate_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": "2021-01-12T04:55:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T04:55:21.000Z", "max_issues_repo_path": "3rdparty/boost_1_73_0/libs/math/test/univariate_statistics_test.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-13T08:54:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-17T17:25:14.000Z", "max_forks_repo_path": "3rdparty/boost_1_73_0/libs/math/test/univariate_statistics_test.cpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-08-28T07:14:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-13T11:18:41.000Z", "avg_line_length": 30.3252480706, "max_line_length": 125, "alphanum_fraction": 0.6031630613, "num_tokens": 8749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637648915617, "lm_q2_score": 0.8267117898012105, "lm_q1q2_score": 0.7106941697007501}}
{"text": "/*! \\file 2d_area_fill.cpp\n  \\brief Demonstration of area fill below curves.\n  \\date 2007\n  \\author Jacob Voytko and Paul A. Bristow\n*/\n\n// Copyright Jacob Voytko 2007\n// Copyright Paul A. Bristow 2009\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#include <boost/svg_plot/svg_2d_plot.hpp>\n  using namespace boost::svg; // Needed to get svg colors and others.\n  using boost::svg::svg_2d_plot;\n\n#include <map> \n  using std::map;\n#include <cmath>\n  using std::sin;\n  using std::cos;\n  using std::tan;\n\ndouble my_sin(double x)\n{\n  return 50. * sin(x);\n}\n\ndouble my_cos(double x)\n{\n  return 50. * cos(x);\n}\n\ndouble my_tan(double x)\n{\n  return 50. * tan(x);\n}\n\nint main()\n{\n  map<double, double> data_sin;\n  map<double, double> data_cos;\n  map<double, double> data_tan;\n  \n  double inter = 3.14159265 / 8.; // 16 points per cycle of 2 pi.\n\n  for(double i = 0; i <= 10.; i+=inter)\n  { // Just 10 data points for each function.\n    data_sin[i] = my_sin(i);\n    data_cos[i] = my_cos(i);\n    data_tan[i] = my_tan(i);\n  } // for\n\n  svg_2d_plot my_plot;\n\n  // Size/scale settings.\n  my_plot.size(700, 500)\n         .x_range(-1, 10)\n         .y_range(-75, 75);\n\n  // Text settings.\n  my_plot.title(\"Plot of 50 * sin(x), cos(x) and tan(x)\")\n         .title_font_size(20)\n         .x_label(\"x\")\n         .y_label(\"50 * f(x)\")\n         .x_major_labels_side(bottom)\n         .y_major_labels_side(left)\n         .x_major_grid_on(true)\n         .y_major_grid_on(true)\n         .x_major_grid_color(cyan)\n         .y_major_grid_color(cyan)\n         ;\n  // Commands.\n  my_plot.plot_window_on(true)\n         .x_label_on(true)\n         ;\n  \n  // Color settings.\n  my_plot.background_color(whitesmoke)\n         .legend_background_color(lightyellow)\n         .legend_border_color(yellow)\n         .plot_background_color(ghostwhite)\n         .title_color(red)\n         ;\n  // X axis settings.\n  my_plot.x_major_interval(2)\n         .x_major_tick_length(14)\n         .x_major_tick_width(1)\n         .x_minor_tick_length(7)\n         .x_minor_tick_width(1)\n         .x_num_minor_ticks(3)\n  \n  // Y axis settings.\n         .y_major_interval(25)\n         .y_num_minor_ticks(5);    \n  \n  svg_2d_plot_series& s_sin = my_plot.plot(data_sin, \"sin(x)\").line_on(true).area_fill(red);\n  std::cout << \"s_sin.area_fill() \" << s_sin.area_fill() << std::endl; // s_sin.area_fill() RGB(255,0,0)\n\n    svg_2d_plot_series& s_cos = my_plot.plot(data_cos, \"cos(x)\").line_on(true).area_fill(blue).shape(square);\n  std::cout << \"s_cos.area_fill() \" << s_cos.area_fill() << std::endl; // s_cos.area_fill() RGB(0,0,255)\n\n  svg_2d_plot_series& s_tan = my_plot.plot(data_tan, \"tan(x)\").shape(cone).line_on(true).area_fill(blank);\n  // Note that svg_color(blank) or svg_color(false) returns a non-color blank, so no fill.\n  std::cout << \"s_tan.area_fill() \" << s_tan.area_fill() << std::endl; // s_tan.area_fill() blank\n\n  std::cout << my_plot.title() << std::endl; // \"Plot of 50 * sin(x), cos(x) and tan(x)\"\n\n  my_plot.write(\"./2d_area_fill_1.svg\");\n\n\n  my_plot.plot(data_sin, \"sin(x)\").line_on(true).area_fill(green).shape(square).fill_color(red);\n  // Note how this overwrites the previously cos fill and tan line.\n  // (It also needs a new title).\n\n  my_plot.title(\"sin overwriting cos and tan\");\n  std::cout << my_plot.title() << std::endl; // \"sin overwriting cos and tan\"\n\n  my_plot.write(\"./2d_area_fill_2.svg\");\n\n   return 0;\n} // int main()\n\n/*\n\nOutput:\n\n2d_area_fill.cpp\nLinking...\nEmbedding manifest...\nAutorun \"j:\\Cpp\\SVG\\debug\\2d_area_fill.exe\"\ns_sin.area_fill() RGB(255,0,0)\ns_cos.area_fill() RGB(0,0,255)\ns_tan.area_fill() blank\nPlot of 50 * sin(x), cos(x) and tan(x)\n\n*/\n", "meta": {"hexsha": "051011824472c39b0386136318cc4abace9de0bc", "size": 3781, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/2d_area_fill.cpp", "max_stars_repo_name": "pabristow/svg_plot", "max_stars_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2016-03-09T03:23:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T14:02:07.000Z", "max_issues_repo_path": "example/2d_area_fill.cpp", "max_issues_repo_name": "pabristow/svg_plot", "max_issues_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2018-03-05T14:39:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-22T09:00:33.000Z", "max_forks_repo_path": "example/2d_area_fill.cpp", "max_forks_repo_name": "pabristow/svg_plot", "max_forks_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2016-11-04T14:36:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-17T08:12:03.000Z", "avg_line_length": 27.0071428571, "max_line_length": 109, "alphanum_fraction": 0.646389844, "num_tokens": 1135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.9019206745523101, "lm_q1q2_score": 0.7106514354750478}}
{"text": "#include <Eigen/Dense>\n#include \"simple_activation.h\"\n\nnamespace MyDL{\n    using namespace Eigen;\n\n    // \u5b9f\u88c5\u304c\u3081\u3093\u3069\u304f\u3055\u3044\u306e\u3067\u76f4\u63a5Eigen::MatrixXd\u3092\u5f15\u6570\u306b\u3068\u308b\u3088\u3046\u5b9f\u88c5\n    MatrixXd softmax(MatrixXd x)\n    {\n        VectorXd max_coeff_vec, rowwise_sum;\n        max_coeff_vec = x.rowwise().maxCoeff();\n\n        x = x.colwise() - max_coeff_vec; // exp\u306e\u30aa\u30fc\u30d0\u30fc\u30d5\u30ed\u30fc\u56de\u907f \u2192 \u5404\u30d0\u30c3\u30c1\u30d9\u30af\u30c8\u30eb\u3054\u3068\u306b\u6700\u5927\u306e\u8981\u7d20\u3092\u62bd\u51fa\n        x = x.array().exp();             // exp\u3092\u5404\u8981\u7d20\u306b\u5b9f\u884c\n        rowwise_sum = x.rowwise().sum(); // \u30d0\u30c3\u30c1\u30d9\u30af\u30c8\u30eb\u3054\u3068\u306b\u7dcf\u548c\u3092\u8a08\u7b97\n\n        x.array().colwise() /= rowwise_sum.array(); // \u51fa\u529b\u306e\u7dcf\u548c\u304c1\u306b\u306a\u308b\u3088\u3046\u8abf\u6574\n        return x;\n    }\n\n    MatrixXd sigmoid(MatrixXd x)\n    {\n        x = x.unaryExpr([](double p) { return 1 / (1 + exp(-p)); });\n        return x;\n    }\n}", "meta": {"hexsha": "ba81bfc4dbc52cb3769e6d1b18f5f8b593b5a38b", "size": 702, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "simple_lib/src/simple_activation.cpp", "max_stars_repo_name": "potedo/zeroDL_cpp", "max_stars_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-22T15:26:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-22T15:26:20.000Z", "max_issues_repo_path": "simple_lib/src/simple_activation.cpp", "max_issues_repo_name": "potedo/zeroDL_cpp", "max_issues_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "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": "simple_lib/src/simple_activation.cpp", "max_forks_repo_name": "potedo/zeroDL_cpp", "max_forks_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "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.0, "max_line_length": 79, "alphanum_fraction": 0.594017094, "num_tokens": 267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632996617212, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.7106325964124464}}
{"text": "#include \"k_points_util.h\"\n\n#include <boost/functional/hash.hpp>\n#include \"../array_math.h\"\n\nsize_t KPointsUtil::get_n_k_points(const double rcut) {\n  size_t count = 0;\n  const int8_t n_max = floor(rcut);\n  for (int8_t i = -n_max; i <= n_max; i++) {\n    for (int8_t j = -n_max; j <= n_max; j++) {\n      for (int8_t k = -n_max; k <= n_max; k++) {\n        if (i * i + j * j + k * k > pow(rcut, 2)) continue;\n        count++;\n      }\n    }\n  }\n  return count;\n}\n\nstd::vector<std::array<int8_t, 3>> KPointsUtil::generate_k_points(const double rcut) {\n  std::vector<std::array<int8_t, 3>> k_points;\n  const int8_t n_max = floor(rcut);\n  for (int8_t i = -n_max; i <= n_max; i++) {\n    for (int8_t j = -n_max; j <= n_max; j++) {\n      for (int8_t k = -n_max; k <= n_max; k++) {\n        if (i * i + j * j + k * k > pow(rcut, 2)) continue;\n        k_points.push_back(std::array<int8_t, 3>({i, j, k}));\n      }\n    }\n  }\n  std::stable_sort(\n      k_points.begin(),\n      k_points.end(),\n      [](const std::array<int8_t, 3>& a, const std::array<int8_t, 3>& b) -> bool {\n        return squared_norm(a) < squared_norm(b);\n      });\n  return k_points;\n}\n\nstd::vector<std::array<int8_t, 3>> KPointsUtil::get_k_diffs(\n    const std::vector<std::array<int8_t, 3>>& k_points) {\n  // Generate all possible differences between two different k points.\n  std::unordered_set<std::array<int8_t, 3>, boost::hash<std::array<int8_t, 3>>> k_diffs_set;\n  std::vector<std::array<int8_t, 3>> k_diffs;\n  const size_t n_orbs = k_points.size();\n  for (size_t p = 0; p < n_orbs; p++) {\n    for (size_t q = 0; q < n_orbs; q++) {\n      if (p == q) continue;\n      const auto& diff_pq = k_points[q] - k_points[p];\n      if (k_diffs_set.count(diff_pq) == 1) continue;\n      k_diffs.push_back(diff_pq);\n      k_diffs_set.insert(diff_pq);\n    }\n  }\n\n  // Sort k_diffs into ascending order so that later sorting hci queue will be faster.\n  std::stable_sort(\n      k_diffs.begin(),\n      k_diffs.end(),\n      [](const std::array<int8_t, 3>& a, const std::array<int8_t, 3>& b) -> bool {\n        return squared_norm(a) < squared_norm(b);\n      });\n\n  return k_diffs;\n}", "meta": {"hexsha": "de6e9c905ac26ca7da34a94e8c866556fc1b49b7", "size": 2124, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/heg_solver/k_points_util.cc", "max_stars_repo_name": "jl2922/hci-17c", "max_stars_repo_head_hexsha": "401a04d67c1d37e83dacc73bebeb8561c13bd4b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-08-21T13:55:00.000Z", "max_stars_repo_stars_event_max_datetime": "2017-08-21T13:55:00.000Z", "max_issues_repo_path": "src/heg_solver/k_points_util.cc", "max_issues_repo_name": "jl2922/hci-17c", "max_issues_repo_head_hexsha": "401a04d67c1d37e83dacc73bebeb8561c13bd4b2", "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/heg_solver/k_points_util.cc", "max_forks_repo_name": "jl2922/hci-17c", "max_forks_repo_head_hexsha": "401a04d67c1d37e83dacc73bebeb8561c13bd4b2", "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.6769230769, "max_line_length": 92, "alphanum_fraction": 0.593220339, "num_tokens": 698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.7981867777396212, "lm_q1q2_score": 0.7106210842352647}}
{"text": "/*\nHeaders for file \"utils.cpp\".\n\nCopyright (c) 2021 Gabriele Gilardi\n*/\n\n#ifndef __UTILS_H_\n#define __UTILS_H_\n\n#include <random>\n#include <Eigen/Dense>\n\nusing namespace std;\nusing namespace Eigen;\n\nArrayXXd rnd(uniform_real_distribution<double> dist, mt19937_64& generator,\n             int nr=1, int nc=1);\nArrayXXd rnd(normal_distribution<double> dist, mt19937_64& generator,\n             int nr=1, int nc=1);\nArrayXi cumsum(ArrayXi X);\nArrayXi cumprod(ArrayXi X);\ndouble stdev(ArrayXd X, int ddof=0);\ndouble rmse(ArrayXd X, ArrayXd Y);\ndouble accuracy(ArrayXd A, ArrayXd B, double tol=1.e-5);\ndouble calc_corr(ArrayXd X, ArrayXd Y);\nArrayXd normalize(ArrayXd X, double mu=0.0, double sigma=1.0);\nArrayXd scale(ArrayXd X, double Xmin, double Xmax, double a=-1.0, double b=1.0);\nArrayXi shuffle(int nel, mt19937_64& gen);\nVectorXd exact_sol(MatrixXd A, VectorXd b);\n\n#endif\n ", "meta": {"hexsha": "b8a8d94e8d5427e1ca2eef87bedcfcceec2b144d", "size": 878, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Code_Cpp_Eigen/utils.hpp", "max_stars_repo_name": "gabrielegilardi/ANFIS-metaheuristic", "max_stars_repo_head_hexsha": "28c9e3ed03720ebe56ca2e5aa08bff654084e9fc", "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": "Code_Cpp_Eigen/utils.hpp", "max_issues_repo_name": "gabrielegilardi/ANFIS-metaheuristic", "max_issues_repo_head_hexsha": "28c9e3ed03720ebe56ca2e5aa08bff654084e9fc", "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": "Code_Cpp_Eigen/utils.hpp", "max_forks_repo_name": "gabrielegilardi/ANFIS-metaheuristic", "max_forks_repo_head_hexsha": "28c9e3ed03720ebe56ca2e5aa08bff654084e9fc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-26T10:03:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-26T10:03:44.000Z", "avg_line_length": 27.4375, "max_line_length": 80, "alphanum_fraction": 0.7334851936, "num_tokens": 259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.874077222043951, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.710508811028283}}
{"text": "#include <cradle/geometry/grid_points.hpp>\n#include <cradle/geometry/regular_grid.hpp>\n\n#include <boost/assign/std/vector.hpp>\n\n#include <cradle/test.hpp>\n\nusing namespace cradle;\nusing namespace boost::assign;\n\nTEST_CASE(\"regular_grid_test\")\n{\n    regular_grid<1, float> default_constructed;\n\n    vector2d p0 = make_vector<double>(0, 0);\n    vector2d spacing = make_vector<double>(1, 0.5);\n    vector2u n_points = make_vector<unsigned>(2, 3);\n\n    regular_grid<2, double> grid(p0, spacing, n_points);\n    REQUIRE(grid.p0 == p0);\n    REQUIRE(grid.spacing == spacing);\n    REQUIRE(grid.n_points == n_points);\n\n    std::vector<vector2d> correct_points;\n    correct_points += make_vector<double>(0, 0), make_vector<double>(1, 0),\n        make_vector<double>(0, 0.5), make_vector<double>(1, 0.5),\n        make_vector<double>(0, 1), make_vector<double>(1, 1);\n    CRADLE_CHECK_RANGES_ALMOST_EQUAL(\n        make_grid_point_list(grid), correct_points);\n}\n\nTEST_CASE(\"grid_bounding_box_test\")\n{\n    vector2d p0 = make_vector<double>(-1, 0);\n    vector2d spacing = make_vector<double>(1, 0.5);\n    vector2u n_points = make_vector<unsigned>(2, 3);\n\n    regular_grid<2, double> grid(p0, spacing, n_points);\n\n    REQUIRE(\n        bounding_box(grid)\n        == box2d(make_vector<double>(-1, 0), make_vector<double>(1, 1)));\n}\n\nvector3d\nget_point_at_index(regular_grid<3, double> const& grid, size_t index)\n{\n    size_t x_index = index % grid.n_points[0];\n    size_t y_index = (index / grid.n_points[0]) % grid.n_points[1];\n    size_t z_index = (index / grid.n_points[0]) / grid.n_points[1];\n    return make_vector(\n        grid.p0[0] + x_index * grid.spacing[0],\n        grid.p0[1] + y_index * grid.spacing[1],\n        grid.p0[2] + z_index * grid.spacing[2]);\n}\n", "meta": {"hexsha": "c63d3026942a66075c18bce9164d246aee2577e2", "size": 1749, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/geometry/regular_grid.cpp", "max_stars_repo_name": "mghro/astroid-core", "max_stars_repo_head_hexsha": "72736f64bed19ec3bb0e92ebee4d7cf09fc0399f", "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": "unit_tests/geometry/regular_grid.cpp", "max_issues_repo_name": "mghro/astroid-core", "max_issues_repo_head_hexsha": "72736f64bed19ec3bb0e92ebee4d7cf09fc0399f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-10-26T18:45:47.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-26T18:46:06.000Z", "max_forks_repo_path": "unit_tests/geometry/regular_grid.cpp", "max_forks_repo_name": "mghro/astroid-core", "max_forks_repo_head_hexsha": "72736f64bed19ec3bb0e92ebee4d7cf09fc0399f", "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.2321428571, "max_line_length": 75, "alphanum_fraction": 0.6775300172, "num_tokens": 503, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467643431002, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.7104096741348699}}
{"text": "#include <fmt/core.h>\n#include <yaml-cpp/yaml.h>\n\n#include <Eigen/Dense>\n#include <iostream>\n#include <random>\n\n#include \"Metropolis.hpp\"\n#include \"NumpySaver.hpp\"\n#include \"Timer.hpp\"\n\nusing namespace Eigen;\nusing std::cout, std::endl;\n\nusing Array1d = Array<double, 1, 1>;\n\nconstexpr double pow2(double x) { return x * x; };\nconstexpr double pow3(double x) { return x * x * x; };\n\ndouble pdf_1d(const Array1d& x, double alpha) {\n  return std::exp(-2 * alpha * x[0] * x[0]);\n}\n\ndouble energy_1d(const Array1d& x, double alpha) {\n  return alpha + x[0] * x[0] * (1. / 2. - 2 * alpha * alpha);\n}\n\n/**\n * @brief\n *\n * @param x = {x0, y0, x1, y1}\n * @param alpha\n * @param lambda\n * @return double\n */\ndouble pdf_wavefunction_2d(const Array4d& x, double alpha, double lambda) {\n  double r = std::sqrt(pow2(x[0] - x[2]) + pow2(x[1] - x[3]));\n  return std::exp(-pow2(x[0]) - pow2(x[1]) - pow2(x[2]) - pow2(x[3]) +\n                  2. * lambda * r / (1. + alpha * r));\n}\n\nconstexpr double derivative_factor(double r, double x, double x_other,\n                                   double alpha, double lambda) {\n  using std::pow;\n  return -1. + lambda / pow2(1 + alpha * r) / r -\n         lambda * pow2(x - x_other) / pow3((1. + alpha * r) * r) *\n             (1. + 3. * alpha * r) +\n         pow2(-x + lambda * (x - x_other) / pow2(1. + alpha * r) / r);\n}\n\ndouble energy_2d(const Array4d& x, double alpha, double lambda) {\n  double r = std::sqrt(pow2(x[0] - x[2]) + pow2(x[1] - x[3]));\n\n  double dx1 = derivative_factor(r, x[0], x[2], alpha, lambda);\n  double dx2 = derivative_factor(r, x[2], x[0], alpha, lambda);\n  double dy1 = derivative_factor(r, x[1], x[3], alpha, lambda);\n  double dy2 = derivative_factor(r, x[3], x[1], alpha, lambda);\n\n  return (-dx1 + pow2(x[0]) - dx2 + pow2(x[2]) - dy1 + pow2(x[1]) - dy2 +\n          pow2(x[3])) /\n             2. +\n         lambda / r;\n}\n\nstd::tuple<double, double> golden_search_simple(std::function<double(double)> f,\n                                                double xmin, double xmax,\n                                                double tol) {\n  constexpr double golden_ratio = 1.618033988749895;\n  double x1, x2;\n  if (xmin >= xmax)\n    throw std::invalid_argument(\"xmin must be smaller than xmax\");\n\n  while (xmax - xmin > tol) {\n    x1 = xmax - (xmax - xmin) / golden_ratio;\n    x2 = xmin + (xmax - xmin) / golden_ratio;\n\n    if (f(x1) < f(x2))\n      xmax = x2;\n    else\n      xmin = x1;\n  }\n\n  return {xmin, xmax};\n}\n\nstd::tuple<double, double> golden_search(std::function<double(double)> f,\n                                         double xmin, double xmax, double tol) {\n  constexpr double golden_ratio = 1.618033988749895;\n  double x1 = xmax - (xmax - xmin) / golden_ratio;\n  double x2 = xmin + (xmax - xmin) / golden_ratio;\n  double f1 = f(x1);\n  double f2 = f(x2);\n\n  if (xmin >= xmax)\n    throw std::invalid_argument(\"xmin must be smaller than xmax\");\n\n  while (xmax - xmin > tol) {\n    if (f1 < f2) {\n      xmax = x2;\n      x2 = x1;\n      f2 = f1;\n      x1 = xmax - (xmax - xmin) / golden_ratio;\n      f1 = f(x1);\n    } else {\n      xmin = x1;\n      x1 = x2;\n      f1 = f2;\n      x2 = xmin + (xmax - xmin) / golden_ratio;\n      f2 = f(x2);\n    }\n  }\n\n  return {xmin, xmax};\n}\n\nstd::tuple<double, double> adaptive_golden_search(\n    std::function<std::tuple<double, double>(double, Index sample)> f,\n    double xmin, double xmax, double tol, Index start_sample = 1000) {\n  constexpr double golden_ratio = 1.618033988749895;\n  Index sample = start_sample;\n\n  double x1 = xmax - (xmax - xmin) / golden_ratio;\n  double x2 = xmin + (xmax - xmin) / golden_ratio;\n  auto [f1, f1_err] = f(x1, sample);\n  auto [f2, f2_err] = f(x2, sample);\n\n  std::tuple<double, double> buf;\n\n  if (xmin >= xmax)\n    throw std::invalid_argument(\"xmin must be smaller than xmax\");\n\n  while (xmax - xmin > tol) {\n    if (f1 < f2) {\n      xmax = x2;\n      x2 = x1;\n      f2 = f1;\n      x1 = xmax - (xmax - xmin) / golden_ratio;\n      std::tie(f1, f1_err) = f(x1, sample);\n    } else {\n      xmin = x1;\n      x1 = x2;\n      f1 = f2;\n      x2 = xmin + (xmax - xmin) / golden_ratio;\n      std::tie(f2, f2_err) = f(x2, sample);\n    }\n    if (std::abs(f1 - f2) < f1_err + f2_err) {\n      sample += (Index)pow2((f1_err + f2_err) / std::abs(f1 - f2));\n    }\n  }\n\n  return {xmin, xmax};\n}\n\nvoid test_1D_metropolis() {\n  Array1d argstart;\n  argstart << 0;\n\n  std::uniform_real_distribution<> step(-2, 2);\n  std::normal_distribution<> step_gauss(0, 1);\n\n  using namespace std::placeholders;\n  auto pdf_normal = std::bind(pdf_1d, _1, 1. / 4.);\n\n  MetropolisAlgorithm<1> malg_uniform(pdf_normal, argstart, step);\n  MetropolisAlgorithm<1, std::normal_distribution<> > malg_normal(\n      pdf_normal, argstart, step_gauss);\n\n  auto test_1 = malg_uniform.get_sample(100000);\n  auto test_2 = malg_normal.get_sample(100000);\n\n  auto [mean, std] =\n      Timer::measure_time([&]() { malg_uniform.get_sample(100000); }, .1);\n  cout << \"Generating 100000 events with uniform step took \" << mean << \"\u00b1\"\n       << std << \"ms\\n\";\n\n  auto [mean_n, std_n] =\n      Timer::measure_time([&]() { malg_normal.get_sample(100000); }, .1);\n  cout << \"Generating 100000 events with normal step took \" << mean_n << \"\u00b1\"\n       << std_n << \"ms\\n\";\n  NumpySaver(\"build/output/test_normal_distribution.npy\") << test_1 << test_2;\n}\n\ndouble optimal_alpha_2d(double lambda, Index sample = 100000) {\n  using namespace std::placeholders;\n\n  Array4d argstart;\n  argstart << 0, 1, 0, -1;\n  std::normal_distribution<> step_gauss(0, 1);\n\n  std::function<double(double)> f = [&](double alpha) {\n    auto pdf = std::bind(pdf_wavefunction_2d, _1, alpha, lambda);\n    auto energy = std::bind(energy_2d, _1, alpha, lambda);\n    MetropolisAlgorithm<4, std::normal_distribution<> > malg(pdf, argstart,\n                                                             step_gauss);\n    auto [mean, std, var] = malg.average(energy, sample);\n    return mean;\n  };\n\n  auto [xmin, xmax] = golden_search(f, .1, 1, 1e-6);\n  return (xmin + xmax) / 2;\n}\n\nvoid test_2D_metropolis(double lambda = 1) {\n  Array4d argstart;\n  argstart << 0, 1, 0, -1;\n\n  std::uniform_real_distribution<> step(-2, 2);\n  std::normal_distribution<> step_gauss(0, 1);\n\n  using namespace std::placeholders;\n  double alpha = optimal_alpha_2d(lambda);\n  auto pdf_2d = std::bind(pdf_wavefunction_2d, _1, alpha, lambda);\n\n  MetropolisAlgorithm<4, std::normal_distribution<> > malg_normal(\n      pdf_2d, argstart, step_gauss);\n\n  auto test_1 = malg_normal.get_sample(100000);\n\n  auto [mean, std] =\n      Timer::measure_time([&]() { malg_normal.get_sample(100000); }, .1);\n  cout << \"Generating 100000 2D events with uniform step took \" << mean << \"\u00b1\"\n       << std << \"ms\\n\";\n\n  NumpySaver(\"build/output/test_2D_distribution.npy\")\n      << test_1.col(0) << test_1.col(1) << test_1.col(2) << test_1.col(3);\n}\n\nvoid test_1D_energy(Index n = 300) {\n  using namespace std::placeholders;\n\n  Array1d argstart;\n  argstart << 0;\n  std::normal_distribution<> step_gauss(0, 1);\n\n  ArrayXd alphas = ArrayXd::LinSpaced(n, 0.1, 1);\n  ArrayXd means(n);\n  ArrayXd stds(n);\n  ArrayXd vars(n);\n\n  for (Index i = 0; i < n; i++) {\n    auto pdf_normal = std::bind(pdf_1d, _1, alphas[i]);\n    auto energy = std::bind(energy_1d, _1, alphas[i]);\n    MetropolisAlgorithm<1, std::normal_distribution<> > malg_normal(\n        pdf_normal, argstart, step_gauss);\n    auto [mean, std, var] = malg_normal.average(energy, 100000);\n    means[i] = mean;\n    stds[i] = std;\n    vars[i] = var;\n  }\n\n  NumpySaver(\"build/output/test_1d_energy.npy\")\n      << alphas << means << stds << vars;\n}\n\nvoid test_2D_energy(Index n = 300, double lambda = 1) {\n  using namespace std::placeholders;\n\n  Array4d argstart;\n  argstart << 0, 1, 0, -1;\n  std::normal_distribution<> step_gauss(0, 1);\n\n  ArrayXd alphas = ArrayXd::LinSpaced(n, 0.1, 1);\n  ArrayXd means(n);\n  ArrayXd stds(n);\n  ArrayXd vars(n);\n\n  for (Index i = 0; i < n; i++) {\n    auto pdf = std::bind(pdf_wavefunction_2d, _1, alphas[i], lambda);\n    auto energy = std::bind(energy_2d, _1, alphas[i], lambda);\n    MetropolisAlgorithm<4, std::normal_distribution<> > malg(pdf, argstart,\n                                                             step_gauss);\n    auto [mean, std, var] = malg.average(energy, 100000);\n    means[i] = mean;\n    stds[i] = std;\n    vars[i] = var;\n  }\n\n  NumpySaver(fmt::format(\"build/output/test_2d_energy_{}.npy\", lambda))\n      << alphas << means << stds << vars;\n}\n\nvoid find_1d_alpha(Index sample = 1000000) {\n  using namespace std::placeholders;\n\n  Array1d argstart;\n  argstart << 0;\n  std::normal_distribution<> step_gauss(0, 1);\n\n  std::function<double(double)> f = [&](double alpha) {\n    auto pdf = std::bind(pdf_1d, _1, alpha);\n    auto energy = std::bind(energy_1d, _1, alpha);\n    MetropolisAlgorithm<1, std::normal_distribution<> > malg(pdf, argstart,\n                                                             step_gauss);\n    auto [mean, std, var] = malg.average(energy, sample);\n    return mean;\n  };\n\n  auto [xmin, xmax] = golden_search(f, .1, 1, 1e-6);\n  cout << \"Optimal \u03b1 for 1D case is between \" << xmin << \" and \" << xmax << \" (\"\n       << f(xmin) << \" < E <\" << f(xmax) << \")\" << endl;\n}\n\nvoid find_2d_alpha(double lambda = 1, Index sample = 1000000) {\n  using namespace std::placeholders;\n\n  Array4d argstart;\n  argstart << 0, 1, 0, -1;\n  std::normal_distribution<> step_gauss(0, 1);\n\n  std::function<double(double)> f = [&](double alpha) {\n    auto pdf = std::bind(pdf_wavefunction_2d, _1, alpha, lambda);\n    auto energy = std::bind(energy_2d, _1, alpha, lambda);\n    MetropolisAlgorithm<4, std::normal_distribution<> > malg(pdf, argstart,\n                                                             step_gauss);\n    auto [mean, std, var] = malg.average(energy, sample);\n    return mean;\n  };\n\n  auto [xmin, xmax] = golden_search(f, .1, 1, 1e-6);\n  cout << \"Optimal \u03b1 for 2D case (\u03bb=\" << lambda << \") is between \" << xmin\n       << \" and \" << xmax << \" (\" << f(xmin) << \" < E <\" << f(xmax) << \")\"\n       << endl;\n}\n\nvoid find_2d_alpha_adaptive(double lambda = 1) {\n  using namespace std::placeholders;\n\n  Array4d argstart;\n  argstart << 0, 1, 0, -1;\n  std::normal_distribution<> step_gauss(0, 1);\n\n  std::function<std::tuple<double, double>(double, Index)> f =\n      [&](double alpha, double sample) {\n        auto pdf = std::bind(pdf_wavefunction_2d, _1, alpha, lambda);\n        auto energy = std::bind(energy_2d, _1, alpha, lambda);\n        MetropolisAlgorithm<4, std::normal_distribution<> > malg(pdf, argstart,\n                                                                 step_gauss);\n        auto [mean, std, var] = malg.average(energy, sample);\n        return std::tuple<double, double>({mean, std});\n      };\n\n  auto [xmin, xmax] = adaptive_golden_search(f, .1, 1, 1e-6);\n  cout << \"Optimal (adaptive) \u03b1 for 2D case (\u03bb=\" << lambda << \") is between \"\n       << xmin << \" and \" << xmax << endl;\n}\n\nvoid energy_function_test() {\n  cout << \"E_2d(1, 0, 2, 0|\u03bb=1,\u03b1=1)=\" << energy_2d({1, 0, 2, 0}, 1, 1) << endl;\n  cout << \"E_2d(1.1, 3.1, -5.6, -5|\u03bb=2.1,\u03b1=1.1)=\"\n       << energy_2d({1.1, 3.1, -5.6, -5}, 1.1, 2.1) << endl;\n}\n\nint main(int argc, char const* argv[]) {\n  energy_function_test();\n  test_1D_metropolis();\n  test_2D_metropolis();\n  test_1D_energy();\n  test_2D_energy(300, 0);\n  test_2D_energy(300, 1);\n  test_2D_energy(300, 2);\n  test_2D_energy(300, 8);\n  find_1d_alpha();\n  find_2d_alpha(0);\n  find_2d_alpha(1);\n  find_2d_alpha(2);\n  find_2d_alpha(8);\n  return 0;\n}\n", "meta": {"hexsha": "8eaf9d937ce679a7cdf3ee37522c792630f7ecb3", "size": 11483, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Project03-QuantumMC/quantummc.cpp", "max_stars_repo_name": "The-Ludwig/ComputationalPhysicsSU22", "max_stars_repo_head_hexsha": "67cd47b1adf42087a300bcaa97f6ea5c6df691f2", "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": "Project03-QuantumMC/quantummc.cpp", "max_issues_repo_name": "The-Ludwig/ComputationalPhysicsSU22", "max_issues_repo_head_hexsha": "67cd47b1adf42087a300bcaa97f6ea5c6df691f2", "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": "Project03-QuantumMC/quantummc.cpp", "max_forks_repo_name": "The-Ludwig/ComputationalPhysicsSU22", "max_forks_repo_head_hexsha": "67cd47b1adf42087a300bcaa97f6ea5c6df691f2", "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.1192411924, "max_line_length": 80, "alphanum_fraction": 0.5909605504, "num_tokens": 3661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872046026642944, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.7103776274662543}}
{"text": "#include \"parameters.h\"\n\n#include <NTL/RR.h>\n\nnamespace {\n    using namespace NTL;\n}\n\nnamespace gnfs {\n    long param_d(const ZZ& n) {\n        RR ln = log(conv<RR>(n));\n        RR base = (3 * ln) / log(ln);\n        return conv<long>(pow(base, RR(1.0/3)));\n    }\n\n    long param_B(const ZZ& n) {\n        RR ln = log(conv<RR>(n));\n        RR base = 8.0 / 9 * ln * log(ln) * log(ln);\n        return conv<long>(exp(pow(base, RR(1.0/3))));\n    }\n\n    std::pair<ZZ, ZZX> param_mf(const ZZ& n, long d) {\n        ZZ m = conv<ZZ>(pow(conv<RR>(n), RR(1.0/d)));\n\n        // Write n in base m\n        ZZX f;\n        ZZ cur = n;\n        long i = 0;\n        while (cur != 0) {\n            SetCoeff(f, i, cur % m);\n            cur /= m;\n            i++;\n        }\n\n        return std::make_pair(m, f);\n    }\n}\n", "meta": {"hexsha": "552f5a0443e4d15990e4e5413c9771ea0d46e8de", "size": 795, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/parameters.cc", "max_stars_repo_name": "MathSquared/general-number-field-sieve", "max_stars_repo_head_hexsha": "0ab4efd447f24b726597ec9a6ddae669b1709a20", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-05-25T09:36:07.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-23T11:54:46.000Z", "max_issues_repo_path": "src/parameters.cc", "max_issues_repo_name": "MathSquared/general-number-field-sieve", "max_issues_repo_head_hexsha": "0ab4efd447f24b726597ec9a6ddae669b1709a20", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-06T10:34:07.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-06T10:34:07.000Z", "max_forks_repo_path": "src/parameters.cc", "max_forks_repo_name": "MathSquared/general-number-field-sieve", "max_forks_repo_head_hexsha": "0ab4efd447f24b726597ec9a6ddae669b1709a20", "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": 20.9210526316, "max_line_length": 54, "alphanum_fraction": 0.4528301887, "num_tokens": 252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897459384731, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.7102162787003418}}
{"text": "/*\n * ex_main.cpp\n *\n *  Created on: 2017. 6. 6.\n *      Author: cho\n */\n\n#include <random>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/ublas/io.hpp>\n//#include \"io.hpp\"\n\nusing namespace std;\nnamespace ublas = boost::numeric::ublas;\n\n/// number of data\nconst unsigned int N = 3;\n\nint main () {\n\t// random number generator\n\trandom_device rd;      // obtain seed\n\tmt19937_64 gen(rd());  // mersenne twister engine\n\n\t// vector\n\tcout << \"============== vector\" << endl;\n\t{\n\t\tublas::vector<double> t (N); // time vector, sec\n\t\tfor (unsigned i = 0; i < t.size(); ++i) t(i) = i;\n\t\tcout << \"t(\"<<N<<\") = \" << t << endl;\n\n\t\tuniform_int_distribution<int> dis_y( 0, 10 );\n\t\tublas::vector<double> y (N); // measured value\n\t\tfor (unsigned i = 0; i < y.size(); ++i) y(i) = dis_y(gen);\n\t\tcout << \"y(\"<<N<<\") = \" << y << endl;\n\n\t\tfor (unsigned i = 0; i < N; ++i) {\n\t\t\tublas::unit_vector<double> u(N, i);\n\t\t\tcout << \"unit_vector(\"<<N<<\",\"<<i<<\") = \" << u << endl;\n\t\t}\n\n\t\tublas::zero_vector<double> z(N);\n\t\tcout << \"zero_vector(\"<<N<<\") = \" << z << endl;\n\n\t\tublas::scalar_vector<double> s(N, 3);\n\t\tcout << \"scalar_vector(\"<<N<<\",3) = \" << s << endl;\n\n\t\tublas::scalar_vector<double> one(N, 1);\n\t\tcout << \"one(\"<<N<<\",1) = \" << one << endl;\n\t}\n\n\t// range\n\tcout << \"============== range, slice\" << endl;\n\t{\n\t\tublas::range r1(0, N);\n\t\tfor (unsigned i = 0; i < r1.size(); ++ i) {\n\t\t\tcout << \"range(0,N) r(\"<<i<<\") = \" << r1(i) << endl;\n\t\t}\n\n\t\tublas::range r2(3, N);\n\t\tfor (unsigned i = 0; i < r2.size(); ++ i) {\n\t\t\tcout << \"range(3,N) r(\"<<i<<\") = \" << r2(i) << endl;\n\t\t}\n\n\t\tublas::slice s2(0, 2, N);\n\t\tfor (unsigned i = 0; i < s2.size(); ++ i) {\n\t\t\tcout << \"slice(0,2,N) s2(\"<<i<<\") = \" << s2(i) << endl;\n\t\t}\n\n\t\tublas::slice s3(1, 3, N);\n\t\tfor (unsigned i = 0; i < s3.size(); ++ i) {\n\t\t\tcout << \"slice(1,3,N) s(\"<<i<<\") = \" << s3(i) << endl;\n\t\t}\n\t}\n\n\t// matrix\n\tcout << \"============== matrix\" << endl;\n\t{\n\t\tublas::matrix<double> m;\n\t\tcout << \"m()          = \" << m << endl;\n\n\t\tm.resize( N, N );\n\t\tcout << \"m.resize(N,N)= \" << m << endl;\n\n\t\tm.clear();\n\t\tcout << \"m.clear()    = \" << m << endl;\n\n\t\tfor (unsigned i = 0; i < m.size1 (); ++ i)\n\t\t\tfor (unsigned j = 0; j < m.size2 (); ++ j)\n\t\t\t\tm (i, j) = i*10 + j;\n\t\tcout << \"matrix       = \" << m << endl;\n\n\t\tcout << \"transpose    = \" << ublas::trans(m) << endl;\n\t\tcout << \"column(m, 1) = \" << ublas::column (m, 1) << endl;\n\t\tcout << \"column(m, 2) = \" << ublas::column (m, 2) << endl;\n\t\tcout << \"row(m, 1)    = \" << ublas::row (m, 1) << endl;\n\t\tcout << \"row(m, 2)    = \" << ublas::row (m, 2) << endl;\n\t\tcout << \"project(m, range(0,1), range(0,N))     = \"\n\t\t\t\t<< ublas::project(m, ublas::range(0,1), ublas::range(0,N)) << endl;\n\t\tcout << \"project(m, range(N-1,N), range(N-1,N)) = \"\n\t\t\t\t<< ublas::project(m, ublas::range(N-1,N), ublas::range(N-1,N)) << endl;\n\t\tcout << \"project(m, slice(1,2,2), slice(1,2,2)) = \"\n\t\t\t\t<< ublas::project(m, ublas::slice(0,2,2), ublas::slice(0,2,2)) << endl;\n\n\t\tauto m_temp = m;\n\t\tfor ( unsigned i = 0; i < m_temp.size2(); ++i ) {\n\t\t\tublas::column( m_temp, i) = ublas::scalar_vector<double>(m_temp.size1(),1);\n\t\t\tcout << \"m_temp       = \" << m_temp << endl;\n\t\t}\n\n\t\tm_temp = m;\n\t\tfor ( unsigned i = 0; i < m_temp.size1(); ++i ) {\n\t\t\tublas::row( m_temp, i ) = ublas::scalar_vector<double>(m_temp.size2(),1);\n\t\t\tcout << \"m_temp       = \" << m_temp << endl;\n\t\t}\n\n\t\tublas::identity_matrix<double> mi(N);\n\t\tcout << \"identity(N)      = \" << mi << endl;\n\n\t\tublas::zero_matrix<double> zero(N);\n\t\tcout << \"zero(N)          = \" << zero << endl;\n\n\t\tublas::scalar_matrix<double> ones(1, 1, 1);\n\t\tcout << \"sizeof( scalar_matrix(1, 1, 1) ) = \" << sizeof(ones) << endl;\n\t\tublas::scalar_matrix<double> twos(1000, 2000000, 2);\n\t\tcout << \"sizeof( scalar_matrix(1000, 2000000, 2) ) = \" << sizeof(twos) << endl;\n\n\t\tublas::matrix<double> ones1(1, 1, 1);\n\t\tcout << \"sizeof( matrix(1, 1, 1) ) = \" << sizeof(ones1) << endl;\n\t\tublas::matrix<double> twos1(10000, 20000, 2);\n\t\tcout << \"sizeof( matrix(10000, 20000, 2) ) = \" << sizeof(twos1) << endl;\n\t}\n\n\t// matrix\n\tcout << \"============== triangular_matrix\" << endl;\n\t{\n\t\tublas::triangular_matrix<double, ublas::lower> l(N,N);\n\t\tfor ( unsigned i = 0; i < l.size1(); ++i )\n\t\t\tfor ( unsigned j = 0; j <= i; ++j )\n\t\t\t\tl(i,j) = 10*i + j;\n\t\tcout << \"l(N, N)           = \" << l << endl;\n\n\t\tublas::triangular_matrix<double, ublas::unit_lower> ul(N,N);\n\t\tfor ( unsigned i = 0; i < ul.size1(); ++i )\n\t\t\tfor ( unsigned j = 0; j < i; ++j )\n\t\t\t\tul(i,j) = 10*i + j;\n\t\tcout << \"ul(N, N)          = \" << ul << endl;\n\n\t\tublas::triangular_matrix<double, ublas::upper> u(N,N);\n\t\tfor ( unsigned i = 0; i < u.size1(); ++i )\n\t\t\tfor ( unsigned j = i; j < u.size2(); ++j )\n\t\t\t\tu(i,j) = 10*i + j+1;\n\t\tcout << \"u(N, N)           = \" << u << endl;\n\n\t\tublas::triangular_matrix<double, ublas::unit_upper> uu(N,N);\n\t\tfor ( unsigned i = 0; i < uu.size1(); ++i )\n\t\t\tfor ( unsigned j = i+1; j < uu.size2(); ++j )\n\t\t\t\tuu(i,j) = 10*i + j+1;\n\t\tcout << \"uu(N, N)          = \" << uu << endl;\n\t}\n}\n\n\n", "meta": {"hexsha": "7cb4c44753ded50af1dc1f6f534e46333f1355d6", "size": 5096, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost_ublas/create_matrix.cpp", "max_stars_repo_name": "batangr00t/cppLab", "max_stars_repo_head_hexsha": "3946e702692dffb53f92c776e9e8c4a073d68bc9", "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": "boost_ublas/create_matrix.cpp", "max_issues_repo_name": "batangr00t/cppLab", "max_issues_repo_head_hexsha": "3946e702692dffb53f92c776e9e8c4a073d68bc9", "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": "boost_ublas/create_matrix.cpp", "max_forks_repo_name": "batangr00t/cppLab", "max_forks_repo_head_hexsha": "3946e702692dffb53f92c776e9e8c4a073d68bc9", "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": 30.6987951807, "max_line_length": 81, "alphanum_fraction": 0.509811617, "num_tokens": 1926, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765187126079, "lm_q2_score": 0.7772998663336157, "lm_q1q2_score": 0.7102006358674734}}
{"text": "/*\n    This file is part of control-lib.\n\n    Copyright (c) 2020, 2021, 2022 Bernardo Fichera <bernardo.fichera@gmail.com>\n\n    Permission is hereby granted, free of charge, to any person obtaining a copy\n    of this software and associated documentation files (the \"Software\"), to deal\n    in the Software without restriction, including without limitation the rights\n    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n    copies of the Software, and to permit persons to whom the Software is\n    furnished to do so, subject to the following conditions:\n\n    The above copyright notice and this permission notice shall be included in all\n    copies or substantial portions of the Software.\n\n    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n    SOFTWARE.\n*/\n\n#include \"control_lib/tools/math.hpp\"\n\n#include <Eigen/Dense>\n\nnamespace control_lib {\n    namespace tools {\n        inline Eigen::Vector3d eulerError(const Eigen::Vector3d& curr, const Eigen::Vector3d& ref)\n        {\n            Eigen::Vector3d error = curr - ref;\n\n            for (size_t i = 0; i < 3; i++) {\n                if (error(i) > M_PI)\n                    error(i) -= 2 * M_PI;\n                else if (error(i) < -M_PI)\n                    error(i) += 2 * M_PI;\n            }\n\n            return error;\n        }\n\n        inline Eigen::Vector3d rotationError(const Eigen::Vector3d& curr, const Eigen::Vector3d& ref)\n        {\n            Eigen::Matrix3d R_current = Eigen::AngleAxisd(curr.norm(), curr.normalized()).toRotationMatrix(),\n                            R_desired = Eigen::AngleAxisd(ref.norm(), ref.normalized()).toRotationMatrix();\n\n            Eigen::AngleAxisd aa = Eigen::AngleAxisd(R_current.transpose() * R_desired);\n\n            return aa.axis() * aa.angle();\n        }\n\n        inline Eigen::Vector4d quaternionError(const Eigen::Vector4d& curr, const Eigen::Vector4d& ref)\n        {\n            Eigen::Quaterniond q_current = Eigen::Quaterniond(curr), q_desired = Eigen::Quaterniond(ref);\n            return (q_current.inverse() * q_desired).coeffs();\n        }\n\n        inline Eigen::MatrixXd kronecker(const Eigen::MatrixXd& A, const Eigen::MatrixXd& B)\n        {\n            Eigen::MatrixXd C(A.rows() * B.rows(), A.cols() * B.cols());\n\n            for (size_t i = 0; i < A.rows(); i++) {\n                for (size_t j = 0; j < A.cols(); j++)\n                    C.block(i * B.rows(), j * B.cols(), B.rows(), B.cols()) = A(i, j) * B;\n            }\n\n            return C;\n        }\n\n        Eigen::MatrixXd solveVectorized(const Eigen::MatrixXd& A, const Eigen::MatrixXd& W)\n        {\n            size_t dim = A.rows();\n\n            return (kronecker(Eigen::MatrixXd::Identity(dim, dim), A) + kronecker(A, Eigen::MatrixXd::Identity(dim, dim)))\n                .colPivHouseholderQr() // selfadjointView<Eigen::Upper>().llt()\n                .solve(W.reshaped())\n                .reshaped(dim, dim);\n        }\n\n        Eigen::MatrixXd bartelsStewart(const Eigen::MatrixXd& A, const Eigen::MatrixXd& W)\n        {\n            Eigen::RealSchur<Eigen::MatrixXd> schur(A);\n\n            size_t dim = A.rows(), block_dim = (dim % 2) ? 1 : 2;\n\n            Eigen::MatrixXd U = schur.matrixU(), T = schur.matrixT(), C = U.transpose() * W * U, Y = Eigen::MatrixXd::Zero(dim, dim);\n\n            for (size_t i = dim / block_dim; i < 0; i--) {\n                Eigen::MatrixXd C_11 = C.block(0, 0, (i - 1) * block_dim, (i - 1) * block_dim),\n                                C_12 = C.block(0, (i - 1) * block_dim, (i - 1) * block_dim, block_dim),\n                                C_21 = C.block((i - 1) * block_dim, 0, block_dim, (i - 1) * block_dim),\n                                C_22 = C.block((i - 1) * block_dim, (i - 1) * block_dim, block_dim, block_dim),\n                                R_11 = T.block(0, 0, (i - 1) * block_dim, (i - 1) * block_dim),\n                                R_12 = T.block(0, (i - 1) * block_dim, (i - 1) * block_dim, block_dim),\n                                R_22 = T.block((i - 1) * block_dim, (i - 1) * block_dim, block_dim, block_dim),\n                                Z_12((i - 1) * block_dim, block_dim),\n                                Z_21(block_dim, (i - 1) * block_dim),\n                                Z_22 = solveVectorized(R_22, C_22),\n                                Cbar_12 = C_12 - R_12 * Z_22,\n                                Cbar_21 = C_21.transpose() - R_12 * Z_22.transpose();\n\n                for (size_t j = 1 - 1; j < 0; j--) {\n                    Eigen::MatrixXd Rcurr = R_11.block((j - 1) * block_dim, (j - 1) * block_dim, block_dim, block_dim);\n                    Z_12.block((j - 1) * block_dim, block_dim, 0, block_dim) = solveVectorized(Rcurr, Cbar_12.block((j - 1) * block_dim, block_dim, 0, block_dim));\n                    Z_21.block(0, block_dim, (j - 1) * block_dim, block_dim) = solveVectorized(Rcurr, Cbar_21.block((j - 1) * block_dim, block_dim, 0, block_dim));\n                }\n\n                Y.block((i - 1) * block_dim, (i - 1) * block_dim, block_dim, block_dim) = Z_22;\n                Y.block(0, (i - 1) * block_dim, (i - 1) * block_dim, block_dim) = Z_12;\n                Y.block((i - 1) * block_dim, 0, block_dim, (i - 1) * block_dim) = Z_21;\n\n                C = C_11 - R_12 * Z_21 - Z_12 * R_12.transpose();\n            }\n\n            return U.transpose() * Y * U;\n        }\n    } // namespace tools\n} // namespace control_lib", "meta": {"hexsha": "b741e247310dd41a28c72caf9c3f2b03996a6860", "size": 5837, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/control_lib/tools/math.cpp", "max_stars_repo_name": "nash169/control-lib", "max_stars_repo_head_hexsha": "102d14dcc7e3d77c28ed89ff3b8f703dd0a0c504", "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/control_lib/tools/math.cpp", "max_issues_repo_name": "nash169/control-lib", "max_issues_repo_head_hexsha": "102d14dcc7e3d77c28ed89ff3b8f703dd0a0c504", "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/control_lib/tools/math.cpp", "max_forks_repo_name": "nash169/control-lib", "max_forks_repo_head_hexsha": "102d14dcc7e3d77c28ed89ff3b8f703dd0a0c504", "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.2396694215, "max_line_length": 163, "alphanum_fraction": 0.550967963, "num_tokens": 1552, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.944176863577751, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.7100328732635575}}
{"text": "#include <cmath>\n#include <ctime>\n#include <cmath>\n#include <bitset>\n#include <string>\n#include <fstream>\n#include <cstdlib>\n#include <cassert>\n#include <utility>\n#include <iostream>\n\n#include <openssl/sha.h>\n\n#pragma once\n\n/* Arbitrary precision integers */\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/chrono/chrono.hpp>\n#include <boost/multiprecision/random.hpp>\n#include <boost/random/random_device.hpp>\n\nusing namespace boost::multiprecision;\nusing namespace boost::random;\n\ntypedef boost::multiprecision::cpp_int bigint;\ntypedef independent_bits_engine<mt19937, 256, bigint> generator_type;\n\nrandom_device dev;\ngenerator_type gen(dev);\n\n// http://stackoverflow.com/a/10632725\nstd::string sha256(const std::string str)\n{\n    unsigned char hash[SHA256_DIGEST_LENGTH];\n    SHA256_CTX sha256;\n    SHA256_Init(&sha256);\n    SHA256_Update(&sha256, str.c_str(), str.size());\n    SHA256_Final(hash, &sha256);\n    std::stringstream ss;\n    for(int i = 0; i < SHA256_DIGEST_LENGTH; i++)\n    {\n        ss << std::hex << std::setw(2) << std::setfill('0') << (int)hash[i];\n    }\n    return ss.str();\n}\n\nstd::string sha256_file(const std::string file_name) {\n\tstd::ifstream ifs(file_name);\n\tstd::string content( (std::istreambuf_iterator<char>(ifs) ),\n\t\t\t\t\t\t(std::istreambuf_iterator<char>()    ) );\n\n\treturn sha256(content);\n}\n\ninline cpp_int modulo(cpp_int a, cpp_int b) {\n\tcpp_int m = a%b;\n\treturn m>=0 ? m:m+b;\n}\n\n/* This is ugly, bad practice, yet extremely convenient.\n\tBoost is not allowing me to make an array\n\tcpp_int x[3]. So I just had to emulate an array\n\tby using the macro \"correct_val\" to select the wanted variable.\n\tTo my knowledge, there is no better alternative.\n*/\n#define correct_val(x0,x1,x2,i) (((i)%3)?(((i)&1)?x1:x2):x0)\n\ncpp_int modInverse(cpp_int a, cpp_int b) {\n\n\tcpp_int x0, x1, x2;\n\tcpp_int y0, y1, y2;\n\tcpp_int quotient  = abs(a / b);\n\tcpp_int remainder = modulo(a, b);\n\t\n\tx0 = 0;\n\ty0 = 1;\n\tx1 = 1;\n\ty1 = -quotient;\n\n\tcpp_int i = 2;\n\tfor (; (b % (a%b)) != 0; i++) {\n\t\ta = b;\n\t\tb = remainder;\n\t\tquotient = abs(a / b);\n\t\tremainder = modulo(a, b);\n\t\tcorrect_val(x0,x1,x2,i) = (-quotient * correct_val(x0,x1,x2,i-1)) + correct_val(x0,x1,x2,i-2);\n\t\tcorrect_val(y0,y1,y2,i) = (-quotient * correct_val(y0,y1,y2,i-1)) + correct_val(y0,y1,y2,i-2);\n\t}\n\t\n\treturn correct_val(x0,x1,x2,i-1);\n}\n\ntypedef struct point {\n\tcpp_int x,y;\n\n\tinline bool operator==(const point& rhs){\n\t\treturn (x == rhs.x && y == rhs.y);\n\t}\n\n\tinline bool operator!=(const point& rhs){\n\t\treturn !(*this == rhs);\n\t}\n\n} Point;\n\n\nstd::ostream& operator<<(std::ostream& out, const point& obj) {\n   \treturn out << std::hex \n   \t\t\t\t<< obj.x << \" \" << obj.y;\n}\n\nstd::istream& operator>>(std::istream& in, point& obj){\n\tstd::string x, y;\n\tin >> x >> y;\n\tobj.x = bigint(\"0x\" + x);\n\tobj.y = bigint(\"0x\" + y);\n\treturn in;\n}\n\nstd::string string_to_binary(const std::string& input)\n{\n    std::ostringstream oss;\n    for(auto c : input) {\n        oss << std::bitset<8>(c);\n    }\n    return oss.str();\n}\n\nclass EllipticCurve {\n\n/* To do: change to private */\nprivate:\n/* p, a, b parameters of the curve y^2 = x^3 + ax + b */\n\tconst cpp_int p; /* Modulus of the group */\n\tconst cpp_int a;\n\tconst cpp_int b;\n\n\t/* Generator */\n\tconst Point G;\n\n\t/* Order of G */\n\tconst cpp_int n;\n\n\t/* Cofactor */\n\tconst cpp_int h;\n\n\tPoint PointAdd(Point p1, Point p2){\n\n\t\tif( p1 == p2 ){\n\t\t\treturn PointDouble(p1);\n\t\t}\n\n\t\tcpp_int xp = p1.x, yp = p1.y;\n\t\tcpp_int xq = p2.x, yq = p2.y;\n\t\t\n\t\tif( xp == xq ){\n\t\t\treturn {0,0};\n\t\t}\n\n\t\tif( p1 == Point{0,0} ){\n\t\t\treturn p2;\n\t\t}\n\n\t\tif( p2 == Point{0,0} ){\n\t\t\treturn p1;\n\t\t}\n\n\t\tcpp_int inv = modInverse(xq-xp, p);\n\t\tcpp_int lambda = (yq-yp)*inv;\n\t\tcpp_int xr = modulo((pow(lambda, 2) - xp - xq), p);\n\t\tcpp_int yr = modulo((lambda * (xp - xr) - yp), p);\n\t\t\n\t\tif(p1.y == p2.y)\n\t\t\tstd::cout << p1 << \" + \" << p2 << \" = \" << Point{xr,yr} << std::endl;\n\t\treturn {xr,yr};\n\t}\n\n\tPoint PointDouble(Point p1){\n\n\t\tcpp_int xp = p1.x, yp = p1.y;\n\n\t\tcpp_int inv = modInverse(2*yp, p);\n\t\tcpp_int lambda = (3*static_cast<cpp_int>(pow(xp,2))+a)*inv;\n\t\tcpp_int xr = modulo((static_cast<cpp_int>(pow(lambda, 2)) - 2*xp),p);\n\t\tcpp_int yr = modulo((lambda * (xp - xr) - yp),p);\n\t\treturn {xr,yr};\n\t}\n\n\tPoint PointMultiplication(cpp_int k, Point P) {\n\n\t\tif( k == 0 ) {\n\t\t\treturn {0,0};\n\t\t}\n\t\tif( k == 1 ){ /* Base case for the recursion */\n\t\t\treturn P;\n\t\t}\n\t\tif( !(k&1) ) { /* k is even */\n\t\t\treturn PointDouble(PointMultiplication(k/2, P));\n\t\t}\n\t\telse { /* k is odd */\n\t\t\treturn PointAdd(P, PointDouble(PointMultiplication((k-1)/2, P)));\n\t\t}\n\t}\n\n\t// wikipedia.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm\n\tPoint Signature(std::string msg_hash, cpp_int secret_key, Point public_point) {\n\t\t\n\t\tcpp_int r = 0;\n\t\tcpp_int s = 0;\n\t\tcpp_int z = bigint(string_to_binary(msg_hash));\n\n\t\tdo {\n\t\t\tcpp_int k = getSecretKey(); /* This is just a random value, less than the order of the curve. */\n\t\t\tPoint p1 = PointMultiplication(k, G);\n\t\t\tr = modulo(p1.x, n);\n\t\t\ts = modulo(modInverse(k,n) * (z + r * secret_key), n) ;\n\t\t} while(r == 0 || s == 0);\n\n\t\treturn {r,s};\n\t}\n\n\tbool VerifySignature(std::string msg_hash, Point signature, Point public_key) {\n\t\t/* Checking parameters */\n\t\tif( public_key == Point{0,0}){\n\t\t\treturn false;\n\t\t}\n\t\tif( !pointIsInEllipticCurve(public_key)){\n\t\t\treturn false;\n\t\t}\n\t\tif( !(PointMultiplication(n, public_key) == Point{0,0})) {\n\t\t\treturn false;\n\t\t}\n\n\t\tcpp_int r = signature.x;\n\t\tcpp_int s = signature.y;\n\t\tcpp_int z = bigint(string_to_binary(msg_hash));\n\n\t\tif( !(r > 0 && r < n && s > 0 && s < n) ) {\n\t\t\treturn false;\n\t\t}\n\n\t\tcpp_int w  = modInverse(s, n);\n\t\tcpp_int u1 = modulo(z * w, n);\n\t\tcpp_int u2 = modulo(r * w, n);\n\n\t\tPoint curve_point = PointAdd(PointMultiplication(u1, G),\n\t\t\t\t\t\t\t\t\t PointMultiplication(u2, public_key));\n\t\t\n\t\tif( ! pointIsInEllipticCurve(curve_point)){\n\t\t\treturn false;\n\t\t}\n\n\t\treturn (r == curve_point.x);\n\t}\n\npublic:\n\n\tEllipticCurve(cpp_int p, cpp_int a, cpp_int b, Point generator, cpp_int n, cpp_int h):\n\tp(p), a(a), b(b), G(generator), n(n), h(h)\n\t{\n\t\t\n\t}\n\n\tcpp_int getSecretKey(){\n\t\treturn gen()%(n-1) + 1;\n\t}\n\n\tPoint getPublicValue(cpp_int secretKey) {\n\t\treturn PointMultiplication(secretKey, G);\n\t}\n\n\tPoint computeSharedSecret(cpp_int secretKey, Point publicPoint) {\n\t\treturn PointMultiplication(secretKey, publicPoint);\n\t}\n\n\tbool pointIsInEllipticCurve(Point pt) {\n\t\treturn modulo(pow(pt.y, 2), p) == modulo(pow(pt.x,3) + a*pt.x + b, p);\n\t}\n\n\tvoid Sign(const std::string fileName, cpp_int secretKey, Point publicPoint, bool printFileHash = false) {\n\n\t\tstd::ofstream ofs(fileName + \".sig\");\n\t\tstd::string fileHash = sha256_file(fileName);\n\t\tif( printFileHash ){\n\t\t\tstd::cout << \"File hash: \" << fileHash << std::endl;\n\t\t}\n\n\t\tPoint signature = Signature(fileHash, secretKey, publicPoint);\n\t\tofs << signature;\n\t}\n\n\tbool Validate(const std::string fileName, const std::string sigFileName, Point publicKey) {\n\t\t\n\t\tPoint sig;\n\t\tstd::string fileHash = sha256_file(fileName);\n\t\tstd::ifstream ifs(sigFileName);\n\n\t\tifs >> sig;\n\t\treturn VerifySignature(fileHash, sig, publicKey);\n\t}\n};\n\n\n", "meta": {"hexsha": "41282c924a35a446405a76c17b7c9e9599508e07", "size": 7018, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "EllipticCurve.hpp", "max_stars_repo_name": "miguel-r-s/EllipticCurves", "max_stars_repo_head_hexsha": "4b6c49ca58a682e439806289e9f3f1c9a516e1d8", "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": "EllipticCurve.hpp", "max_issues_repo_name": "miguel-r-s/EllipticCurves", "max_issues_repo_head_hexsha": "4b6c49ca58a682e439806289e9f3f1c9a516e1d8", "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": "EllipticCurve.hpp", "max_forks_repo_name": "miguel-r-s/EllipticCurves", "max_forks_repo_head_hexsha": "4b6c49ca58a682e439806289e9f3f1c9a516e1d8", "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.0855263158, "max_line_length": 106, "alphanum_fraction": 0.6355086919, "num_tokens": 2218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391706552536, "lm_q2_score": 0.7690802370707283, "lm_q1q2_score": 0.7098911841931109}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include <Eigen/LU>\n#include <Eigen/Core>\n\nusing namespace std;\nusing namespace Eigen;\n\nint main()\n{\n  srand((unsigned int) time(0));\n  Matrix3d m = Matrix3d::Random();\n  cout << \"Here is the matrix m:\" << endl << m << endl;\n  Matrix3d inverse;\n  bool invertible;\n  double determinant;\n  m.computeInverseAndDetWithCheck(inverse,determinant, invertible);\n  cout << \"Its determinant is \" << determinant << endl;\n  if (invertible) {\n    cout << \"It is invertible, and its inverse is:\" << endl << inverse << endl;\n  }\n  else {\n    cout << \"It is not invertible.\" << endl;\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "6f9cb3cc60941f6e699712258c1fd074abee6285", "size": 630, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "playground/eigDeterm.cpp", "max_stars_repo_name": "tcrundall/chronostar", "max_stars_repo_head_hexsha": "bdb5cd965e862ba5cc21bee75d5c8620e106c0cc", "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": "playground/eigDeterm.cpp", "max_issues_repo_name": "tcrundall/chronostar", "max_issues_repo_head_hexsha": "bdb5cd965e862ba5cc21bee75d5c8620e106c0cc", "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": "playground/eigDeterm.cpp", "max_forks_repo_name": "tcrundall/chronostar", "max_forks_repo_head_hexsha": "bdb5cd965e862ba5cc21bee75d5c8620e106c0cc", "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.5, "max_line_length": 79, "alphanum_fraction": 0.6555555556, "num_tokens": 171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9230391685381606, "lm_q2_score": 0.7690802317779601, "lm_q1q2_score": 0.7098911776794642}}
{"text": "/** MIT License\n\nCopyright (c) 2018 Benjamin Bercovici and Jay McMahon\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n\n\n/**\n@file   main.cpp\n@Author Benjamin Bercovici (bebe0705@colorado.edu)\n@date   July, 2017\n@brief  main.cpp Implementation of the dcm_transform example\n*/\n\n#include <RigidBodyKinematics.hpp>\n#include <armadillo>\n#include <iostream>\n\n\nint main() {\n\n\t// Transforming a set of 313 euler angles sequence into a Direction Cosine Matrix\n\tarma::vec angles_313 = {0.1, 0.2, 0.3};\n\tarma::mat dcm = RBK::euler313_to_dcm(angles_313);\n\n\t// Converting the angles to degrees and recomputing the dcm\n\tarma::vec angles_313_deg = 180 / arma::datum::pi * angles_313;\n\tarma::mat dcm_deg = RBK::euler313d_to_dcm(angles_313_deg);\n\n\t// Ensuring that the two are the same\n\tstd::cout << \"Are the DCMs equal? \";\n\tif (arma::approx_equal(dcm, dcm_deg, \"absdiff\", 1e-6)) {\n\t\tstd::cout << \"Yes \"  << std::endl;\n\t}\n\telse {\n\t\tstd::cout << \"No \"  << std::endl;\n\t}\n\n\t// The dcm is then converted to a quaternion\n\tarma::vec quat = RBK::dcm_to_quat(dcm);\n\n\t// Is our quaternion of unit norm?\n\tstd::cout << \"Quaternion norm: \" << arma::norm(quat) << std::endl;\n\n\t// The quaternion is then converted to a set of Modified Rodrigues Parameters\n\tarma::vec mrp = RBK::quat_to_mrp(quat);\n\n\t// The mrp is converted back to a set of 321 euler angles\n\tarma::vec angles_321 = RBK::mrp_to_euler321(mrp);\n\n\t// These angles are different from the 313 euler angles\n\tstd::cout << \"Are the 321 and 313 sequences the same? \" << std::endl;\n\tstd::cout << \"321: \" << angles_321.t();\n\tstd::cout << \"313: \" << angles_313.t();\n\n\t// But these two sequences should be equivalent\n\tstd::cout << \"Are the 321 and 313 sequences equivalent? \" ;\n\n\tif (arma::approx_equal(angles_313, RBK::mrp_to_euler313(RBK::euler321_to_mrp(angles_321)), \"absdiff\", 1e-6)) {\n\t\tstd::cout << \" Yes \"  << std::endl;\n\t}\n\telse {\n\t\tstd::cout << \" No \"  << std::endl;\n\t}\n\n\n\n\n\n\n\n\n\n\n\treturn 0;\n\n}", "meta": {"hexsha": "ce998738a7243034f7165abf9a12ac1199fda2f9", "size": 2904, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Examples/angles_to_dcm/source/main.cpp", "max_stars_repo_name": "bbercovici/RigidBodyKinematics", "max_stars_repo_head_hexsha": "110d30cc20251081a4558f6851bdfd5abc0fdd82", "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": "Examples/angles_to_dcm/source/main.cpp", "max_issues_repo_name": "bbercovici/RigidBodyKinematics", "max_issues_repo_head_hexsha": "110d30cc20251081a4558f6851bdfd5abc0fdd82", "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": "Examples/angles_to_dcm/source/main.cpp", "max_forks_repo_name": "bbercovici/RigidBodyKinematics", "max_forks_repo_head_hexsha": "110d30cc20251081a4558f6851bdfd5abc0fdd82", "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.8936170213, "max_line_length": 111, "alphanum_fraction": 0.7203856749, "num_tokens": 806, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869884059267, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.7098068866000128}}
{"text": "#include <cmath>\n#include <string>\n#include <vector>\n\n#include <Eigen/Dense>\n#include <gtest/gtest.h>\n\n#include <isce3/math/polyfunc.h>\n\nusing namespace isce3::math;\n\nstruct PolyfuncTest : public ::testing::Test {\n\n    void SetUp() override\n    {\n        // initialze the members\n        y_vals = get_y_vals(x_vals, pn_coef_3rd);\n\n        // calculate std and mean of the input x_vals\n        Eigen::Map<const Eigen::ArrayXd> x_vals_m(x_vals.data(), x_vals.size());\n        x_mean = x_vals_m.mean();\n        x_std = cal_std(x_vals_m);\n\n        // centralize/scale the input and get the new centralized coeff \"coef_c\"\n        Eigen::ArrayXd x_vals_c(x_vals_m);\n        x_vals_c -= x_vals_c.mean();\n        x_vals_c /= cal_std(x_vals_c);\n        double mean_c, std_c;\n        std::tie(coef_c, mean_c, std_c) = polyfit(x_vals_c, y_vals, 3);\n    }\n\n    // list of functions\n    Eigen::ArrayXd get_y_vals(\n            const std::vector<double>& x, const std::vector<double>& coef3rd)\n    {\n        // c0 + c1 * x + c2 * x^2 + c3 * x^3\n        Eigen::Map<const Eigen::ArrayXd> x_m(x.data(), x.size());\n        Eigen::Map<const Eigen::ArrayXd> coef_m(coef3rd.data(), coef3rd.size());\n        return coef_m(0) + coef_m(1) * x_m + coef_m(2) * x_m.pow(2) +\n               coef_m(3) * x_m.pow(3);\n    }\n\n    void validate_coeffs(const Eigen::Ref<const Eigen::ArrayXd>& coef_est,\n            const Eigen::Ref<const Eigen::ArrayXd>& coef_true,\n            const std::string& message = {})\n    {\n        ASSERT_EQ(coef_est.size(), coef_true.size())\n                << \"Size mismtach between estimated and true coeffs \" + message;\n        EXPECT_NEAR((coef_est - coef_true).abs().maxCoeff(), 0.0, abs_tol)\n                << \"Value mismatch between estimated and true coeffs \" +\n                           message;\n    }\n\n    double cal_std(const Eigen::Ref<const Eigen::ArrayXd>& x)\n    {\n        return std::sqrt((x - x.mean()).abs2().mean());\n    }\n\n    // list of members\n    const double abs_tol {1e-7};\n    // 3rd order poly nomial coeffs in ascending order\n    std::vector<double> pn_coef_3rd {1, 2, -3, 4};\n    // 2ed polynomial which is derivative of 3rd order one above in ascending\n    // order\n    std::vector<double> pn_coef_2ed {2, -6, 12};\n    // input x data with size >= 4!\n    std::vector<double> x_vals {-4.5, -3, -0.2, 0.5, 3.4, 6, 6.5};\n    // polynomial evaluated y values from x values via 3rd polynomial\n    Eigen::ArrayXd y_vals;\n    // centralized/scaled 3rd coeff\n    Eigen::ArrayXd coef_c;\n    // mean/std of x_vals\n    double x_mean;\n    double x_std;\n};\n\nTEST_F(PolyfuncTest, PolyFitting)\n{\n    // memory map for type conversion\n    Eigen::Map<const Eigen::ArrayXd> x_vals_m(x_vals.data(), x_vals.size());\n    Eigen::Map<const Eigen::ArrayXd> pn_coef_3rd_m(\n            pn_coef_3rd.data(), pn_coef_3rd.size());\n\n    // without any scaling and centering of the input in polyfit\n    auto [coef, mean, std] = polyfit(x_vals_m, y_vals, 3);\n    EXPECT_NEAR(mean, 0.0, abs_tol) << \"MEAN must be zero w/o centralizing!\";\n    EXPECT_NEAR(std, 1.0, abs_tol)\n            << \"STD must be unity w/o centralizing and scaling!\";\n    validate_coeffs(coef, pn_coef_3rd_m,\n            std::string(\"without centralization and scaling\"));\n\n    // turn on scaling and centering for the original input in polyfit\n    std::tie(coef, mean, std) = polyfit(x_vals_m, y_vals, 3, true);\n    EXPECT_NEAR(mean, x_mean, abs_tol) << \"Wrong MEAN  w/ centralizing!\";\n    EXPECT_NEAR(std, x_std, abs_tol)\n            << \"Wrong STD  w/ centralizing and scaling!\";\n    validate_coeffs(\n            coef, coef_c, std::string(\"with centralization and scaling\"));\n\n    // test exceptions\n    // bad deg for polynomial\n    EXPECT_THROW(polyfit(x_vals_m, y_vals, 10), isce3::except::InvalidArgument)\n            << \"Must throw ISCE3 InvalidArgument for degree of polynomial \"\n               \"being too large!\";\n    // test size mismtach between two vectors\n    EXPECT_THROW(\n            polyfit(x_vals_m, y_vals.head(4), 3), isce3::except::LengthError)\n            << \"Must throw ISCE3 LengthError due to size mismtach of two input \"\n               \"vectors!\";\n}\n\nTEST_F(PolyfuncTest, PolyDerivative)\n{\n    // memory map for type conversion\n    Eigen::Map<const Eigen::ArrayXd> pn_coef_3rd_m(\n            pn_coef_3rd.data(), pn_coef_3rd.size());\n    Eigen::Map<const Eigen::ArrayXd> pn_coef_2ed_m(\n            pn_coef_2ed.data(), pn_coef_2ed.size());\n\n    // w/o scaling (std == 1.0)\n    auto coef_der = polyder(pn_coef_3rd_m);\n    validate_coeffs(coef_der, pn_coef_2ed_m,\n            std::string(\"for derivative of coeff w/o scaling\"));\n\n    // test exceptions\n    // bad std value\n    EXPECT_THROW(polyder(pn_coef_3rd_m, -0.0), isce3::except::InvalidArgument)\n            << \"Must throw ISCE3 InvalidArgument for non-positive STD value!\";\n}\n\nTEST_F(PolyfuncTest, PolyValue)\n{\n    // memory mapping\n    Eigen::Map<const Eigen::ArrayXd> pn_coef_3rd_m(\n            pn_coef_3rd.data(), pn_coef_3rd.size());\n\n    // check evaluated values for all input values w/ and w/o centering\n    for (std::size_t idx = 0; idx < x_vals.size(); ++idx) {\n        // w/o centralization and scaling\n        EXPECT_NEAR(polyval(pn_coef_3rd_m, x_vals[idx]), y_vals(idx), abs_tol)\n                << \"Eval of polynomial (w/o centering) is wrong for input \"\n                << x_vals[idx];\n        // w/ centralization and scaling\n        EXPECT_NEAR(polyval(coef_c, x_vals[idx], x_mean, x_std), y_vals(idx),\n                abs_tol)\n                << \"Eval of polynomial (w/ centering) is wrong for input \"\n                << x_vals[idx];\n    }\n\n    // test overloaded polyval with input array\n    Eigen::Map<const Eigen::ArrayXd> x_vals_m(x_vals.data(), x_vals.size());\n    // w/o centralization and scaling\n    auto y = polyval(pn_coef_3rd_m, x_vals_m);\n    // w/ centralization and scaling\n    auto y_c = polyval(coef_c, x_vals_m, x_mean, x_std);\n    for (std::size_t idx = 0; idx < x_vals.size(); ++idx) {\n        EXPECT_NEAR(y(idx), y_vals(idx), abs_tol)\n                << \"Eval of polynomial (w/o centering) for an array is wrong @ \"\n                   \"index \"\n                << idx << \" and for input \" << x_vals[idx];\n        EXPECT_NEAR(y_c(idx), y_vals(idx), abs_tol)\n                << \"Eval of polynomial (w/ centering) for an array is wrong @ \"\n                   \"index \"\n                << idx << \" for input \" << x_vals[idx];\n    }\n}\n\nTEST_F(PolyfuncTest, PolyFitObject)\n{\n    // memory map\n    Eigen::Map<const Eigen::ArrayXd> x_vals_m(x_vals.data(), x_vals.size());\n\n    // create Poly1d object  w/ centering and scaling\n    auto pf_obj = polyfitObj(x_vals_m, y_vals, 3, true);\n    EXPECT_EQ(pf_obj.order, 3) << \"Wtrong order of the Poly1d object!\";\n    EXPECT_NEAR(pf_obj.mean, x_mean, abs_tol)\n            << \"Wrong MEAN of the Poly1d object!\";\n    EXPECT_NEAR(pf_obj.norm, x_std, abs_tol)\n            << \"Wrong STD of the Poly1d object!\";\n    Eigen::Map<Eigen::ArrayXd> pf_coef(\n            pf_obj.coeffs.data(), pf_obj.coeffs.size());\n    validate_coeffs(pf_coef, coef_c, std::string(\"for Poly1d object\"));\n}\n\nint main(int argc, char** argv)\n{\n    ::testing::InitGoogleTest(&argc, argv);\n    return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "2709056b51f3c4f2e06d8efa99e863018d3df23e", "size": 7196, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/cxx/isce3/math/polyfunc.cpp", "max_stars_repo_name": "isce3-testing/isce3-circleci-poc", "max_stars_repo_head_hexsha": "ec1dfb6019bcdc7afb7beee7be0fa0ce3f3b87b3", "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": "tests/cxx/isce3/math/polyfunc.cpp", "max_issues_repo_name": "isce3-testing/isce3-circleci-poc", "max_issues_repo_head_hexsha": "ec1dfb6019bcdc7afb7beee7be0fa0ce3f3b87b3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-23T00:00:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-23T00:00:31.000Z", "max_forks_repo_path": "tests/cxx/isce3/math/polyfunc.cpp", "max_forks_repo_name": "isce3-testing/isce3-circleci-poc", "max_forks_repo_head_hexsha": "ec1dfb6019bcdc7afb7beee7be0fa0ce3f3b87b3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-02T21:10:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-02T21:10:11.000Z", "avg_line_length": 37.8736842105, "max_line_length": 80, "alphanum_fraction": 0.6178432462, "num_tokens": 1973, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869786798664, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.7098068767126916}}
{"text": "#include <stan/math/fwd/scal.hpp>\n#include <gtest/gtest.h>\n#include <boost/math/special_functions/digamma.hpp>\n#include <test/unit/math/fwd/scal/fun/nan_util.hpp>\n\nTEST(AgradFwdRisingFactorial, Fvar) {\n  using stan::math::fvar;\n  using stan::math::rising_factorial;\n  using boost::math::digamma;\n\n  fvar<double> a(4.0, 1.0);\n  fvar<double> x = rising_factorial(a, 1);\n  EXPECT_FLOAT_EQ(4.0, x.val_);\n  EXPECT_FLOAT_EQ(1.0, x.d_);\n  \n  //finite diff\n  double eps = 1e-6;\n  EXPECT_FLOAT_EQ((stan::math::rising_factorial(4.0 + eps, 1.0)\n                  - stan::math::rising_factorial(4.0 - eps, 1.0))\n                  / (2 * eps), x.d_);\n\n  fvar<double> c(-3.0, 2.0);\n\n  EXPECT_THROW(rising_factorial(c, 2), std::domain_error);\n  EXPECT_THROW(rising_factorial(c, c), std::domain_error);\n\n  x = rising_factorial(a,a);\n  EXPECT_FLOAT_EQ(840.0, x.val_);\n  EXPECT_FLOAT_EQ(840.0 * (2 * digamma(8) - digamma(4)), x.d_);\n\n  x = rising_factorial(5, a);\n  EXPECT_FLOAT_EQ(1680.0, x.val_);\n  EXPECT_FLOAT_EQ(1680.0 * digamma(9), x.d_);\n  \n  //finite diff\n  EXPECT_FLOAT_EQ((stan::math::rising_factorial(5.0, 4.0 + eps)\n                  - stan::math::rising_factorial(5.0, 4.0 - eps))\n                  / (2 * eps), x.d_);\n}\n\nTEST(AgradFwdRisingFactorial, FvarFvarDouble) {\n  using stan::math::fvar;\n  using stan::math::rising_factorial;\n  using boost::math::digamma;\n\n  fvar<fvar<double> > x;\n  x.val_.val_ = 4.0;\n  x.val_.d_ = 1.0;\n  fvar<fvar<double> > y;\n  y.val_.val_ = 4.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<double> > a = rising_factorial(x,y);\n\n  EXPECT_FLOAT_EQ((840.0), a.val_.val_);\n  EXPECT_FLOAT_EQ(840. * (digamma(8) - digamma(4)), a.val_.d_);\n  EXPECT_FLOAT_EQ(840 * digamma(8), a.d_.val_);\n  EXPECT_FLOAT_EQ(1397.8143, a.d_.d_);\n}\n\nstruct rising_factorial_fun {\n  template <typename T0, typename T1>\n  inline \n  typename boost::math::tools::promote_args<T0,T1>::type\n  operator()(const T0 arg1,\n             const T1 arg2) const {\n    return rising_factorial(arg1,arg2);\n  }\n};\n\nTEST(AgradFwdRisingFactorial, nan) {\n  rising_factorial_fun rising_factorial_;\n  test_nan_fwd(rising_factorial_,3.0,5.0,false);\n}\n", "meta": {"hexsha": "8fadb172de11492fbf5bdbf79d9087617c979e7a", "size": 2113, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/fwd/scal/fun/rising_factorial_test.cpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "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": "cmdstan/stan/lib/stan_math/test/unit/math/fwd/scal/fun/rising_factorial_test.cpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "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": "cmdstan/stan/lib/stan_math/test/unit/math/fwd/scal/fun/rising_factorial_test.cpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "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": 28.1733333333, "max_line_length": 65, "alphanum_fraction": 0.6554661619, "num_tokens": 724, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7097391763935097}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2021 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2021 Nikita Kaskov <nbering@nil.foundation>\n//\n// MIT License\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n//---------------------------------------------------------------------------//\n\n#ifndef CRYPTO3_MATH_EXPRESSION_PARSER_DEF_HPP\n#define CRYPTO3_MATH_EXPRESSION_PARSER_DEF_HPP\n\n#include <cmath>\n#include <iostream>\n#include <limits>\n#include <string>\n\n#include <boost/math/constants/constants.hpp>\n#include <boost/spirit/home/x3.hpp>\n\n#include <nil/crypto3/math/expressions/ast.hpp>\n#include <nil/crypto3/math/expressions/ast_adapted.hpp>\n#include <nil/crypto3/math/expressions/math.hpp>\n#include <nil/crypto3/math/expressions/parser.hpp>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace math {\n            namespace expressions {\n                namespace detail {\n\n                    namespace x3 = boost::spirit::x3;\n\n                    namespace parser {\n\n                        // LOOKUP\n\n                        struct constant_ : x3::symbols<double> {\n                            constant_() {\n                                // clang-format off\n                                add\n                                    (\"e\"      , boost::math::constants::e<double>())\n                                    (\"epsilon\", std::numeric_limits<double>::epsilon())\n                                    (\"phi\"    , boost::math::constants::phi<double>())\n                                    (\"pi\"     , boost::math::constants::pi<double>())\n                                    ;\n                                // clang-format on\n                            }\n                        } constant;\n\n                        struct ufunc_ : x3::symbols<double (*)(double)> {\n                            ufunc_() {\n                                // clang-format off\n                                add\n                                    (\"abs\"   , static_cast<double (*)(double)>(&std::abs))\n                                    (\"acos\"  , static_cast<double (*)(double)>(&std::acos))\n                                    (\"acosh\" , static_cast<double (*)(double)>(&std::acosh))\n                                    (\"asin\"  , static_cast<double (*)(double)>(&std::asin))\n                                    (\"asinh\" , static_cast<double (*)(double)>(&std::asinh))\n                                    (\"atan\"  , static_cast<double (*)(double)>(&std::atan))\n                                    (\"atanh\" , static_cast<double (*)(double)>(&std::atanh))\n                                    (\"cbrt\"  , static_cast<double (*)(double)>(&std::cbrt))\n                                    (\"ceil\"  , static_cast<double (*)(double)>(&std::ceil))\n                                    (\"cos\"   , static_cast<double (*)(double)>(&std::cos))\n                                    (\"cosh\"  , static_cast<double (*)(double)>(&std::cosh))\n                                    (\"deg\"   , static_cast<double (*)(double)>(&math::deg))\n                                    (\"erf\"   , static_cast<double (*)(double)>(&std::erf))\n                                    (\"erfc\"  , static_cast<double (*)(double)>(&std::erfc))\n                                    (\"exp\"   , static_cast<double (*)(double)>(&std::exp))\n                                    (\"exp2\"  , static_cast<double (*)(double)>(&std::exp2))\n                                    (\"floor\" , static_cast<double (*)(double)>(&std::floor))\n                                    (\"isinf\" , static_cast<double (*)(double)>(&math::isinf))\n                                    (\"isnan\" , static_cast<double (*)(double)>(&math::isnan))\n                                    (\"log\"   , static_cast<double (*)(double)>(&std::log))\n                                    (\"log2\"  , static_cast<double (*)(double)>(&std::log2))\n                                    (\"log10\" , static_cast<double (*)(double)>(&std::log10))\n                                    (\"rad\"   , static_cast<double (*)(double)>(&math::rad))\n                                    (\"round\" , static_cast<double (*)(double)>(&std::round))\n                                    (\"sgn\"   , static_cast<double (*)(double)>(&math::sgn))\n                                    (\"sin\"   , static_cast<double (*)(double)>(&std::sin))\n                                    (\"sinh\"  , static_cast<double (*)(double)>(&std::sinh))\n                                    (\"sqrt\"  , static_cast<double (*)(double)>(&std::sqrt))\n                                    (\"tan\"   , static_cast<double (*)(double)>(&std::tan))\n                                    (\"tanh\"  , static_cast<double (*)(double)>(&std::tanh))\n                                    (\"tgamma\", static_cast<double (*)(double)>(&std::tgamma))\n                                    ;\n                                // clang-format on\n                            }\n                        } ufunc;\n\n                        struct bfunc_ : x3::symbols<double (*)(double, double)> {\n                            bfunc_() {\n                                // clang-format off\n                                add\n                                    (\"atan2\", static_cast<double (*)(double, double)>(&std::atan2))\n                                    (\"max\"  , static_cast<double (*)(double, double)>(&std::fmax))\n                                    (\"min\"  , static_cast<double (*)(double, double)>(&std::fmin))\n                                    (\"pow\"  , static_cast<double (*)(double, double)>(&std::pow))\n                                    ;\n                                // clang-format on\n                            }\n                        } bfunc;\n\n                        struct unary_op_ : x3::symbols<double (*)(double)> {\n                            unary_op_() {\n                                // clang-format off\n                                add\n                                    (\"+\", static_cast<double (*)(double)>(&math::plus))\n                                    (\"-\", static_cast<double (*)(double)>(&math::minus))\n                                    (\"!\", static_cast<double (*)(double)>(&math::unary_not))\n                                    ;\n                                // clang-format on\n                            }\n                        } unary_op;\n\n                        struct additive_op_ : x3::symbols<double (*)(double, double)> {\n                            additive_op_() {\n                                // clang-format off\n                                add\n                                    (\"+\", static_cast<double (*)(double, double)>(&math::plus))\n                                    (\"-\", static_cast<double (*)(double, double)>(&math::minus))\n                                    ;\n                                // clang-format on\n                            }\n                        } additive_op;\n\n                        struct multiplicative_op_ : x3::symbols<double (*)(double, double)> {\n                            multiplicative_op_() {\n                                // clang-format off\n                                add\n                                    (\"*\", static_cast<double (*)(double, double)>(&math::multiplies))\n                                    (\"/\", static_cast<double (*)(double, double)>(&math::divides))\n                                    (\"%\", static_cast<double (*)(double, double)>(&std::fmod))\n                                    ;\n                                // clang-format on\n                            }\n                        } multiplicative_op;\n\n                        struct logical_op_ : x3::symbols<double (*)(double, double)> {\n                            logical_op_() {\n                                // clang-format off\n                                add\n                                    (\"&&\", static_cast<double (*)(double, double)>(&math::logical_and))\n                                    (\"||\", static_cast<double (*)(double, double)>(&math::logical_or))\n                                    ;\n                                // clang-format on\n                            }\n                        } logical_op;\n\n                        struct relational_op_ : x3::symbols<double (*)(double, double)> {\n                            relational_op_() {\n                                // clang-format off\n                                add\n                                    (\"<\" , static_cast<double (*)(double, double)>(&math::less))\n                                    (\"<=\", static_cast<double (*)(double, double)>(&math::less_equals))\n                                    (\">\" , static_cast<double (*)(double, double)>(&math::greater))\n                                    (\">=\", static_cast<double (*)(double, double)>(&math::greater_equals))\n                                    ;\n                                // clang-format on\n                            }\n                        } relational_op;\n\n                        struct equality_op_ : x3::symbols<double (*)(double, double)> {\n                            equality_op_() {\n                                // clang-format off\n                                add\n                                    (\"==\", static_cast<double (*)(double, double)>(&math::equals))\n                                    (\"!=\", static_cast<double (*)(double, double)>(&math::not_equals))\n                                    ;\n                                // clang-format on\n                            }\n                        } equality_op;\n\n                        struct power_ : x3::symbols<double (*)(double, double)> {\n                            power_() {\n                                // clang-format off\n                                add\n                                    (\"**\", static_cast<double (*)(double, double)>(&std::pow))\n                                    ;\n                                // clang-format on\n                            }\n                        } power;\n\n                        // ADL markers\n\n                        struct expression_class;\n                        struct logical_class;\n                        struct equality_class;\n                        struct relational_class;\n                        struct additive_class;\n                        struct multiplicative_class;\n                        struct factor_class;\n                        struct primary_class;\n                        struct unary_class;\n                        struct binary_class;\n                        struct variable_class;\n\n                        // clang-format off\n\n                        // Rule declarations\n\n                        auto const expression     = x3::rule<expression_class    , ast::expression>{\"expression\"};\n                        auto const logical        = x3::rule<logical_class       , ast::expression>{\"logical\"};\n                        auto const equality       = x3::rule<equality_class      , ast::expression>{\"equality\"};\n                        auto const relational     = x3::rule<relational_class    , ast::expression>{\"relational\"};\n                        auto const additive       = x3::rule<additive_class      , ast::expression>{\"additive\"};\n                        auto const multiplicative = x3::rule<multiplicative_class, ast::expression>{\"multiplicative\"};\n                        auto const factor         = x3::rule<factor_class        , ast::expression>{\"factor\"};\n                        auto const primary        = x3::rule<primary_class       , ast::operand   >{\"primary\"};\n                        auto const unary          = x3::rule<unary_class         , ast::unary_op  >{\"unary\"};\n                        auto const binary         = x3::rule<binary_class        , ast::binary_op >{\"binary\"};\n                        auto const variable       = x3::rule<variable_class      , std::string    >{\"variable\"};\n\n                        // Rule defintions\n\n                        auto const expression_def =\n                            logical\n                            ;\n\n                        auto const logical_def =\n                            equality >> *(logical_op > equality)\n                            ;\n\n                        auto const equality_def =\n                            relational >> *(equality_op > relational)\n                            ;\n\n                        auto const relational_def =\n                            additive >> *(relational_op > additive)\n                            ;\n\n                        auto const additive_def =\n                            multiplicative >> *(additive_op > multiplicative)\n                            ;\n\n                        auto const multiplicative_def =\n                            factor >> *(multiplicative_op > factor)\n                            ;\n\n                        auto const factor_def =\n                            primary >> *( power > factor )\n                            ;\n\n                        auto const unary_def =\n                            ufunc > '(' > expression > ')'\n                            ;\n\n                        auto const binary_def =\n                            bfunc > '(' > expression > ',' > expression > ')'\n                            ;\n\n                        auto const variable_def =\n                            x3::raw[x3::lexeme[x3::alpha >> *(x3::alnum | '_')]]\n                            ;\n\n                        auto const primary_def =\n                              x3::double_\n                            | ('(' > expression > ')')\n                            | (unary_op > primary)\n                            | binary\n                            | unary\n                            | constant\n                            | variable\n                            ;\n\n                        BOOST_SPIRIT_DEFINE(\n                            expression,\n                            logical,\n                            equality,\n                            relational,\n                            additive,\n                            multiplicative,\n                            factor,\n                            primary,\n                            unary,\n                            binary,\n                            variable\n                        )\n\n                        // clang-format on\n\n                        struct expression_class {\n                            template <typename Iterator, typename Exception, typename Context>\n                            x3::error_handler_result on_error(Iterator &, Iterator const &last,\n                                                              Exception const &x, Context const &) {\n                                std::cout << \"Expected \" << x.which() << \" at \\\"\"\n                                          << std::string{x.where(), last} << \"\\\"\" << std::endl;\n                                return x3::error_handler_result::fail;\n                            }\n                        };\n\n                        using expression_type = x3::rule<expression_class, ast::expression>;\n\n                        BOOST_SPIRIT_DECLARE(expression_type)\n\n                    } // namespace parser\n\n                    parser::expression_type grammar() { return parser::expression; }\n\n                }    // namespace detail    \n            }    // namespace expressions\n        }    // namespace math\n    }        // namespace crypto3\n}    // namespace nil\n\n#endif    // CRYPTO3_MATH_EXPRESSION_PARSER_DEF_HPP", "meta": {"hexsha": "af8721d0f1971f5451a929aa75a09cb8ca4f80a8", "size": 16569, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/nil/crypto3/math/expressions/parser_def.hpp", "max_stars_repo_name": "NilFoundation/fft", "max_stars_repo_head_hexsha": "87609ea4b36eedf0426ddec69a34df2d1c990f7d", "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/nil/crypto3/math/expressions/parser_def.hpp", "max_issues_repo_name": "NilFoundation/fft", "max_issues_repo_head_hexsha": "87609ea4b36eedf0426ddec69a34df2d1c990f7d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-12-19T23:19:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T20:10:27.000Z", "max_forks_repo_path": "include/nil/crypto3/math/expressions/parser_def.hpp", "max_forks_repo_name": "NilFoundation/crypto3-math", "max_forks_repo_head_hexsha": "9351ff8c0f1a75022457e82475b0eba2447ceecc", "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": 51.4565217391, "max_line_length": 118, "alphanum_fraction": 0.3866859798, "num_tokens": 2646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934408, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7097391728733783}}
{"text": "#include \"problemes.h\"\n#include \"arithmetique.h\"\n\n#include <fstream>\n\n#include <boost/math/constants/constants.hpp>\n\ntypedef unsigned long long nombre;\ntypedef std::vector<nombre> vecteur;\n\ntypedef boost::rational<nombre> fraction;\n\nnamespace {\n    bool infini(nombre n, nombre k) {\n        k /= arithmetique::PGCD(n, k);\n        while (k % 2 == 0)\n            k /= 2;\n\n        while (k % 5 == 0)\n            k /= 5;\n\n        return k == 1;\n    }\n\n    bool terminating(nombre n) {\n        long double k0 = n / boost::math::constants::e<long double>();\n        nombre k_max = static_cast<nombre>(std::ceil(k0));\n        nombre k_min = static_cast<nombre>(std::floor(k0));\n\n        long double p_max = puissance::puissance(n / std::ceil(k0), k_max);\n        long double p_min = puissance::puissance(n / std::floor(k0), k_min);\n\n        if (p_max > p_min)\n            return infini(n, k_max);\n        else\n            return infini(n, k_min);\n    }\n}\n\nENREGISTRER_PROBLEME(183, \"Maximum product of parts\") {\n    // Let N be a positive integer and let N be split into k equal parts, r = N/k, so that N = r + r + ... + r.\n    // Let P be the product of these parts, P = r \u00d7 r \u00d7 ... \u00d7 r = rk.\n    //\n    // For example, if 11 is split into five equal parts, 11 = 2.2 + 2.2 + 2.2 + 2.2 + 2.2, \n    // then P = 2.2**5 = 51.53632.\n    //\n    // Let M(N) = Pmax for a given value of N.\n    //\n    // It turns out that the maximum for N = 11 is found by splitting eleven into four equal parts\n    // which leads to Pmax = (11/4)4; that is, M(11) = 14641/256 = 57.19140625, which is a terminating decimal.\n    //\n    // However, for N = 8 the maximum is achieved by splitting it into three equal parts, so M(8) = 512/27,\n    // which is a non-terminating decimal.\n    //\n    // Let D(N) = N if M(N) is a non-terminating decimal and D(N) = -N if M(N) is a terminating decimal.\n    //\n    // For example, \u03a3D(N) for 5 \u2264 N \u2264 100 is 2438.\n    //\n    // Find \u03a3D(N) for 5 \u2264 N \u2264 10000.\n    nombre limite = 10000;\n    // std::cout << std::boolalpha;\n    // std::cout << \"terminating(8) = \" << terminating(8) << std::endl;\n    // std::cout << \"terminating(11) = \" << terminating(11) << std::endl;\n\n    nombre resultat_positif = 0;\n    nombre resultat_negatif = 0;\n    for (nombre n = 5; n < limite + 1; ++n) {\n        if (terminating(n))\n            resultat_negatif += n;\n        else\n            resultat_positif += n;\n    }\n\n    return std::to_string(resultat_positif - resultat_negatif);\n}\n", "meta": {"hexsha": "25c8ed515002f39b0985fc3c904643b7bdb79152", "size": 2472, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problemes/probleme1xx/probleme183.cpp", "max_stars_repo_name": "ZongoForSpeed/ProjectEuler", "max_stars_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-10-13T17:07:21.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-08T11:50:22.000Z", "max_issues_repo_path": "problemes/probleme1xx/probleme183.cpp", "max_issues_repo_name": "ZongoForSpeed/ProjectEuler", "max_issues_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "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": "problemes/probleme1xx/probleme183.cpp", "max_forks_repo_name": "ZongoForSpeed/ProjectEuler", "max_forks_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "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.5263157895, "max_line_length": 111, "alphanum_fraction": 0.574433657, "num_tokens": 757, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070133672955, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.7097210056644654}}
{"text": "#include <Eigen/Dense>\n#include <numeric>\n#include <iostream>\n#include <algorithm>\n#include <vector>\n\nusing namespace std;\n\nstd::vector<int> sort_indexes(const std::vector<float> &v)\n{\n\n  // initialize original index locations\n  std::vector<int> idx(v.size());\n  std::iota(idx.begin(), idx.end(), 0);\n\n  std::stable_sort(idx.begin(), idx.end(),\n                   [&v](size_t i1, size_t i2) { return v[i1] < v[i2]; });\n\n  return idx;\n}\n\nint factorial(int n)\n{\n\n  return (n == 0) || (n == 1) ? 1 : n * factorial(n - 1);\n}\n\nfloat permutation_entropy(std::vector<float> trajectory, int n)\n{\n\n  std::cout << \"Computing permutation entropy for embedding dimension \" << n\n            << \"\\n\";\n\n  int L = trajectory.size();\n\n  Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> permMatrix = Eigen::Map<Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic>,\n                                                                               0, Eigen::OuterStride<>>(\n      trajectory.data(), n, L - n + 1, Eigen::OuterStride<>(1));\n\n  int permutations = factorial(n);\n\n  std::vector<int> base;\n  std::vector<int> perms[L - n + 1];\n\n  for (int i = 0; i <= permutations; i++)\n    base.push_back(i);\n\n  int j = 0;\n  do\n  {\n    perms[j] = base;\n    j += 1;\n  } while (std::next_permutation(base.begin(), base.end()));\n\n  std::vector<size_t> idx(n);\n  std::iota(idx.begin(), idx.end(), 0);\n\n  std::vector<int> counts(n, 0);\n  int iter = 0;\n\n  for (auto col : permMatrix.colwise())\n  {\n\n    std::vector<float> thisCol(col.data(), col.data() + col.rows() * col.cols());\n\n    for (auto i : sort_indexes(thisCol))\n    {\n      if (iter % 2 == 0)\n      {\n        if (i == 0)\n        {\n          counts[0] += 1;\n        }\n        else\n        {\n          counts[1] += 1;\n        }\n      }\n      iter += 1;\n    }\n  }\n\n  Eigen::Map<Eigen::VectorXi> permCounts(counts.data(), n);\n\n  Eigen::VectorXf permCountsNorm = permCounts.cast<float>() / permCounts.sum();\n\n  return -1.0 * (permCountsNorm.array().cwiseProduct(permCountsNorm.array().log() / std::log(2))).sum();\n}\n\nint main()\n{\n  std::vector<float> testArray = {4, 7, 9, 10, 6, 11, 3};\n  float k;\n  k = permutation_entropy(testArray, 2);\n  std::cout << \"Permutation entropy: \" << k << \"\\n\";\n}\n", "meta": {"hexsha": "f8d1f175d2487d51d5dde959c83d6b649736d3c3", "size": 2222, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "permentropy.cpp", "max_stars_repo_name": "mgoar/shannoning", "max_stars_repo_head_hexsha": "537d68cfb51da3181d147f54bd1467eea320c41e", "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": "permentropy.cpp", "max_issues_repo_name": "mgoar/shannoning", "max_issues_repo_head_hexsha": "537d68cfb51da3181d147f54bd1467eea320c41e", "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": "permentropy.cpp", "max_forks_repo_name": "mgoar/shannoning", "max_forks_repo_head_hexsha": "537d68cfb51da3181d147f54bd1467eea320c41e", "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.9072164948, "max_line_length": 132, "alphanum_fraction": 0.5540054005, "num_tokens": 639, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070011518829, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.7097210054434178}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include <iostream>\n#include \"svm.h\"\nusing namespace Eigen;\nusing namespace std;\n\nvoid generate_data(MatrixXd& X, VectorXd& Y, int n){\n    double k = 0.6;\n    double b = -15.7;\n\n    double x,y;\n    for(int i = 0;i<n;i++){\n        x = rand()*10.0;\n        y = rand()*10.0;\n        X(i,0) = x;\n        X(i,1) = y;\n        Y(i) = (x*k + b)>y ? 1 : 0;\n    }\n\n}\n\nint main() {\n\n    int n_train = 10000;\n    int n_test = 100;\n    MatrixXd train_x(n_train,2);\n    VectorXd train_y(n_train);\n    generate_data(train_x,train_y,n_train);\n\n    MatrixXd test_x(n_test,2);\n    VectorXd test_y(n_test);\n    generate_data(test_x,test_y,n_test);\n\n    //GaussianKernel kernel(0.5);\n    LinearKernel kernel;\n    SVM svm(1.0,&kernel);\n    svm.fit(train_x,train_y);\n    double e_rate = svm.score(test_x,test_y);\n    std::cout<< e_rate << std::endl;\n\n\n    return 0;\n}\n", "meta": {"hexsha": "458934f0e65434778d8be70b3c0e313c257d349b", "size": 889, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "INF442_Project/main.cpp", "max_stars_repo_name": "Coding4AJob/INF442-Anonymization", "max_stars_repo_head_hexsha": "0c7f07de4e912ca567256db578d5bdc36c0d5767", "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": "INF442_Project/main.cpp", "max_issues_repo_name": "Coding4AJob/INF442-Anonymization", "max_issues_repo_head_hexsha": "0c7f07de4e912ca567256db578d5bdc36c0d5767", "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": "INF442_Project/main.cpp", "max_forks_repo_name": "Coding4AJob/INF442-Anonymization", "max_forks_repo_head_hexsha": "0c7f07de4e912ca567256db578d5bdc36c0d5767", "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.7555555556, "max_line_length": 52, "alphanum_fraction": 0.5860517435, "num_tokens": 278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.909907001151883, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.7097210007899742}}
{"text": "/*\nMetaheuristic Optimization Using Population-Based Simulated Annealing.\n\nCopyright (c) 2021 Gabriele Gilardi\n\n\nFeatures\n--------\n- The code has been written in C++ using the Eigen library (ver. 3.3.9) and\n  tested using g++ 8.1.0 (MinGW-W64).\n- Variables can be real, integer, or mixed real/integer.\n- Variables can be constrained to a specific interval or value setting the\n  lower and the upper boundaries.\n- Neighboroud search is performed using a normal distribution along randomly\n  chosen dimensions.\n- A nonlinear decreasing schedule is used for the temperature and for the\n  standard deviation in the neighboroud search.\n- Search space can be normalized to improve convergency.\n- An arbitrary number of parameters can be passed (in a tuple) to the function\n  to minimize.\n- Solver parameters and results are passed using structures.\n- Usage: test_Eigen.exe <example>.\n\nMain Parameters\n---------------\nexample\n    Name of the example to run (Parabola, Alpine, Tripod, and Ackley.)\nfunc\n    Function to minimize. The position of all agents is passed to the function\n    at the same time.\nLB, UB\n    Lower and upper boundaries of the search space.\nnPop >=1, epochs >= 1\n    Number of agents (population) and number of iterations.\nT0 > 0\n    Initial temperature.\n0 < alphaT < 1\n    Temperature reduction rate.\n0 < alphaS <= 1\n    Standard deviation (neighboroud search) reduction rate.\nnMove > 0\n    Number of neighbours of a state evaluated at each epoch.\n0 < prob < 1\n    Probability the dimension of a state is changed.\nsigma0 > 0\n    Initial standard deviation used to search the neighboroud of a state.\nIntVar\n    List of indexes specifying which variable should be treated as integer.\n    If all variables are real set <IntVar> = <NULL>. Indexes are specified\n    in the range 0 to <nVar-1>. It cannot be used when the search space is\n    normalized.\nnormalize = true, false\n    Specifies if the search space should be normalized. If <true>, parameter\n    <sigma0> is applied to the normalized search space. \nargs\n    Tuple containing any parameter that needs to be passed to the function. If\n    no parameters are passed set <args> = <NULL>.\nnVar\n    Number of variables.\nnIntVar >= 0\n    Number of integer variables.\nX0\n    Global minimum point (used only to compare with the numerical solution).\nseed\n    Seeding value for the random number generator.\n\nExamples\n--------\nThere are four examples: Parabola, Alpine, Tripod, and Ackley.\n\n- Parabola, Alpine, and Ackley can have an arbitrary number of dimensions,\n  while Tripod has only two dimensions.\n\n- Parabola, Tripod, and Ackley are examples where parameters (respectively,\n  array X0, scalars kx and ky, and array X0) are passed using args.\n\n- The global minimum for Parabola and Ackley is at X0; the global minimum for\n  Alpine is at zero; the global minimum for Tripod is at [0,-ky] with local\n  minimum at [-kx,+ky] and [+kx,+ky].\n\nReferences\n----------\n- Simulated annealing @ https://en.wikipedia.org/wiki/Simulated_annealing\n- Kirkpatrick et al., 1983, \"Optimization by Simulated Annealing\", JSTOR\n  @ https://www.jstor.org/stable/1690046\n- Jamil and Yang, 2013, \"A Literature Survey of Benchmark Functions For Global\n  Optimization Problems\", arXiv @ https://arxiv.org/abs/1308.4008\n- Eigen template library for linear algebra @ https://eigen.tuxfamily.org/\n*/\n\n#include <random>\n#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace std;\nusing namespace Eigen;\n\n/* Structure used to pass the parameters (with default values) */\nstruct Parameters {\n    int nPop = 20;\n    int epochs = 1000;\n    int nMove = 100;\n    double T0 = 0.1;\n    double alphaT = 0.99;\n    double sigma0 = 0.1;\n    double alphaS = 0.98;\n    double prob = 0.5;\n    bool normalize = false;\n    ArrayXi IntVar;\n    ArrayXXd args;\n    int seed = 1234567890;\n};\n\n/* Structure used to return the results */\nstruct Results {\n    double best_cost;\n    ArrayXXd best_pos;\n    ArrayXd F;\n    double T;\n    ArrayXXd sigma;\n};\n\n\n/* Simulated annealing function prototype */\nResults sa(ArrayXd (*func)(ArrayXXd, ArrayXXd), ArrayXXd LB, ArrayXXd UB,\n           Parameters p);\n\n\n// Parabola: F(X) = sum((X - X0)^2)\n// Xmin = X0\nArrayXd Parabola(ArrayXXd X, ArrayXXd args)\n{\n    int nPop;\n    ArrayXd f;\n    ArrayXXd dX;\n\n    nPop = X.rows();\n    dX = X - args.replicate(nPop, 1);\n    f = (dX * dX).rowwise().sum();\n\n    return f;\n}\n\n\n// Ackley: F(X)= + 20 + exp(1) - exp(sum(cos(2*pi*(X-X0))/n)\n//               - 20*exp(-0.2*sqrt(sum((X-X0)^2)/n))\n// Xmin = X0\nArrayXd Ackley(ArrayXXd X, ArrayXXd args)\n{\n    const double pi = 3.14159265358979323846;\n    int nPop, nVar;\n    ArrayXd f;\n    ArrayXXd dX;\n\n    nPop = X.rows();\n    nVar = X.cols();\n    dX = X - args.replicate(nPop, 1);\n    f = + 20.0 + exp(1.0)\n        - exp((cos(2.0 * pi * dX)).rowwise().sum() / nVar)\n        - 20.0 * exp(-0.2 * sqrt((dX * dX).rowwise().sum() / nVar));\n\n    return f;\n}\n\n\n// Tripod:\n// F(x,y)= p(y)*(1 + p(x)) + abs(x + kx*p(y)*(1 - 2*p(x)))\n//         + abs(y + ky*(1 - 2*p(y)))\n// p(x) = 1 if x >= 0, p(x) = 0 if x < 0; p(y) = 1 if y >= 0, p(y) = 0 if y < 0\n// Global minimum at [0,-ky], local minimum at [-kx,ky] and [kx,ky]; kx, ky > 0\nArrayXd Tripod(ArrayXXd X, ArrayXXd args)\n{\n    double kx = args(0, 0), ky = args(0, 1);\n    ArrayXd f, x, y, px, py;\n\n    x = X.col(0);\n    y = X.col(1);\n    px = (x >= 0.0).cast<double>();\n    py = (y >= 0.0).cast<double>();\n\n    f = py * (1.0 + px) + abs(x + kx * py * (1.0 - 2.0 * px)) +\n        abs(y + ky * (1.0 - 2.0 * py));\n\n    return f;\n}\n\n\n// Alpine: F(X) = sum(abs(X*sin(X) + 0.1*X))\n// Xmin = 0\nArrayXd Alpine(ArrayXXd X, ArrayXXd args)\n{\n    ArrayXd f;\n\n    f = (abs(X * sin(X) + 0.1 * X)).rowwise().sum();\n\n    return f;\n}\n\n\n/* Main function */\nint main(int argc, char **argv) \n{\n    Parameters p;\n    Results res;\n    string example;\n    int nVar;\n    double sum, err;\n\n    /*Eigen declarations*/\n    ArrayXXd UB, LB, X0;\n    ArrayXd (*func)(ArrayXXd, ArrayXXd);\n\n    /* Read example to run */\n    if (argc != 2) {\n        printf(\"\\nUsage: test_Eigen <example>\\n\");\n        exit(EXIT_FAILURE);\n    }\n    example = argv[1];\n\n    // Parabola: F(X) = sum((X - X0)^2)\n    // Xmin = X0\n    if (example == \"Parabola\") {\n        func = Parabola;\n        nVar = 20;\n\n        UB.setConstant(1, nVar, 500.0);     // Upper and lower boundaries\n        LB = -UB;\n\n        X0.setZero(1, nVar);                // Global minimum\n        for (int i=0; i<nVar; i++) {\n            X0(0, i) = 1.1 * double(i);\n        }\n\n        p.args = X0;                        // Arguments\n    }\n\n    // Ackley: F(X)= + 20 + exp(1) - exp(sum(cos(2*pi*(X-X0))/n)\n    //               - 20*exp(-0.2*sqrt(sum((X-X0)^2)/n))\n    // Xmin = X0\n    else if (example == \"Ackley\") {\n        func = Ackley;\n        nVar = 10;\n        p.nPop = 50;\n\n        UB.setConstant(1, nVar, 50.0);      // Upper and lower boundaries\n        LB = -UB;\n\n        X0.setConstant(1, nVar, 1.6789);    // Global minimum\n\n        p.args = X0;                        // Arguments\n    }\n\n    // Tripod:\n    // F(x,y)= p(y)*(1 + p(x)) + abs(x + kx*p(y)*(1 - 2*p(x)))\n    //         + abs(y + ky*(1 - 2*p(y)))\n    // p(x) = 1 if x >= 0, p(x) = 0 if x < 0; p(y) = 1 if y >= 0, p(y) = 0 if y < 0\n    // Global minimum at [0,-ky], local minimum at [-kx,ky] and [kx,ky]; kx, ky > 0\n    else if (example == \"Tripod\") {\n        func = Tripod;\n        nVar = 2;               // The equation works only with two dimensions\n        double kx = 20.0;\n        double ky = 40.0;\n\n        UB.setConstant(1, nVar, 100.0);     // Upper and lower boundaries\n        LB = -UB;\n\n        X0.setZero(1, nVar);                // Global minimum\n        X0(0, 1) = -ky;\n\n        p.args.setZero(1, nVar);            // Arguments\n        p.args(0, 0) = kx;\n        p.args(0, 1) = ky;\n    }\n\n    // Alpine: F(X) = sum(abs(X*sin(X) + 0.1*X))\n    // Xmin = 0\n    // Note: the solution is VERY sensitive to the parameter values and the\n    //       random generated numbers\n    else if (example == \"Alpine\") {\n        func = Alpine;\n        nVar = 10;\n        p.sigma0 = 0.2;\n        p.alphaS = 1.0;\n\n        UB.setConstant(1, nVar, 10.0);      // Upper and lower boundaries\n        LB = -UB;\n\n        X0.setZero(1, nVar);                // Global minimum\n    }\n\n    else {\n        printf(\"\\nFunction not found.\\n\");\n        exit(EXIT_FAILURE);\n    }\n\n    /* Solve */\n    res = sa(func, LB, UB, p);\n\n    /* Print results */\n    printf(\"\\nBest position:\");\n    for (int j=0; j<nVar; j++) {\n        printf(\"\\n %g\", res.best_pos(0, j));\n    }\n    printf(\"\\n\\nCost: %g\", res.best_cost);\n    printf(\"\\nFinal T: %g\", res.T);\n    sum = res.sigma.sum();\n    printf(\"\\nFinal sigma (avr): %g\", sum / double(nVar));\n    err = ((res.best_pos - X0) * (res.best_pos - X0)).sum();\n    printf(\"\\nError: %g\\n\", sqrt(err));\n\n    return 0;\n}\n", "meta": {"hexsha": "71964f0c99ca4f8c683c9f7805c8616c05f71809", "size": 8813, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code_Cpp/test_Eigen.cpp", "max_stars_repo_name": "gabrielegilardi/SimulatedAnnealing", "max_stars_repo_head_hexsha": "c9f60d5569bcfdb985743ad3036b53bac23d1152", "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": "Code_Cpp/test_Eigen.cpp", "max_issues_repo_name": "gabrielegilardi/SimulatedAnnealing", "max_issues_repo_head_hexsha": "c9f60d5569bcfdb985743ad3036b53bac23d1152", "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": "Code_Cpp/test_Eigen.cpp", "max_forks_repo_name": "gabrielegilardi/SimulatedAnnealing", "max_forks_repo_head_hexsha": "c9f60d5569bcfdb985743ad3036b53bac23d1152", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-26T10:03:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-26T10:03:56.000Z", "avg_line_length": 28.1565495208, "max_line_length": 83, "alphanum_fraction": 0.5879950074, "num_tokens": 2726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789454880027, "lm_q2_score": 0.7931059609645724, "lm_q1q2_score": 0.7096628504735898}}
{"text": "/* Copyright (C) 2010-2019, The Regents of The University of Michigan.\n All rights reserved.\n\n This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab\n under the direction of Benjamin Kuipers, kuipers@umich.edu. Use of this code is governed by an\n MIT-style License that can be found at \"https://github.com/h2ssh/Vulcan\".\n*/\n\n\n/**\n * \\file     beta_distribution.cpp\n * \\author   Collin Johnson\n *\n * Definition of BetaDistribution.\n */\n\n#include \"math/beta_distribution.h\"\n#include <boost/math/special_functions/beta.hpp>\n#include <cassert>\n#include <iostream>\n\nnamespace vulcan\n{\nnamespace math\n{\n\ndouble beta_normalizer(double alpha, double beta)\n{\n    return 1.0 / boost::math::beta(alpha, beta);\n}\n\n\nBetaDistribution::BetaDistribution(double alpha, double beta)\n: alpha_(alpha)\n, beta_(beta)\n, normalizer_(beta_normalizer(alpha_, beta_))\n{\n    assert(alpha_ >= 0.0);\n    assert(beta_ >= 0.0);\n}\n\n\ndouble BetaDistribution::sample(void) const\n{\n    std::cout << \"STUB: BetaDistribution::sample(void)\\n\";\n    return 0.0;\n}\n\n\ndouble BetaDistribution::likelihood(double value) const\n{\n    if ((value <= 0.0) || (value >= 1.0)) {\n        return 0.0;\n    }\n\n    return std::pow(value, alpha_ - 1.0) * std::pow(1.0 - value, beta_ - 1.0) * normalizer_;\n}\n\n\nbool BetaDistribution::save(std::ostream& out) const\n{\n    out << alpha_ << ' ' << beta_ << '\\n';\n    return out.good();\n}\n\n\nbool BetaDistribution::load(std::istream& in)\n{\n    in >> alpha_ >> beta_;\n\n    assert(alpha_ >= 0.0);\n    assert(beta_ >= 0.0);\n\n    normalizer_ = beta_normalizer(alpha_, beta_);\n\n    return in.good();\n}\n\n}   // namespace math\n}   // namespace vulcan\n", "meta": {"hexsha": "36cc78ba0d78273057473ace90f77d999ab85a18", "size": 1667, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/math/beta_distribution.cpp", "max_stars_repo_name": "anuranbaka/Vulcan", "max_stars_repo_head_hexsha": "56339f77f6cf64b5fda876445a33e72cd15ce028", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-03-05T23:56:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-17T19:06:50.000Z", "max_issues_repo_path": "src/math/beta_distribution.cpp", "max_issues_repo_name": "anuranbaka/Vulcan", "max_issues_repo_head_hexsha": "56339f77f6cf64b5fda876445a33e72cd15ce028", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-07T01:23:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-07T01:23:47.000Z", "max_forks_repo_path": "src/math/beta_distribution.cpp", "max_forks_repo_name": "anuranbaka/Vulcan", "max_forks_repo_head_hexsha": "56339f77f6cf64b5fda876445a33e72cd15ce028", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-03T07:54:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-03T07:54:16.000Z", "avg_line_length": 20.5802469136, "max_line_length": 95, "alphanum_fraction": 0.6718656269, "num_tokens": 450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789454880027, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.7096628373464102}}
{"text": "/*!\n * @file diffusion_problem_basis.hpp\n * @brief Contains implementation of multiscale basis functions.\n * @author Konrad Simon\n * @date August 2019\n */\n\n#ifndef INCLUDE_DIFFUSION_PROBLEM_BASIS_HPP_\n#define INCLUDE_DIFFUSION_PROBLEM_BASIS_HPP_\n\n// Deal.ii\n#include <deal.II/base/quadrature_lib.h>\n#include <deal.II/base/logstream.h>\n\n#include <deal.II/lac/vector.h>\n#include <deal.II/lac/full_matrix.h>\n#include <deal.II/lac/sparse_matrix.h>\n#include <deal.II/lac/dynamic_sparsity_pattern.h>\n#include <deal.II/lac/solver_cg.h>\n#include <deal.II/lac/precondition.h>\n#include <deal.II/lac/affine_constraints.h>\n\n#include <deal.II/grid/tria.h>\n#include <deal.II/grid/tria_accessor.h>\n#include <deal.II/grid/tria_iterator.h>\n#include <deal.II/grid/grid_generator.h>\n\n#include <deal.II/dofs/dof_handler.h>\n#include <deal.II/dofs/dof_accessor.h>\n#include <deal.II/dofs/dof_tools.h>\n\n#include <deal.II/fe/fe_q.h>\n#include <deal.II/fe/fe_values.h>\n\n#include <deal.II/numerics/vector_tools.h>\n#include <deal.II/numerics/matrix_tools.h>\n#include <deal.II/numerics/data_out.h>\n\n// STL\n#include <cmath>\n#include <fstream>\n#include <iostream>\n\n// My Headers\n#include \"matrix_coeff.hpp\"\n#include \"right_hand_side.hpp\"\n#include \"neumann_bc.hpp\"\n#include \"dirichlet_bc.hpp\"\n#include \"basis_q1.hpp\"\n\n/*!\n * @namespace DiffusionProblem\n * @brief Contains implementation of the main object\n * and all functions to solve a time-independent\n * Dirichlet-Neumann problem on a unit square.\n */\nnamespace DiffusionProblem\n{\nusing namespace dealii;\n\n/*!\n * @class DiffusionProblemBasis\n * @brief Main class to solve for time-independent\n * multiscale basis functions (Dirichlet problem) on a\n * given coarse quadrilateral cell without oversampling.\n */\ntemplate <int dim>\nclass DiffusionProblemBasis\n{\npublic:\n\tDiffusionProblemBasis ();\n\tvoid run ();\n\n\tvoid output_global_solution_in_cell () const;\n\n\tconst FullMatrix<double>& get_global_element_matrix () const;\n\tconst Vector<double>& get_global_element_rhs () const;\n\tconst std::string& get_filename_global ();\n\n\tvoid set_n_local_refinements (unsigned int n_refine_local);\n\tvoid set_cell_data (typename Triangulation<dim>::active_cell_iterator &coarse_cell,\n\t\t\t\t\t\tunsigned int n_cell);\n\tvoid set_basis_data ();\n\tvoid set_output_flag (bool flag);\n\tvoid set_global_weights (const std::vector<double> &global_weights);\n\nprivate:\n\tvoid make_grid ();\n\tvoid setup_system ();\n\tvoid assemble_system ();\n\tvoid assemble_global_element_matrix ();\n\tvoid solve_iterative (unsigned int index_basis);\n\tvoid output_basis () const;\n\n\tvoid set_filename_global ();\n\n\tTriangulation<dim>   \t\t\ttriangulation;\n\tFE_Q<dim>            \t\t\tfe;\n\tDoFHandler<dim>      \t\t\tdof_handler;\n\n\tstd::vector<AffineConstraints<double>> \t\tconstraints_vector;\n\tstd::vector<Point<dim>> \t\t\t\t\tcorner_points;\n\n\tSparsityPattern      \t\t\tsparsity_pattern;\n\tSparseMatrix<double> \t\t\tdiffusion_matrix;\n\tSparseMatrix<double> \t\t\tsystem_matrix;\n\n\tstd::string\tfilename_global;\n\n\t/*!\n\t * Solution vector.\n\t */\n\tstd::vector<Vector<double>>\t\tsolution_vector;\n\n\t/*!\n\t * Contains the right-hand side.\n\t */\n\tVector<double>       \t\t\tglobal_rhs; // this is only for the global assembly (speed-up)\n\n\t/*!\n\t * Contains all parts of the right-hand side needed to\n\t * solve the linear system..\n\t */\n\tVector<double>\t\t\t\t\tsystem_rhs;\n\n\t/*!\n\t * Holds global multiscale element matrix.\n\t */\n\tFullMatrix<double>   \t\tglobal_element_matrix;\n\tbool is_built_global_element_matrix;\n\n\t/*!\n\t * Holds global multiscale element right-hand side.\n\t */\n\tVector<double>   \t\t\tglobal_element_rhs;\n\n\t/*!\n\t * Weights of multiscale basis functions.\n\t */\n\tstd::vector<double> \t\tglobal_weights;\n\tbool is_set_global_weights;\n\n\t/*!\n\t * Global solution\n\t */\n\tVector<double>\t\t\tglobal_solution;\n\n\t/*!\n\t * Number of local refinements.\n\t */\n\tunsigned int n_refine_local;\n\tbool is_set_n_refine_local;\n\n\t/*!\n\t * Global cell number.\n\t */\n\tunsigned int global_cell_number;\n\n\t/*!\n\t * Iterator to global cell..\n\t */\n\ttypename Triangulation<dim>::active_cell_iterator global_cell;\n\tbool is_set_global_cell;\n\n\n\t/*!\n\t * Object carries set of local \\f$Q_1\\f$-basis functions.\n\t */\n\tCoefficients::BasisQ1<dim> basis_q1;\n\tbool is_set_basis_data;\n\n\t/*!\n\t * Write basis functions as vtu.\n\t */\n\tbool output_flag;\n};\n\n\n/*!\n * Default constructor.\n */\ntemplate <int dim>\nDiffusionProblemBasis<dim>::DiffusionProblemBasis ()\n:\nfe (1),\ndof_handler (triangulation),\nconstraints_vector (GeometryInfo<dim>::vertices_per_cell),\ncorner_points (GeometryInfo<dim>::vertices_per_cell),\nfilename_global (\"\"),\nsolution_vector (GeometryInfo<dim>::vertices_per_cell),\nglobal_element_matrix (fe.dofs_per_cell,\n\tfe.dofs_per_cell),\nis_built_global_element_matrix (false),\nglobal_element_rhs (fe.dofs_per_cell),\nglobal_weights (fe.dofs_per_cell, 0),\nis_set_global_weights (false),\nn_refine_local (0),\nis_set_n_refine_local (false),\nglobal_cell_number (0),\nglobal_cell (),\nis_set_global_cell (false),\nbasis_q1 (),\nis_set_basis_data (false),\noutput_flag (false)\n{}\n\n\n/*!\n * @brief Set up the grid with a certain number of refinements.\n *\n * Generate a triangulation of \\f$[0,1]^{\\rm{dim}}\\f$ with edges/faces\n * numbered form \\f$1,\\dots,2\\rm{dim}\\f$.\n */\ntemplate <int dim>\nvoid DiffusionProblemBasis<dim>::make_grid ()\n{\n\tAssert (is_set_n_refine_local,\n\t\t\t\tExcMessage (\"Number of local refinements must be set first.\"));\n\tAssert (is_set_global_cell,\n\t\t\t\tExcMessage (\"Global cell data must be set first.\"));\n\n\tGridGenerator::general_cell(triangulation, corner_points, /* colorize faces */ false);\n\n\ttriangulation.refine_global (n_refine_local);\n}\n\n\n/*!\n * @brief Setup sparsity pattern and system matrix.\n *\n * Compute sparsity pattern and reserve memory for the sparse system matrix\n * and a number of right-hand side vectors. Also build a constraint object\n * to take care of Dirichlet boundary conditions.\n */\ntemplate <int dim>\nvoid DiffusionProblemBasis<dim>::setup_system ()\n{\n\tdof_handler.distribute_dofs (fe);\n\n\tstd::cout << \"Global cell   \"\n\t\t\t<< global_cell_number\n\t\t\t<< \":   \"\n\t\t\t<< triangulation.n_active_cells() << \" active fine cells --- \"\n\t\t\t<< dof_handler.n_dofs() << \" subgrid dof\"\n\t\t\t<< std::endl;\n\n\t/*\n\t * Set up Dirichlet boundary conditions and sparsity pattern.\n\t */\n\tDynamicSparsityPattern dsp(dof_handler.n_dofs());\n\n\tfor (unsigned int index_basis = 0;\n\t\t\tindex_basis<GeometryInfo<dim>::vertices_per_cell;\n\t\t\t++index_basis)\n\t{\n\t\tbasis_q1.set_index (index_basis);\n\n\t\tconstraints_vector[index_basis].clear();\n\t\tDoFTools::make_hanging_node_constraints(dof_handler, constraints_vector[index_basis]);\n\n\t\tVectorTools::interpolate_boundary_values(dof_handler,\n\t\t\t\t\t\t\t\t\t\t\t\t\t/*boundary id*/ 0,\n\t\t\t\t\t\t\t\t\t\t\t\t\tbasis_q1,\n\t\t\t\t\t\t\t\t\t\t\t\t\tconstraints_vector[index_basis]);\n\t\tconstraints_vector[index_basis].close();\n\t}\n\n\tDoFTools::make_sparsity_pattern (dof_handler,\n\t\t\t\t\t\t\t\t\tdsp,\n\t\t\t\t\t\t\t\t\tconstraints_vector[0], // sparsity pattern is the same for each basis\n\t\t\t\t\t\t\t\t\t/*keep_constrained_dofs =*/ true); // for time stepping this is essential to be true\n\tsparsity_pattern.copy_from(dsp);\n\n\tsystem_matrix.reinit (sparsity_pattern);\n\tdiffusion_matrix.reinit (sparsity_pattern);\n\n\tfor (unsigned int index_basis = 0;\n\t\t\tindex_basis<GeometryInfo<dim>::vertices_per_cell;\n\t\t\t++index_basis)\n\t{\n\t\tsolution_vector[index_basis].reinit (dof_handler.n_dofs());\n\t}\n\tsystem_rhs.reinit (dof_handler.n_dofs());\n\tglobal_rhs.reinit (dof_handler.n_dofs());\n}\n\n\n/*!\n * @brief Assemble the system matrix and the static right hand side.\n *\n * Assembly routine to build the time-independent (static) part.\n * Neumann boundary conditions will be put on edges/faces\n * with odd number. Constraints are not applied here yet.\n */\ntemplate <int dim>\nvoid DiffusionProblemBasis<dim>::assemble_system ()\n{\n\tQGauss<dim>  quadrature_formula(fe.degree + 1);\n\n\tFEValues<dim> \tfe_values (fe, quadrature_formula,\n\t\t\t\t\t\t\t\tupdate_values    |  update_gradients |\n\t\t\t\t\t\t\t\tupdate_quadrature_points  |  update_JxW_values);\n\n\tconst unsigned int   \tdofs_per_cell = fe.dofs_per_cell;\n\tconst unsigned int   \tn_q_points    = quadrature_formula.size();\n\n\tFullMatrix<double>   cell_diffusion_matrix (dofs_per_cell, dofs_per_cell);\n\tFullMatrix<double>   cell_mass_matrix (dofs_per_cell, dofs_per_cell);\n\tVector<double>       cell_rhs (dofs_per_cell);\n\n\tstd::vector<types::global_dof_index> local_dof_indices (dofs_per_cell);\n\n\t/*\n\t * Matrix coefficient and vector to store the values.\n\t */\n\tconst Coefficients::MatrixCoeff<dim> \t\tmatrix_coeff;\n\tstd::vector<Tensor<2,dim>> \tmatrix_coeff_values(n_q_points);\n\n\t/*\n\t * Right hand side and vector to store the values.\n\t */\n\tconst Coefficients::RightHandSide<dim> \tright_hand_side;\n\tstd::vector<double>      \trhs_values(n_q_points);\n\n\t/*\n\t * Integration over cells.\n\t */\n\tfor (const auto &cell: dof_handler.active_cell_iterators())\n\t{\n\t\tcell_diffusion_matrix = 0;\n\t\tcell_rhs = 0;\n\n\t\tfe_values.reinit (cell);\n\n\t\t// Now actually fill with values.\n\t\tmatrix_coeff.value_list(fe_values.get_quadrature_points (),\n\t\t\t\t\t\t  \t  \t  matrix_coeff_values);\n\t\tright_hand_side.value_list(fe_values.get_quadrature_points(),\n\t\t\t\t\t\t\t\t\t   rhs_values);\n\n\t\tfor (unsigned int q_index=0; q_index<n_q_points; ++q_index)\n\t\t{\n\t\t\tfor (unsigned int i=0; i<dofs_per_cell; ++i)\n\t\t\t{\n\t\t\t\tfor (unsigned int j=0; j<dofs_per_cell; ++j)\n\t\t\t\t{\n\n\t\t\t\t\tcell_diffusion_matrix(i,j) += fe_values.shape_grad(i,q_index) *\n\t\t\t\t\t\t\t\t\t\t matrix_coeff_values[q_index] *\n\t\t\t\t\t\t\t\t\t\t fe_values.shape_grad(j,q_index) *\n\t\t\t\t\t\t\t\t\t\t fe_values.JxW(q_index);\n\t\t\t\t} // end ++j\n\n\t\t\t\tcell_rhs(i) += fe_values.shape_value(i,q_index) *\n\t\t\t\t\t\t\t\t   rhs_values[q_index] *\n\t\t\t\t\t\t\t\t   fe_values.JxW(q_index);\n\t\t\t} // end ++i\n\t\t} // end ++q_index\n\n\t\t// get global indices\n\t\tcell->get_dof_indices (local_dof_indices);\n\t\t/*\n\t\t * Now add the cell matrix and rhs to the right spots\n\t\t * in the global matrix and global rhs. Constraints will\n\t\t * be taken care of later.\n\t\t */\n\t\tfor (unsigned int i = 0; i < dofs_per_cell; ++i)\n\t\t{\n\t\t\tfor (unsigned int j = 0; j < dofs_per_cell; ++j)\n\t\t\t{\n\t\t\t\tdiffusion_matrix.add(local_dof_indices[i],\n\t\t\t\t\t\t\tlocal_dof_indices[j],\n\t\t\t\t\t\t\tcell_diffusion_matrix(i, j));\n\t\t\t}\n\t\t\tglobal_rhs(local_dof_indices[i]) += cell_rhs(i);\n\t\t}\n\t} // end ++cell\n}\n\n\n/*!\n *\n */\ntemplate <int dim>\nvoid\nDiffusionProblemBasis<dim>::assemble_global_element_matrix ()\n{\n\t// First, reset.\n\tglobal_element_matrix = 0;\n\n\t// Get lengths of tmp vectors for assembly\n\tconst unsigned int dofs_per_cell = fe.n_dofs_per_cell();\n\n\tVector<double>\t\t\ttmp (dof_handler.n_dofs());\n\n\t// This assembles the local contribution to the global global matrix\n\t// with an algebraic trick. It uses the local system matrix stored in\n\t// the respective basis object.\n\tfor (unsigned int i_test=0;\n\t\t\ti_test < dofs_per_cell;\n\t\t\t++i_test)\n\t{\n\t\t// set an alias name\n\t\tconst Vector<double>& test_vec = solution_vector[i_test];\n\n\t\tfor (unsigned int i_trial=0;\n\t\t\t\ti_trial<dofs_per_cell;\n\t\t\t\t++i_trial)\n\t\t{\n\t\t\t// set an alias name\n\t\t\tconst Vector<double>& trial_vec = solution_vector[i_trial];\n\n\t\t\t// tmp = system_matrix*trial_vec\n\t\t\tdiffusion_matrix.vmult(tmp, trial_vec);\n\n\t\t\t// global_element_diffusion_matrix = test_vec*tmp\n\t\t\tglobal_element_matrix(i_test,i_trial) += (test_vec * tmp);\n\n\t\t\t// reset\n\t\t\ttmp = 0;\n\t\t} // end for i_trial\n\n\t\tglobal_element_rhs(i_test) += test_vec * global_rhs;\n\n\t} // end for i_test\n\n\tis_built_global_element_matrix = true;\n}\n\n\n/*!\n * @brief Iterative solver.\n *\n * CG-based solver with SSOR-preconditioning.\n */\ntemplate <int dim>\nvoid DiffusionProblemBasis<dim>::solve_iterative (unsigned int index_basis)\n{\n\tSolverControl           solver_control (1000, 1e-12);\n\tSolverCG<>              solver (solver_control);\n\n\tPreconditionSSOR<> preconditioner;\n\tpreconditioner.initialize(system_matrix, 1.2);\n\n\tsolver.solve (system_matrix,\n\t\t\t\tsolution_vector[index_basis],\n\t\t\t\tsystem_rhs,\n\t\t\t\tpreconditioner);\n\n\tconstraints_vector[index_basis].distribute (solution_vector[index_basis]);\n\n\tstd::cout << \"   \"\n\t\t\t<< \"(cell   \"\n\t\t\t<< global_cell_number\n\t\t\t<< \") \"\n\t\t\t<< \"(basis   \"\n\t\t\t<< index_basis\n\t\t\t<< \")   \"\n\t\t\t<< solver_control.last_step()\n\t\t\t<< \" fine CG iterations needed to obtain convergence.\"\n\t\t\t<< std::endl;\n}\n\n\n/*!\n * Return the multiscale element matrix produced\n * from local basis functions.\n */\ntemplate <int dim>\nconst FullMatrix<double>&\nDiffusionProblemBasis<dim>::get_global_element_matrix () const\n{\n\treturn global_element_matrix;\n}\n\n\n/*!\n * Get the right hand-side that was locally assembled\n * to speed up the global assembly.\n */\ntemplate <int dim>\nconst Vector<double>&\nDiffusionProblemBasis<dim>::get_global_element_rhs () const\n{\n\treturn global_element_rhs;\n}\n\n/*!\n * Return filename for local pvtu record.\n */\ntemplate <int dim>\nconst std::string&\nDiffusionProblemBasis<dim>::get_filename_global ()\n{\n\treturn filename_global;\n}\n\n\n/*!\n * Set the number of local refinements.\n * @param n_refine_local\n */\ntemplate <int dim>\nvoid\nDiffusionProblemBasis<dim>::set_n_local_refinements (unsigned int n_refine)\n{\n\tn_refine_local = n_refine;\n\n\tis_set_n_refine_local = true;\n}\n\n\n/*!\n * Set the global cell data.\n * @param coarse_cell\n * @param n_cell_global\n */\ntemplate <int dim>\nvoid\nDiffusionProblemBasis<dim>::set_cell_data (typename Triangulation<dim>::active_cell_iterator &coarse_cell,\n\t\t\t\t\t\t\t\t\t\tunsigned int n_cell_global)\n{\n\tglobal_cell = coarse_cell;\n\tglobal_cell_number = n_cell_global;\n\n\tfor (unsigned int vertex_n=0;\n\t\t\t vertex_n<GeometryInfo<dim>::vertices_per_cell;\n\t\t\t ++vertex_n)\n\t{\n\t\tcorner_points[vertex_n] = global_cell->vertex(vertex_n);\n\t}\n\n\tis_set_global_cell = true;\n}\n\n\n/*!\n * Initialize the basis coefficients for the global cell.\n * @param coarse_cell\n */\ntemplate <int dim>\nvoid\nDiffusionProblemBasis<dim>::set_basis_data ()\n{\n\tAssert (is_set_global_cell,\n\t\t\t\t\tExcMessage (\"Pointer to global cell must be set first.\"));\n\n\tbasis_q1.set_coeff (global_cell);\n\n\tis_set_basis_data = true;\n}\n\n\n/*!\n * Set the output flag to write basis functions to disk as vtu.\n * @param flag\n */\ntemplate <int dim>\nvoid\nDiffusionProblemBasis<dim>::set_output_flag (bool flag)\n{\n\toutput_flag = flag;\n}\n\n\n/*!\n * @brief Set global weights.\n * @param weights\n *\n * The coarse weights of the global solution determine\n * the local multiscale solution. They must be computed\n * and then set locally to write an output.\n */\ntemplate <int dim>\nvoid\nDiffusionProblemBasis<dim>::set_global_weights (const std::vector<double> &weights)\n{\n\t// Copy assignment of global weights\n\tglobal_weights = weights;\n\n\t// reinitialize the global solution on this cell\n\tglobal_solution.reinit (dof_handler.n_dofs());\n\n\tconst unsigned int dofs_per_cell\t= fe.n_dofs_per_cell();\n\n\t// Set global solution using the weights and the local basis.\n\tfor (unsigned int index_basis=0;\n\t\t\tindex_basis<dofs_per_cell;\n\t\t\t++index_basis)\n\t{\n\t\t// global_solution = 1*global_solution + global_weights[index_basis]*solution_vector[index_basis]\n\t\tglobal_solution.sadd (1, global_weights[index_basis], solution_vector[index_basis]);\n\t}\n\n\tis_set_global_weights = true;\n}\n\n\n/*!\n * Define the gloabl filename for pvtu-file in global output.\n */\ntemplate <int dim>\nvoid\nDiffusionProblemBasis<dim>::set_filename_global ()\n{\n\tfilename_global += (dim == 2 ?\n\t\t\t\"solution-ms_fine-2d\" :\n\t\t\t\"solution-ms_fine-3d\");\n\n\tfilename_global += \"_cell-\" + Utilities::int_to_string(global_cell_number, 4) + \".vtu\";\n}\n\n\n/*!\n * @brief Write basis results to disk.\n *\n * Write basis results to disk in vtu-format.\n */\ntemplate <int dim>\nvoid\nDiffusionProblemBasis<dim>::output_basis () const\n{\n\tDataOut<dim> data_out;\n\tdata_out.attach_dof_handler (dof_handler);\n\tfor (unsigned int index_basis=0;\n\t\t\t\tindex_basis<GeometryInfo<dim>::vertices_per_cell;\n\t\t\t\t++index_basis)\n\t{\n\t\tdata_out.add_data_vector (solution_vector[index_basis], \"basis_\" + Utilities::int_to_string(index_basis, 1));\n\t}\n\tdata_out.build_patches ();\n\n\tstd::string filename = \"basis\";\n\tfilename += \"_cell-\" + Utilities::int_to_string(global_cell_number, 4);\n\tfilename += \".vtu\";\n\n\tstd::ofstream output (dim == 2 ?\n\t\t\t\t\t\"2d-\" + filename :\n\t\t\t\t\t\"3d-\" + filename);\n\n\tdata_out.write_vtu (output);\n}\n\n\n/*!\n * Write out global solution in cell.\n */\ntemplate <int dim>\nvoid\nDiffusionProblemBasis<dim>::output_global_solution_in_cell () const\n{\n\tAssert (is_set_global_weights,\n\t\t\t\tExcMessage (\"Global weights must be set first.\"));\n\n\tDataOut<dim> data_out;\n\tdata_out.attach_dof_handler (dof_handler);\n\tdata_out.add_data_vector (global_solution, \"solution\");\n\tdata_out.build_patches ();\n\n\tstd::ofstream output (filename_global.c_str());\n\tdata_out.write_vtu (output);\n}\n\n\n/*!\n * @brief Run function of the object.\n *\n * Run the computation after object is built.\n */\ntemplate <int dim>\nvoid DiffusionProblemBasis<dim>::run ()\n{\n\tAssert (is_set_basis_data,\n\t\t\t\t\t\tExcMessage (\"All basis data must be set first.\"));\n\n\tmake_grid ();\n\n\tsetup_system ();\n\n\tassemble_system ();\n\n\tset_filename_global ();\n\n\tfor (unsigned int index_basis=0;\n\t\t\tindex_basis<GeometryInfo<dim>::vertices_per_cell;\n\t\t\t++index_basis)\n\t{\n\t\t// reset everything\n\t\tsystem_rhs.reinit(solution_vector[index_basis].size());\n\t\tsystem_matrix.reinit (sparsity_pattern);\n\n\t\tsystem_matrix.copy_from(diffusion_matrix);\n\n\t\t// Now take care of constraints\n\t\tconstraints_vector[index_basis].condense(system_matrix, system_rhs);\n\n\t\t// Now solve\n\t\tsolve_iterative (index_basis);\n\t}\n\n\tassemble_global_element_matrix ();\n\n\tif (output_flag)\n\t\toutput_basis ();\n}\n\n} // end namespace DiffusionProblem\n\n#endif /* INCLUDE_DIFFUSION_PROBLEM_BASIS_HPP_ */\n", "meta": {"hexsha": "e0e36a718b81c23a4238a8814da2114bfcd508d4", "size": 17323, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/diffusion_problem_basis.hpp", "max_stars_repo_name": "konsim83/deal.ii-9.1.1_SS19_demo_elliptic_multiscale_fem", "max_stars_repo_head_hexsha": "cde9eabcbdee1271f4d36ce67d9168b65251ad32", "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/diffusion_problem_basis.hpp", "max_issues_repo_name": "konsim83/deal.ii-9.1.1_SS19_demo_elliptic_multiscale_fem", "max_issues_repo_head_hexsha": "cde9eabcbdee1271f4d36ce67d9168b65251ad32", "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": "include/diffusion_problem_basis.hpp", "max_forks_repo_name": "konsim83/deal.ii-9.1.1_SS19_demo_elliptic_multiscale_fem", "max_forks_repo_head_hexsha": "cde9eabcbdee1271f4d36ce67d9168b65251ad32", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-10-19T15:42:43.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-19T15:42:43.000Z", "avg_line_length": 24.3985915493, "max_line_length": 111, "alphanum_fraction": 0.7221035617, "num_tokens": 4376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952811593495, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.7096553411133171}}
{"text": "#include <wav2midi/fft/fft.hpp>\n#include <boost/math/constants/constants.hpp>\n\nnamespace wav2midi::fft {\n    namespace {\n        using namespace std::complex_literals;\n\n        constexpr auto pi = boost::math::constants::pi<double>();\n\n        // @see http://geisterchor.blogspot.jp/2015/05/cfft.html\n        std::complex<double> twiddle_factor(std::size_t n, uint32_t jk) {\n            return std::exp(-1.0i * (2 * pi * jk / n));\n        }\n\n        void fft_detail(std::vector<std::complex<double>> & x, std::size_t n) {\n            if (n <= 1) return;\n\n            std::vector<std::complex<double>> x_e(n/2);\n            std::vector<std::complex<double>> x_o(n/2);\n\n            for (auto j = 0u; j < n/2; ++j) {\n                x_e[j] = (x[j] + x[j + n/2]);\n                x_o[j] = (x[j] - x[j + n/2]) * twiddle_factor(n, j);\n            }\n\n            fft_detail(x_e, n/2);\n            fft_detail(x_o, n/2);\n\n            for (auto j = 0u; j < n/2; ++j) {\n                x[2*j    ] = x_e[j];\n                x[2*j + 1] = x_o[j];\n            }\n        }\n    }\n\n// public\n    fft::fft(const std::vector<double> & samplings, window::window_t window) {\n        const auto n = samplings.size();\n\n        for (auto i = 0u; i < n; ++i) {\n            auto x = double(i) / (n - 1);\n            frequencies_.emplace_back(samplings[i] * window(x));\n        }\n    }\n\n    const std::vector<std::complex<double>> & fft::execute() {\n        const auto n = frequencies_.size();\n        fft_detail(frequencies_, n);\n        return frequencies_;\n    }\n}\n", "meta": {"hexsha": "4a6652e7111f8cd37c981d55a201ad2b57437a8c", "size": 1540, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/wav2midi/fft/fft.cpp", "max_stars_repo_name": "mrk21/wav2midi", "max_stars_repo_head_hexsha": "01b7667c2fd7e18893a5cc97069aabc9397126e6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2018-11-14T04:46:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T13:28:38.000Z", "max_issues_repo_path": "src/wav2midi/fft/fft.cpp", "max_issues_repo_name": "mrk21/wav2midi", "max_issues_repo_head_hexsha": "01b7667c2fd7e18893a5cc97069aabc9397126e6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-01-12T21:40:34.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-12T22:06:01.000Z", "max_forks_repo_path": "src/wav2midi/fft/fft.cpp", "max_forks_repo_name": "mrk21/wav2midi", "max_forks_repo_head_hexsha": "01b7667c2fd7e18893a5cc97069aabc9397126e6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2018-07-04T14:34:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-30T13:38:35.000Z", "avg_line_length": 29.6153846154, "max_line_length": 79, "alphanum_fraction": 0.4967532468, "num_tokens": 439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403959948494, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.7096126515335395}}
{"text": "#include <iostream>\n#include <armadillo>\n#include <cmath>\n#include <time.h>\n#include <fstream>\n\n#include \"../code-fredrik/comp_eig.hh\"\n\nusing namespace std;\nusing namespace arma;\n\nvoid RHO_A_FILL(vec &rho, mat &A, int N,double rhoN); //rho, kind of like a linespace\n                                                 //A, Tridiagonal matrix\nvoid Maxoff(mat &A, int N,int &k, int &l, double &max);        //Finds the max element of a matrix\n\nint main(){\n    int values[] = { 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100 };\n    fstream Outfile;\n    Outfile.open(\"steps.dat\",ios::out);\n    Outfile << \"N     epsilon    steps  step_time  error\"<<endl;\n    for(int iter = 0; iter < 20; iter++){\n        int N = values[iter]; //matrix size; N x N\n        double rhoN = 6;\n        double eps = 1E-10;\n        double max;\n        int k,l;\n\n        double total_error = 0;\n        double total_time = 0;\n        int total_iterations = 0;\n\n        // run 10 times and average\n        int zcount = 10;\n        for(int z = 0; z < zcount; z++) {\n          std::cout << N << std::endl;\n          mat A(N,N,fill::zeros); //indexes go from (0) to (N-1)\n          mat S(N,N,fill::eye);\n          vec rho(N,fill::zeros);\n          vec eigen(N);\n\n\n          RHO_A_FILL(rho,A,N,rhoN);\n          Maxoff(A,N,k,l,max);\n          //A.print();\n          int iterations = 0;\n\n          // solve with Armadillo's eig_sym\n          vec arma_eigenvalues;\n          mat arma_eigenvectors;\n          eig_sym(arma_eigenvalues, arma_eigenvectors, A);\n\n          double tau, t, s, c, il, ik, kk, ll, s_ik, s_il;\n          double start, finish;\n\n          start = clock();                      //clock value before eigen solve\n          while(max > eps){\n              tau = (A(l,l)-A(k,k))/(2.*A(k,l));\n              if(tau>0){\n                  t = 1.0/(tau + sqrt(1.0 + tau*tau));\n              } else{\n                  t = -1.0/( -tau + sqrt(1.0 + tau*tau));\n              }\n\n              //cosine and sine\n              c = 1./sqrt(1.+t*t);\n              s = t*c;\n\n              //Jacobi rotating A round theta in N-dim space\n              for(int i = 0; i<N; i++){\n                  if ((i != k) && (i !=l)){\n\n                      ik = A(i,k)*c - A(i,l)*s;\n                      il = A(i,l)*c + A(i,k)*s;\n                      A(i,k) = ik;\n                      A(i,l) = il;\n                      A(k,i) = ik;\n                      A(l,i) = il;\n                  }\n                  s_ik = S(i,k);\n                  s_il = S(i,l);\n                  S(i,k) = c*s_ik - s*s_il;\n                  S(i,l) = c*s_il + s*s_ik;\n              }\n\n              kk = A(k,k)*c*c - 2.*A(k,l)*c*s + A(l,l)*s*s;\n              ll = A(l,l)*c*c + 2.*A(k,l)*c*s + A(k,k)*s*s;\n              A(k,k) = kk;\n              A(l,l) = ll ;\n              A(k,l) = 0;\n              A(l,k) = 0;\n\n              iterations++;\n              Maxoff(A,N,k,l,max);\n\n\n          } //end of while\n          finish = clock();                    //clock value after eigen solve\n\n          //[eigen] is now eigenvalues\n          for(int i = 0; i<N;i++){\n              eigen(i) = A(i,i);\n          }\n\n          // eigen.print();\n\n          // compare eigenvectors from own method with armadillo\n          total_error += comp_eig(eigen, S, arma_eigenvalues, arma_eigenvectors);\n\n          total_time += (finish -start)/CLOCKS_PER_SEC/iterations;\n          total_iterations += iterations;\n\n          /*\n          fstream outfile;\n          outfile.open(\"eigenvectors.dat\",ios::out);\n\n          for (int i = 0; i<N; i++){\n              for (int j = 0; j<N; j++){\n                  if(j%N == 0){outfile<<endl;}\n                  outfile << S(i,j)<<\" \";\n                  }\n              }\n          outfile.close();\n          */\n        }\n\n\n        Outfile <<N <<\" \"<<eps<<\" \"<<((double)total_iterations / zcount)<<\" \"<<(total_time / zcount) <<\" \"<<(total_error / zcount)<<endl;\n\n    //    Outfile.close();\n    }\n} //end of main\n\n\nvoid RHO_A_FILL(vec &rho, mat &A, int N,double rhoN){\n    double h = rhoN/(N);\n    for(int i = 0; i < N;i++){\n        rho(i) = i*h;\n        A(i,i) = 2./(h*h)+(rho(i)*rho(i));\n        if(i<N-1){\n            A(i+1,i) = -1./(h*h);\n            A(i,i+1) = -1./(h*h);\n            }\n        }\n    }\n\nvoid Maxoff(mat &A, int N,int &k, int &l, double &max){\n    max = 0;\n    for(int i = 0; i < N ; i++){\n        for(int j = i+1; j < N ; j++){\n            if ( A(i,j)*A(i,j) > max){\n                max =A(i,j)*A(i,j);\n                k = i;\n                l = j;\n                }\n            }\n        }\n\n    }\n", "meta": {"hexsha": "979570aa9514e5b8847f227378ecf9417a29bf62", "size": 4592, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "project2/code-joseph/jacobi_step_data.cpp", "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-joseph/jacobi_step_data.cpp", "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-joseph/jacobi_step_data.cpp", "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": 28.8805031447, "max_line_length": 137, "alphanum_fraction": 0.4102787456, "num_tokens": 1329, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403999037784, "lm_q2_score": 0.7634837527911057, "lm_q1q2_score": 0.7096126445142027}}
{"text": "/* Tags: Minimal Spanning Tree, DFS, 2nd MST\n\n  Key idea: * we look for 2nd best MST\n            * construct MST with Kruskal\n              --> Leias solution (equivalent to her Prim algorithm in terms of weight)\n            * compute max edge on pairwise paths in MST with DFS in O(n^2) (paths are unique in tree)\n            * loop through all edges _not_ in MST and\n              compute best differences in adding edge (u,v) and\n              removing worst edge on MST path between u and v\n            * WHY? 2nd best MST is attained by adding a single edge that previosuly wasnt in MST\n                   and then deleting the largest edge in the cycle that is introduced.\n            * Since the graph is fully connected here, it is more efficient to \n              precompute pairwise max_edge_weights in O(n^2) than to do it for each \n              edge in O(E * V)\n*/\n\n// STL includes\n#include <iostream>\n#include <vector>\n#include <queue>\n#include <stack>\n\n// BGL includes\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\n#include <boost/pending/disjoint_sets.hpp>\n\ntypedef std::size_t                                            Index;\n\ntypedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS,\n  boost::no_property, boost::property<boost::edge_weight_t, int> >      weighted_graph;\ntypedef boost::property_map<weighted_graph, boost::edge_weight_t>::type weight_map;\ntypedef boost::graph_traits<weighted_graph>::edge_descriptor            edge_desc;\ntypedef boost::graph_traits<weighted_graph>::vertex_descriptor          vertex_desc;\n// edge: (u,v,c)\ntypedef std::tuple<int,int,int> Edge;\ntypedef std::vector<Edge> EdgeV;\n\nvoid testcase()\n{\n  int n, tatt;\n  std::cin >> n >> tatt;\n  EdgeV edges;\n  edges.reserve(n*n);\n  for(int i = 0; i < n - 1; i++) {\n      for(int j = 0; j < n - i - 1; j++) {\n            int c;\n            std::cin >> c;\n            edges.emplace_back(i, i + j + 1, c);\n      }\n  }\n\n  std::sort(edges.begin(), edges.end(),\n      [](const Edge& e1, const Edge& e2) -> bool {\n        return std::get<2>(e1) < std::get<2>(e2);\n            });\n  \n  // construct MST with Kruskal --> Leias solution (equivalent to her Prim algorithm)\n  std::vector<std::vector<int>> edge_in_mst(n, std::vector<int>(n, 0)); // nonzero means included\n  boost::disjoint_sets_with_storage<> uf(n);\n  int mst_cost = 0;\n  int n_components = n;\n  std::vector<std::vector<int>> mst_edges(n, std::vector<int>(0));\n  for (EdgeV::const_iterator e = edges.begin(); e != edges.end(); ++e) {\n    Index i1 = std::get<0>(*e);\n    Index i2 = std::get<1>(*e);\n    Index c1 = uf.find_set(i1);\n    Index c2 = uf.find_set(i2);\n    int cost = std::get<2>(*e);\n    if(c1 != c2) {\n      mst_cost += cost;\n      uf.link(c1, c2);\n      edge_in_mst[i1][i2] = cost;\n      edge_in_mst[i2][i1] = cost;\n      mst_edges[i1].push_back(i2);\n      mst_edges[i2].push_back(i1);\n      if(--n_components == 1) break;\n    }\n  }\n \n  // compute max edge on pairwise paths in MST with DFS\n  std::vector<std::vector<int>> max_e_betw(n, std::vector<int>(n, 0));\n  for(int i = 0; i < n; i++) {\n      std::stack<std::pair<int,int>> Q; // pair of (node, max edge on path form i to node)\n      Q.push({i,0});\n      std::vector<bool> visited(n, false);\n      while(!Q.empty()) {\n        auto v = Q.top();\n        int j = v.first; int c = v.second;\n        Q.pop();\n        if(!visited[j]) {\n          visited[j] = true;\n          max_e_betw[i][j] = c;\n          for(auto k : mst_edges[j]) Q.push({k, std::max(c, edge_in_mst[j][k])});\n        }\n      }\n  }\n  \n  // loop through all edges not in MST, compute best differences in adding edge (u,v) and\n  // removing worst edge on MST path between u and v\n  int min_diff = std::numeric_limits<int>::max();\n  for (EdgeV::const_iterator e = edges.begin(); e != edges.end(); ++e) {\n    Index i1 = std::get<0>(*e);\n    Index i2 = std::get<1>(*e);\n    int cost = std::get<2>(*e);\n    if(edge_in_mst[i1][i2] == 0) {\n        min_diff = std::min(min_diff, cost - max_e_betw[i1][i2]);\n    }\n  }\n\n  std::cout << mst_cost + min_diff << std::endl;\n}\n\nint main() {\n    std::ios_base::sync_with_stdio(false);\n\n    int t;\n    std::cin >> t;\n    for (int i = 0; i < t; ++i)\n        testcase();\n}\n", "meta": {"hexsha": "e54c1893e6649423a7cfed325f4d82edcbfbe3f0", "size": 4252, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problems/week11-return_of_the_jedi/src/algorithm.cpp", "max_stars_repo_name": "haeggee/algolab", "max_stars_repo_head_hexsha": "176a7d4efbbfb2842f46e93250be00d3b59e0ec3", "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": "problems/week11-return_of_the_jedi/src/algorithm.cpp", "max_issues_repo_name": "haeggee/algolab", "max_issues_repo_head_hexsha": "176a7d4efbbfb2842f46e93250be00d3b59e0ec3", "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": "problems/week11-return_of_the_jedi/src/algorithm.cpp", "max_forks_repo_name": "haeggee/algolab", "max_forks_repo_head_hexsha": "176a7d4efbbfb2842f46e93250be00d3b59e0ec3", "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.8524590164, "max_line_length": 101, "alphanum_fraction": 0.5914863594, "num_tokens": 1220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096181702032, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.7096032978424542}}
{"text": "/*\n * Copyright (c) 2013-2014 Masahide Kashiwagi (kashi@waseda.jp)\n */\n\n#ifndef CARDANO_HPP\n#define CARDANO_HPP\n\n// Solve polynomial equations of degree 3/4\n// by Cardano/Ferrari's methods\n\n#include <kv/interval.hpp>\n#include <kv/rdouble.hpp>\n#include <kv/complex.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n\n\nnamespace kv {\n\nnamespace ub = boost::numeric::ublas;\n\n\ntemplate <class T> bool cardano(const ub::vector< complex< interval<T> > > &in, ub::vector< complex< interval<T> > >& out)\n{\n\tcomplex< interval<T> > a, b, c, p, q, w, m, n, nt, nn, tmp;\n\tint i;\n\tbool flag;\n\n\tif (in.size() != 4) return false;\n\tif (zero_in(in(3).real()) && zero_in(in(3).imag())) return false;\n\n\ta = in(2) / in(3);\n\tb = in(1) / in(3);\n\tc = in(0) / in(3);\n\n\tp = b - pow(a, 2) / 3.;\n\tq = 2 * pow(a, 3) /27. - a * b / 3. + c;\n\tw = complex< interval<T> >(-1., sqrt(interval<T>(3.))) / 2.;\n\n\ttmp = sqrt(pow(q, 2)/4. + pow(p, 3) / 27.) ;\n\tm = pow(-q / 2. + tmp, 1. / interval<T>(3.));\n\tn = pow(-q / 2. - tmp, 1. / interval<T>(3.));\n\n\tnt = n;\n\tflag = false;\n\n\tfor (i=0; i<3; i++) {\n\t\ttmp = m * nt + p/3.;\n\t\tif (zero_in(tmp.real()) && zero_in(tmp.imag())) {\n\t\t\tif (flag == false) {\n\t\t\t\tnn = nt;\n\t\t\t\tflag = true;\n\t\t\t} else {\n\t\t\t\tnn.real() = interval<T>::hull(nn.real(), nt.real());\n\t\t\t\tnn.imag() = interval<T>::hull(nn.imag(), nt.imag());\n\t\t\t}\n\t\t}\n\t\tnt = w * nt;\n\t}\n\n\tout.resize(3);\n\tout(0) = m + nn - a / 3.;\n\tout(1) = w * m + w * w * nn - a / 3.;\n\tout(2) = w * w * m + w * nn - a / 3.;\n\n\treturn true;\n}\n\ntemplate <class T> bool ferrari(const ub::vector< complex< interval<T> > > &in, ub::vector< complex< interval<T> > >& out) \n{\n\tcomplex< interval<T> > a, b, c, d, p, q, r, tmp;\n\tub::vector< complex< interval<T> > > ci, co;\n\tcomplex< interval<T> > l, m, n, nt, nn;\n\tint i;\n\tbool flag;\n\n\tif (in.size() != 5) return false;\n\tif (zero_in(in(4).real()) && zero_in(in(3).imag())) return false;\n\n\ta = in(3) / in(4);\n\tb = in(2) / in(4);\n\tc = in(1) / in(4);\n\td = in(0) / in(4);\n\n\tp = b - pow(a, 2) * 3. / 8.;\n\tq = c - b * a / 2. + pow(a, 3) / 8.;\n\tr = d - c * a / 4. + b * pow(a, 2) / 16. - pow(a, 4) * 3. / 256.;\n\n\tci.resize(4);\n\tci(3) = 1.;\n\tci(2) = -p / 2.;\n\tci(1) = -r;\n\tci(0) = r * p / 2. - pow(q, 2) / 8.;\n\n\tcardano(ci, co);\n\n\tl = co(0);\n\tm = sqrt(2. * l - p);\n\tn = sqrt(pow(l, 2) - r);\n\n\tnt = n;\n\tflag = false;\n\n\tfor (i=0; i<2; i++) {\n\t\ttmp = 2. * m * nt + q;\n\t\tif (zero_in(tmp.real()) && zero_in(tmp.imag())) {\n\t\t\tif (flag == false) {\n\t\t\t\tnn = nt;\n\t\t\t\tflag = true;\n\t\t\t} else {\n\t\t\t\tnn.real() = interval<T>::hull(nn.real(), nt.real());\n\t\t\t\tnn.imag() = interval<T>::hull(nn.imag(), nt.imag());\n\t\t\t}\n\t\t}\n\t\tnt = -nt;\n\t}\n\n\tout.resize(4);\n\tout(0) = (m + sqrt(pow(m, 2) - 4. * (l - nn))) / 2. - a / 4.;\n\tout(1) = (m - sqrt(pow(m, 2) - 4. * (l - nn))) / 2. - a / 4.;\n\tout(2) = (-m + sqrt(pow(m, 2) - 4. * (l + nn))) / 2. - a / 4.;\n\tout(3) = (-m - sqrt(pow(m, 2) - 4. * (l + nn))) / 2. - a / 4.;\n\n\treturn true;\n}\n\n} // namespace kv\n\n#endif // CARDANO_HPP\n", "meta": {"hexsha": "2471b1e0739f55506dc76d5ece4c25b3ab368007", "size": 2923, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "kv/cardano-ferrari.hpp", "max_stars_repo_name": "soonho-tri/kv", "max_stars_repo_head_hexsha": "4963be6560d8600cdc9ff22d004b2b965ae7b1df", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 67.0, "max_stars_repo_stars_event_min_datetime": "2017-01-04T15:30:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T05:45:02.000Z", "max_issues_repo_path": "src/interval/kv/cardano-ferrari.hpp", "max_issues_repo_name": "takafumihoriuchi/HyLaGI", "max_issues_repo_head_hexsha": "26b9f32a84611ee62d9cbbd903773d224088c959", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2017-02-10T02:59:45.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-10T14:17:08.000Z", "max_forks_repo_path": "src/interval/kv/cardano-ferrari.hpp", "max_forks_repo_name": "takafumihoriuchi/HyLaGI", "max_forks_repo_head_hexsha": "26b9f32a84611ee62d9cbbd903773d224088c959", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-09-29T02:27:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T05:45:04.000Z", "avg_line_length": 22.6589147287, "max_line_length": 123, "alphanum_fraction": 0.4960656859, "num_tokens": 1197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086368, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.7096032764448432}}
{"text": "#include \"catch.hpp\"\n#include \"nbsimCatchMain.h\"\n#include \"nbsimMyFunctions.h\"\n#include \"nbsimParticle.h\"\n#include \"nbsimMassiveParticle.h\"\n#include <iostream>\n#include <vector>\n#include <Eigen/Dense>\n#include <math.h>\n\nTEST_CASE(\"check if the particle moves as excepted when no acceleration\",\"[Particle]\"){\n    \n    Eigen::Vector3d zero_acceleration(0,0,0),test_position(0,0,0),test_velocity(1,1,1);\n    nbsim::Particle test1_particle(test_position,test_velocity);\n    double test1_timestep=0.01, test1_time=5;\n    for(double i=0;i<test1_time;i+=test1_timestep){\n        test1_particle.integrateTimestep(zero_acceleration,test1_timestep);\n    }\n    REQUIRE(test1_particle.getVelocity().isApprox(test_velocity,0));\n    REQUIRE(test1_particle.getPosition().isApprox(test_position+test_velocity*test1_time,0.01));\n\n}\n\nTEST_CASE(\"check if the particle moves as excepted when constant acceleration\",\"[Particle]\"){\n    Eigen::Vector3d constant_acceleration(1,1,1),test_position(0,0,0),test_velocity(1,1,1);\n    nbsim::Particle test2_particle(test_position,test_velocity);\n    double test2_timestep=0.01, test2_time=5;\n    for(double i=0;i<test2_time;i+=test2_timestep){\n        test2_particle.integrateTimestep(constant_acceleration,test2_timestep);\n    }\n    REQUIRE(test2_particle.getVelocity().isApprox(test_velocity+constant_acceleration*test2_time,0.01)); //v=v_0+a*t\n    REQUIRE(test2_particle.getPosition().isApprox(test_position+test_velocity*test2_time+0.5*constant_acceleration*test2_time*test2_time,0.01)); //d=d_0+0.5*a*t^2\n\n}\n\nTEST_CASE(\"check if the particle moves as excepted when a fictitious centripetal acceleration applied\",\"[Particle]\"){\n    \n    Eigen::Vector3d test_position(1,0,0),test_velocity(0,1,0);\n    nbsim::Particle test3_particle(test_position,test_velocity);\n    \n    double test3_timestep=0.001, test3_time=2*M_PI;\n    for(double i=0;i<test3_time;i+=test3_timestep){\n        Eigen::Vector3d centripetal_acceleration=-test3_particle.getPosition();\n        test3_particle.integrateTimestep(centripetal_acceleration,test3_timestep);\n    }\n    REQUIRE(test3_particle.getVelocity().isApprox(test_velocity,0.01));\n    REQUIRE(test3_particle.getPosition().isApprox(test_position,0.01));\n    \n}\n\nTEST_CASE(\"check if the massive particle moves as excepted when no attractors\",\"[MassiveParticle]\"){\n    Eigen::Vector3d test_position(1,0,0),test_velocity(0,1,0);\n    double test_mass=1,test4_timestep=0.01, test4_time=5;\n    nbsim::MassiveParticle test4_massive_particle(test_position,test_velocity,test_mass);\n    for(double i=0;i<test4_time;i+=test4_timestep){\n        test4_massive_particle.integrateTimestep(test4_timestep);\n    }\n    REQUIRE(test4_massive_particle.getVelocity().isApprox(test_velocity,0));\n    REQUIRE(test4_massive_particle.getPosition().isApprox(test_position+test_velocity*test4_time,0.01));\n}\n\nTEST_CASE(\"check if two massive particles move together as excepted\",\"[MassiveParticle]\"){\n    Eigen::Vector3d test_position1(1,0,0),test_velocity1(0,0.5,0),test_position2(-1,0,0),test_velocity2(0,-0.5,0);\n    double test_mass=1/(6.67408e-11),test5_timestep=0.001, test5_time=2*M_PI;\n    //nbsim::MassiveParticle test5_massive_particle1(test_position1,test_velocity1,test_mass),test5_massive_particle2(test_position2,test_velocity2,test_mass);\n    std::shared_ptr<nbsim::MassiveParticle> ptr_particle1(new nbsim::MassiveParticle(test_position1,test_velocity1,test_mass)),ptr_particle2(new nbsim::MassiveParticle(test_position2,test_velocity2,test_mass));\n    ptr_particle1->addAttractor(ptr_particle2);\n    ptr_particle2->addAttractor(ptr_particle1);\n    for(double i=0;i<test5_time;i+=test5_timestep){\n        ptr_particle1->calculateAcceleration();\n        ptr_particle1->integrateTimestep(test5_timestep);\n        ptr_particle2->calculateAcceleration();\n        ptr_particle2->integrateTimestep(test5_timestep);\n    }\n    double test_distance=(ptr_particle1->getPosition()-ptr_particle2->getPosition()).norm();\n    REQUIRE(std::abs(test_distance)-2<0.01);\n    \n}", "meta": {"hexsha": "793ae3ace74c8a67439e57630f759579df13c0a6", "size": 4002, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Testing/nbsimTest.cpp", "max_stars_repo_name": "zys711/cpp_Assignment2", "max_stars_repo_head_hexsha": "f705f8a53d358c85f2d7e7d1a36536492d448a8e", "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": "Testing/nbsimTest.cpp", "max_issues_repo_name": "zys711/cpp_Assignment2", "max_issues_repo_head_hexsha": "f705f8a53d358c85f2d7e7d1a36536492d448a8e", "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": "Testing/nbsimTest.cpp", "max_forks_repo_name": "zys711/cpp_Assignment2", "max_forks_repo_head_hexsha": "f705f8a53d358c85f2d7e7d1a36536492d448a8e", "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": 51.3076923077, "max_line_length": 210, "alphanum_fraction": 0.7683658171, "num_tokens": 1087, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.8056321796478255, "lm_q1q2_score": 0.7095984697587572}}
{"text": "//\n// Copyright 2019 Olzhas Zhumabek <anonymous.from.applecity@gmail.com>\n// Copyright 2021 Pranam Lashkari <plashkari628@gmail.com>\n//\n// Use, modification and distribution are 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#ifndef BOOST_GIL_IMAGE_PROCESSING_NUMERIC_HPP\n#define BOOST_GIL_IMAGE_PROCESSING_NUMERIC_HPP\n\n#include <boost/gil/image_processing/kernel.hpp>\n#include <boost/gil/image_processing/convolve.hpp>\n#include <boost/gil/image_view.hpp>\n#include <boost/gil/typedefs.hpp>\n#include <boost/gil/detail/math.hpp>\n// fixes ambigious call to std::abs, https://stackoverflow.com/a/30084734/4593721\n#include <cstdlib>\n#include <cmath>\n\nnamespace boost { namespace gil {\n\n/// \\defgroup ImageProcessingMath\n/// \\brief Math operations for IP algorithms\n///\n/// This is mostly handful of mathemtical operations that are required by other\n/// image processing algorithms\n///\n/// \\brief Normalized cardinal sine\n/// \\ingroup ImageProcessingMath\n///\n/// normalized_sinc(x) = sin(pi * x) / (pi * x)\n///\ninline double normalized_sinc(double x)\n{\n    return std::sin(x * boost::gil::detail::pi) / (x * boost::gil::detail::pi);\n}\n\n/// \\brief Lanczos response at point x\n/// \\ingroup ImageProcessingMath\n///\n/// Lanczos response is defined as:\n/// x == 0: 1\n/// -a < x && x < a: 0\n/// otherwise: normalized_sinc(x) / normalized_sinc(x / a)\ninline double lanczos(double x, std::ptrdiff_t a)\n{\n    // means == but <= avoids compiler warning\n    if (0 <= x && x <= 0)\n        return 1;\n\n    if (static_cast<double>(-a) < x && x < static_cast<double>(a))\n        return normalized_sinc(x) / normalized_sinc(x / static_cast<double>(a));\n\n    return 0;\n}\n\n#if BOOST_WORKAROUND(BOOST_MSVC, >= 1400)\n#pragma warning(push)\n#pragma warning(disable:4244) // 'argument': conversion from 'const Channel' to 'BaseChannelValue', possible loss of data\n#endif\n\ninline void compute_tensor_entries(\n    boost::gil::gray16s_view_t dx,\n    boost::gil::gray16s_view_t dy,\n    boost::gil::gray32f_view_t m11,\n    boost::gil::gray32f_view_t m12_21,\n    boost::gil::gray32f_view_t m22)\n{\n    for (std::ptrdiff_t y = 0; y < dx.height(); ++y) {\n        for (std::ptrdiff_t x = 0; x < dx.width(); ++x) {\n            auto dx_value = dx(x, y);\n            auto dy_value = dy(x, y);\n            m11(x, y) = dx_value * dx_value;\n            m12_21(x, y) = dx_value * dy_value;\n            m22(x, y) = dy_value * dy_value;\n        }\n    }\n}\n\n#if BOOST_WORKAROUND(BOOST_MSVC, >= 1400)\n#pragma warning(pop)\n#endif\n\n/// \\brief Generate mean kernel\n/// \\ingroup ImageProcessingMath\n///\n/// Fills supplied view with normalized mean\n/// in which all entries will be equal to\n/// \\code 1 / (dst.size()) \\endcode\ntemplate <typename T = float, typename Allocator = std::allocator<T>>\ninline detail::kernel_2d<T, Allocator> generate_normalized_mean(std::size_t side_length)\n{\n    if (side_length % 2 != 1)\n        throw std::invalid_argument(\"kernel dimensions should be odd and equal\");\n    const float entry = 1.0f / static_cast<float>(side_length * side_length);\n\n    detail::kernel_2d<T, Allocator> result(side_length, side_length / 2, side_length / 2);\n    for (auto& cell: result) {\n        cell = entry;\n    }\n\n    return result;\n}\n\n/// \\brief Generate kernel with all 1s\n/// \\ingroup ImageProcessingMath\n///\n/// Fills supplied view with 1s (ones)\ntemplate <typename T = float, typename Allocator = std::allocator<T>>\ninline detail::kernel_2d<T, Allocator> generate_unnormalized_mean(std::size_t side_length)\n{\n    if (side_length % 2 != 1)\n        throw std::invalid_argument(\"kernel dimensions should be odd and equal\");\n\n    detail::kernel_2d<T, Allocator> result(side_length, side_length / 2, side_length / 2);\n    for (auto& cell: result) {\n        cell = 1.0f;\n    }\n\n    return result;\n}\n\n/// \\brief Generate Gaussian kernel\n/// \\ingroup ImageProcessingMath\n///\n/// Fills supplied view with values taken from Gaussian distribution. See\n/// https://en.wikipedia.org/wiki/Gaussian_blur\ntemplate <typename T = float, typename Allocator = std::allocator<T>>\ninline detail::kernel_2d<T, Allocator> generate_gaussian_kernel(std::size_t side_length, double sigma)\n{\n    if (side_length % 2 != 1)\n        throw std::invalid_argument(\"kernel dimensions should be odd and equal\");\n\n\n    const double denominator = 2 * boost::gil::detail::pi * sigma * sigma;\n    auto middle = side_length / 2;\n    std::vector<T, Allocator> values(side_length * side_length);\n    for (std::size_t y = 0; y < side_length; ++y)\n    {\n        for (std::size_t x = 0; x < side_length; ++x)\n        {\n            const auto delta_x = middle > x ? middle - x : x - middle;\n            const auto delta_y = middle > y ? middle - y : y - middle;\n            const double power = (delta_x * delta_x +  delta_y * delta_y) / (2 * sigma * sigma);\n            const double nominator = std::exp(-power);\n            const float value = static_cast<float>(nominator / denominator);\n            values[y * side_length + x] = value;\n        }\n    }\n\n    return detail::kernel_2d<T, Allocator>(values.begin(), values.size(), middle, middle);\n}\n\n/// \\brief Generates Sobel operator in horizontal direction\n/// \\ingroup ImageProcessingMath\n///\n/// Generates a kernel which will represent Sobel operator in\n/// horizontal direction of specified degree (no need to convolve multiple times\n/// to obtain the desired degree).\n/// https://www.researchgate.net/publication/239398674_An_Isotropic_3_3_Image_Gradient_Operator\ntemplate <typename T = float, typename Allocator = std::allocator<T>>\ninline detail::kernel_2d<T, Allocator> generate_dx_sobel(unsigned int degree = 1)\n{\n    switch (degree)\n    {\n        case 0:\n        {\n            return detail::get_identity_kernel<T, Allocator>();\n        }\n        case 1:\n        {\n            detail::kernel_2d<T, Allocator> result(3, 1, 1);\n            std::copy(detail::dx_sobel.begin(), detail::dx_sobel.end(), result.begin());\n            return result;\n        }\n        default:\n            throw std::logic_error(\"not supported yet\");\n    }\n\n    //to not upset compiler\n    throw std::runtime_error(\"unreachable statement\");\n}\n\n/// \\brief Generate Scharr operator in horizontal direction\n/// \\ingroup ImageProcessingMath\n///\n/// Generates a kernel which will represent Scharr operator in\n/// horizontal direction of specified degree (no need to convolve multiple times\n/// to obtain the desired degree).\n/// https://www.researchgate.net/profile/Hanno_Scharr/publication/220955743_Optimal_Filters_for_Extended_Optical_Flow/links/004635151972eda98f000000/Optimal-Filters-for-Extended-Optical-Flow.pdf\ntemplate <typename T = float, typename Allocator = std::allocator<T>>\ninline detail::kernel_2d<T, Allocator> generate_dx_scharr(unsigned int degree = 1)\n{\n    switch (degree)\n    {\n        case 0:\n        {\n            return detail::get_identity_kernel<T, Allocator>();\n        }\n        case 1:\n        {\n            detail::kernel_2d<T, Allocator> result(3, 1, 1);\n            std::copy(detail::dx_scharr.begin(), detail::dx_scharr.end(), result.begin());\n            return result;\n        }\n        default:\n            throw std::logic_error(\"not supported yet\");\n    }\n\n    //to not upset compiler\n    throw std::runtime_error(\"unreachable statement\");\n}\n\n/// \\brief Generates Sobel operator in vertical direction\n/// \\ingroup ImageProcessingMath\n///\n/// Generates a kernel which will represent Sobel operator in\n/// vertical direction of specified degree (no need to convolve multiple times\n/// to obtain the desired degree).\n/// https://www.researchgate.net/publication/239398674_An_Isotropic_3_3_Image_Gradient_Operator\ntemplate <typename T = float, typename Allocator = std::allocator<T>>\ninline detail::kernel_2d<T, Allocator> generate_dy_sobel(unsigned int degree = 1)\n{\n    switch (degree)\n    {\n        case 0:\n        {\n            return detail::get_identity_kernel<T, Allocator>();\n        }\n        case 1:\n        {\n            detail::kernel_2d<T, Allocator> result(3, 1, 1);\n            std::copy(detail::dy_sobel.begin(), detail::dy_sobel.end(), result.begin());\n            return result;\n        }\n        default:\n            throw std::logic_error(\"not supported yet\");\n    }\n\n    //to not upset compiler\n    throw std::runtime_error(\"unreachable statement\");\n}\n\n/// \\brief Generate Scharr operator in vertical direction\n/// \\ingroup ImageProcessingMath\n///\n/// Generates a kernel which will represent Scharr operator in\n/// vertical direction of specified degree (no need to convolve multiple times\n/// to obtain the desired degree).\n/// https://www.researchgate.net/profile/Hanno_Scharr/publication/220955743_Optimal_Filters_for_Extended_Optical_Flow/links/004635151972eda98f000000/Optimal-Filters-for-Extended-Optical-Flow.pdf\ntemplate <typename T = float, typename Allocator = std::allocator<T>>\ninline detail::kernel_2d<T, Allocator> generate_dy_scharr(unsigned int degree = 1)\n{\n    switch (degree)\n    {\n        case 0:\n        {\n            return detail::get_identity_kernel<T, Allocator>();\n        }\n        case 1:\n        {\n            detail::kernel_2d<T, Allocator> result(3, 1, 1);\n            std::copy(detail::dy_scharr.begin(), detail::dy_scharr.end(), result.begin());\n            return result;\n        }\n        default:\n            throw std::logic_error(\"not supported yet\");\n    }\n\n    //to not upset compiler\n    throw std::runtime_error(\"unreachable statement\");\n}\n\n/// \\brief Compute xy gradient, and second order x and y gradients\n/// \\ingroup ImageProcessingMath\n///\n/// Hessian matrix is defined as a matrix of partial derivates\n/// for 2d case, it is [[ddxx, dxdy], [dxdy, ddyy].\n/// d stands for derivative, and x or y stand for direction.\n/// For example, dx stands for derivative (gradient) in horizontal\n/// direction, and ddxx means second order derivative in horizon direction\n/// https://en.wikipedia.org/wiki/Hessian_matrix\ntemplate <typename GradientView, typename OutputView>\ninline void compute_hessian_entries(\n    GradientView dx,\n    GradientView dy,\n    OutputView ddxx,\n    OutputView dxdy,\n    OutputView ddyy)\n{\n    auto sobel_x = generate_dx_sobel();\n    auto sobel_y = generate_dy_sobel();\n    detail::convolve_2d(dx, sobel_x, ddxx);\n    detail::convolve_2d(dx, sobel_y, dxdy);\n    detail::convolve_2d(dy, sobel_y, ddyy);\n}\n\n}} // namespace boost::gil\n\n#endif\n", "meta": {"hexsha": "3ac989ccb9e2f3436667797c212d352703e8b847", "size": 10411, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/gil/image_processing/numeric.hpp", "max_stars_repo_name": "Paul92/gil", "max_stars_repo_head_hexsha": "da0655fb66dd161a643e1ca0ed51937548465d18", "max_stars_repo_licenses": ["BSL-1.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": "include/boost/gil/image_processing/numeric.hpp", "max_issues_repo_name": "Paul92/gil", "max_issues_repo_head_hexsha": "da0655fb66dd161a643e1ca0ed51937548465d18", "max_issues_repo_licenses": ["BSL-1.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": "include/boost/gil/image_processing/numeric.hpp", "max_forks_repo_name": "Paul92/gil", "max_forks_repo_head_hexsha": "da0655fb66dd161a643e1ca0ed51937548465d18", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.4735099338, "max_line_length": 194, "alphanum_fraction": 0.6728460282, "num_tokens": 2630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.7879312056025699, "lm_q1q2_score": 0.7095555200568958}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\r\n// for linear algebra.\r\n//\r\n// Copyright (C) 2008 Benoit Jacob <jacob.benoit.1@gmail.com>\r\n// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>\r\n//\r\n// This Source Code Form is subject to the terms of the Mozilla\r\n// Public License v. 2.0. If a copy of the MPL was not distributed\r\n// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.\r\n\r\n#include \"main.h\"\r\n#include <Eigen/LU>\r\n\r\ntemplate<typename MatrixType> void determinant(const MatrixType& m)\r\n{\r\n  /* this test covers the following files:\r\n     Determinant.h\r\n  */\r\n  Index size = m.rows();\r\n\r\n  MatrixType m1(size, size), m2(size, size);\r\n  m1.setRandom();\r\n  m2.setRandom();\r\n  typedef typename MatrixType::Scalar Scalar;\r\n  Scalar x = internal::random<Scalar>();\r\n  VERIFY_IS_APPROX(MatrixType::Identity(size, size).determinant(), Scalar(1));\r\n  VERIFY_IS_APPROX((m1*m2).eval().determinant(), m1.determinant() * m2.determinant());\r\n  if(size==1) return;\r\n  Index i = internal::random<Index>(0, size-1);\r\n  Index j;\r\n  do {\r\n    j = internal::random<Index>(0, size-1);\r\n  } while(j==i);\r\n  m2 = m1;\r\n  m2.row(i).swap(m2.row(j));\r\n  VERIFY_IS_APPROX(m2.determinant(), -m1.determinant());\r\n  m2 = m1;\r\n  m2.col(i).swap(m2.col(j));\r\n  VERIFY_IS_APPROX(m2.determinant(), -m1.determinant());\r\n  VERIFY_IS_APPROX(m2.determinant(), m2.transpose().determinant());\r\n  VERIFY_IS_APPROX(numext::conj(m2.determinant()), m2.adjoint().determinant());\r\n  m2 = m1;\r\n  m2.row(i) += x*m2.row(j);\r\n  VERIFY_IS_APPROX(m2.determinant(), m1.determinant());\r\n  m2 = m1;\r\n  m2.row(i) *= x;\r\n  VERIFY_IS_APPROX(m2.determinant(), m1.determinant() * x);\r\n  \r\n  // check empty matrix\r\n  VERIFY_IS_APPROX(m2.block(0,0,0,0).determinant(), Scalar(1));\r\n}\r\n\r\nvoid test_determinant()\r\n{\r\n  for(int i = 0; i < g_repeat; i++) {\r\n    int s = 0;\r\n    CALL_SUBTEST_1( determinant(Matrix<float, 1, 1>()) );\r\n    CALL_SUBTEST_2( determinant(Matrix<double, 2, 2>()) );\r\n    CALL_SUBTEST_3( determinant(Matrix<double, 3, 3>()) );\r\n    CALL_SUBTEST_4( determinant(Matrix<double, 4, 4>()) );\r\n    CALL_SUBTEST_5( determinant(Matrix<std::complex<double>, 10, 10>()) );\r\n    s = internal::random<int>(1,EIGEN_TEST_MAX_SIZE/4);\r\n    CALL_SUBTEST_6( determinant(MatrixXd(s, s)) );\r\n    TEST_SET_BUT_UNUSED_VARIABLE(s)\r\n  }\r\n}\r\n", "meta": {"hexsha": "a9775bf853cfeed95231b8346cb1ea7527731e52", "size": 2333, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/eigen-eigen-323c052e1731/test/determinant.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/test/determinant.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/test/determinant.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": 34.8208955224, "max_line_length": 87, "alphanum_fraction": 0.6540934419, "num_tokens": 713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.8289387998695209, "lm_q1q2_score": 0.709448222633993}}
{"text": "\ufeff#include <cmath>\n#include <cstdlib>\n#include <tuple>\n#include <iostream>\n#include <Eigen/Dense>\n\nnamespace LogisticRegression\n{\n\t//Z(X\u2081,X\u2082)=1(\u03b8\u2081X\u2081+\u03b8\u2082X\u2082>800)\n\t//Z(X\u2081,X\u2082)=0(\u03b8\u2081X\u2081+\u03b8\u2082X\u2082<=800)\n\t//\u03b8\u2081=10,\u03b8\u2082=150,X\u2082=1\n\tstd::tuple<Eigen::MatrixX2d, Eigen::VectorXd> RandomGenterateTrainSet(size_t counts)\n\t{\n\t\tEigen::MatrixX2d train_input(counts, 2);\n\t\tEigen::VectorXd train_output(counts);\n\t\tfor (size_t i = 0; i < counts; i++)\n\t\t{\n\t\t\tdouble X\u2081 = std::rand() % 100 + 20, X\u2082 = 1;\n\t\t\ttrain_input(i, 0) = X\u2081;\n\t\t\ttrain_input(i, 1) = X\u2082;\n\t\t\tdouble \u03b8\u2081 = 10, \u03b8\u2082 = 150;\n\t\t\tdouble loss = /*std::rand() % 11 - 5;*/0;\n\t\t\tdouble hx = \u03b8\u2081 * X\u2081 + \u03b8\u2082 * X\u2082 + loss;\n\t\t\ttrain_output[i] = hx > 800 ? 1 : 0;\n\t\t}\n\t\t/*for (size_t i = 0; i < train_input.cols() - 1; i++)\n\t\t{\n\t\t\tauto&& col_i = train_input.col(i);\n\t\t\tcol_i = (col_i.array() - col_i.sum() / train_input.rows() / 2) / (col_i.maxCoeff() - col_i.minCoeff());\n\t\t}*/\n\t\treturn { train_input/*.normalized()*/, train_output };\n\t}\n\n\t//        -z\n\t//hx=1/1+e\n\t//          i      i      i         i\n\t//-1/m * \u2211y log(hx )+(1-y )log(1-hx )\n\tdouble LossFunction(const Eigen::MatrixXd& model, const Eigen::MatrixXd& train_input, const Eigen::MatrixXd& train_output)\n\t{\n\t\tauto z = (train_input * model).array();\n\t\t//translation relative position\n\t\tauto length = z.maxCoeff() / 2 + z.minCoeff() / 2;\n\t\tauto z_translation = z - length;\n\t\tauto hx = 1 / (1 + Eigen::exp(-1 * z_translation));\n\t\t//(0,1)\n\t\tconstexpr double multiple = 0.999999;\n\t\tauto hx_limit = hx * multiple;\n\t\t//std::cout << hx_limit << \"\\n\\n\";\n\t\t//std::cout << train_output << \"\\n\\n\";\n\t\treturn -1.0 / train_output.rows() * (train_output.array() * Eigen::log(hx_limit) + (1 - train_output.array()) * Eigen::log(1 - hx_limit)).sum();\n\t}\n\n\t//                            i      i     i\n\t//\u03b8 = \u03b8 - \u03b1 * 1/m * \u2211(h(x) - y(x) ) * x\n\t// j    j                                  j\n\tvoid GradientDescent(Eigen::MatrixXd& model, const Eigen::MatrixXd& train_input, const Eigen::MatrixXd& train_output, const Eigen::VectorXd& learning_rate, size_t batch_size)\n\t{\n\t\tfor (size_t i = 0; i < batch_size; i++)\n\t\t{\n\t\t\tfor (size_t train_index = 0; train_index < train_input.rows(); train_index++)\n\t\t\t{\n\t\t\t\tauto z = (train_input * model).array();\n\t\t\t\t//translation relative position\n\t\t\t\tauto length = z.maxCoeff() / 2 + z.minCoeff() / 2;\n\t\t\t\tauto z_translation = z - length;\n\t\t\t\tauto hx = 1 / (1 + Eigen::exp(-1 * z_translation));\n\t\t\t\t//(0,1)\n\t\t\t\tconstexpr double multiple = 0.999999;\n\t\t\t\tauto hx_limit = hx * multiple;\n\t\t\t\tauto hx_sub_yx = hx_limit.matrix() - train_output;\n\t\t\t\t//std::cout << hx_sub_yx << \"\\n\\n\";\n\t\t\t\tEigen::MatrixXd duplicate_line(model.cols(), train_input.cols());\n\t\t\t\tauto&& reference = duplicate_line << train_input.row(train_index);\n\t\t\t\tfor (size_t line = 0; line < model.cols() - 1; line++)\n\t\t\t\t{\n\t\t\t\t\treference, train_input.row(train_index);\n\t\t\t\t}\n\t\t\t\tEigen::MatrixXd update = learning_rate.array() * (1.0 / train_input.rows() * hx_sub_yx.row(train_index) * duplicate_line).transpose().array();\n\t\t\t\t//std::cout << duplicate_line << \"\\n\\n\";\n\t\t\t\t//std::cout << update << \"\\n\\n\";\n\t\t\t\tstd::cout << LossFunction(model, train_input, train_output) << \"\\n\\n\";\n\t\t\t\tmodel -= update;\n\t\t\t\t//std::cout << model << \"\\n\\n\";\n\t\t\t}\n\t\t}\n\t}\n}\n\nint main()\n{\n\tstd::cout << std::boolalpha;\n\n\tauto [train_input, train_output] = LogisticRegression::RandomGenterateTrainSet(100);\n\t//std::cout << train_input << std::endl;\n\t//std::cout << train_output << std::endl;\n\n\tEigen::MatrixXd model = Eigen::Vector2d(1, 200);\n\tEigen::Vector2d learning_rate(0.0001, 0.001);\n\tdouble limit = 0.05;\n\tsize_t batch_size = 100;\n\t//std::cout << LogisticRegression::LossFunction(model, train_input, train_output) << std::endl;\n\tLogisticRegression::GradientDescent(model, train_input, train_output, learning_rate, batch_size);\n\treturn 0;\n}", "meta": {"hexsha": "3bf77a056a50a40e0cc919b425fc0bf2b65c94e2", "size": 3774, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "LogisticRegression.cpp", "max_stars_repo_name": "yonghenghuanmie/MachineLearning", "max_stars_repo_head_hexsha": "bb37ffc8cac3641eff32e7e31e25e7692c5fcb74", "max_stars_repo_licenses": ["ECL-2.0", "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": "LogisticRegression.cpp", "max_issues_repo_name": "yonghenghuanmie/MachineLearning", "max_issues_repo_head_hexsha": "bb37ffc8cac3641eff32e7e31e25e7692c5fcb74", "max_issues_repo_licenses": ["ECL-2.0", "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": "LogisticRegression.cpp", "max_forks_repo_name": "yonghenghuanmie/MachineLearning", "max_forks_repo_head_hexsha": "bb37ffc8cac3641eff32e7e31e25e7692c5fcb74", "max_forks_repo_licenses": ["ECL-2.0", "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": 36.2884615385, "max_line_length": 175, "alphanum_fraction": 0.6144674086, "num_tokens": 1215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475810629193, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.709409237142244}}
{"text": "#include <vector>\n#include <Eigen/Dense>\n#include \"bspline.hpp\"\n\nusing namespace bspline_storve;\n\n// Workaround for MSVC2012 not supporting curly brace initialization for std::vector\ntemplate <typename T, size_t N>\nstd::vector<T> makeVector(const T(&data)[N]) {\n    return std::vector<T>(data, data + N);\n}\n\nstd::vector<float> stdVectorToFloat(const std::vector<double>& in) {\n    std::vector<float> res(in.begin(), in.end());\n    return res;\n}\n\nvoid testBasisFunctions1() {\n    // Enough knots for one cubic b-spline\n\n    const float tempKnots[] = {0.0, 1.0, 1.0, 3.0, 4.0};\n    std::vector<float> knots = makeVector(tempKnots);\n    float x = 1.0;\n    int p = 3;\n    float b = bsplineBasis(0, p, x, knots);\n    std::cout << \"b = \" << b << std::endl;\n}\n\nvoid testBSplineMatrix() {\n    int k = 3;\n    int mu = 3;\n    const float tempKnots[] = {1,2,3,4,5,6,7,8,9,10,11,12};\n    std::vector<float> knots = makeVector(tempKnots);\n    float x = 1.0f;\n    auto res = bsplineMatrix(k, mu, x, knots);\n    std::cout << \"Bk = \" << res << std::endl;\n}\n\nvoid testDegree1() {\n    std::cout << __FUNCTION__ << std::endl;\n    const float tempKnots[] = {0.0, 1.0, 3.0};\n    std::vector<float> knots = makeVector(tempKnots);\n    bool pass = true;\n    for (float x = -1.0; x < 4.0; x += 0.001f) {\n        float b1 = bsplineBasis(0, 1, x, knots);\n        float b2 = B1(0, x, knots);\n        if (std::abs(b1-b2) > 1e-6) {\n            std::cout << \"Error: \" << b1 << \" \" << b2 << std::endl;\n            pass = false;\n        }\n    }\n    if (!pass) {\n        std::cout << __FUNCTION__ << \" error\\n\";\n    }\n}\n\nvoid testDegree2() {\n    std::cout << __FUNCTION__ << std::endl;\n    const float tempKnots[] = {0.0f, 1.0f, 3.0f, 4.0f};\n    std::vector<float> knots = makeVector(tempKnots);\n    bool pass = true;\n    for (float x = -1.0; x < 5.0; x += 0.001f) {\n        float b1 = bsplineBasis(0, 2, x, knots);\n        float b2 = B2(0, x, knots);\n        if (std::abs(b1-b2) > 1e-6) {\n            std::cout << \"Error: \" << b1 << \" \" << b2 << std::endl;\n            pass = false;\n        }\n    }\n    if (!pass) {\n        std::cout << __FUNCTION__ << \" error\\n\";\n    }\n}\n\nvoid testDegree3() {\n    std::cout << __FUNCTION__ << std::endl;\n    const float tempKnots[] = {0.0, 1.0, 3.0, 4.0, 5.0, 6.0};\n    std::vector<float> knots = makeVector(tempKnots);\n    bool pass = true;\n    for (int j = 0; j < 2; j++) {\n        for (float x = -1.0; x < 7.0; x += 0.001f) {\n            float b1 = bsplineBasis(j, 3, x, knots);\n            float b2 = B3(j, x, knots);\n            if (std::abs(b1-b2) > 1e-6) {\n                std::cout << \"Error: \" << b1 << \" \" << b2 << std::endl;\n                pass = false;\n            }\n        }\n    }\n    if (!pass) {\n        std::cout << __FUNCTION__ << \" error\\n\";\n    }\n}\n\nvoid testLinAlg1() {\n    std::cout << __FUNCTION__ << std::endl;\n    Eigen::Matrix2d a;\n    Eigen::MatrixXd b(2,2), c(2,2);\n    a << 1,2,3,4;\n    b << 2,3,1,4;\n    a *= b;\n   // std::cout << c << std::endl;\n}\n\nvoid testLinAlg2() {\n using namespace Eigen;\n Matrix2d a;\na << 1, 2,\n3, 4;\nVector3d v(1,2,3);\nstd::cout << \"a * 2.5 =\\n\" << a * 2.5 << std::endl;\nstd::cout << \"0.1 * v =\\n\" << 0.1 * v << std::endl;\nstd::cout << \"Doing v *= 2;\" << std::endl;\nv *= 2;\nstd::cout << \"Now v =\\n\" << v << std::endl;\n}\n\nvoid testLeastSquares() {\n    using namespace Eigen;\n    MatrixXf A = MatrixXf::Random(3,2);\n    std::cout << \"A:\" << A << std::endl;\n    VectorXf b = VectorXf::Random(3);\n    std::cout << \"b: \" << b << std::endl;\n    std::cout << \"LSQ solution: \" << A.jacobiSvd(ComputeThinU | ComputeThinV).solve(b) << std::endl;\n}\n\nvoid testLinAlg3() {\n    using namespace Eigen;\n    Matrix2d mat;\n    mat << 1, 2,\n    3, 4;\n    Vector2d u(-1,1), v(2,0);\n    std::cout << \"Here is mat*mat:\\n\" << mat*mat << std::endl;\n    std::cout << \"Here is mat*u:\\n\" << mat*u << std::endl;\n    std::cout << \"Here is u^T*mat:\\n\" << u.transpose()*mat << std::endl;\n    std::cout << \"Here is u^T*v:\\n\" << u.transpose()*v << std::endl;\n    std::cout << \"Here is u*v^T:\\n\" << u*v.transpose() << std::endl;\n    std::cout << \"Let's multiply mat by itself\" << std::endl;\n    mat = mat*mat;\n    std::cout << \"Now mat is mat:\\n\" << mat << std::endl;\n}\n\nint main(void) {\n    std::cout << \"Test\" << std::endl;\n    \n    testBasisFunctions1();\n    testDegree1();\n    testDegree2();\n    testDegree3();\n    testLinAlg3();\n    testLeastSquares();\n    testBSplineMatrix();\n\n}\n", "meta": {"hexsha": "6fa28a36b5c76c030b092ad96d58b5306d85f198", "size": 4410, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/demo.cpp", "max_stars_repo_name": "sigurdstorve/supersplines", "max_stars_repo_head_hexsha": "a49cac9f7e166b660fb1da688f9bf5d90f05dcdb", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-07T02:40:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T07:09:08.000Z", "max_issues_repo_path": "cpp/demo.cpp", "max_issues_repo_name": "sigurdstorve/supersplines", "max_issues_repo_head_hexsha": "a49cac9f7e166b660fb1da688f9bf5d90f05dcdb", "max_issues_repo_licenses": ["BSL-1.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": "cpp/demo.cpp", "max_forks_repo_name": "sigurdstorve/supersplines", "max_forks_repo_head_hexsha": "a49cac9f7e166b660fb1da688f9bf5d90f05dcdb", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4516129032, "max_line_length": 100, "alphanum_fraction": 0.5242630385, "num_tokens": 1583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995482, "lm_q2_score": 0.7981867801399694, "lm_q1q2_score": 0.7093955149951863}}
{"text": "#ifndef RBF_INTERPOLATION_HPP\n#define RBF_INTERPOLATION_HPP\n\n#include <vector>\n#include <Eigen/Core>\n\nnamespace mathtoolbox\n{\n    enum class RbfType\n    {\n        Gaussian,         // f(r) = exp(-(epsilon * r)^2)\n        ThinPlateSpline,  // f(r) = (r^2) * log(r)\n        InverseQuadratic, // f(r) = (1 + (epsilon * r)^2)^(-1)\n        Linear,           // f(r) = r\n    };\n\n    class RbfInterpolation\n    {\n    public:\n        RbfInterpolation(RbfType rbf_type = RbfType::ThinPlateSpline, double epsilon = 2.0);\n\n        // API\n        void   SetData(const Eigen::MatrixXd& X, const Eigen::VectorXd& y);\n        void   ComputeWeights(bool use_regularization = false, double lambda = 0.001);\n        double GetValue(const Eigen::VectorXd& x) const;\n\n        // Getter methods\n        const Eigen::VectorXd& GetY() const { return y; }\n        const Eigen::MatrixXd& GetX() const { return X; }\n        const Eigen::VectorXd& GetW() const { return w; }\n\n    private:\n\n        // Function type\n        RbfType rbf_type;\n\n        // A control parameter used in some kernel functions\n        double epsilon;\n\n        // Data points\n        Eigen::MatrixXd X;\n        Eigen::VectorXd y;\n\n        // Weights\n        Eigen::VectorXd w;\n\n        // Returns f(r)\n        double GetRbfValue(double r) const;\n\n        // Returns f(||xj - xi||)\n        double GetRbfValue(const Eigen::VectorXd& xi, const Eigen::VectorXd& xj) const;\n    };\n}\n\n#endif // RBF_INTERPOLATION_HPP\n", "meta": {"hexsha": "2da6f308d52faecf0aac8273a5b1c1f6a5e68373", "size": 1459, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mathtoolbox/rbf-interpolation.hpp", "max_stars_repo_name": "josefgraus/self_similiarity", "max_stars_repo_head_hexsha": "c032daa3009f60fdc8a52c437a07c6e3ba2efe4b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-25T09:35:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-25T09:35:14.000Z", "max_issues_repo_path": "include/mathtoolbox/rbf-interpolation.hpp", "max_issues_repo_name": "josefgraus/self_similiarity", "max_issues_repo_head_hexsha": "c032daa3009f60fdc8a52c437a07c6e3ba2efe4b", "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": "include/mathtoolbox/rbf-interpolation.hpp", "max_forks_repo_name": "josefgraus/self_similiarity", "max_forks_repo_head_hexsha": "c032daa3009f60fdc8a52c437a07c6e3ba2efe4b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-09-22T13:02:45.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-08T00:21:36.000Z", "avg_line_length": 26.0535714286, "max_line_length": 92, "alphanum_fraction": 0.5819054147, "num_tokens": 384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.888758793492457, "lm_q2_score": 0.7981867705385763, "lm_q1q2_score": 0.7093955111655057}}
{"text": "/**\n * @file kalman_filter.cpp\n * @brief Kalman Filter.\n * \n */\n\n#include <kalman_filter.hpp>\n#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace filter;\n\nKalmanFilter::KalmanFilter(\n    const Eigen::MatrixXd& A,\n    const Eigen::MatrixXd& C,\n    const Eigen::MatrixXd& Q,\n    const Eigen::MatrixXd& R,\n    const Eigen::MatrixXd& P\n    ):\n    A(A), C(C), Q(Q), R(R), P0(P),\n    m(C.rows()), n(A.rows()),\n    I(n, n), x_hat(n), x_hat_new(n),\n    initialized(false)\n{\n    // Initialize the identity transformation.\n    I.setIdentity();\n}\n\nvoid KalmanFilter::init(double t0, const Eigen::VectorXd& x0)\n{\n    // Set parameters based on initial guess.\n    x_hat = x0;\n    P = P0;\n    this->t0 = t0;\n    initialized = true;\n}\n\nvoid KalmanFilter::init()\n{\n    // Set parameters to zero.\n    x_hat.setZero();\n    P = P0;\n    t0 = 0;\n    initialized = true;\n}\n\nEigen::VectorXd KalmanFilter::compute(const Eigen::VectorXd& y, double dt)\n{\n    // Error handling.\n    if(!this->initialized) throw std::runtime_error(\"Filter is not initialized!\");\n\n    // Set the new state.\n    x_hat_new = A * x_hat;\n\n    // Predict error covariance.\n    P = A * P * A.transpose() + Q;\n\n    // Update Kalman gain.\n    K = P * C.transpose() * (C * P * C.transpose() + R).inverse();\n\n    // Update estimate covariance.\n    P = (I - K * C) * P;\n\n    // Update state.\n    x_hat_new += K * (y - C * x_hat_new);\n    x_hat = x_hat_new;\n\n    return x_hat;\n}", "meta": {"hexsha": "f34592c4c9cf5eecc55afcc6a8154a2e0084d5da", "size": 1429, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/signal_processing/src/kalman_filter.cpp", "max_stars_repo_name": "duckstarr/controller", "max_stars_repo_head_hexsha": "ed8020a4ba010981a6ea7377f39f0d1490359450", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2021-05-15T21:58:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-03T04:34:54.000Z", "max_issues_repo_path": "src/signal_processing/src/kalman_filter.cpp", "max_issues_repo_name": "duckstarr/controller", "max_issues_repo_head_hexsha": "ed8020a4ba010981a6ea7377f39f0d1490359450", "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/signal_processing/src/kalman_filter.cpp", "max_forks_repo_name": "duckstarr/controller", "max_forks_repo_head_hexsha": "ed8020a4ba010981a6ea7377f39f0d1490359450", "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": 20.7101449275, "max_line_length": 82, "alphanum_fraction": 0.5962211337, "num_tokens": 406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533144915913, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.70927121719978}}
{"text": "#include <Eigen/Dense>\n\nEigen::Vector2d eval_mat_mul(Eigen::Matrix2d in_mat, Eigen::Vector2d in_vec) {\n  return in_mat * in_vec;\n}\n\ndouble sqrt_sum_vec(const Eigen::VectorXd vec) {\n  return vec.cwiseSqrt().sum();\n}\n", "meta": {"hexsha": "9542fffb6bc5d8bba0726d58ef8382cc78b44db9", "size": 215, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/pycpp_examples/src/examples.hpp", "max_stars_repo_name": "RAIL-group/RAIL-software-infrastructure-demos", "max_stars_repo_head_hexsha": "98efc7d5d93957e85e9a10cb3881bf824b3f6187", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-12-27T11:46:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T01:19:18.000Z", "max_issues_repo_path": "src/pycpp_examples/src/examples.hpp", "max_issues_repo_name": "RAIL-group/RAIL-software-infrastructure-demos", "max_issues_repo_head_hexsha": "98efc7d5d93957e85e9a10cb3881bf824b3f6187", "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/pycpp_examples/src/examples.hpp", "max_forks_repo_name": "RAIL-group/RAIL-software-infrastructure-demos", "max_forks_repo_head_hexsha": "98efc7d5d93957e85e9a10cb3881bf824b3f6187", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-11T18:21:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T18:21:35.000Z", "avg_line_length": 21.5, "max_line_length": 78, "alphanum_fraction": 0.7348837209, "num_tokens": 63, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147439, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.7092364971678393}}
{"text": "#include \"gtest/gtest.h\"\n\n#include <Eigen/Dense>\n\nusing Eigen::Vector3d;\n\nTEST(eigen, vector3_dot) {\n        Vector3d v1(1, 1, 1);\n        Vector3d v2(1, 2, 3);\n        EXPECT_EQ(6, v1.dot(v2));\n}\n\nint main(int argc, char **argv) {\n        ::testing::InitGoogleTest(&argc, argv);\n        return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "c0f3cf8abee5b8955a57fbddd1952944b0a82d32", "size": 314, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/test_eigen.cc", "max_stars_repo_name": "mozuysal/virg-workspace", "max_stars_repo_head_hexsha": "ff0df41ceb288609c5279a85d9d04dbbc178d33e", "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": "test/test_eigen.cc", "max_issues_repo_name": "mozuysal/virg-workspace", "max_issues_repo_head_hexsha": "ff0df41ceb288609c5279a85d9d04dbbc178d33e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-02-07T11:26:33.000Z", "max_issues_repo_issues_event_max_datetime": "2017-02-07T12:43:41.000Z", "max_forks_repo_path": "test/test_eigen.cc", "max_forks_repo_name": "mozuysal/virg-workspace", "max_forks_repo_head_hexsha": "ff0df41ceb288609c5279a85d9d04dbbc178d33e", "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": 18.4705882353, "max_line_length": 47, "alphanum_fraction": 0.5923566879, "num_tokens": 100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8856314858927011, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.7091180475586418}}
{"text": "#include \"gtest/gtest.h\"\n#include <Eigen/Dense>\n\n\n#include <casadi/casadi.hpp>\n#include <vector>\n\nclass Rosenbrock {\npublic:\n    using var_t = Eigen::Vector2d;\n    using gradient_t = Eigen::Vector2d;\n    using hessian_t = Eigen::Matrix2d;\n\n    casadi::Function m_f;\n    casadi::Function m_grad;\n    casadi::Function m_hess;\n\n    Rosenbrock()\n    {\n        casadi::SX x = casadi::SX::sym(\"x\", 2);\n        const double a = 1;\n        const double b = 100;\n\n        casadi::SX z = 0;\n        for (int i = 0; i < x.rows() - 1; i++) {\n            z += pow(a - x(i), 2) + b * pow(x(i + 1) - pow(x(i), 2), 2);\n        }\n\n        casadi::SX f_sym = z;\n        casadi::SX grad_sym = casadi::SX::gradient(f_sym, x);\n        casadi::SX hess_sym = casadi::SX::jacobian(grad_sym, x);\n\n        m_f = casadi::Function(\"f\", {x}, {f_sym});\n        m_grad = casadi::Function(\"g\", {x}, {grad_sym});\n        m_hess = casadi::Function(\"h\", {x}, {hess_sym});\n    }\n\n    void operator()(const var_t& x, double& value)\n    {\n        std::vector<double> xv(x.size());\n        var_t::Map(&xv[0]) = x;\n        casadi::DM res;\n        res = m_f({casadi::DM(xv)})[0];\n        value = *casadi::DM::densify(res).nonzeros().data();\n    }\n\n    void gradient(const var_t& x, gradient_t& grad, double& value)\n    {\n        this->operator()(x, value);\n\n        casadi::DM res;\n        std::vector<double> xv(x.size());\n        var_t::Map(&xv[0]) = x;\n\n        res = m_grad({casadi::DM(xv)})[0];\n        grad = gradient_t::Map(casadi::DM::densify(res).nonzeros().data());\n    }\n\n    void hessian(const var_t& x, hessian_t& hess, gradient_t& grad, double& value)\n    {\n        gradient(x, grad, value);\n\n        casadi::DM res;\n        std::vector<double> xv(x.size());\n        var_t::Map(&xv[0]) = x;\n\n        res = m_hess({casadi::DM(xv)})[0];\n        hess = hessian_t::Map(casadi::DM::densify(res).nonzeros().data());\n    }\n};\n\nclass SimpleQP {\npublic:\n    Eigen::Matrix2d H;\n    Eigen::Vector2d h;\n    Eigen::Vector2d l, u;\n\n    SimpleQP()\n    {\n        H << 10, 0,\n            0, 0.1;\n        h << -1, -2;\n\n        l << -1, -1;\n        u << 1, 1;\n    }\n\n    void operator()(const Eigen::Vector2d& x, double& value)\n    {\n        value = 0.5 * x.dot(H * x) + h.dot(x);\n    }\n\n    void gradient(const Eigen::Vector2d& x, Eigen::Vector2d& grad, double& value)\n    {\n        this->operator()(x, value);\n        grad << H * x + h;\n    }\n\n    void hessian(const Eigen::Vector2d& x,\n                 Eigen::Matrix2d& hess,\n                 Eigen::Vector2d& grad,\n                 double& value)\n    {\n        gradient(x, grad, value);\n        hess << H;\n    }\n};\n\nTEST(TrustRegionTestCase, TestRosenbrock) {\n    SimpleQP prob;\n    // Rosenbrock prob;\n\n    using Scalar = double;\n    using var_t = Eigen::Vector2d;\n    using gradient_t = Eigen::Vector2d;\n    using hessian_t = Eigen::Matrix2d;\n\n    var_t x0(0, 0);\n\n    Scalar cost, trust_region;\n    var_t x;\n    hessian_t B;\n    gradient_t g;\n    Eigen::LLT<hessian_t> cholesky;\n\n    const Scalar epsilon = 1e-4;\n    const Scalar eta = 0; // 0 < eta < 10e-3\n    const Scalar trust_region_max_radius = 1e3;\n    x = x0;\n    trust_region = 0.1;\n\n    // Algorithm 6.2 Trust-Region Method\n    int iter;\n    for (iter = 0; iter < 100; iter++) {\n        std::cout << \"x \" << x.transpose() << std::endl;\n\n        prob.hessian(x, B, g, cost);\n        var_t p, q, x_step;\n\n        Scalar lambda = 0.1; // TODO: initial value?\n        for (int i = 0; i < 3; i++) {\n            // Algorithm 4.3 Trust Region Subproblem\n            cholesky.compute(B + lambda * B.Identity());\n\n            // TODO: what if B is indefinite?\n            if (cholesky.info() != Eigen::Success) {\n                lambda *= 2;\n                continue;\n            }\n\n            p = cholesky.solve(-g);\n            q = cholesky.matrixL().solve(p);\n            // std::cout << \"p \" << p.transpose() << std::endl;\n            // std::cout << \"q \" << p.transpose() << std::endl;\n            lambda = lambda + p.dot(p) / q.dot(q) * (p.norm() - trust_region) / trust_region;\n\n            // std::cout << \"B\\n\" << B << std::endl;\n            // std::cout << \"B+\\n\" << (B + lambda * B.Identity()) << std::endl;\n\n        }\n        cholesky.compute(B + lambda * B.Identity());\n        p = cholesky.solve(-g);\n\n        std::cout << \"g \" << g.transpose() << std::endl;\n        std::cout << \"p \" << p.transpose() << std::endl;\n\n        x_step = x + p;\n\n        Scalar ared, pred, rho;\n        Scalar cost_step;\n        gradient_t g_step;\n\n        prob.gradient(x_step, g_step, cost_step);\n        pred = -(g.dot(p) + 0.5 * p.dot(B * p));\n        ared = cost - cost_step;\n        rho = ared / pred;\n\n        printf(\"rho %f\\n\", rho);\n\n        if (rho > eta) {\n            x = x + p;\n        } else {\n            printf(\"reject step\\n\");\n            // reject step: x = x;\n        }\n\n        // trust region update\n        if (rho < 0.1) {\n            printf(\"shrink trust region, %f\\n\", trust_region);\n            trust_region = 0.5 * trust_region;\n        } else if (rho > 0.75) {\n            if (p.norm() < 0.8 * trust_region) {\n                // keep trust region\n                printf(\"keep trust region\\n\");\n            } else {\n                trust_region = fmin(2.0 * trust_region, trust_region_max_radius);\n                printf(\"increase trust region, %f\\n\", trust_region);\n            }\n        } else {\n            // keep trust region\n            printf(\"keep trust region\\n\");\n        }\n\n        // do SR1 or BFGS update\n        // if (SR1 condition 6.26) {\n        //     y = grad - grad_prev;\n        //     SR1_update(B, p, y);\n        // }\n\n        if (g.lpNorm<Eigen::Infinity>() < epsilon) {\n            break;\n        }\n    }\n    std::cout << \"x \" << x.transpose() << std::endl;\n    std::cout << \"iter \" << iter << std::endl;\n}\n\nint main(int argc, char **argv)\n{\n    ::testing::InitGoogleTest(&argc, argv);\n    return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "49e8dc3d4b0daf12b627b00d62f3f2fe3344b655", "size": 5925, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "polympc/src/solvers/trust_region_tests/trust_region_test.cpp", "max_stars_repo_name": "alexandreguerradeoliveira/rocket_gnc", "max_stars_repo_head_hexsha": "164e96daca01d9edbc45bfaac0f6b55fe7324f24", "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": "polympc/src/solvers/trust_region_tests/trust_region_test.cpp", "max_issues_repo_name": "alexandreguerradeoliveira/rocket_gnc", "max_issues_repo_head_hexsha": "164e96daca01d9edbc45bfaac0f6b55fe7324f24", "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": "polympc/src/solvers/trust_region_tests/trust_region_test.cpp", "max_forks_repo_name": "alexandreguerradeoliveira/rocket_gnc", "max_forks_repo_head_hexsha": "164e96daca01d9edbc45bfaac0f6b55fe7324f24", "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.5695067265, "max_line_length": 93, "alphanum_fraction": 0.4953586498, "num_tokens": 1749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.8006920116079209, "lm_q1q2_score": 0.7091180463147723}}
{"text": "/*\n * Copyright Nick Thompson, 2020\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 <numeric>\n#include <utility>\n#include <iomanip>\n#include <iostream>\n#include <random>\n#include <cmath>\n#include <boost/core/demangle.hpp>\n#include <boost/hana/for_each.hpp>\n#include <boost/hana/ext/std/integer_sequence.hpp>\n#include <boost/math/tools/condition_numbers.hpp>\n#include <boost/math/special_functions/daubechies_wavelet.hpp>\n#include <boost/math/special_functions/next.hpp>\n#include <boost/math/quadrature/trapezoidal.hpp>\n\n#ifdef BOOST_HAS_FLOAT128\n#include <boost/multiprecision/float128.hpp>\nusing boost::multiprecision::float128;\n#endif\n\n\nusing boost::math::constants::pi;\nusing boost::math::constants::root_two;\n\ntemplate<typename Real>\nvoid test_exact_value()\n{\n    // The global phase of the wavelet is not constrained by anything other than convention.\n    // Make sure that our conventions match the rest of the world:\n    auto psi = boost::math::daubechies_wavelet<Real, 2>(2);\n    Real computed = psi(1);\n    Real expected = -1.366025403784439;\n    CHECK_MOLLIFIED_CLOSE(expected, computed, 0.0001);\n}\n\ntemplate<typename Real, int p>\nvoid test_quadratures()\n{\n    std::cout << \"Testing quadratures of \" << p << \" vanishing moment Daubechies wavelet on type \" << boost::core::demangle(typeid(Real).name()) << \"\\n\";\n    using boost::math::quadrature::trapezoidal;\n    auto psi = boost::math::daubechies_wavelet<Real, p>();\n    std::cout << \"Wavelet functor size is \" << psi.bytes() << \" bytes\" << std::endl;\n        \n    Real tol = std::numeric_limits<Real>::epsilon();\n    Real error_estimate = std::numeric_limits<Real>::quiet_NaN();\n    Real L1 = std::numeric_limits<Real>::quiet_NaN();\n    auto [a, b] = psi.support();\n    CHECK_ULP_CLOSE(Real(-p+1), a, 0);\n    CHECK_ULP_CLOSE(Real(p), b, 0);\n    // A wavelet is a function of zero average; ensure the quadrature over its support is zero.\n    Real Q = trapezoidal(psi, a, b, tol, 15, &error_estimate, &L1);\n    if (!CHECK_MOLLIFIED_CLOSE(Real(0), Q, Real(0.0001)))\n    {\n        std::cerr << \"  Quadrature of \" << p << \" vanishing moment wavelet does not vanish.\\n\";\n        std::cerr << \"  Error estimate: \" << error_estimate << \", L1 norm: \" << L1 << \"\\n\";\n    }\n    auto psi_sq = [psi](Real x) {\n        Real t = psi(x);\n        return t*t;\n    };\n    Q = trapezoidal(psi_sq, a, b, tol, 15, &error_estimate, &L1);\n    Real quad_tol = 2000*std::sqrt(std::numeric_limits<Real>::epsilon())/(p*p*p);\n    if (!CHECK_MOLLIFIED_CLOSE(Real(1), Q, quad_tol))\n    {\n        std::cerr << \"  L2 norm of \" << p << \" vanishing moment wavelet does not vanish.\\n\";\n        std::cerr << \"  Error estimate: \" << error_estimate << \", L1 norm: \" << L1 << \"\\n\";\n    }\n    // psi is orthogonal to its integer translates: \\int \\psi(x-k) \\psi(x) \\, \\mathrm{d}x = 0\n    // g_n = 1/sqrt(2) <psi(t/2), phi(t-n)> (Mallat, 7.55)\n\n    // Now hit the boundary. Much can go wrong here; this just tests for segfaults:\n    int samples = 500;\n    Real xlo = a;\n    Real xhi = b;\n    for (int i = 0; i < samples; ++i)\n    {\n        CHECK_ULP_CLOSE(Real(0), psi(xlo), 0);\n        CHECK_ULP_CLOSE(Real(0), psi(xhi), 0);\n        if constexpr (p > 2)\n        {\n            CHECK_ULP_CLOSE(Real(0), psi.prime(xlo), 0);\n            CHECK_ULP_CLOSE(Real(0), psi.prime(xhi), 0);\n            if constexpr (p >= 6) {\n                CHECK_ULP_CLOSE(Real(0), psi.double_prime(xlo), 0);\n                CHECK_ULP_CLOSE(Real(0), psi.double_prime(xhi), 0);\n            }\n        }\n        xlo = std::nextafter(xlo, std::numeric_limits<Real>::lowest());\n        xhi = std::nextafter(xhi, std::numeric_limits<Real>::max());\n    }\n\n    xlo = a;\n    xhi = b;\n    for (int i = 0; i < samples; ++i) {\n        std::cout << std::setprecision(std::numeric_limits<Real>::max_digits10);\n        assert(abs(psi(xlo)) <= 5);\n        assert(abs(psi(xhi)) <= 5);\n        if constexpr (p > 2)\n        {\n            assert(abs(psi.prime(xlo)) <= 5);\n            assert(abs(psi.prime(xhi)) <= 5);\n            if constexpr (p >= 6)\n            {\n                assert(abs(psi.double_prime(xlo)) <= 5);\n                assert(abs(psi.double_prime(xhi)) <= 5);\n            }\n        }\n        xlo = std::nextafter(xlo, std::numeric_limits<Real>::max());\n        xhi = std::nextafter(xhi, std::numeric_limits<Real>::lowest());\n    }\n}\n\nint main()\n{\n    test_exact_value<double>();\n\n    boost::hana::for_each(std::make_index_sequence<17>(), [&](auto i){\n        test_quadratures<float, i+3>();\n        test_quadratures<double, i+3>();\n    });\n\n    return boost::math::test::report_errors();\n}\n", "meta": {"hexsha": "eb92c271cd248f9576c6f5d9dc2da95519b521d8", "size": 4768, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/math/test/daubechies_wavelet_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/daubechies_wavelet_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/daubechies_wavelet_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": 36.3969465649, "max_line_length": 153, "alphanum_fraction": 0.6115771812, "num_tokens": 1368, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600902, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.7090842472935874}}
{"text": "/*=============================================================================\n  Copyright (c) 2010-2016 Bolero MURAKAMI\n  https://github.com/bolero-MURAKAMI/Sprig\n\n  Distributed under the Boost Software License, Version 1.0. (See accompanying\n  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n=============================================================================*/\n#ifndef SPRIG_CURVE_CATMULL_ROM_SPLINE_HPP\n#define SPRIG_CURVE_CATMULL_ROM_SPLINE_HPP\n\n#include <sprig/config/config.hpp>\n\n#ifdef SPRIG_USING_PRAGMA_ONCE\n#\tpragma once\n#endif\t// #ifdef SPRIG_USING_PRAGMA_ONCE\n\n#include <boost/geometry/core/access.hpp>\n#include <sprig/detail/pow.hpp>\n\nnamespace sprig {\n\t//\n\t// catmull_rom_spline\n\t//\n\ttemplate<typename T, typename Point>\n\tSPRIG_INLINE Point\n\tcatmull_rom_spline(T const& t, Point const& p0, Point const& p1, Point const& p2, Point const& p3) {\n\t\tnamespace bg = boost::geometry;\n\t\tusing sprig::detail::pow2;\n\t\tusing sprig::detail::pow3;\n\t\treturn value_type(\n\t\t\t(-bg::get<0>(p0) + 3 * bg::get<0>(p1) - 3 * bg::get<0>(p2) + bg::get<0>(p3)) / 2 * pow3(t)\n\t\t\t\t+ (2 * bg::get<0>(p0) - 5 * bg::get<0>(p1) + 4 * bg::get<0>(p2) - bg::get<0>(p3) / 2 * pow2(t)\n\t\t\t\t+ (-bg::get<0>(p0) + bg::get<0>(p2)) / 2 * t\n\t\t\t\t+ bg::get<0>(p1)\n\t\t\t\t,\n\t\t\t(-bg::get<1>(p0) + 3 * bg::get<1>(p1) - 3 * bg::get<1>(p2) + bg::get<1>(p3)) / 2 * pow3(t)\n\t\t\t\t+ (2 * bg::get<1>(p0) - 5 * bg::get<1>(p1) + 4 * bg::get<1>(p2) - bg::get<1>(p3)) / 2 * pow2(t)\n\t\t\t\t+ (-bg::get<1>(p0) + bg::get<1>(p2)) / 2 * t\n\t\t\t\t+ bg::get<1>(p1)\n\t\t\t);\n\t}\n\t//\n\t// catmull_rom_spline_start\n\t//\n\ttemplate<typename T, typename Point>\n\tSPRIG_INLINE Point\n\tcatmull_rom_spline_start(T const& t, Point const& p0, Point const& p1, Point const& p2) {\n\t\tnamespace bg = boost::geometry;\n\t\tusing sprig::detail::pow2;\n\t\treturn value_type(\n\t\t\t(bg::get<0>(p0) - 2 * bg::get<0>(p1) + bg::get<0>(p2)) / 2 * pow2(t)\n\t\t\t\t+ (-3 * bg::get<0>(p0) + 4 * bg::get<0>(p1) - bg::get<0>(p2)) / 2 * t\n\t\t\t\t+ bg::get<0>(p0)\n\t\t\t\t,\n\t\t\t(bg::get<1>(p0) - 2 * bg::get<1>(p1) + bg::get<1>(p2)) / 2 * pow2(t)\n\t\t\t\t+ (-3 * bg::get<1>(p0) + 4 * bg::get<1>(p1) - bg::get<1>(p2)) / 2 * t\n\t\t\t\t+ bg::get<1>(p0)\n\t\t\t);\n\t}\n\t//\n\t// catmull_rom_spline_end\n\t//\n\ttemplate<typename T, typename Point>\n\tSPRIG_INLINE Point\n\tcatmull_rom_spline_end(T const& t, Point const& p0, Point const& p1, Point const& p2) {\n\t\tnamespace bg = boost::geometry;\n\t\tusing sprig::detail::pow2;\n\t\treturn value_type(\n\t\t\t(bg::get<0>(p0) - 2 * bg::get<0>(p1) + bg::get<0>(p2)) / 2 * pow2(t)\n\t\t\t\t+ (-bg::get<0>(p0) + bg::get<0>(p2)) / 2 * t\n\t\t\t\t+ bg::get<0>(p1)\n\t\t\t\t,\n\t\t\t(bg::get<1>(p0) - 2 * bg::get<1>(p1) + bg::get<1>(p2)) / 2 * pow2(t)\n\t\t\t\t+ (-bg::get<1>(p0) + bg::get<1>(p2)) / 2 * t\n\t\t\t\t+ bg::get<1>(p1)\n\t\t\t);\n\t}\n\n\t//\n\t// catmull_rom_spline_f\n\t//\n\ttemplate<typename Point>\n\tstruct catmull_rom_spline_f {\n\tpublic:\n\t\ttypedef Point result_type;\n\tprivate:\n\t\tPoint p0_;\n\t\tPoint p1_;\n\t\tPoint p2_;\n\t\tPoint p3_;\n\tpublic:\n\t\tcatmull_rom_spline_f(Point const& p0, Point const& p1, Point const& p2, Point const& p3)\n\t\t\t: p0_(p0), p1_(p1), p2_(p2), p3_(p3)\n\t\t{}\n\t\ttemplate<typename T>\n\t\tPoint operator()(T const& t) const {\n\t\t\treturn sprig::catmull_rom_spline(t, p0_, p1_, p2_, p3_);\n\t\t}\n\t};\n\t//\n\t// catmull_rom_spline_start_f\n\t//\n\ttemplate<typename Point>\n\tstruct catmull_rom_spline_start_f {\n\tpublic:\n\t\ttypedef Point result_type;\n\tprivate:\n\t\tPoint p0_;\n\t\tPoint p1_;\n\t\tPoint p2_;\n\tpublic:\n\t\tcatmull_rom_spline_start_f(Point const& p0, Point const& p1, Point const& p2)\n\t\t\t: p0_(p0), p1_(p1), p2_(p2)\n\t\t{}\n\t\ttemplate<typename T>\n\t\tPoint operator()(T const& t) const {\n\t\t\treturn sprig::catmull_rom_spline_start(t, p0_, p1_, p2_);\n\t\t}\n\t};\n\t//\n\t// catmull_rom_spline_end_f\n\t//\n\ttemplate<typename Point>\n\tstruct catmull_rom_spline_end_f {\n\tpublic:\n\t\ttypedef Point result_type;\n\tprivate:\n\t\tPoint p0_;\n\t\tPoint p1_;\n\t\tPoint p2_;\n\tpublic:\n\t\tcatmull_rom_spline_end_f(Point const& p0, Point const& p1, Point const& p2)\n\t\t\t: p0_(p0), p1_(p1), p2_(p2)\n\t\t{}\n\t\ttemplate<typename T>\n\t\tPoint operator()(T const& t) const {\n\t\t\treturn sprig::catmull_rom_spline_end(t, p0_, p1_, p2_);\n\t\t}\n\t};\n\n\t//\n\t// make_catmull_rom_spline\n\t//\n\ttemplate<typename Point>\n\tSPRIG_INLINE sprig::catmull_rom_spline_f<Point>\n\tmake_catmull_rom_spline(Point const& p0, Point const& p1, Point const& p2, Point const& p3) {\n\t\treturn sprig::catmull_rom_spline_f<Point>(p0, p1, p2, p3);\n\t}\n\t//\n\t// make_catmull_rom_spline_start\n\t//\n\ttemplate<typename Point>\n\tSPRIG_INLINE sprig::catmull_rom_spline_start_f<Point>\n\tmake_catmull_rom_spline_start(Point const& p0, Point const& p1, Point const& p2) {\n\t\treturn sprig::catmull_rom_spline_start_f<Point>(p0, p1, p2);\n\t}\n\t//\n\t// make_catmull_rom_spline_end\n\t//\n\ttemplate<typename Point>\n\tSPRIG_INLINE sprig::catmull_rom_spline_end_f<Point>\n\tmake_catmull_rom_spline_end(Point const& p0, Point const& p1, Point const& p2) {\n\t\treturn sprig::catmull_rom_spline_end_f<Point>(p0, p1, p2);\n\t}\n}\t// namespace sprig\n\n#endif\t// #ifndef SPRIG_CURVE_CATMULL_ROM_SPLINE_HPP\n", "meta": {"hexsha": "ea00028b04803dd3b82f7f33eba4ed1cdae082b7", "size": 4962, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sprig/curve/catmull_rom_spline.hpp", "max_stars_repo_name": "bolero-MURAKAMI/Sprig", "max_stars_repo_head_hexsha": "51ce4db4f4d093dee659a136f47249e4fe91fc7a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-10-24T13:56:24.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-28T13:21:22.000Z", "max_issues_repo_path": "sprig/curve/catmull_rom_spline.hpp", "max_issues_repo_name": "bolero-MURAKAMI/Sprig", "max_issues_repo_head_hexsha": "51ce4db4f4d093dee659a136f47249e4fe91fc7a", "max_issues_repo_licenses": ["BSL-1.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": "sprig/curve/catmull_rom_spline.hpp", "max_forks_repo_name": "bolero-MURAKAMI/Sprig", "max_forks_repo_head_hexsha": "51ce4db4f4d093dee659a136f47249e4fe91fc7a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2016-04-12T03:26:06.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-28T13:21:22.000Z", "avg_line_length": 29.5357142857, "max_line_length": 101, "alphanum_fraction": 0.6249496171, "num_tokens": 1886, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834277, "lm_q2_score": 0.7826624840223699, "lm_q1q2_score": 0.7090842433202743}}
{"text": "static bool eigen_did_assert = false;\n#define eigen_assert(X) if(!eigen_did_assert && !(X)){ std::cout << \"### Assertion raised in \" << __FILE__ << \":\" << __LINE__ << \":\\n\" #X << \"\\n### The following would happen without assertions:\\n\"; eigen_did_assert = true;}\n\n#include <iostream>\n#include <Eigen/Eigen>\n\n#ifndef M_PI\n#define M_PI 3.1415926535897932384626433832795\n#endif\n\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  Matrix3f A(3,3);\nA << 1,2,3,  4,5,6,  7,8,10;\nPartialPivLU<Matrix3f> luOfA(A); // compute LU decomposition of A\nVector3f b;\nb << 3,3,4;\nVector3f x;\nx = luOfA.solve(b);\ncout << \"The solution with right-hand side (3,3,4) is:\" << endl;\ncout << x << endl;\nb << 1,1,1;\nx = luOfA.solve(b);\ncout << \"The solution with right-hand side (1,1,1) is:\" << endl;\ncout << x << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "8057b20f3c1ab807cf318381217d0eec1ce0b6bc", "size": 852, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/snippets/compile_Tutorial_solve_reuse_decomposition.cpp", "max_stars_repo_name": "mousepawmedia/libdeps", "max_stars_repo_head_hexsha": "b004d58d5b395ceaf9fdc993cfb00e91334a5d36", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2021-02-27T11:00:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T10:31:46.000Z", "max_issues_repo_path": "doc/snippets/compile_Tutorial_solve_reuse_decomposition.cpp", "max_issues_repo_name": "mousepawmedia/libdeps", "max_issues_repo_head_hexsha": "b004d58d5b395ceaf9fdc993cfb00e91334a5d36", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-11-14T23:14:58.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-14T23:14:58.000Z", "max_forks_repo_path": "doc/snippets/compile_Tutorial_solve_reuse_decomposition.cpp", "max_forks_repo_name": "mousepawmedia/libdeps", "max_forks_repo_head_hexsha": "b004d58d5b395ceaf9fdc993cfb00e91334a5d36", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-03-13T13:28:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-05T02:26:02.000Z", "avg_line_length": 25.0588235294, "max_line_length": 224, "alphanum_fraction": 0.6525821596, "num_tokens": 288, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898153067649, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.7090842393469606}}
{"text": "#define PEAK_FLOPS 512\n\n#include <iostream>\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n#include <Eigen/Dense>\n#include <Eigen/Core>\n\n#include <chrono> \nusing namespace std::chrono; \n\nusing namespace Eigen;\n\nint main(int argc, char *argv[])\n{\n    Eigen::initParallel();\n    int m, n, k, i, j, loop_count;\n    m = atoi(argv[1]);\n    k = atoi(argv[2]);\n    n = atoi(argv[3]);\n    loop_count = atoi(argv[4]);\n\n    Eigen::MatrixXf A(m, k);\n    Eigen::MatrixXf B(k, n);\n    Eigen::MatrixXf C(m, n);\n    \n    printf (\" =============== Eigen ================\\n\");\n    printf (\" Using %i CPU cores\\n\", Eigen::nbThreads( ));\n    printf (\" Matrix multiplication C=A*B,\\n\"\n            \" matrix A(%ix%i) and matrix B(%ix%i)\\n\\n\", m, k, k, n);\n\n    C.noalias() += A*B;\n    auto time_start = high_resolution_clock::now(); \n    for (i = 0; i < loop_count; i++) {\n      C.noalias() += A*B;\n    }\n\n    auto time_end = high_resolution_clock::now(); \n    auto t = duration_cast<microseconds>(time_end - time_start).count() * 1e-6; \n    double time_avg = t/loop_count;\n    double gflop = (2.0*m*n*k)*1E-9;\n    printf(\" Total time  : %e secs \\n\", t);\n    printf(\" Average time: %e secs \\n\", time_avg);\n    printf(\" GFlop/sec   : %.5f  \\n\", gflop/time_avg);\n    printf(\" FLOPS Util. : %.5f  \\n\", gflop/time_avg/PEAK_FLOPS);\n\n}\n", "meta": {"hexsha": "cdaf260389b8d4e1350f4c60ffc82352c7542042", "size": 1318, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "library-math/eigen.cpp", "max_stars_repo_name": "Emma926/mcbench", "max_stars_repo_head_hexsha": "14e4c4741fb823abb75b7bc5a68c88a7798ce904", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2020-03-13T16:12:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T07:14:24.000Z", "max_issues_repo_path": "library-math/eigen.cpp", "max_issues_repo_name": "Emma926/mcbench", "max_issues_repo_head_hexsha": "14e4c4741fb823abb75b7bc5a68c88a7798ce904", "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": "library-math/eigen.cpp", "max_forks_repo_name": "Emma926/mcbench", "max_forks_repo_head_hexsha": "14e4c4741fb823abb75b7bc5a68c88a7798ce904", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-01-07T02:56:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-08T13:26:20.000Z", "avg_line_length": 26.8979591837, "max_line_length": 80, "alphanum_fraction": 0.5735963581, "num_tokens": 409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898102301018, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.7090842261879389}}
{"text": "#ifndef __NED_CLASS__\n#define __NED_CLASS__\n\n#include \"math.h\"\n#include <Eigen/Dense>\n\nnamespace geodesy_ned {\n    static const double a = 6378137;\n    static const double b = 6356752.3142;\n    static const double esq = 6.69437999014 * 0.001;\n    static const double e1sq = 6.73949674228 * 0.001;\n    static const double f = 1 / 298.257223563;\n\n    class Ned {\n    public:\n\n        Ned( const double lat,\n             const double lon,\n             const double height )\n        {\n            // Save NED origin\n            _init_lat = deg2Rad( lat );\n            _init_lon = deg2Rad( lon );\n            _init_h = height;\n\n            // Compute ECEF of NED origin\n            geodetic2Ecef( lat, lon, height,\n                        _init_ecef_x,\n                        _init_ecef_y,\n                        _init_ecef_z );\n\n            // Compute ECEF to NED and NED to ECEF matrices\n            double phiP = atan2( _init_ecef_z, sqrt( pow( _init_ecef_x, 2 ) +\n                                                    pow( _init_ecef_y, 2 ) ) );\n\n            _ecef_to_ned_matrix = __nRe__( phiP, _init_lon );\n            _ned_to_ecef_matrix = __nRe__( _init_lat, _init_lon ).transpose();\n        }\n\n\n        void\n        geodetic2Ecef( const double lat,\n                    const double lon,\n                    const double height,\n                    double& x,\n                    double& y,\n                    double& z )\n        {\n            // Convert geodetic coordinates to ECEF.\n            // http://code.google.com/p/pysatel/source/browse/trunk/coord.py?r=22\n            double lat_rad = deg2Rad( lat );\n            double lon_rad = deg2Rad( lon );\n            double xi = sqrt(1 - esq * sin( lat_rad ) * sin( lat_rad ) );\n            x = ( a / xi + height ) * cos( lat_rad ) * cos( lon_rad );\n            y = ( a / xi + height ) * cos( lat_rad ) * sin( lon_rad );\n            z = ( a / xi * ( 1 - esq ) + height ) * sin( lat_rad );\n        }\n\n        void\n        ecef2Geodetic( const double x,\n                    const double y,\n                    const double z,\n                    double& lat,\n                    double& lon,\n                    double& height )\n        {\n            // Convert ECEF coordinates to geodetic.\n            // J. Zhu, \"Conversion of Earth-centered Earth-fixed coordinates\n            // to geodetic coordinates,\" IEEE Transactions on Aerospace and\n            // Electronic Systems, vol. 30, pp. 957-961, 1994.\n\n            double r = sqrt( x * x + y * y );\n            double Esq = a * a - b * b;\n            double F = 54 * b * b * z * z;\n            double G = r * r + (1 - esq) * z * z - esq * Esq;\n            double C = (esq * esq * F * r * r) / pow( G, 3 );\n            double S = __cbrt__( 1 + C + sqrt( C * C + 2 * C ) );\n            double P = F / (3 * pow( (S + 1 / S + 1), 2 ) * G * G);\n            double Q = sqrt( 1 + 2 * esq * esq * P );\n            double r_0 =  -(P * esq * r) / (1 + Q) + sqrt( 0.5 * a * a * (1 + 1.0 / Q) - P * (1 - esq) * z * z / (Q * (1 + Q)) - 0.5 * P * r * r);\n            double U = sqrt( pow( (r - esq * r_0), 2 ) + z * z );\n            double V = sqrt( pow( (r - esq * r_0), 2 ) + (1 - esq) * z * z );\n            double Z_0 = b * b * z / (a * V);\n            height = U * (1 - b * b / (a * V));\n            lat = rad2Deg( atan( (z + e1sq * Z_0) / r ) );\n            lon = rad2Deg( atan2( y, x ) );\n        }\n\n\n        void\n        ecef2Ned( const double x,\n                const double y,\n                const double z,\n                double& north,\n                double& east,\n                double& depth )\n        {\n            // Converts ECEF coordinate pos into local-tangent-plane ENU\n            // coordinates relative to another ECEF coordinate ref. Returns a tuple\n            // (East, North, Up).\n\n            Eigen::Vector3d vect, ret;\n            vect(0) = x - _init_ecef_x;\n            vect(1) = y - _init_ecef_y;\n            vect(2) = z - _init_ecef_z;\n            ret = _ecef_to_ned_matrix * vect;\n            north = ret(0);\n            east = ret(1);\n            depth = -ret(2);\n        }\n\n\n        void\n        ned2Ecef( const double north,\n                const double east,\n                const double depth,\n                double& x,\n                double& y,\n                double& z )\n        {\n            // NED (north/east/down) to ECEF coordinate system conversion.\n            Eigen::Vector3d ned, ret;\n            ned(0) = north;\n            ned(1) = east;\n            ned(2) = -depth;\n            ret = _ned_to_ecef_matrix * ned;\n            x = ret(0) + _init_ecef_x;\n            y = ret(1) + _init_ecef_y;\n            z = ret(2) + _init_ecef_z;\n        }\n\n\n        void\n        geodetic2Ned( const double lat,\n                    const double lon,\n                    const double height,\n                    double& north,\n                    double& east,\n                    double& depth )\n        {\n            // Geodetic position to a local NED system \"\"\"\n            double x, y, z;\n            geodetic2Ecef( lat, lon, height,\n                        x, y, z );\n            ecef2Ned( x, y, z,\n                    north, east, depth );\n        }\n\n\n        void\n        ned2Geodetic( const double north,\n                    const double east,\n                    const double depth,\n                    double& lat,\n                    double& lon,\n                    double& height )\n        {\n            // Local NED position to geodetic\n            double x, y, z;\n            ned2Ecef( north, east, depth,\n                    x, y, z );\n            ecef2Geodetic( x, y, z,\n                        lat, lon, height );\n        }\n\n\n    private:\n        double _init_lat;\n        double _init_lon;\n        double _init_h;\n        double _init_ecef_x;\n        double _init_ecef_y;\n        double _init_ecef_z;\n        Eigen::Matrix3d _ecef_to_ned_matrix;\n        Eigen::Matrix3d _ned_to_ecef_matrix;\n\n\n        double\n        __cbrt__( const double x )\n        {\n            if( x >= 0.0 ) {\n                return pow( x, 1.0/3.0 );\n            }\n            else {\n                return -pow( fabs(x), 1.0/3.0 );\n            }\n        }\n\n\n        Eigen::Matrix3d\n        __nRe__( const double lat_rad,\n                const double lon_rad )\n        {\n            double sLat = sin( lat_rad );\n            double sLon = sin( lon_rad );\n            double cLat = cos( lat_rad );\n            double cLon = cos( lon_rad );\n\n            Eigen::Matrix3d ret;\n            ret(0, 0) = -sLat*cLon;     ret(0, 1) = -sLat*sLon;     ret(0, 2) = cLat;\n            ret(1, 0) = -sLon;          ret(1, 1) = cLon;           ret(1, 2) = 0.0;\n            ret(2, 0) = cLat*cLon;      ret(2, 1) = cLat*sLon;      ret(2, 2) = sLat;\n\n            return ret;\n        }\n\n        double\n        rad2Deg( const double radians )\n        {\n            return ( radians / M_PI ) * 180.0;\n        }\n\n\n        double\n        deg2Rad( const double degrees )\n        {\n            return ( degrees / 180.0 ) * M_PI;\n        }\n\n    };\n}; // namespace geodesy_ned\n#endif // __NED_CLASS__\n", "meta": {"hexsha": "9f38877c162c834f63cbd99fd33745cfa7c5ac3f", "size": 7101, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dependencies/asctec_mav_framework/asctec_hl_gps/src/geodesy_ned.hpp", "max_stars_repo_name": "sahibdhanjal/astrobee", "max_stars_repo_head_hexsha": "5bc4e6e58adcf1bc7e1c3719ced736063bba276c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-07-07T06:13:20.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-07T06:13:20.000Z", "max_issues_repo_path": "dependencies/asctec_mav_framework/asctec_hl_gps/src/geodesy_ned.hpp", "max_issues_repo_name": "sahibdhanjal/astrobee", "max_issues_repo_head_hexsha": "5bc4e6e58adcf1bc7e1c3719ced736063bba276c", "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": "dependencies/asctec_mav_framework/asctec_hl_gps/src/geodesy_ned.hpp", "max_forks_repo_name": "sahibdhanjal/astrobee", "max_forks_repo_head_hexsha": "5bc4e6e58adcf1bc7e1c3719ced736063bba276c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-09-09T05:49:51.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-09T05:49:51.000Z", "avg_line_length": 31.8430493274, "max_line_length": 146, "alphanum_fraction": 0.4381073088, "num_tokens": 1935, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966762263737, "lm_q2_score": 0.7490872187162396, "lm_q1q2_score": 0.709083471440451}}
{"text": "// Copyright Yamaha 2021\n// MIT License\n// https://github.com/yamaha-bps/cbr_math/blob/master/LICENSE\n\n#ifndef CBR_MATH__GEODETIC_HPP_\n#define CBR_MATH__GEODETIC_HPP_\n\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n\n#include <exception>\n#include <utility>\n\n#include \"geodetic_data.hpp\"\n#include \"math.hpp\"\n\nnamespace cbr::geo\n{\n\n/***************************************************************************\n * \\brief Converts geographic coordinates into geocentric ones.\n ***************************************************************************/\ntemplate<typename _ref = WGS84>\nvoid geographic2geocentric(\n  const Eigen::Ref<const Eigen::Vector3d> lla,\n  Eigen::Ref<Eigen::Vector3d> llr)\n{\n  constexpr double b2a2 = _ref::b2 / _ref::a2;\n  const double theta = atan(tan(lla[0]) * b2a2);\n  const double cosTheta = cos(theta);\n  const double sinTheta = sin(theta);\n\n  const double r =\n    1. / sqrt((cosTheta * cosTheta) / (_ref::a2) +(sinTheta * sinTheta) / (_ref::b2));\n\n  const double thetaPrime =\n    atan2(r * sinTheta + lla[2] * sin(lla[0]), r * cosTheta + lla[2] * cos(lla[0]));\n\n  const double rPrime = (r * cosTheta + lla[2] * cos(lla[0])) / cos(thetaPrime);\n\n  llr[0] = thetaPrime;\n  llr[1] = lla[1];\n  llr[2] = rPrime;\n}\n\ntemplate<typename _ref = WGS84>\nEigen::Vector3d geographic2geocentric(const Eigen::Ref<const Eigen::Vector3d> lla)\n{\n  Eigen::Vector3d llr;\n  geographic2geocentric<_ref>(lla, llr);\n  return llr;\n}\n\n\n/***************************************************************************\n * \\brief Converts geocentric coordinates into earth-centered-earth-fixed.\n ***************************************************************************/\ntemplate<typename _ref = WGS84>\nvoid llr2ecef(\n  const Eigen::Ref<const Eigen::Vector3d> llr,\n  Eigen::Ref<Eigen::Vector3d> ecef)\n{\n  const double cosTheta = cos(llr[0]);\n  const double sinTheta = sin(llr[0]);\n\n  ecef[0] = llr[2] * cosTheta * cos(llr[1]);\n  ecef[1] = llr[2] * cosTheta * sin(llr[1]);\n  ecef[2] = llr[2] * sinTheta;\n}\n\ntemplate<typename _ref = WGS84>\nEigen::Vector3d llr2ecef(const Eigen::Ref<const Eigen::Vector3d> llr)\n{\n  Eigen::Vector3d ecef;\n  llr2ecef<_ref>(llr, ecef);\n  return ecef;\n}\n\n\n/***************************************************************************\n * \\brief Converts geographic coordinates into earth-centered-earth-fixed.\n ***************************************************************************/\ntemplate<typename _ref = WGS84>\nvoid lla2ecef(\n  const Eigen::Ref<const Eigen::Vector3d> lla,\n  Eigen::Ref<Eigen::Vector3d> ecef)\n{\n  geographic2geocentric<_ref>(lla, ecef);\n  llr2ecef<_ref>(ecef, ecef);\n}\n\ntemplate<typename _ref = WGS84>\nEigen::Vector3d lla2ecef(const Eigen::Ref<const Eigen::Vector3d> lla)\n{\n  Eigen::Vector3d ecef;\n  lla2ecef<_ref>(lla, ecef);\n  return ecef;\n}\n\n// forward-declaration\ntemplate<typename _ref = WGS84>\nEigen::Matrix3d geo2ecef(const Eigen::Ref<const Eigen::Vector2d> ll);\n\ntemplate<typename _ref = WGS84, typename derived>\nstd::pair<Eigen::Vector3d, Eigen::Quaterniond> lla2ecef(\n  const Eigen::Ref<const Eigen::Vector3d> lla,\n  const Eigen::QuaternionBase<derived> & R_NWU)\n{\n  const Eigen::Vector3d T_W_S = lla2ecef<_ref>(lla);\n  const Eigen::Quaterniond R_W_NWU(geo2ecef<_ref>(lla.template head<2>()));\n\n  return {T_W_S, R_W_NWU * R_NWU};\n}\n\n/***************************************************************************\n * \\brief Converts earth-centered-earth-fixed (ecef) coordinates into\n * geographic latitude, longitude and altitude (lla)\n ***************************************************************************/\ntemplate<typename _ref = WGS84>\nvoid ecef2lla(\n  const Eigen::Ref<const Eigen::Vector3d> ecef,\n  Eigen::Ref<Eigen::Vector3d> lla)\n{\n  const double x = ecef[0];\n  const double y = ecef[1];\n  const double z = ecef[2];\n\n  double & lat = lla[0];\n  double & lon = lla[1];\n  double & ht = lla[2];\n\n  constexpr double a1 = _ref::a * _ref::e2;\n  constexpr double a2 = a1 * a1;\n  constexpr double a3 = a1 * _ref::e2 / 2.;\n  constexpr double a4 = (5. / 2.) * a2;\n  constexpr double a5 = a1 + a3;\n  constexpr double a6 = 1. - _ref::e2;\n\n  double zp, w2, w, z2, r2, r, s2, c2, s, c, ss;  // NOLINT\n  double g, rg, rf, u, v, m, f, p;  // NOLINT\n  zp = fabs(z);\n  w2 = x * x + y * y;\n  w = sqrt(w2);\n  z2 = z * z;\n  r2 = w2 + z2;\n  r = sqrt(r2);\n  if (r < 100000.) {\n    lat = 0.;\n    lon = 0.;\n    ht = -1.e7;\n    return;\n  }\n\n  lon = atan2(y, x);\n  s2 = z2 / r2;\n  c2 = w2 / r2;\n  u = a2 / r;\n  v = a3 - a4 / r;\n\n  if (c2 > .3) {\n    s = (zp / r) * (1. + c2 * (a1 + u + s2 * v) / r);\n    lat = asin(s);\n    ss = s * s;\n    c = sqrt(1. - ss);\n  } else {\n    c = (w / r) * (1. - s2 * (a5 - u - c2 * v) / r);\n    lat = acos(c);\n    ss = 1. - c * c;\n    s = sqrt(ss);\n  }\n\n  g = 1. - _ref::e2 * ss;\n  rg = _ref::a / sqrt(g);\n  rf = a6 * rg;\n  u = w - rg * c;\n  v = zp - rf * s;\n  f = c * u + s * v;\n  m = c * v - s * u;\n  p = m / (rf / g + f);\n  lat = lat + p;\n  ht = f + m * p / 2.;\n\n  if (z < 0.) {\n    lat = -lat;\n  }\n}\n\ntemplate<typename _ref = WGS84>\nEigen::Vector3d ecef2lla(const Eigen::Ref<const Eigen::Vector3d> ecef)\n{\n  Eigen::Vector3d lla;\n  ecef2lla<_ref>(ecef, lla);\n  return lla;\n}\n\ntemplate<typename _ref = WGS84, typename derived>\nstd::pair<Eigen::Vector3d, Eigen::Quaterniond> ecef2lla(\n  const Eigen::Ref<const Eigen::Vector3d> T_ecef,\n  const Eigen::QuaternionBase<derived> & q_ecef)\n{\n  const Eigen::Vector3d lla = ecef2lla<_ref>(T_ecef);\n  const Eigen::Matrix3d R_W_NWU = geo2ecef<_ref>(lla.head<2>());\n\n  return {lla, Eigen::Quaterniond(R_W_NWU.transpose()) * q_ecef};\n}\n\n/***************************************************************************\n * \\brief Converts earth-centered-earth-fixed (ecef) coordinates into\n * geocentric latitude, longitude and radius (llr)\n ***************************************************************************/\ntemplate<typename _ref = WGS84>\nvoid ecef2llr(\n  const Eigen::Ref<const Eigen::Vector3d> ecef,\n  Eigen::Ref<Eigen::Vector3d> llr)\n{\n  const double z = ecef[2];\n  llr[2] = ecef.norm();\n  llr[1] = atan2(ecef[1], ecef[0]);\n  llr[0] = asin(z / llr[2]);\n}\n\ntemplate<typename _ref = WGS84>\nEigen::Vector3d ecef2llr(const Eigen::Ref<const Eigen::Vector3d> ecef)\n{\n  Eigen::Vector3d llr;\n  ecef2llr<_ref>(ecef, llr);\n  return llr;\n}\n\n\n/***************************************************************************\n * \\brief Converts north-west-up geographic or geocentric orientation into\n * earth-centered-earth-fixed one. Latitude and longitude must be in the\n * same frame as the orientation.\n ***************************************************************************/\ntemplate<typename _ref = WGS84>\nvoid geo2ecef(\n  const Eigen::Ref<const Eigen::Vector2d> ll,\n  Eigen::Ref<Eigen::Matrix3d> M_ecef_ll)\n{\n  const double cosTheta = cos(ll[0]);\n  const double sinTheta = sin(ll[0]);\n  const double cosLong = cos(ll[1]);\n  const double sinLong = sin(ll[1]);\n\n  M_ecef_ll <<\n    -sinTheta * cosLong, sinLong, cosTheta * cosLong,\n    -sinTheta * sinLong, -cosLong, cosTheta * sinLong,\n    cosTheta, 0., sinTheta;\n}\n\ntemplate<typename _ref>\nEigen::Matrix3d geo2ecef(\n  const Eigen::Ref<const Eigen::Vector2d> ll)\n{\n  Eigen::Matrix3d M_ecef_ll;\n  geo2ecef<_ref>(ll, M_ecef_ll);\n  return M_ecef_ll;\n}\n\ntemplate<typename _ref = WGS84,\n  typename derivedIn,\n  typename derivedOut>\nvoid geo2ecef(\n  const Eigen::QuaternionBase<derivedIn> & qIn,\n  const Eigen::Ref<const Eigen::Vector2d> ll,\n  Eigen::QuaternionBase<derivedOut> & qOut)\n{\n  qOut = Eigen::Quaterniond(geo2ecef<_ref>(ll)) * qIn;\n}\n\ntemplate<typename _ref = WGS84, typename derived>\nEigen::Quaterniond geo2ecef(\n  const Eigen::QuaternionBase<derived> & qIn,\n  const Eigen::Ref<const Eigen::Vector2d> ll)\n{\n  Eigen::Quaterniond qOut;\n  geo2ecef<_ref>(qIn, ll, qOut);\n  return qOut;\n}\n\n/***************************************************************************\n * \\brief Converts geocentric north-west-up orientation into geographic one\n *  given geographic coordinates.\n ***************************************************************************/\ntemplate<typename _ref = WGS84,\n  typename derivedIn,\n  typename derivedOut>\nvoid imu2nwu(\n  const Eigen::QuaternionBase<derivedIn> & qIn,\n  const Eigen::Ref<const Eigen::Vector3d> lla,\n  Eigen::QuaternionBase<derivedOut> & qOut)\n{\n  const Eigen::Vector3d llr = geographic2geocentric<_ref>(lla);\n  const Eigen::Matrix3d qEC = geo2ecef<_ref>(llr.head<2>());\n  const Eigen::Matrix3d qEG = geo2ecef<_ref>(lla.head<2>());\n\n  qOut = (qEG.transpose() * qEC) * qIn;\n}\n\ntemplate<typename _ref = WGS84, typename derived>\nEigen::Quaterniond imu2nwu(\n  const Eigen::QuaternionBase<derived> & qIn,\n  const Eigen::Ref<const Eigen::Vector3d> lla)\n{\n  Eigen::Quaterniond qOut;\n  imu2nwu<_ref>(qIn, lla, qOut);\n  return qOut;\n}\n\n/***************************************************************************\n * \\brief Converts geographic north-west-up orientation into geocentric one\n *  given geographic coordinates.\n ***************************************************************************/\ntemplate<typename _ref = WGS84,\n  typename derivedIn,\n  typename derivedOut>\nvoid nwu2imu(\n  const Eigen::QuaternionBase<derivedIn> & qIn,\n  const Eigen::Ref<const Eigen::Vector3d> lla,\n  Eigen::QuaternionBase<derivedOut> & qOut)\n{\n  const Eigen::Vector3d llr = geographic2geocentric<_ref>(lla);\n  const Eigen::Matrix3d qEC = geo2ecef<_ref>(llr.head<2>());\n  const Eigen::Matrix3d qEG = geo2ecef<_ref>(lla.head<2>());\n\n  qOut = (qEC.transpose() * qEG) * qIn;\n}\n\ntemplate<typename _ref = WGS84, typename derived>\nEigen::Quaterniond nwu2imu(\n  const Eigen::QuaternionBase<derived> & qIn,\n  const Eigen::Ref<const Eigen::Vector3d> lla)\n{\n  Eigen::Quaterniond qOut;\n  nwu2imu<_ref>(qIn, lla, qOut);\n  return qOut;\n}\n\n/***************************************************************************\n * \\brief Computes gnomonic projection of lla onto the plane tangent to the\n * ellipsoid at llaRef (the altitude of llaRef is ignored). The projection\n * is done from a point with a geographic altitude equal to 0, and the z\n * component of the result is the original geographic altitude. If the\n * projection is impossible, the function returns false, otherwise it\n * returns true.\n ***************************************************************************/\ntemplate<typename _ref = WGS84>\nbool lla2gnomonic(\n  const Eigen::Ref<const Eigen::Vector3d> lla,\n  const Eigen::Ref<const Eigen::Vector3d> llaRef,\n  Eigen::Ref<Eigen::Vector3d> xyz)\n{\n  const double cosLatRef = cos(llaRef[0]);\n  const double sinLatRef = sin(llaRef[0]);\n  const double cosLongRef = cos(llaRef[1]);\n  const double sinLongRef = sin(llaRef[1]);\n\n  const Eigen::Vector3d x{\n    -sinLatRef * cosLongRef,\n    -sinLatRef * sinLongRef,\n    cosLatRef};\n\n  const Eigen::Vector3d y{\n    sinLongRef,\n    -cosLongRef,\n    0.};\n\n  const Eigen::Vector3d z{\n    cosLatRef * cosLongRef,\n    cosLatRef * sinLongRef,\n    sinLatRef};\n\n  const Eigen::Vector3d ecef = lla2ecef<_ref>(Eigen::Vector3d(lla[0], lla[1], 0.));\n  if (z.dot(ecef) < 1e-9) {\n    return false;\n  }\n\n  const Eigen::Vector3d ecefRef = lla2ecef<_ref>(Eigen::Vector3d(llaRef[0], llaRef[1], 0.));\n\n  Eigen::Matrix3d M;\n  M.col(0) = -x;\n  M.col(1) = -y;\n  M.col(2) = ecef;\n\n  const double alti = lla[2];\n\n  xyz = M.fullPivLu().solve(ecefRef);\n\n  if (xyz[2] <= 0.) {\n    return false;\n  }\n\n  xyz[2] = alti;\n\n  return true;\n}\n\ntemplate<typename _ref = WGS84>\nstd::pair<bool, Eigen::Vector3d> lla2gnomonic(\n  const Eigen::Ref<const Eigen::Vector3d> lla,\n  const Eigen::Ref<const Eigen::Vector3d> llaRef)\n{\n  std::pair<bool, Eigen::Vector3d> out;\n  out.first = lla2gnomonic<_ref>(lla, llaRef, out.second);\n  return out;\n}\n\n\n/***************************************************************************\n * \\brief Computes inverse gnomonic projection from the plane tangent to the\n * ellipsoid at llaRef (the altitude of llaRef is ignored). The altitude of\n * the result is the z component of the projection.\n ***************************************************************************/\ntemplate<typename _ref = WGS84>\nvoid gnomonic2lla(\n  const Eigen::Ref<const Eigen::Vector3d> xyz,\n  const Eigen::Ref<const Eigen::Vector3d> llaRef,\n  Eigen::Ref<Eigen::Vector3d> lla)\n{\n  const double cosLatRef = cos(llaRef[0]);\n  const double sinLatRef = sin(llaRef[0]);\n  const double cosLongRef = cos(llaRef[1]);\n  const double sinLongRef = sin(llaRef[1]);\n\n  const Eigen::Vector3d x{\n    -sinLatRef * cosLongRef,\n    -sinLatRef * sinLongRef,\n    cosLatRef};\n\n  const Eigen::Vector3d y{\n    sinLongRef,\n    -cosLongRef,\n    0.};\n\n  Eigen::Vector3d ecef = lla2ecef<_ref>(Eigen::Vector3d(llaRef[0], llaRef[1], 0.));\n\n  ecef += xyz[0] * x + xyz[1] * y;\n\n  const double alti = xyz[2];\n\n  ecef2llr<_ref>(ecef, lla);\n  constexpr double a2b2 = _ref::a2 / _ref::b2;\n  lla[0] = atan(a2b2 * tan(lla[0]));\n  lla[2] = alti;\n}\n\ntemplate<typename _ref = WGS84>\nEigen::Vector3d gnomonic2lla(\n  const Eigen::Ref<const Eigen::Vector3d> xyz,\n  const Eigen::Ref<const Eigen::Vector3d> llaRef)\n{\n  Eigen::Vector3d lla;\n  gnomonic2lla<_ref>(xyz, llaRef, lla);\n  return lla;\n}\n\n\n/***************************************************************************\n * \\brief Converts geographic coordinates into north-west-up ones.\n ***************************************************************************/\ntemplate<typename _ref = WGS84>\nvoid lla2nwu(\n  const Eigen::Ref<const Eigen::Vector3d> lla,\n  const Eigen::Ref<const Eigen::Vector3d> llaRef,\n  Eigen::Ref<Eigen::Vector3d> nwu)\n{\n  const Eigen::Vector3d ecefRef = lla2ecef<_ref>(llaRef);\n  const Eigen::Vector3d ecef = lla2ecef<_ref>(lla);\n  nwu = geo2ecef<_ref>(llaRef.head<2>()).transpose() * (ecef - ecefRef);\n}\n\ntemplate<typename _ref = WGS84>\nEigen::Vector3d lla2nwu(\n  const Eigen::Ref<const Eigen::Vector3d> lla,\n  const Eigen::Ref<const Eigen::Vector3d> llaRef)\n{\n  Eigen::Vector3d nwu;\n  lla2nwu<_ref>(lla, llaRef, nwu);\n  return nwu;\n}\n\ntemplate<typename _ref = WGS84,\n  typename derived>\nvoid lla2nwu(\n  const Eigen::Ref<const Eigen::Vector3d> lla,\n  const Eigen::Ref<const Eigen::Vector3d> llaRef,\n  const Eigen::QuaternionBase<derived> & qRef,\n  Eigen::Ref<Eigen::Vector3d> nwu)\n{\n  lla2nwu<_ref>(lla, llaRef, nwu);\n  nwu = qRef.toRotationMatrix().transpose() * nwu;\n}\n\ntemplate<typename _ref = WGS84,\n  typename derived>\nEigen::Vector3d lla2nwu(\n  const Eigen::Ref<const Eigen::Vector3d> lla,\n  const Eigen::Ref<const Eigen::Vector3d> llaRef,\n  const Eigen::QuaternionBase<derived> & qRef)\n{\n  Eigen::Vector3d nwu;\n  lla2nwu<_ref>(lla, llaRef, qRef, nwu);\n  return nwu;\n}\n\n/***************************************************************************\n * \\brief Transforms a geographic frame into north-west-up one.\n ***************************************************************************/\ntemplate<typename _ref = WGS84,\n  typename derived1,\n  typename derived2,\n  typename derived3>\nvoid lla2nwu(\n  const Eigen::Ref<const Eigen::Vector3d> lla,\n  const Eigen::QuaternionBase<derived1> & q,\n  const Eigen::Ref<const Eigen::Vector3d> llaRef,\n  const Eigen::QuaternionBase<derived2> & qRef,\n  Eigen::Ref<Eigen::Vector3d> nwu,\n  Eigen::QuaternionBase<derived3> & qNwu)\n{\n  const Eigen::Vector3d ecefFrame = lla2ecef<_ref>(lla);\n  const Eigen::Vector3d ecefRef = lla2ecef<_ref>(llaRef);\n\n  const Eigen::Quaterniond qEcefFrame = geo2ecef<_ref>(q, lla.head<2>());\n  const Eigen::Quaterniond qEcefRefInv = geo2ecef<_ref>(qRef, llaRef.head<2>()).conjugate();\n\n  nwu = qEcefRefInv.toRotationMatrix() * (ecefFrame - ecefRef);\n  qNwu = qEcefRefInv * qEcefFrame;\n}\n\ntemplate<typename _ref = WGS84,\n  typename derived1,\n  typename derived2>\nvoid lla2nwu(\n  const Eigen::Ref<const Eigen::Vector3d> lla,\n  const Eigen::QuaternionBase<derived1> & q,\n  const Eigen::Ref<const Eigen::Vector3d> llaRef,\n  Eigen::Ref<Eigen::Vector3d> nwu,\n  Eigen::QuaternionBase<derived2> & qNwu)\n{\n  lla2nwu<_ref>(lla, q, llaRef, Eigen::Quaterniond::Identity(), nwu, qNwu);\n}\n\n/***************************************************************************\n * \\brief Converts north-west-up coordinates into geographic ones.\n ***************************************************************************/\ntemplate<typename _ref = WGS84>\nvoid nwu2lla(\n  const Eigen::Ref<const Eigen::Vector3d> nwu,\n  const Eigen::Ref<const Eigen::Vector3d> llaRef,\n  Eigen::Ref<Eigen::Vector3d> lla)\n{\n  const Eigen::Vector3d ecefRef = lla2ecef<_ref>(llaRef);\n  lla = ecefRef + geo2ecef<_ref>(llaRef.head<2>()) * nwu;\n  ecef2lla<_ref>(lla, lla);\n}\n\ntemplate<typename _ref = WGS84>\nEigen::Vector3d nwu2lla(\n  const Eigen::Ref<const Eigen::Vector3d> nwu,\n  const Eigen::Ref<const Eigen::Vector3d> llaRef)\n{\n  Eigen::Vector3d lla;\n  nwu2lla<_ref>(nwu, llaRef, lla);\n  return lla;\n}\n\ntemplate<typename _ref = WGS84,\n  typename derived>\nvoid nwu2lla(\n  const Eigen::Ref<const Eigen::Vector3d> nwu,\n  const Eigen::Ref<const Eigen::Vector3d> llaRef,\n  const Eigen::QuaternionBase<derived> & qRef,\n  Eigen::Ref<Eigen::Vector3d> lla)\n{\n  lla = qRef.toRotationMatrix() * nwu;\n  nwu2lla<_ref>(lla, llaRef, lla);\n}\n\ntemplate<typename _ref = WGS84,\n  typename derived>\nEigen::Vector3d nwu2lla(\n  const Eigen::Ref<const Eigen::Vector3d> nwu,\n  const Eigen::Ref<const Eigen::Vector3d> llaRef,\n  const Eigen::QuaternionBase<derived> & qRef)\n{\n  Eigen::Vector3d lla;\n  nwu2lla<_ref>(nwu, llaRef, qRef, lla);\n  return lla;\n}\n\n/***************************************************************************\n * \\brief Transforms a north-west-up frame into a geographic one.\n ***************************************************************************/\ntemplate<typename _ref = WGS84,\n  typename derived1,\n  typename derived2,\n  typename derived3>\nvoid nwu2lla(\n  const Eigen::Ref<const Eigen::Vector3d> nwu,\n  const Eigen::QuaternionBase<derived1> & q,\n  const Eigen::Ref<const Eigen::Vector3d> llaRef,\n  const Eigen::QuaternionBase<derived2> & qRef,\n  Eigen::Ref<Eigen::Vector3d> lla,\n  Eigen::QuaternionBase<derived3> & qLla)\n{\n  const Eigen::Vector3d ecefRef = lla2ecef<_ref>(llaRef);\n  const Eigen::Quaterniond qEcefRef = geo2ecef<_ref>(qRef, llaRef.head<2>());\n  const Eigen::Quaterniond qEcefFrame = qEcefRef * q;\n\n  const Eigen::Vector3d ecefFrame = ecefRef + qEcefRef.toRotationMatrix() * nwu;\n  ecef2lla<_ref>(ecefFrame, lla);\n\n  const Eigen::Matrix3d RotEcefFrameInv = geo2ecef<_ref>(lla.head<2>()).transpose();\n  qLla = RotEcefFrameInv * qEcefFrame;\n}\n\ntemplate<typename _ref = WGS84,\n  typename derived1,\n  typename derived2>\nvoid nwu2lla(\n  const Eigen::Ref<const Eigen::Vector3d> lla,\n  const Eigen::QuaternionBase<derived1> & q,\n  const Eigen::Ref<const Eigen::Vector3d> llaRef,\n  Eigen::Ref<Eigen::Vector3d> nwu,\n  Eigen::QuaternionBase<derived2> & qNwu)\n{\n  nwu2lla<_ref>(lla, q, llaRef, Eigen::Quaterniond::Identity(), nwu, qNwu);\n}\n\n/***************************************************************************\n * \\brief Returns cartesian distance in the earth-centered-earth-fixed frame\n * for 2 points given by their geographic latitude, longitude and altitude\n ***************************************************************************/\ntemplate<typename _ref = WGS84>\ndouble distCartesian(\n  const Eigen::Ref<const Eigen::Vector3d> pt1,\n  const Eigen::Ref<const Eigen::Vector3d> pt2)\n{\n  Eigen::Vector3d ecef1;\n  Eigen::Vector3d ecef2;\n  lla2ecef<_ref>(pt1, ecef1);\n  lla2ecef<_ref>(pt2, ecef2);\n  return (ecef1 - ecef2).norm();\n}\n\n\n/***************************************************************************\n * \\brief Returns geodesic distance using Vincenty's formula. Throws a\n * runtime_error if it doesn't converge.\n ***************************************************************************/\ntemplate<typename _ref = WGS84>\ndouble distGeodesicVincenty(\n  const Eigen::Ref<const Eigen::Vector2d> pt1,\n  const Eigen::Ref<const Eigen::Vector2d> pt2,\n  const double tol = 1e-10,\n  const uint64_t maxIter = 1000)\n{\n  double sin_sigma, cos_sigma, sigma, sin_alpha, cos_sq_alpha, cos2sigma;  // NOLINT\n  double C, lam_pre;  // NOLINT\n\n  // convert to radians\n  const auto & latp = pt1[0];\n  const auto & latc = pt2[0];\n  const auto & longp = pt1[1];\n  const auto & longc = pt2[1];\n\n  const double u1 = atan((1 - _ref::f) * tan(latc));\n  const double u2 = atan((1 - _ref::f) * tan(latp));\n\n  const double lon = longp - longc;\n  double lam = lon;\n  double diff = 1.;\n  std::size_t iter = 0;\n  bool converged = false;\n  while (iter < maxIter) {\n    sin_sigma = sqrt(\n      powFast<2>((cos(u2) * sin(lam))) +\n      powFast<2>(cos(u1) * sin(u2) - sin(u1) * cos(u2) * cos(lam)));\n    cos_sigma = sin(u1) * sin(u2) + cos(u1) * cos(u2) * cos(lam);\n    sigma = atan(sin_sigma / cos_sigma);\n    sin_alpha = (cos(u1) * cos(u2) * sin(lam)) / sin_sigma;\n    cos_sq_alpha = 1. - powFast<2>(sin_alpha);\n    cos2sigma = cos_sigma - ((2. * sin(u1) * sin(u2)) / cos_sq_alpha);\n    C = (_ref::f / 16.) * cos_sq_alpha * (4 + _ref::f * (4. - 3. * cos_sq_alpha));\n    lam_pre = lam;\n    lam = lon + (1. - C) * _ref::f * sin_alpha *\n      (sigma +\n      C * sin_sigma * (cos2sigma + C * cos_sigma * (2. * powFast<2>(cos2sigma) - 1.)));\n    diff = fabs(lam_pre - lam);\n\n    if (fabs(diff) <= tol) {\n      converged = true;\n      break;\n    }\n    iter++;\n  }\n\n  if (!converged) {\n    throw std::runtime_error(\"distGeodesicVincenty failed to converge.\");\n  }\n\n  const double usq = cos_sq_alpha * ((_ref::a2 - _ref::b2) / _ref::b2);\n  const double A = 1. + (usq / 16384.) * (4096. + usq * (-768. + usq * (320. - 175. * usq)));\n  const double B = (usq / 1024.) * (256. + usq * (-128. + usq * (74. - 47. * usq)));\n  const double delta_sig =\n    B * sin_sigma *\n    (cos2sigma + 0.25 * B *\n    (cos_sigma * (-1. + 2. * powFast<2>(cos2sigma)) -\n    (1. / 6.) * B * cos2sigma * (-3. + 4. * powFast<2>(sin_sigma)) *\n    (-3. + 4. * powFast<2>(cos2sigma))));\n\n  return _ref::b * A * (sigma - delta_sig);\n}\n\n\n/***************************************************************************\n * \\brief Returns great circle distance using mean curvature radius\n * at the mean latitude of the points.\n ***************************************************************************/\ntemplate<typename _ref = WGS84>\ndouble distGreatCircle(\n  const Eigen::Ref<const Eigen::Vector2d> pt1,\n  const Eigen::Ref<const Eigen::Vector2d> pt2)\n{\n  const auto & lat1 = pt1[0];\n  const auto & lat2 = pt2[0];\n  const auto & lon1 = pt1[1];\n  const auto & lon2 = pt2[1];\n\n  const double dLat = (lat2 - lat1);\n  const double dLon = (lon2 - lon1);\n\n  const double a = powFast<2>(sin(dLat / 2.)) + powFast<2>(sin(dLon / 2.)) * cos(lat1) * cos(lat2);\n  const double c = 2. * asin(sqrt(a));\n\n  return _ref::r * c;\n}\n\n}  // namespace cbr\n\n#endif  // CBR_MATH__GEODETIC_HPP_\n", "meta": {"hexsha": "236a525ecd9e36b91528217b50845b06d108e337", "size": 22577, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/cbr_math/geodetic.hpp", "max_stars_repo_name": "yamaha-bps/cbr_math", "max_stars_repo_head_hexsha": "cf1ad7d4661f4b0063d07e00a4e0052454518931", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-24T17:41:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-24T17:41:16.000Z", "max_issues_repo_path": "include/cbr_math/geodetic.hpp", "max_issues_repo_name": "yamaha-bps/cbr_math", "max_issues_repo_head_hexsha": "cf1ad7d4661f4b0063d07e00a4e0052454518931", "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": "include/cbr_math/geodetic.hpp", "max_forks_repo_name": "yamaha-bps/cbr_math", "max_forks_repo_head_hexsha": "cf1ad7d4661f4b0063d07e00a4e0052454518931", "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.3454301075, "max_line_length": 99, "alphanum_fraction": 0.5959604908, "num_tokens": 6885, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966732132748, "lm_q2_score": 0.7490872131147276, "lm_q1q2_score": 0.7090834638810045}}
{"text": "// Utilities.hpp\n//\n// Handy functions to help with numerical linear algebra.\n//\n// (C) Datasim Education BV 2017\n//\n\n#ifndef Utilities_HPP\n#define Utilities_HPP\n\n#include <vector>\n#include <functional>\n#include <iostream>\n#include <boost/lexical_cast.hpp>\n\nvoid print(const std::vector<double>& v)\n{\n\t// In C++11, use a range-based for loop.\n\tfor (std::vector<double>::const_iterator i = v.begin(); i < v.end(); ++i)\n\t{\n\t\tstd::cout << *i << \",\";\n\t}\n\tstd::cout << '\\n';\n}\n\ndouble LInfinityNorm(const std::vector<double>& v1, const std::vector<double>& v2)\n{ // Max of absolute value of elements of v1 - v2\n\n\tdouble result = std::abs(v1[0] - v2[0]);\n\n\tfor (std::size_t j = 1; j < v1.size(); ++j)\n\t{\n\t\tresult = std::max<double>(result, std::abs(v1[j] - v2[j]));\n\t}\n\n\treturn result;\n}\n\nstd::pair<double, std::size_t> HotSpotError(const std::vector<double>& v1, const std::vector<double>& v2)\n{ // Max of absolute value of elements of v1 - v2 and identify *where* it occurs\n\n\tdouble result = std::abs(v1[0] - v2[0]);\n\tstd::size_t index = 0;\n\n\tfor (std::size_t j = 1; j < v1.size(); ++j)\n\t{\n\t\tdouble tmp = std::max<double>(result, std::abs(v1[j] - v2[j]));\n\n\t\tif (result < tmp)\n\t\t{ // Find the max difference\n\n\t\t\tresult = tmp;\n\t\t\tindex = j;\n\t\t}\n\t}\n\n\treturn std::pair<double,std::size_t>(result, index);\n}\n\nstd::size_t findAbscissa(const std::vector<double>& x, double xvar) \n{ // Will give index of LHS value <= xvar. \n  \n//\tstd::cout << xvar; int yy; std::cin >> yy;\n\tif (xvar < x[0] || xvar >  x[x.size() - 1])\n\t{\n\t\tstd::string s = \"\\nValue \" + boost::lexical_cast<std::string>(xvar) + \" not in range \"\n\t\t\t+ \"(\" + boost::lexical_cast<std::string>(x[0]) + \",\"\n\t\t\t+ boost::lexical_cast<std::string>(x[x.size() - 1]) + \")\";\n\t\tthrow std::out_of_range(s);\n\t}\n\n\tauto posA = std::lower_bound(std::begin(x), std::end(x), xvar); // Log complexity\n\t\t\t\t\t\t\t\t\t\t\t\t\n\tstd::size_t index = std::distance(std::begin(x), posA);\n\n\treturn index;\n}\n\nstd::vector<double> CreateMesh(std::size_t n, double a, double b)\n{ // Create a mesh of size n+1 on closed interval [a,b]\n\n\tstd::vector<double> x(n + 1);\n\tx[0] = a; x[x.size()-1] = b;\n\t\n\tdouble h = (b - a) / static_cast<double>(n);\n\tfor (std::size_t j = 1; j < x.size() - 1; ++j)\n\t{\n\t\tx[j] = x[j - 1] + h;\n\t}\n\n\treturn x;\n}\n\n/*\nstd::vector<double> CreateDiscreteFunction(std::size_t n, double a, double b, \n\t\t\t\t\t\t\t\t\t\t\tconst std::function<double (double)>& f)\n{ // Create a discrete function from a continuous function y = f(x)\n\n\tstd::vector<double> y(n + 1);\n\n\tdouble h = (b - a) / static_cast<double>(n);\n\tdouble x = a;\n\tfor (std::size_t j = 0; j < y.size(); ++j)\n\t{\n\t\ty[j] = f(x);\n\t\tx += h;\n\t}\n\n\treturn y;\n}\n*/\ntemplate <typename Vector>\n\tVector CreateDiscreteFunction(const std::vector<double>& x, const std::function<double(double)>& f)\n{ // Create a discrete function from a continuous function y = f(x)\n\n\tVector y(x.size());\n\t\n\tfor (std::size_t j = 0; j < y.size(); ++j)\n\t{\n\t\ty[j] = f(x[j]);\n\t}\n\n\treturn y;\n}\n\ntemplate <typename Matrix>\n\tMatrix CreateDiscreteFunction2d(const std::vector<double>& x , const std::vector<double>& y,\n\t\t\t\t\t\t\t\t\tconst std::function<double (double x, double y)>& f)\n{ // Create a discrete function from a continuous function m = f(x,y)\n\n\tstd::size_t nr = x.size();\n\tstd::size_t nc = y.size();\n\n\tMatrix m(nr,nc);\n\n\tfor (std::size_t i = 0; i < nr; ++i)\n\t{\n\t\tfor (std::size_t j = 0; j < nc; ++j)\n\t\t{\n\t\t\tm(i, j) = f(x[i],y[j]);\n\t\t}\n\t}\n\n\treturn m;\n}\n\n#endif\n", "meta": {"hexsha": "5c3b11007db7218476915f4e0a258e522152bb7a", "size": 3409, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Level_9/myUtilities/ExcelDriver/Utilities.hpp", "max_stars_repo_name": "ZhehaoLi9705/QuantNet_CPP", "max_stars_repo_head_hexsha": "a889f4656e757842f4163b0cda7e098cc6ad1193", "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": "Level_9/myUtilities/ExcelDriver/Utilities.hpp", "max_issues_repo_name": "ZhehaoLi9705/QuantNet_CPP", "max_issues_repo_head_hexsha": "a889f4656e757842f4163b0cda7e098cc6ad1193", "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": "Level_9/myUtilities/ExcelDriver/Utilities.hpp", "max_forks_repo_name": "ZhehaoLi9705/QuantNet_CPP", "max_forks_repo_head_hexsha": "a889f4656e757842f4163b0cda7e098cc6ad1193", "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.0337837838, "max_line_length": 105, "alphanum_fraction": 0.604576122, "num_tokens": 1085, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.8774767922879693, "lm_q1q2_score": 0.7090602346130656}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\ndouble cross_entropy_error(MatrixXd&, MatrixXd&); // \u30d7\u30ed\u30c8\u30bf\u30a4\u30d7\u5ba3\u8a00\ndouble cross_entropy_error(MatrixXd&, VectorXd&); // \u30d7\u30ed\u30c8\u30bf\u30a4\u30d7\u5ba3\u8a00\n\nint main(){\n    using std::cout;\n    using std::endl;\n\n    MatrixXd y = MatrixXd::Zero(3, 5);\n    MatrixXd t = MatrixXd::Zero(3, 5);\n    double cross_entropy;\n\n    t(0, 2) = 1;\n    t(1, 4) = 1;\n    t(2, 0) = 1;\n\n    y << 0.1, 0.4, 0.1, 0.1, 0.1,  0.3, 0.1, 0.1, 0.1, 0.4,  0.3, 0.2, 0.2, 0.1, 0.2;\n\n    cross_entropy = cross_entropy_error(y, t);\n    cout << \"cross entoropy: \" << cross_entropy << endl;\n\n    VectorXd t_label = VectorXd::Zero(3);\n    double cross_entropy_label;\n\n    t_label << 2, 4, 0;\n\n    cross_entropy_label = cross_entropy_error(y, t_label);\n    cout << \"cross entropy label: \" << cross_entropy_label << endl;\n\n    return 0;\n}\n\n\n// one-hot label\u30d0\u30fc\u30b8\u30e7\u30f3\u306e \u306e\u30df\u30cb\u30d0\u30c3\u30c1\u5b9f\u88c5\ndouble cross_entropy_error(MatrixXd& y, MatrixXd& t){\n    int batch_size = y.rows();\n    double ret = (t.array() * y.array().log()).sum() / batch_size;\n    return -ret;\n}\n\n// \u901a\u5e38\u30e9\u30d9\u30eb\u30d0\u30fc\u30b8\u30e7\u30f3\u306e\u30df\u30cb\u30d0\u30c3\u30c1\u5b9f\u88c5\ndouble cross_entropy_error(MatrixXd& y, VectorXd& t){\n    int batch_size = y.rows();\n    VectorXd associated_label_vector = VectorXd::Zero(batch_size);\n    // \u4f7f\u3063\u3066\u3044\u308bEigen\u306e\u30d0\u30fc\u30b8\u30e7\u30f3\u304c3.3.9\u4ee5\u4e0a\u306a\u3089\u3001 Fancy Index\u304c\u4f7f\u3048\u308b\u306f\u305a\u3060\u304c\u3001\u3069\u3046\u3082\u9055\u3046\u3088\u3046\u306a\u306e\u3067\u3053\u308c\u3067\u5bfe\u5fdc\n    for(int i=0; i<batch_size; i++){\n        associated_label_vector(i) = y(i, t(i));\n    }\n    double ret = associated_label_vector.array().log().sum() / batch_size;\n    return -ret;\n}", "meta": {"hexsha": "302b075d0689808e95fd5c1609f7092a12b1bd7f", "size": 1477, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch4/batch_cross_entropy.cpp", "max_stars_repo_name": "potedo/zeroDL_cpp", "max_stars_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-22T15:26:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-22T15:26:20.000Z", "max_issues_repo_path": "ch4/batch_cross_entropy.cpp", "max_issues_repo_name": "potedo/zeroDL_cpp", "max_issues_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "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/batch_cross_entropy.cpp", "max_forks_repo_name": "potedo/zeroDL_cpp", "max_forks_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "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.8545454545, "max_line_length": 85, "alphanum_fraction": 0.6411645227, "num_tokens": 552, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767970940975, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.7090602303850309}}
{"text": "//\n//\n// MIT License\n//\n// Copyright (c) 2020 Stellacore Corporation.\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject\n// to the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY\n// KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n// BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN\n// AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR\n// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n//\n//\n\n/*! \\file\n\\brief  This file contains main application program HelloHomography\n*/\n\n\n#include \"libdat/info.h\"\n#include \"libio/stream.h\"\n\n#include \"libla/eigen.h\"\n\n#include <Eigen/Dense>\n\n#include <iostream>\n\n\nnamespace\n{\n\t//! Create a matrix proportional to identity\n\tdat::grid<double>\n\tnormCoefficients\n\t\t( double const & diagValue = 9.\n\t\t, size_t const & dim = 8u\n\t\t)\n\t{\n\t\tdat::grid<double> matrix(dim, dim);\n\t\tstd::fill(std::begin(matrix), std::end(matrix), 0.);\n\t\tfor (size_t kk{0u} ; kk < dim ; ++kk)\n\t\t{\n\t\t\tmatrix(kk, kk) = diagValue;\n\t\t}\n\t\treturn matrix;\n\t}\n\n\t//! Simulate right-hand-side vector\n\tdat::grid<double>\n\trhsValues\n\t\t( size_t const & dim = 8u\n\t\t)\n\t{\n\t\tdat::grid<double> rhs(dim, 1u);\n\t\tstd::iota(std::begin(rhs), std::end(rhs), 1.);\n\t\treturn rhs;\n\t}\n\n\t//! Grid of requested size filled with null data values\n\tdat::grid<double>\n\tnullGrid\n\t\t( dat::Extents const & hwSize = {}\n\t\t)\n\t{\n\t\tdat::grid<double> grid(hwSize);\n\t\tstd::fill(std::begin(grid), std::end(grid), dat::nullValue<double>());\n\t\treturn grid;\n\t}\n\n\t//! Grid version of matrix inverse\n\tdat::grid<double>\n\tinverseGrid\n\t\t( dat::grid<double> const & srcGrid\n\t\t)\n\t{\n\t\t// allocate input/output space\n\t\tdat::grid<double> invGrid{ nullGrid(srcGrid.hwSize()) };\n\n\t\t// utilize la::eigen to map grid data structures into Eigen operations\n\t\tusing la::eigen::withGrid;\n\t\tla::eigen::ConstMap<double> const srcMat{ withGrid(srcGrid) };\n\t\tla::eigen::WriteMap<double> invMat{ withGrid(&invGrid) };\n\n\t\t// Eigen matrix operation (here vanilla matrix inversion)\n\t\tinvMat = Eigen::Inverse<la::eigen::Matrix_t<double> >(srcMat);\n\n\t\treturn invGrid;\n\t}\n\n\t//! Least squares solution\n\tdat::grid<double>\n\tsolutionFor\n\t\t( dat::grid<double> const & normGrid\n\t\t, dat::grid<double> const & rhsGrid\n\t\t)\n\t{\n\t\t// allocate space\n\t\tsize_t const numParms{ normGrid.high() };\n\t\tassert(numParms == normGrid.wide());\n\t\tassert(normGrid.high() == rhsGrid.high());\n\t\tdat::grid<double> solnGrid{ nullGrid(dat::Extents{ numParms, 1u }) };\n\n\t\t// utilize la::eigen to map grid data structures into Eigen operations\n\t\tusing la::eigen::withGrid;\n\t\tla::eigen::ConstMap<double> const normMat{ withGrid(normGrid) };\n\t\tla::eigen::WriteMap<double> solnMat{ withGrid(&solnGrid) };\n\n\t\tla::eigen::ConstMap<double> const rhs{ la::eigen::withGrid(rhsGrid) };\n\t\tsolnMat = Eigen::BDCSVD<la::eigen::Matrix_t<double> >\n\t\t\t(normMat, (Eigen::ComputeThinU | Eigen::ComputeThinV)).solve(rhs);\n\t\treturn solnGrid;\n\t}\n}\n\n\n//! Program that demonstrates use of Eigen to operate on dat::grid data\nint main()\n{\n\t// Create a simple coefficient matrix\n\tdat::grid<double> const normGrid{ normCoefficients() };\n\tdat::grid<double> const rhsGrid{ rhsValues() };\n\tio::out() << normGrid.infoStringContents(\"normGrid\", \"%9.3f\") << std::endl;\n\tio::out() << rhsGrid.infoStringContents(\"rhsGrid\", \"%9.3f\") << std::endl;\n\n\t// Demonstrate matrix inversion\n\tdat::grid<double> invGrid{ inverseGrid(normGrid) };\n\tio::out() << invGrid.infoStringContents(\"invGrid\", \"%9.3f\") << std::endl;\n\n\t// compute least squares solution\n\tdat::grid<double> const solnGrid{ solutionFor(normGrid, rhsGrid) };\n\tio::out() << solnGrid.infoStringContents(\"solnGrid\", \"%9.3f\") << std::endl;\n\n\treturn 0;\n}\n\n", "meta": {"hexsha": "62f98f19e8a83acd75421402570063cc1e0d269b", "size": 4326, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "demola/demoInverseLS.cpp", "max_stars_repo_name": "transpixel/tpqz", "max_stars_repo_head_hexsha": "2d8400b1be03292d0c5ab74710b87e798ae6c52c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-06-01T00:21:16.000Z", "max_stars_repo_stars_event_max_datetime": "2017-06-01T00:21:16.000Z", "max_issues_repo_path": "demola/demoInverseLS.cpp", "max_issues_repo_name": "transpixel/tpqz", "max_issues_repo_head_hexsha": "2d8400b1be03292d0c5ab74710b87e798ae6c52c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-06-01T00:26:16.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-09T21:06:27.000Z", "max_forks_repo_path": "demola/demoInverseLS.cpp", "max_forks_repo_name": "transpixel/tpqz", "max_forks_repo_head_hexsha": "2d8400b1be03292d0c5ab74710b87e798ae6c52c", "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.84, "max_line_length": 76, "alphanum_fraction": 0.6964863615, "num_tokens": 1216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767970940974, "lm_q2_score": 0.8080672135527631, "lm_q1q2_score": 0.7090602303850306}}
{"text": "/*\n * A very basic demo of libeigen3.\n *\n * USAGE:\n *    g++ -o random -I /PATH/TO/EIGEN/ random.cc\n * or\n *    g++ -o random $(pkg-config --cflags eigen3) random.cc\n */\n\n#include <cstdlib>\n#include <ctime>\n#include <iostream>\n\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\nint main()\n{\n    // Initialize the pseudo-random number generator (Eigen uses rand() internally).\n    srand(time(0));\n\n    MatrixXd m1 = MatrixXd::Random(3, 3);\n    Matrix3d m2 = Matrix3d::Random();\n\n    std::cout << m1 << std::endl;\n    std::cout << m2 << std::endl;\n}\n", "meta": {"hexsha": "3abed898e70f154192ab23dc8d0402a96af3e334", "size": 546, "ext": "cc", "lang": "C++", "max_stars_repo_path": "cpp/eigen/eigen3/random/random.cc", "max_stars_repo_name": "jeremiedecock/snippets", "max_stars_repo_head_hexsha": "4bd4e7f459eee610d5cf19f845299ca942ff4b64", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2015-06-08T13:01:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-30T08:20:04.000Z", "max_issues_repo_path": "cpp/eigen/eigen3/random/random.cc", "max_issues_repo_name": "jeremiedecock/snippets", "max_issues_repo_head_hexsha": "4bd4e7f459eee610d5cf19f845299ca942ff4b64", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-10-22T02:36:10.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-22T02:36:10.000Z", "max_forks_repo_path": "cpp/eigen/eigen3/random/random.cc", "max_forks_repo_name": "jeremiedecock/snippets", "max_forks_repo_head_hexsha": "4bd4e7f459eee610d5cf19f845299ca942ff4b64", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-10-31T09:48:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T15:59:45.000Z", "avg_line_length": 18.8275862069, "max_line_length": 84, "alphanum_fraction": 0.6153846154, "num_tokens": 160, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.8080672066194945, "lm_q1q2_score": 0.7090602217121319}}
{"text": "#include <PCP/Curvature/Methods/VCM.h>\n#include <PCP/Curvature/GlobalEstimationData.h>\n\n#include <PCP/Geometry/Geometry.h>\n\n#include <Eigen/Eigenvalues>\n\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/vcm_estimate_normals.h>\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;\ntypedef Kernel::Point_3 Point_3;\ntypedef Kernel::Vector_3 Vector_3;\n// Point with normal vector stored in a std::pair.\ntypedef std::pair<Point_3, Vector_3> PointVectorPair;\ntypedef std::vector<PointVectorPair> PointList;\ntypedef std::array<double,6> Covariance;\n\nnamespace pcp {\n\nvoid compute_VCM(const Geometry& in_points, Scalar r, GlobalEstimationData& e)\n{\n    e.resize(in_points.size());\n\n    // convert to CGAL type\n    std::vector<PointVectorPair> points(in_points.size());\n    #pragma omp parallel for\n    for(int i=0; i<in_points.size(); ++i)\n    {\n        points[i].first  = Point_3( in_points.point(i).x(),  in_points.point(i).y(),  in_points.point(i).z());\n        points[i].second = Vector_3(in_points.normal(i).x(), in_points.normal(i).y(), in_points.normal(i).z());\n    }\n\n    const Scalar offset_radius = r;\n    const Scalar convolution_radius = 0.5 * r;\n\n    std::vector<Covariance> cov;\n\n    CGAL::First_of_pair_property_map<PointVectorPair> point_map;\n    const auto np = CGAL::parameters::point_map(point_map).geom_traits(Kernel());\n\n    CGAL::compute_vcm(points, cov, offset_radius, convolution_radius, np);\n\n    #pragma omp parallel for\n    for(int i=0; i<in_points.size(); ++i)\n    {\n        const Covariance& a = cov[i];\n        Matrix3 C;\n        C << a[0], a[1], a[2],\n             a[1], a[3], a[4],\n             a[2], a[4], a[5];\n\n        Eigen::SelfAdjointEigenSolver<Matrix3> solver(C);\n        const Scalar  l2   = solver.eigenvalues()[0];\n        const Scalar  l1   = solver.eigenvalues()[1];\n        const Vector3 dir2 = solver.eigenvectors().col(0);\n        const Vector3 dir1 = solver.eigenvectors().col(1);\n        const Vector3 N    = solver.eigenvectors().col(2);\n\n        const Scalar k1 = 2 * std::sqrt(l1) / r;\n        const Scalar k2 = 2 * std::sqrt(l2) / r;\n\n        const Scalar H = 0.5 * (k1 + k2);\n\n        // arbitrary set to 10 because 0 == error\n        // TODO use voronoi diagram\n        const int nei_count = 10;\n\n        e[i] = PointWiseEstimationData(k1, k2, H, N, dir1, dir2, nei_count);\n    }\n}\n\n} // namespace pcp\n\n", "meta": {"hexsha": "6508ef18bc74b8e7cdcc811f7d3e2583ec0b8dac", "size": 2396, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "figures/src/PCP/Curvature/Methods/VCM.cpp", "max_stars_repo_name": "STORM-IRIT/algebraic-shape-operator", "max_stars_repo_head_hexsha": "8de592549562cf8cff51044a459ce64a75176e42", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-07-29T18:19:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-12T12:42:52.000Z", "max_issues_repo_path": "figures/src/PCP/Curvature/Methods/VCM.cpp", "max_issues_repo_name": "STORM-IRIT/algebraic-shape-operator", "max_issues_repo_head_hexsha": "8de592549562cf8cff51044a459ce64a75176e42", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-07-12T08:51:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-14T09:38:17.000Z", "max_forks_repo_path": "figures/src/PCP/Curvature/Methods/VCM.cpp", "max_forks_repo_name": "STORM-IRIT/algebraic-shape-operator", "max_forks_repo_head_hexsha": "8de592549562cf8cff51044a459ce64a75176e42", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-07-12T08:52:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-17T11:40:21.000Z", "avg_line_length": 32.3783783784, "max_line_length": 111, "alphanum_fraction": 0.6544240401, "num_tokens": 683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299509069105, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.7089978248345358}}
{"text": "#include <catch/catch2.hpp>\n\n#include <orient/from_angle_axis.hpp>\n\n#include <Eigen/Geometry>\n#include <gtsam/base/numericalDerivative.h>\n#include <gtsam/geometry/Rot3.h>\n\nTEST_CASE(\"rotationMatrixFromAngleAxis\")\n{ \n  Eigen::Vector3d aa;\n  SECTION(\"Zero\"){\n    aa = Eigen::Vector3d::Zero();\n  }\n  SECTION(\"almost_zero\"){\n    aa = 1e-15 * Eigen::Vector3d::Random();\n  }\n  SECTION(\"Random\"){\n    aa = Eigen::Vector3d::Random();\n  }\n\n  const auto calc = orient::rotationMatrixFromAngleAxis(aa);\n  const auto act = gtsam::Rot3::Expmap(aa).matrix();\n  CHECK( calc.isApprox(act) );\n}\n\nTEST_CASE(\"rotationMatrixFromAngleAxis_derivative\")\n{ \n  Eigen::Vector3d aa;\n  SECTION(\"Zero\"){\n    aa = Eigen::Vector3d::Zero();\n  }\n  SECTION(\"almost_zero\"){\n    aa = 1e-15 * Eigen::Vector3d::Random();\n  }\n  SECTION(\"Random\"){\n    aa = Eigen::Vector3d::Random();\n  }\n\n  const auto [v, J] = orient::rotationMatrixFromAngleAxisWD(aa);\n  auto numeric = gtsam::numericalDerivative11(orient::rotationMatrixFromAngleAxis<double>, aa);\n  CHECK( v.isApprox(orient::rotationMatrixFromAngleAxis(aa)) );\n  CHECK( J.isApprox(numeric, 1e-10) );\n}\n\nTEST_CASE(\"quaternionFromAngleAxis\")\n{\n  Eigen::Vector3d aa;\n  SECTION(\"zero\"){\n    aa = Eigen::Vector3d::Zero();\n  }\n  SECTION(\"almost_zero\"){\n    aa = Eigen::Vector3d::Random();\n    aa *= 1e-11 / aa.squaredNorm();\n  }\n  SECTION(\"random\"){\n    aa = Eigen::Vector3d::Random();\n  }\n  SECTION(\"half_PI_angle\"){\n    aa = Eigen::Vector3d::Random();\n    aa *= M_PI / (2*std::sqrt(aa.dot(aa)));\n  }\n  SECTION(\"minus_half_PI_angle\"){\n    aa = Eigen::Vector3d::Random();\n    aa *= -M_PI / (2*std::sqrt(aa.dot(aa)));\n  }\n  SECTION(\"PI_angle\"){\n    aa = Eigen::Vector3d::Random();\n    aa *= M_PI / std::sqrt(aa.dot(aa));\n  }\n  SECTION(\"minus_PI_angle\"){\n    aa = Eigen::Vector3d::Random();\n    aa *= -M_PI / std::sqrt(aa.dot(aa));\n  }\n  SECTION(\"2PI_angle\"){\n    aa = Eigen::Vector3d::Random();\n    aa *= 2*M_PI / std::sqrt(aa.dot(aa));\n  }\n  SECTION(\"minus_2PI_angle\"){\n    aa = Eigen::Vector3d::Random();\n    aa *= -2*M_PI / std::sqrt(aa.dot(aa));\n  }\n\n  const auto angle = std::sqrt(aa.dot(aa));\n  Eigen::Vector3d axis;\n  // use a random axis when angle is really small\n  if (angle > 1e-50)\n    axis = aa / angle;\n  else\n    axis << 1.,0.,0.;\n  Eigen::AngleAxisd eaa{angle, axis};\n  Eigen::Quaterniond equat{eaa};\n\n  Eigen::Vector4d expected = (Eigen::Vector4d() << equat.w(), equat.vec()).finished();\n  Eigen::Vector4d actual = orient::quaternionFromAngleAxis(aa);\n  CHECK( expected.isApprox(actual) );\n}\n\nTEST_CASE(\"quaternionFromAngleAxis_derivative\")\n{\n  Eigen::Vector3d aa;\n  SECTION(\"zero\"){\n    aa = Eigen::Vector3d::Zero();\n  }\n  SECTION(\"almost_zero\"){\n    aa = Eigen::Vector3d::Random();\n    aa *= 1e-11 / aa.squaredNorm();\n  }\n  SECTION(\"Random\"){\n    aa = Eigen::Vector3d::Random();\n  }\n  SECTION(\"half_PI_angle\"){\n    aa = Eigen::Vector3d::Random();\n    aa *= M_PI / (2*std::sqrt(aa.dot(aa)));\n  }\n  SECTION(\"minus_half_PI_angle\"){\n    aa = Eigen::Vector3d::Random();\n    aa *= -M_PI / (2*std::sqrt(aa.dot(aa)));\n  }\n  SECTION(\"PI_angle\"){\n    aa = Eigen::Vector3d::Random();\n    aa *= M_PI / std::sqrt(aa.dot(aa));\n  }\n  SECTION(\"minus_PI_angle\"){\n    aa = Eigen::Vector3d::Random();\n    aa *= -M_PI / std::sqrt(aa.dot(aa));\n  }\n  SECTION(\"2PI_angle\"){\n    aa = Eigen::Vector3d::Random();\n    aa *= 2*M_PI / std::sqrt(aa.dot(aa));\n  }\n  SECTION(\"minus_2PI_angle\"){\n    aa = Eigen::Vector3d::Random();\n    aa *= -2*M_PI / std::sqrt(aa.dot(aa));\n  }\n\n  const auto [v, J] = orient::quaternionFromAngleAxisWD(aa);\n  auto numeric = gtsam::numericalDerivative11(orient::quaternionFromAngleAxis<double>, aa);\n  CHECK( v.isApprox(orient::quaternionFromAngleAxis(aa) ) );\n  CHECK( J.isApprox(numeric, 1e-10) );\n}\n", "meta": {"hexsha": "4a6fdd29b53ad77dac05412a3236a385c9b30289", "size": 3727, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/from_angle_axis_test.cpp", "max_stars_repo_name": "Eskilade/orient", "max_stars_repo_head_hexsha": "d73e9459155e991539c20bfd92c04cb487b65538", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2020-05-11T07:27:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-10T09:23:29.000Z", "max_issues_repo_path": "test/from_angle_axis_test.cpp", "max_issues_repo_name": "Eskilade/orient", "max_issues_repo_head_hexsha": "d73e9459155e991539c20bfd92c04cb487b65538", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-09-20T02:22:15.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-21T01:42:47.000Z", "max_forks_repo_path": "test/from_angle_axis_test.cpp", "max_forks_repo_name": "Eskilade/orient", "max_forks_repo_head_hexsha": "d73e9459155e991539c20bfd92c04cb487b65538", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-09-14T11:11:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-10T04:26:22.000Z", "avg_line_length": 26.2464788732, "max_line_length": 95, "alphanum_fraction": 0.6273141937, "num_tokens": 1146, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357460591569, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.7088662920715838}}
{"text": "/* +------------------------------------------------------------------------+\n   |                     Mobile Robot Programming Toolkit (MRPT)            |\n   |                          https://www.mrpt.org/                         |\n   |                                                                        |\n   | Copyright (c) 2005-2019, Individual contributors, see AUTHORS file     |\n   | See: https://www.mrpt.org/Authors - All rights reserved.               |\n   | Released under BSD License. See: https://www.mrpt.org/License          |\n   +------------------------------------------------------------------------+ */\n\n#include <mrpt/gui.h>\n#include <mrpt/math/CMatrixF.h>\n#include <mrpt/math/CMatrixFixed.h>\n#include <mrpt/math/ops_matrices.h>\n#include <mrpt/math/ops_vectors.h>\n#include <mrpt/math/utils.h>\n#include <mrpt/system/CTicTac.h>\n#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace mrpt;\nusing namespace mrpt::math;\nusing namespace mrpt::system;\nusing namespace std;\n\n#include <mrpt/examples_config.h>\nstring myDataDir(MRPT_EXAMPLES_BASE_DIRECTORY + string(\"math_matrix_example/\"));\n\n// ------------------------------------------------------\n//\t\t\t\tTestChol\n// ------------------------------------------------------\nvoid TestChol()\n{\n\tCMatrixFloat A, B;\n\tA.loadFromTextFile(myDataDir + string(\"in_for_cholesky.txt\"));\n\tA.chol(B);\n\n\tcout << \"Cholesky decomposition result:\" << endl << B;\n}\n\nvoid TestInitMatrix()\n{\n\t// Initialize a matrix from a C array:\n\tconst double numbers[] = {1, 2, 3, 4, 5, 6};\n\tCMatrixDouble M(2, 3, numbers);\n\tcout << \"Initialized matrix (I): \" << endl << M << endl;\n\n\tconst double numbers2[] = {0.5, 4.5, 6.7, 8.9, 15.2};\n\tCVectorDouble v1;\n\tloadVector(v1, numbers2);\n\tcout << \"Initialized double vector: \" << v1 << endl;\n\n\tstd::vector<int> v2;\n\tloadVector(v2, numbers2);\n\tcout << \"Initialized int vector: \" << v2 << endl;\n\n\t/*\t// I/O Test\n\t\tCMatrixD  B(M);\n\t\tCFileOutputStream(\"mat.bin\") << B;\n\t\tCMatrixD  A;\n\t\tCFileInputStream(\"mat.bin\") >> A;\n\t\tcout << \"B:\" << endl << B;\n\t\tcout << \"A:\" << endl << A;\n\t*/\n}\n\nvoid TestHCH()\n{\n\tCMatrixFloat H, C, RES;\n\n\tcout << \"reading H.txt...\";\n\tH.loadFromTextFile(myDataDir + string(\"H.txt\"));\n\tcout << \"ok\" << endl;\n\n\tcout << \"reading C.txt...\";\n\tC.loadFromTextFile(myDataDir + string(\"C.txt\"));\n\tcout << \"ok\" << endl;\n\n\t// RES = H * C * H'\n\tmrpt::math::multiply_HCHt(H, C, RES);\n\tcout << \"Saving RES.txt ...\";\n\tRES.saveToTextFile(\"RES.txt\");\n\tcout << \"ok\" << endl;\n\n\t// The same for a column vector:\n\tH.loadFromTextFile(myDataDir + string(\"H_col.txt\"));\n\tcout << \"H*C*(H') = \" << mrpt::math::multiply_HCHt_scalar(H, C) << endl;\n\tcout << \"Should be= 31.434 \" << endl;\n\n\t// The same for a row vector:\n\tH.loadFromTextFile(myDataDir + string(\"H_row.txt\"));\n\tcout << \"Loaded H: \" << endl << H;\n\tcout << \"H*C*(H') = \" << mrpt::math::multiply_HCHt_scalar(H, C) << endl;\n\tcout << \"Should be= 31.434\" << endl;\n}\n\nvoid TestMatrixTemplate()\n{\n\tCTicTac tictac;\n\tCMatrixDouble M;\n\n\t// --------------------------------------\n\tM.loadFromTextFile(myDataDir + string(\"matrixA.txt\"));\n\tcout << M << \"\\n\";\n\n\tCMatrixDouble eigenVectors;\n\tstd::vector<double> eigenValues;\n\tM.eig(eigenVectors, eigenValues);\n\tcout << \"eigenVectors:\\n\"\n\t\t << eigenVectors << \"\\n Eigenvalues:\\n\"\n\t\t << eigenValues;\n\n\tCMatrixDouble D;\n\tD.setDiagonal(eigenValues);\n\n\tCMatrixDouble RES;\n\tRES = M.asEigen() * D.asEigen() * M.transpose();\n\tcout << \"RES:\\n\" << RES;\n}\n\nvoid TestMatrices()\n{\n\tCMatrixFloat m, l;\n\tCTicTac tictac;\n\tdouble t;\n\n\tm.setSize(4, 4);\n\tm(0, 0) = 4;\n\tm(0, 1) = -2;\n\tm(0, 2) = -1;\n\tm(0, 3) = 0;\n\tm(1, 0) = -2;\n\tm(1, 1) = 4;\n\tm(1, 2) = 0;\n\tm(1, 3) = -1;\n\tm(2, 0) = -1;\n\tm(2, 1) = 0;\n\tm(2, 2) = 4;\n\tm(2, 3) = -2;\n\tm(3, 0) = 0;\n\tm(3, 1) = -1;\n\tm(3, 2) = -2;\n\tm(3, 3) = 4;\n\n\tcout << \"Matrix:\\n\" << m << endl;\n\n\t// I/O test through a text file:\n\tm.saveToTextFile(\"matrix1.txt\");\n\ttictac.Tic();\n\tl.loadFromTextFile(myDataDir + string(\"matrix1.txt\"));\n\tt = tictac.Tac();\n\tcout << \"Read (text file) in \" << 1e6 * t << \"us:\\n\" << l << endl;\n\tmrpt::math::laplacian(m, l);\n\n\tcout << \"Laplacian:\\n\" << l << endl;\n}\n\nvoid TestCov()\n{\n\t// Initialize a matrix from a C array:\n\tconst double numbers[] = {1, 2, 3, 10, 4, 5, 6, 14, 10, -5, -3, 1};\n\tCMatrixDouble Mdyn(4, 3, numbers);\n\tCMatrixFixed<double, 4, 3> Mfix(numbers);\n\n\tvector<CVectorDouble> samples(4);\n\tfor (size_t i = 0; i < 4; i++)\n\t{\n\t\tsamples[i].resize(3);\n\t\tfor (size_t j = 0; j < 3; j++) samples[i][j] = Mdyn(i, j);\n\t}\n\n\tcout << \"COV (vector of vectors): \" << endl\n\t\t << mrpt::math::covVector<vector<CVectorDouble>, Eigen::MatrixXd>(\n\t\t\t\tsamples)\n\t\t << endl;\n\tcout << \"COV (mat fix): \" << endl << mrpt::math::cov(Mfix) << endl;\n\tcout << \"COV (mat dyn): \" << endl << mrpt::math::cov(Mdyn) << endl;\n}\n\n// ------------------------------------------------------\n//\t\t\t\t\t\tMAIN\n// ------------------------------------------------------\nint main()\n{\n\ttry\n\t{\n\t\tTestInitMatrix();\n\t\tTestMatrixTemplate();\n\t\tTestMatrices();\n\t\tTestHCH();\n\t\tTestChol();\n\t\tTestCov();\n\n\t\treturn 0;\n\t}\n\tcatch (exception& e)\n\t{\n\t\tcout << \"MRPT exception caught: \" << e.what() << endl;\n\t\treturn -1;\n\t}\n\tcatch (...)\n\t{\n\t\tprintf(\"Untyped exception!!\");\n\t\treturn -1;\n\t}\n}\n", "meta": {"hexsha": "105e7f73c42a073efe1171f38c1ca415f4c5ba2c", "size": 5150, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "samples/math_matrix_example/test.cpp", "max_stars_repo_name": "zarmomin/mrpt", "max_stars_repo_head_hexsha": "1baff7cf8ec9fd23e1a72714553bcbd88c201966", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-10T06:24:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-10T06:24:08.000Z", "max_issues_repo_path": "samples/math_matrix_example/test.cpp", "max_issues_repo_name": "gao-ouyang/mrpt", "max_issues_repo_head_hexsha": "4af5fdf7e45b00be4a64c3d4f009acb9ef415ec7", "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": "samples/math_matrix_example/test.cpp", "max_forks_repo_name": "gao-ouyang/mrpt", "max_forks_repo_head_hexsha": "4af5fdf7e45b00be4a64c3d4f009acb9ef415ec7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-11T02:55:04.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-11T02:55:04.000Z", "avg_line_length": 25.0, "max_line_length": 80, "alphanum_fraction": 0.5339805825, "num_tokens": 1606, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.7087600317815137}}
{"text": "// Boost.Geometry\n// QuickBook Example\n\n// Copyright (c) 2018, Oracle and/or its affiliates\n// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle\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//[line_interpolate\n//` Shows how to interpolate points on a linestring\n\n#include <iostream>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n\nusing namespace boost::geometry;\n\nint main()\n{\n    typedef boost::geometry::model::d2::point_xy<double> point_type;\n    using segment_type = model::segment<point_type>;\n    using linestring_type = model::linestring<point_type>;\n    using multipoint_type = model::multi_point<point_type>;\n\n    segment_type const s { {0, 0}, {1, 1} };\n    linestring_type const l { {0, 0}, {1, 0}, {1, 1}, {0, 1}, {0, 2} };\n    point_type p;\n    multipoint_type mp;\n\n    std::cout << \"point interpolation\" << std::endl;\n\n    line_interpolate(s, std::sqrt(2)/4, p);\n    std::cout << \"on segment : \" << wkt(p) << std::endl;\n\n    line_interpolate(l, 1.4, p);\n    std::cout << \"on linestring : \" << wkt(p) << std::endl << std::endl;\n\n    std::cout << \"multipoint interpolation\" << std::endl;\n\n    line_interpolate(s, std::sqrt(2)/4, mp);\n    std::cout << \"on segment : \" << wkt(mp) << std::endl;\n\n    mp=multipoint_type();\n    line_interpolate(l, 1.4, mp);\n    std::cout << \"on linestring : \" << wkt(mp) << std::endl;\n\n    return 0;\n}\n\n//]\n\n//[line_interpolate_output\n/*`\nOutput:\n[pre\npoint interpolation\non segment : POINT(0.25 0.25)\non linestring : POINT(1 0.4)\n\nmultipoint interpolation\non segment : MULTIPOINT((0.25 0.25),(0.5 0.5),(0.75 0.75),(1 1))\non linestring : MULTIPOINT((1 0.4),(0.2 1))\n]\n*/\n//]\n", "meta": {"hexsha": "f3804e1affbdc4339aabf91d3e2c279355d8ca58", "size": 1820, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "thirdparty/boost_1_71_0/libs/geometry/doc/src/examples/algorithms/line_interpolate.cpp", "max_stars_repo_name": "anonymouscode1/djxperf", "max_stars_repo_head_hexsha": "b6073a761753aa7a6247f2618977ca3a2633e78a", "max_stars_repo_licenses": ["MIT"], "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": "thirdparty/boost_1_71_0/libs/geometry/doc/src/examples/algorithms/line_interpolate.cpp", "max_issues_repo_name": "anonymouscode1/djxperf", "max_issues_repo_head_hexsha": "b6073a761753aa7a6247f2618977ca3a2633e78a", "max_issues_repo_licenses": ["MIT"], "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/algorithms/line_interpolate.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": 26.3768115942, "max_line_length": 79, "alphanum_fraction": 0.656043956, "num_tokens": 560, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.841825635346563, "lm_q2_score": 0.8418256551882382, "lm_q1q2_score": 0.7086704170298752}}
{"text": "///////////////////////////////////////////////////////////////////\n//  Copyright Eduardo Quintana 2021\n//  Copyright Janek Kozicki 2021\n//  Copyright Christopher Kormanyos 2021\n//  Distributed under the Boost Software License,\n//  Version 1.0. (See accompanying file LICENSE_1_0.txt\n//  or copy at http://www.boost.org/LICENSE_1_0.txt)\n/*\n  boost::math::fft \n  Example use of the algebraic DFT for complex numbers.\n*/\n#include <boost/math/fft/bsl_backend.hpp>\nnamespace fft = boost::math::fft;\n\n#include <iostream>\n#include <vector>\n\nint algebraic_dft_example()\n/*\n    Use the Algebraic DFT algorithm to compute a complex DFT\n*/\n{\n  using Real = double;\n  using Complex = std::complex<Real>;\n  \n  std::vector<Complex> A{1.,-1.,3.,.5,9.},B,C;\n  const int N = A.size();\n  const Real w_phase = 2*boost::math::constants::pi<Real>()/N;\n  const Complex w{cos(w_phase), -sin(w_phase)};\n\n  fft::bsl_algebraic_transform::forward(A.cbegin(),A.cend(),std::back_inserter(B), w);\n  fft::bsl_transform::forward(A.cbegin(),A.cend(),std::back_inserter(C));\n  \n  Real diff =0;\n  for (int i=0;i<N;++i)\n  {\n    diff += abs(B[i]-C[i]);\n  }\n  return diff < 1e-6 ? 0 : 1;\n}\nint main()\n{\n  return algebraic_dft_example();\n}\n\n", "meta": {"hexsha": "53c736b457569f5df4dbbe09abd7763ff71fdefe", "size": 1203, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/fft_ex10.cpp", "max_stars_repo_name": "BoostGSoC21/math", "max_stars_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_stars_repo_licenses": ["BSL-1.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": "example/fft_ex10.cpp", "max_issues_repo_name": "BoostGSoC21/math", "max_issues_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 30.0, "max_issues_repo_issues_event_min_datetime": "2021-06-22T12:59:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-02T09:27:49.000Z", "max_forks_repo_path": "example/fft_ex10.cpp", "max_forks_repo_name": "BoostGSoC21/math", "max_forks_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-07T21:15:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-07T21:15:02.000Z", "avg_line_length": 26.152173913, "max_line_length": 86, "alphanum_fraction": 0.6359102244, "num_tokens": 357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336303, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.7086670767279711}}
{"text": "\n#include <stdlib.h>\n#include <boost/test/unit_test.hpp>\n#include \"matrix.h\"\n#include \"quaternion.h\"\n\n#include <iostream>\n\nnamespace\n{\n\nvoid test_matrix_quaternion_matrix(math::matrix<3, 3> const& tf) {\n\tBOOST_REQUIRE (abs(tf.determinant() - 1) < math::EPSILON);\n\n\tmath::quaternion<> q;\n\tq.set_unit(tf);\n\n\tmath::matrix<3, 3> m;\n\tm.rotation(q.normalized());\n\n\tBOOST_REQUIRE (math::equal(m, tf, math::scalar(0.001)));\n}\n\nvoid test_slerp_i(math::vec<3> const& p, math::vec<3> const& q) {\n\tmath::matrix<3, 3> tf1;\n\ttf1.rotation(p);\n\tmath::quaternion<> q1;\n\tq1.set_unit(tf1);\n\n\tmath::matrix<3, 3> tf2;\n\ttf2.rotation(q);\n\tmath::quaternion<> q2;\n\tq2.set_unit(tf2);\n\n\tmath::quaternion_slerper<> slerper;\n\tslerper.setup(q1, q2);\n\n\tfor (int i = 0; i <= 100; ++i) {\n\t\tmath::scalar x = math::scalar(i) / 100;\n\n\t\tmath::quaternion<> q3 = slerper.interpolate(x);\n\t\tmath::matrix<3, 3> tf3;\n\t\ttf3.rotation(q3);\n\n\t\tmath::vec<3> angles = p * (1 - x) + q * x;\n\t\tmath::matrix<3, 3> tf4;\n\t\ttf4.rotation(angles);\n\n\t\tBOOST_REQUIRE(equal(tf3, tf4, math::scalar(0.001)));\n\t}\n}\n\nvoid test_slerp(math::vec<3> const& p, math::vec<3> const& q) {\n\ttest_slerp_i(p, q);\n\ttest_slerp_i(q, p);\n}\n\n}\n\nBOOST_AUTO_TEST_SUITE (test_quaternion)\n\nBOOST_AUTO_TEST_CASE (identity_matrix)\n{\n\tmath::matrix<3, 3> tf;\n\ttf.identity();\n\n\ttest_matrix_quaternion_matrix(tf);\n}\n\nBOOST_AUTO_TEST_CASE (rotate_90_degrees)\n{\n\tmath::matrix<3, 3> tf;\n\n\ttf.rotation(math::PI / 2, 0, 0);\n\ttest_matrix_quaternion_matrix(tf);\n\n\ttf.rotation(-math::PI / 2, 0, 0);\n\ttest_matrix_quaternion_matrix(tf);\n\n\ttf.rotation(0, math::PI / 2, 0);\n\ttest_matrix_quaternion_matrix(tf);\n\n\ttf.rotation(0, -math::PI / 2, 0);\n\ttest_matrix_quaternion_matrix(tf);\n\n\ttf.rotation(0, 0, math::PI / 2);\n\ttest_matrix_quaternion_matrix(tf);\n\n\ttf.rotation(0, 0, -math::PI / 2);\n\ttest_matrix_quaternion_matrix(tf);\n}\n\nBOOST_AUTO_TEST_CASE (rotate_60_degrees)\n{\n\tmath::matrix<3, 3> tf;\n\n\ttf.rotation(math::PI / 3, 0, 0);\n\ttest_matrix_quaternion_matrix(tf);\n\n\ttf.rotation(-math::PI / 3, 0, 0);\n\ttest_matrix_quaternion_matrix(tf);\n\n\ttf.rotation(0, math::PI / 3, 0);\n\ttest_matrix_quaternion_matrix(tf);\n\n\ttf.rotation(0, -math::PI / 3, 0);\n\ttest_matrix_quaternion_matrix(tf);\n\n\ttf.rotation(0, 0, math::PI / 3);\n\ttest_matrix_quaternion_matrix(tf);\n\n\ttf.rotation(0, 0, -math::PI / 3);\n\ttest_matrix_quaternion_matrix(tf);\n}\n\nBOOST_AUTO_TEST_CASE (rotate_30_degrees)\n{\n\tmath::matrix<3, 3> tf;\n\n\ttf.rotation(math::PI / 6, 0, 0);\n\ttest_matrix_quaternion_matrix(tf);\n\n\ttf.rotation(-math::PI / 6, 0, 0);\n\ttest_matrix_quaternion_matrix(tf);\n\n\ttf.rotation(0, math::PI / 6, 0);\n\ttest_matrix_quaternion_matrix(tf);\n\n\ttf.rotation(0, -math::PI / 6, 0);\n\ttest_matrix_quaternion_matrix(tf);\n\n\ttf.rotation(0, 0, math::PI / 6);\n\ttest_matrix_quaternion_matrix(tf);\n\n\ttf.rotation(0, 0, -math::PI / 6);\n\ttest_matrix_quaternion_matrix(tf);\n}\n\nBOOST_AUTO_TEST_CASE (rotate_random_degrees)\n{\n\tmath::matrix<3, 3> tf;\n\n\tfor (int i = 0; i < 1000; ++i) {\n\t\tmath::vec<3> angles(\n\t\t\t2 * math::scalar(rand()) / RAND_MAX * math::PI,\n\t\t\t2 * math::scalar(rand()) / RAND_MAX * math::PI,\n\t\t\t2 * math::scalar(rand()) / RAND_MAX * math::PI);\n\t\ttf.rotation(angles);\n\t\ttest_matrix_quaternion_matrix(tf);\n\t}\n}\n\nBOOST_AUTO_TEST_CASE (slerp_identity)\n{\n\ttest_slerp(math::vec<3>(0, 0, 0), math::vec<3>(0, 0, 0));\n}\n\nBOOST_AUTO_TEST_CASE (slerp_90_degrees)\n{\n\ttest_slerp(math::vec<3>(0, 0, 0), math::vec<3>(math::PI / 2, 0, 0));\n\ttest_slerp(math::vec<3>(0, 0, 0), math::vec<3>(-math::PI / 2, 0, 0));\n\ttest_slerp(math::vec<3>(0, 0, 0), math::vec<3>(0, math::PI / 2, 0));\n\ttest_slerp(math::vec<3>(0, 0, 0), math::vec<3>(0, -math::PI / 2, 0));\n\ttest_slerp(math::vec<3>(0, 0, 0), math::vec<3>(0, 0, math::PI / 2));\n\ttest_slerp(math::vec<3>(0, 0, 0), math::vec<3>(0, 0, -math::PI / 2));\n\n\ttest_slerp(math::vec<3>(-math::PI/2, 0, 0), math::vec<3>(math::PI / 2, 0, 0));\n\ttest_slerp(math::vec<3>(0, -math::PI/2, 0), math::vec<3>(0, math::PI / 2, 0));\n\ttest_slerp(math::vec<3>(0, 0, -math::PI/2), math::vec<3>(0, 0, math::PI / 2));\n}\n\nBOOST_AUTO_TEST_CASE (slerp_random_degrees)\n{\n\tfor (int i = 0; i < 1000; ++i) {\n\t\tmath::vec<3> axis(\n\t\t\t2 * math::scalar(rand()) / RAND_MAX - 1,\n\t\t\t2 * math::scalar(rand()) / RAND_MAX - 1,\n\t\t\t2 * math::scalar(rand()) / RAND_MAX - 1);\n\n\t\tif (axis.length_sq() < 0.1) continue;\n\n\t\tmath::scalar angle1 = math::scalar(rand()) / RAND_MAX * math::PI * 2;\n\t\tmath::scalar angle2 = angle1 + math::scalar(rand() - 1) / RAND_MAX * math::PI;\n\n\t\tmath::matrix<3,3> tf1;\n\t\ttf1.rotation(axis, angle1);\n\n\t\tmath::matrix<3,3> tf2;\n\t\ttf2.rotation(axis, angle2);\n\n\t\tmath::quaternion<> q1;\n\t\tq1.set_unit(tf1);\n\n\t\tmath::quaternion<> q2;\n\t\tq2.set_unit(tf2);\n\n\t\tmath::quaternion_slerper<> slerper;\n\t\tslerper.setup(q1, q2);\n\n\t\tfor (int j = 0; j <= 100; ++j) {\n\t\t\tmath::scalar x = math::scalar(j) / 100;\n\n\t\t\tmath::quaternion<> q = slerper.interpolate(x);\n\n\t\t\tmath::matrix<3,3> m1;\n\t\t\tm1.rotation(q);\n\n\t\t\tmath::matrix<3,3> m2;\n\t\t\tm2.rotation(axis, angle1 * (1 - x) + angle2 * x);\n\n\t\t\tBOOST_REQUIRE(equal(m1, m2, math::scalar(0.001)));\n\t\t}\n\t}\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n", "meta": {"hexsha": "06e382277f61510f2bcfbd3c93a5848d6f9403ea", "size": 5028, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/math/test_quaternion.cc", "max_stars_repo_name": "mnvl/scratch", "max_stars_repo_head_hexsha": "7717772e0b9a85c8feb73fdc3562425f48b4a727", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-08-15T11:55:32.000Z", "max_stars_repo_stars_event_max_datetime": "2016-08-15T11:55:32.000Z", "max_issues_repo_path": "src/math/test_quaternion.cc", "max_issues_repo_name": "mnvl/scratch", "max_issues_repo_head_hexsha": "7717772e0b9a85c8feb73fdc3562425f48b4a727", "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/math/test_quaternion.cc", "max_forks_repo_name": "mnvl/scratch", "max_forks_repo_head_hexsha": "7717772e0b9a85c8feb73fdc3562425f48b4a727", "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.0642201835, "max_line_length": 80, "alphanum_fraction": 0.6449880668, "num_tokens": 1878, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625126757596, "lm_q2_score": 0.7606506581031359, "lm_q1q2_score": 0.7085175732652171}}
{"text": "#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n\n#include <OpenMesh/Core/IO/MeshIO.hh>\n#include <OpenMesh/Core/Mesh/PolyMesh_ArrayKernelT.hh>\n\n#include <CGAL/boost/graph/graph_traits_PolyMesh_ArrayKernelT.h>\n\n#include <CGAL/point_generators_3.h>\n\n#include <CGAL/Side_of_triangle_mesh.h>\n\n#include <vector>\n#include <fstream>\n#include <limits>\n#include <boost/foreach.hpp>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\n\ntypedef OpenMesh::PolyMesh_ArrayKernelT< > Mesh;\ntypedef K::Point_3 Point;\n\ntypedef boost::graph_traits<Mesh>::vertex_descriptor vertex_descriptor;\n\ndouble max_coordinate(const Mesh& mesh)\n{\n  typedef boost::property_map<Mesh,CGAL::vertex_point_t>::type VPmap;\n  VPmap vpmap = get(CGAL::vertex_point,mesh);\n\n  double max_coord = std::numeric_limits<double>::min();\n  BOOST_FOREACH(vertex_descriptor v, vertices(mesh))\n  {\n    Point p = get(vpmap, v);\n    max_coord = (std::max)(max_coord, p.x());\n    max_coord = (std::max)(max_coord, p.y());\n    max_coord = (std::max)(max_coord, p.z());\n  }\n  return max_coord;\n}\n\nint main(int argc, char* argv[])\n{\n  const char* filename = (argc > 1) ? argv[1] : \"data/eight.off\";\n\n  Mesh mesh;\n  OpenMesh::IO::read_mesh(mesh, filename);\n  if (!CGAL::is_triangle_mesh(mesh))\n  {\n    std::cerr << \"Input geometry is not triangulated.\" << std::endl;\n    return EXIT_FAILURE;\n  }\n \n  CGAL::Side_of_triangle_mesh<Mesh, K> inside(mesh);\n\n  double size = max_coordinate(mesh);\n\n  unsigned int nb_points = 100;\n  std::vector<Point> points;\n  points.reserve(nb_points);\n  CGAL::Random_points_in_cube_3<Point> gen(size);\n  for (unsigned int i = 0; i < nb_points; ++i)\n    points.push_back(*gen++);\n\n  std::cout << \"Test \" << nb_points << \" random points in cube \"\n    << \"[-\" << size << \"; \" << size <<\"]\" << std::endl;\n\n  int nb_inside = 0;\n  int nb_boundary = 0;\n  for (std::size_t i = 0; i < nb_points; ++i)\n  {\n    CGAL::Bounded_side res = inside(points[i]);\n\n    if (res == CGAL::ON_BOUNDED_SIDE) { ++nb_inside; }\n    if (res == CGAL::ON_BOUNDARY) { ++nb_boundary; }\n  }\n\n  std::cout << \"Total query size: \" << points.size() << std::endl;\n  std::cout << \"  \" << nb_inside << \" points inside \" << std::endl;\n  std::cout << \"  \" << nb_boundary << \" points on boundary \" << std::endl;\n  std::cout << \"  \" << points.size() - nb_inside - nb_boundary << \" points outside \" << std::endl;\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "d72781e7791be65fc4bc16747fc830f907d09e4e", "size": 2392, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/examples/Polygon_mesh_processing/point_inside_example_OM.cpp", "max_stars_repo_name": "liminchen/OptCuts", "max_stars_repo_head_hexsha": "cb85b06ece3a6d1279863e26b5fd17a5abb0834d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 187.0, "max_stars_repo_stars_event_min_datetime": "2019-01-23T04:07:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T03:44:58.000Z", "max_issues_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/examples/Polygon_mesh_processing/point_inside_example_OM.cpp", "max_issues_repo_name": "xiaoxie5002/OptCuts", "max_issues_repo_head_hexsha": "1f4168fc867f47face85fcfa3a572be98232786f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-03-22T13:27:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-18T13:23:23.000Z", "max_forks_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/examples/Polygon_mesh_processing/point_inside_example_OM.cpp", "max_forks_repo_name": "xiaoxie5002/OptCuts", "max_forks_repo_head_hexsha": "1f4168fc867f47face85fcfa3a572be98232786f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 34.0, "max_forks_repo_forks_event_min_datetime": "2019-02-13T01:11:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T03:29:40.000Z", "avg_line_length": 28.8192771084, "max_line_length": 98, "alphanum_fraction": 0.6693143813, "num_tokens": 681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.7085138748070476}}
{"text": "#include \"sv/dsol/solve.h\"\n\n#include <Eigen/Cholesky>\n\n#include \"sv/util/logging.h\"\n\nnamespace sv::dsol {\n\nvoid SolveCholesky(const MatrixXdCRef& A,\n                   const VectorXdCRef& b,\n                   VectorXdRef x) {\n  const auto n = x.size();\n  CHECK_EQ(A.rows(), n);\n  CHECK_EQ(A.rows(), n);\n  CHECK_EQ(b.size(), n);\n\n  x = A.selfadjointView<Eigen::Lower>().llt().solve(b);\n}\n\nvoid SolveCholeskyScaled(const MatrixXdCRef& A,\n                         const VectorXdCRef& b,\n                         VectorXdRef x,\n                         VectorXdRef xs) {\n  CHECK_EQ(x.size(), xs.size());\n\n  // Scaling for better numerical stability\n  // See\n  // Numerical Methods in Matrix Computations, by Ake Bjorck\n  // Use L1 norm\n  // S = 1 / sqrt(|diag(H)|_p + 10)\n  const auto s =\n      (A.diagonal().array().abs() + 10).sqrt().inverse().matrix().eval();\n  const auto S = s.asDiagonal();\n  // Note that since S is diagonal, we can safely multipy S * A * S\n\n  // As = S * A * S\n  // bs = S * b\n  // Solve As * xs = bs\n  // S*A*S * xs = S*b => A * (S*xs) = b\n  // Then x = S * xs\n\n  // From Bjorck Theorem 1.2.7\n  // \"It is important to realize that employing an optimal row or column scaling\n  // may not improve the computed solution. Indeed, for a fixed pivot sequence,\n  // the solution computed by GE is not affected by such scalings.\"\n  // Nevertheless, we still scale it to determing whether to stop early or not\n  SolveCholesky(S * A * S, S * b, xs);\n  x = S * xs;\n}\n\n}  // namespace sv::dsol\n", "meta": {"hexsha": "cead8e7bb8de1644993b94b8d12a9d409a8e3e4a", "size": 1504, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sv/dsol/solve.cpp", "max_stars_repo_name": "versatran01/dsol", "max_stars_repo_head_hexsha": "1c390f10f55fed0d0ef62b0f18e9003bd82c3876", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 52.0, "max_stars_repo_stars_event_min_datetime": "2022-03-17T02:03:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T06:11:52.000Z", "max_issues_repo_path": "sv/dsol/solve.cpp", "max_issues_repo_name": "versatran01/dsol", "max_issues_repo_head_hexsha": "1c390f10f55fed0d0ef62b0f18e9003bd82c3876", "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": "sv/dsol/solve.cpp", "max_forks_repo_name": "versatran01/dsol", "max_forks_repo_head_hexsha": "1c390f10f55fed0d0ef62b0f18e9003bd82c3876", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2022-03-17T06:13:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T09:15:58.000Z", "avg_line_length": 28.9230769231, "max_line_length": 80, "alphanum_fraction": 0.5924202128, "num_tokens": 440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094117351309, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.7084890150643992}}
{"text": "#include <iostream>\n#include <set>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/assignment.hpp>\n#include <boost/foreach.hpp>\n\nnamespace matrixManipulation\n{\n      using namespace std;\n      using namespace boost::numeric::ublas;\n\n      template <typename dataType>\n      void printMatrix(matrix<dataType> &mat)\n      {\n            for (int row=0;row<mat.size1();row++)\n            {\n                  for (int col=0;col<mat.size2()-1;col++)\n                  { cout << mat(row,col) << \" \"; }\n                  cout << mat(row,mat.size2()-1) << endl;\n            }\n      };\n\n      template <typename dataType>\n      void rightRot(matrix<dataType> &mat,int iOrigin,int jOrigin,int matSize)\n      {\n            if (matSize<2) {return;}\n            pair<int,int> runner(iOrigin,jOrigin),backRunner(0,0);\n                        \n            for (int i=0;i<matSize-1;i++)\n            {\n                  runner = make_pair(iOrigin,jOrigin+i);\n                  for (int q=0;q<3;q++)\n                  {     \n                        // first transform from runner to its indices in the\n                        // \"relative frame\" by substracting (iOrigin,jOrigin), then \n                        // find backRunner, then transform back by adding (iOrigin,jOrigin)\n                        backRunner = make_pair(\n                              matSize-(runner.second-jOrigin)-1+iOrigin,\n                              (runner.first-iOrigin)+jOrigin); \n                        swapElement(mat,runner,backRunner);\n                        runner = backRunner;\n                  }\n            }\n            rightRot(mat,iOrigin+1,jOrigin+1,matSize-2);     \n      };\n      \n      template <typename dataType>\n      void swapElement(matrix<dataType> &mat, pair<int,int> &index1, pair<int,int> &index2)\n      {\n            dataType temp;\n            int i = index1.first;\n            int j = index1.second;\n            int k = index2.first;\n            int l = index2.second;\n            temp = mat(i,j);\n            mat(i,j) = mat(k,l);\n            mat(k,l) = temp;\n      };\n      \n      \n      // 1.7\n      // for elements with \"target\" value. set its connecting rows and columns \n      // to tne \"target\" value. \n      template <typename dataType>\n      void tunnel(matrix<dataType> &mat, dataType target)\n      {\n            set<int> rowSet,colSet;\n      \n            for (int row=0;row<mat.size1();row++)\n            {\n                  for (int col=0;col<mat.size2();col++)\n                  {\n                        if (mat(row,col)==target)\n                        { rowSet.insert(row); colSet.insert(col); }\n                  }\n            }\n            \n            BOOST_FOREACH(int row,rowSet) { setRow(mat,row,target); }\n            BOOST_FOREACH(int col,colSet) { setCol(mat,col,target); }\n      }\n      \n      template <typename dataType>\n      void setRow(matrix<dataType> &mat, int row, dataType value)\n      { for (int i=0;i<mat.size2();i++) { mat(row,i) = value; } };\n      \n      template <typename dataType>\n      void setCol(matrix<dataType> &mat, int col, dataType value)\n      { for (int i=0;i<mat.size1();i++) { mat(i,col) = value; } };\n      \n}\n\nint main()\n{\n      using namespace matrixManipulation;\n      using namespace boost::numeric::ublas;\n \n      cout << \"testing matrix rotation:\" << endl;\n      matrix<char> matChar(8,8);\n      matChar <<= '0','0','0','0','0','0','0','0',\n                  '0','0','0','0','0','0','0','0',\n                  '0','0','0','0','*','0','0','0',\n                  '0','0','0','0','|','0','0','0',\n                  '0','0','0','0','|','0','0','0',\n                  '0','0','0','0','|','0','0','0',\n                  '0','0','0','0','|','0','0','0',\n                  '0','0','0','0','|','0','0','0',\n      printMatrix(matChar);\n      rightRot(matChar,0,0,8);\n      cout << \"rotated is\" << endl;\n      printMatrix(matChar);\n      \n      cout << \"testing setting values across row and column (tunnel):\" << endl;\n      matrix<int> mat(5,5);\n      mat  <<=    11,12,13,14,15,\n                  16,17,18,19,20,\n                  21,22,23,24,25,\n                  26,27,28,29,30,\n                  31,32,33,34,35;\n      printMatrix(mat);\n      tunnel<int>(mat,23);\n      cout << \"tunneled for 23 is\" << endl;\n      printMatrix(mat);\n      \n      return 0;\n}", "meta": {"hexsha": "32226d6d1b3459b1cddf79a139069875b405f9db", "size": 4327, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/matrixManipulation.cpp", "max_stars_repo_name": "chaohan/code-samples", "max_stars_repo_head_hexsha": "0ae7da954a36547362924003d56a8bece845802c", "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/matrixManipulation.cpp", "max_issues_repo_name": "chaohan/code-samples", "max_issues_repo_head_hexsha": "0ae7da954a36547362924003d56a8bece845802c", "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": "cpp/matrixManipulation.cpp", "max_forks_repo_name": "chaohan/code-samples", "max_forks_repo_head_hexsha": "0ae7da954a36547362924003d56a8bece845802c", "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.616, "max_line_length": 91, "alphanum_fraction": 0.4631384331, "num_tokens": 1092, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213745668094, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.7084457841679876}}
{"text": "#pragma once\n#include <Eigen/Core>\n#include <string>\n#include <igl/readMESH.h>\n#include <igl/readSTL.h>\n#include <igl/slice.h>\n#include <igl/slice_into.h>\n#include \"stiffness_matrix_assembly.hpp\"\n#include \"load_vector_assembly.hpp\"\n#include \"dirichlet_boundary.hpp\"\n\ntypedef Eigen::VectorXd Vector;\n\n//----------------solveBegin----------------\n//! Solve the FEM system.\n//!\n//! @param[out] u will at the end contain the FEM solution.\n//! @param[in] vertices list of triangle vertices for the mesh\n//! @param[in] triangles list of triangles (described by indices)\n//! @param[in] f the RHS f (as in the exercise)\n//! return number of degrees of freedom (without the boundary dofs)\nint solveFiniteElement(Vector& u,\n    const Eigen::MatrixXd& vertices,\n    const Eigen::MatrixXi& triangles,\n    const std::function<double(double, double)>& f)\n{\n    SparseMatrix A;\n    //// ANCSE_START_TEMPLATE\n    assembleStiffnessMatrix(A, vertices, triangles);\n    //// ANCSE_END_TEMPLATE\n\n    Vector F;\n    //// ANCSE_START_TEMPLATE\n    assembleLoadVector(F, vertices, triangles, f);\n    //// ANCSE_END_TEMPLATE\n\n    u.resize(vertices.rows());\n    u.setZero();\n    Eigen::VectorXi interiorVertexIndices;\n\n    auto zerobc = [](double x, double y){ return 0;};\n    // set homogeneous Dirichlet Boundary conditions\n    //// ANCSE_START_TEMPLATE\n    setDirichletBoundary(u, interiorVertexIndices, vertices, triangles, zerobc);\n    F -= A * u;\n    //// ANCSE_END_TEMPLATE\n\n    SparseMatrix AInterior;\n\n    igl::slice(A, interiorVertexIndices, interiorVertexIndices, AInterior);\n    Eigen::SimplicialLDLT<SparseMatrix> solver;\n\n    Vector FInterior;\n\n    igl::slice(F, interiorVertexIndices, FInterior);\n\n    //initialize solver for AInterior\n    //// ANCSE_START_TEMPLATE\n    solver.compute(AInterior);\n\n    if (solver.info() != Eigen::Success) {\n        throw std::runtime_error(\"Could not decompose the matrix\");\n    }\n    //// ANCSE_END_TEMPLATE\n\n    //solve interior system\n    //// ANCSE_START_TEMPLATE\n    Vector uInterior = solver.solve(FInterior);\n    igl::slice_into(uInterior, interiorVertexIndices, u);\n    //// ANCSE_END_TEMPLATE\n\n    return interiorVertexIndices.size();\n\n}\n//----------------solveEnd----------------\n", "meta": {"hexsha": "5142e8ce57ae97c9d84fabb76436397010cf0d89", "size": 2211, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "series0_solution/2d-poissonlFEM/fem_solve.hpp", "max_stars_repo_name": "BeatHubmann/19H-AdvNCSE", "max_stars_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-05T22:38:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-05T22:38:47.000Z", "max_issues_repo_path": "series0_solution/2d-poissonlFEM/fem_solve.hpp", "max_issues_repo_name": "BeatHubmann/19H-AdvNCSE", "max_issues_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "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": "series0_solution/2d-poissonlFEM/fem_solve.hpp", "max_forks_repo_name": "BeatHubmann/19H-AdvNCSE", "max_forks_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-08T20:43:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-08T20:43:27.000Z", "avg_line_length": 29.0921052632, "max_line_length": 80, "alphanum_fraction": 0.684758028, "num_tokens": 526, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.833324587033253, "lm_q2_score": 0.8499711756575749, "lm_q1q2_score": 0.7083018789450171}}
{"text": "//\n//  utils.cpp\n//  Jacobian\n//\n//  Created by David Freifeld\n//  Copyright \u00a9 2020 David Freifeld. All rights reserved.\n//\n\n#include <iostream>\n#include <fstream>\n#include <algorithm>\n#include <cstdlib>\n#include <ctime>\n#include <cmath>\n#include <cstdio>\n#include <fcntl.h>\n#include <unistd.h>\n#include <sys/stat.h>\n#include <Eigen/Dense>\n\n#include \"utils.hpp\"\n\nnamespace Jacobian {\nnamespace activations {\n\ninline float sgn(float val) {return (0.0f < val) - (val < 0.0f);}\n\ndouble fexp(double val)\n{\n\tlong tmp = static_cast<long>(1512775 * val + 1072632447) << 32;\n\treturn *reinterpret_cast<double*>(&tmp);\n}\n\nfloat ftanh(float x)\n{\n\treturn (x*(10+pow(x,2))*(60+pow(x,2)))/\n\t\t(600+(270*pow(x,2))+(11*pow(x,4))+(pow(x,6)/24));\n}\n\n//float ftanh(float val) {return sgn(val) * (1 - 2/(fexp(2*abs(val))+1));}\nfloat fcosh(float val) {return (fexp(val) + fexp(-val)) * 0.5;}\n\n// A bunch of hardcoded activation functions. Avoids much of the slowness of custom functions.\n// Although the std::function makes it not the fastest way, the functionality is worth it.\n// Yes, these functions may be a frustrating to read but they're just equations and I want to conserve space.\n\nfloat sigmoid(float x) {return 1.0/(1+fexp(-x));}\nfloat sigmoid_deriv(float x) {return 1.0/(1+fexp(-x)) * (1 - 1.0/(1+fexp(-x)));}\n\nfloat linear(float x) {return x;}\nfloat linear_deriv(float x) {return 1;}\n\nfloat lecun_tanh(float x) {\n\t//std::cout << ftanh(x) << \" vs \" << tanh(x) << \"\\n\";\n\treturn 1.7159 * ftanh(0.66f * x);}\nfloat lecun_tanh_deriv(float x) {return 1.14393 * pow(1.0/fcosh(0.66f * x), 2);}\n\nfloat inverse_logit(float x) {return (fexp(x)/(fexp(x)+1));}\nfloat inverse_logit_deriv(float x) {return (fexp(x)/pow(fexp(x)+1, 2));}\n\nfloat softplus(float x) {return log(1+fexp(x));}\nfloat softplus_deriv(float x) {return fexp(x)/(fexp(x)+1);}\n\nfloat cloglog(float x) {return 1-fexp(-fexp(x));}\nfloat cloglog_deriv(float x) {return fexp(x-fexp(x));}\n\nfloat step(float x)\n{\n\tif (x > 0) return 1;\n\telse return 0;\n}\nfloat step_deriv(float x) {return 0;}\n\nfloat bipolar(float x)\n{\n\tif (x > 0) return 1;\n\telse if (x == 0) return 0;\n\telse return -1;\n}\nfloat bipolar_deriv(float x) {return 0;}\n\nfloat bipolar_sigmoid(float x) {return (1-fexp(-x))/(1+fexp(-x));}\nfloat bipolar_sigmoid_deriv(float x) {return (2*fexp(x))/(pow(fexp(x)+1,2));}\n\nfloat hard_tanh(float x) {return fmax(-1, fmin(1,x));}\nfloat hard_tanh_deriv(float x)\n{\n\tif (-1 < x && x < 1) return 1;\n\telse return 0;\n}\n\nfloat leaky_relu(float x)\n{\n\tif (x > 0) return x;\n\telse return 0.01 * x;\n}\n\nfloat leaky_relu_deriv(float x)\n{\n\tif (x > 0) return 1;\n\telse return 0.01;\n}\n\nstd::function<float(float)> rectifier(float (*activation)(float))\n{\n\tauto rectified = [activation](float x) -> float {\n\t\tif (x > 0)\n\t\t\treturn (*activation)(x);\n\t\telse\n\t\t\treturn 0;\n\t};\n\treturn rectified;\n}\n} // namespace activations\n\nnamespace optimizers {\nstd::function<void(Layer&, Eigen::MatrixXf, float)> momentum(float beta) {\n\treturn [beta](Layer& layer, const Eigen::MatrixXf delta, const float learning_rate) {\n\t  layer.weights -= (beta * layer.m) + (learning_rate * delta);\n\t  layer.m = (learning_rate * delta);\n\t};\n}\n\nstd::function<void(Layer&, Eigen::MatrixXf, float)> demon(float beta, int max_ep) {\n\tfloat beta_init = beta;\n\tfloat prev_epoch = -1;\n\tfloat epochs = 0;\n\treturn [max_ep, epochs, beta_init, beta](Layer& layer, const Eigen::MatrixXf delta, const float learning_rate) mutable {\n\t\tbeta = beta_init * (1-(epochs/max_ep)) / ((beta_init * (1-(epochs/max_ep))) + (1-beta_init));\n\t\tlayer.weights -= (beta * layer.m) + (learning_rate * delta);\n\t\tlayer.m = (learning_rate * delta);\n\t\tepochs++;\n\t};\n}\n\nstd::function<void(Layer&, Eigen::MatrixXf, float)> adam(float beta1, float beta2, float epsilon) {\n\treturn [beta1, beta2, epsilon](Layer& layer, const Eigen::MatrixXf delta, const float learning_rate) {\n\t\tlayer.m = (beta1 * layer.m) + ((1-beta1)*delta);\n\t\tlayer.v = (beta2 * layer.v) + (1-beta2)*(delta.cwiseProduct(delta));\n\t\tlayer.weights -= learning_rate *\n\t\t\t((layer.v.cwiseSqrt()).array()+epsilon).pow(-1).cwiseProduct(layer.m.array()).matrix();\n\t};\n}\n\nstd::function<void(Layer&, Eigen::MatrixXf, float)> adamax(float beta1, float beta2, float epsilon) {\n\treturn [beta1, beta2, epsilon](Layer &layer,\n\t\t\t\t\t   const Eigen::MatrixXf delta,\n\t\t\t\t\t   const float learning_rate) {\n\t\tlayer.m = (beta1 * layer.m) + ((1 - beta1) * delta);\n\t\tif ((beta2 * layer.v).sum() > delta.array().abs().sum())\n\t\t\tlayer.v = (beta2 * layer.v);\n\t\telse\n\t\t\tlayer.v = delta.array().abs().matrix();\n\t\tlayer.weights -=\n\t\t\tlearning_rate *\n\t\t\t(layer.v.array().pow(-1).cwiseProduct(layer.m.array()))\n\t\t\t\t.matrix();\n\t};\n}\n}\n}\n", "meta": {"hexsha": "00e9d3061aece021b7bea6154643ae82c9d97154", "size": 4618, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/utils.cpp", "max_stars_repo_name": "richardfeynmanrocks/ml-in-parallel", "max_stars_repo_head_hexsha": "6fd978b1f4a97ae789a13e0c2f20638672848aa5", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-10-01T23:28:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T02:21:20.000Z", "max_issues_repo_path": "src/utils.cpp", "max_issues_repo_name": "quantumish/Jacobian", "max_issues_repo_head_hexsha": "6fd978b1f4a97ae789a13e0c2f20638672848aa5", "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": "src/utils.cpp", "max_forks_repo_name": "quantumish/Jacobian", "max_forks_repo_head_hexsha": "6fd978b1f4a97ae789a13e0c2f20638672848aa5", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-14T16:06:20.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-14T16:06:20.000Z", "avg_line_length": 28.5061728395, "max_line_length": 121, "alphanum_fraction": 0.6604590732, "num_tokens": 1428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206686206199, "lm_q2_score": 0.7853085909370422, "lm_q1q2_score": 0.708286049411454}}
{"text": "#include <chrono>\n#include <cmath>\n#include <cstdlib>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\n#include <Eigen/Dense>\n\nint main(int argc, char **argv) {\n  if (argc != 2) {\n    std::cout << \"Usage: ./linear-algebra dim\" << std::endl;\n    return EXIT_FAILURE;\n  }\n\n  std::chrono::time_point<std::chrono::system_clock> start, end;\n  std::chrono::duration<double> elapsed_seconds;\n  std::time_t end_time;\n\n  std::cout << \"Number of threads used by Eigen: \" << Eigen::nbThreads()\n            << std::endl;\n\n  // Allocate matrices and right-hand side vector\n  start = std::chrono::system_clock::now();\n  int dim = std::atoi(argv[1]);\n  Eigen::MatrixXd A = Eigen::MatrixXd::Random(dim, dim);\n  Eigen::VectorXd b = Eigen::VectorXd::Random(dim);\n  end = std::chrono::system_clock::now();\n\n  // Report times\n  elapsed_seconds = end - start;\n  end_time = std::chrono::system_clock::to_time_t(end);\n  std::cout << \"matrices allocated and initialized \"\n            << std::put_time(std::localtime(&end_time), \"%a %b %d %Y %r\\n\")\n            << \"elapsed time: \" << elapsed_seconds.count() << \"s\\n\";\n\n  start = std::chrono::system_clock::now();\n  // Save matrix and RHS\n  Eigen::MatrixXd A1 = A;\n  Eigen::VectorXd b1 = b;\n  end = std::chrono::system_clock::now();\n  end_time = std::chrono::system_clock::to_time_t(end);\n  std::cout << \"Scaling done, A and b saved \"\n            << std::put_time(std::localtime(&end_time), \"%a %b %d %Y %r\\n\")\n            << \"elapsed time: \" << elapsed_seconds.count() << \"s\\n\";\n\n  start = std::chrono::system_clock::now();\n  Eigen::VectorXd x = A.lu().solve(b);\n  end = std::chrono::system_clock::now();\n\n  // Report times\n  elapsed_seconds = end - start;\n  end_time = std::chrono::system_clock::to_time_t(end);\n\n  double relative_error = (A * x - b).norm() / b.norm();\n\n  std::cout << \"Linear system solver done \"\n            << std::put_time(std::localtime(&end_time), \"%a %b %d %Y %r\\n\")\n            << \"elapsed time: \" << elapsed_seconds.count() << \"s\\n\";\n  std::cout << \"relative error is \" << relative_error << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "51880afbd3f4713b4d235791089bdbe612388f18", "size": 2078, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "chapter-03/recipe-07/cxx-example/linear-algebra.cpp", "max_stars_repo_name": "istupsm/cmake-cookbook", "max_stars_repo_head_hexsha": "342d0171802153619ea124c5b8e792ce45178895", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1600.0, "max_stars_repo_stars_event_min_datetime": "2018-05-24T01:32:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T09:24:11.000Z", "max_issues_repo_path": "chapter-03/recipe-07/cxx-example/linear-algebra.cpp", "max_issues_repo_name": "istupsm/cmake-cookbook", "max_issues_repo_head_hexsha": "342d0171802153619ea124c5b8e792ce45178895", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 280.0, "max_issues_repo_issues_event_min_datetime": "2017-08-27T13:10:51.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-23T15:09:58.000Z", "max_forks_repo_path": "chapter-03/recipe-07/cxx-example/linear-algebra.cpp", "max_forks_repo_name": "istupsm/cmake-cookbook", "max_forks_repo_head_hexsha": "342d0171802153619ea124c5b8e792ce45178895", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 475.0, "max_forks_repo_forks_event_min_datetime": "2018-05-23T15:26:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T07:28:19.000Z", "avg_line_length": 32.46875, "max_line_length": 75, "alphanum_fraction": 0.6183830606, "num_tokens": 578, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206765295399, "lm_q2_score": 0.7853085808877581, "lm_q1q2_score": 0.7082860465587397}}
{"text": "#include <gtest/gtest.h>\n\n#include <Eigen/Dense>\n\nnamespace fbstab {\nnamespace test {\n\nusing MatrixXd = Eigen::MatrixXd;\nusing VectorXd = Eigen::VectorXd;\n\nGTEST_TEST(A, B) {\n  int n = 3;\n  int l = 4;\n\n  MatrixXd H = Eigen::MatrixXd::Identity(n, n);\n  MatrixXd G = Eigen::MatrixXd::Random(l, n);\n\n  MatrixXd K(n + l, n + l);\n\n  K.block(0, 0, n, n) = H;\n  K.block(n, 0, l, n) = G;\n  K.block(n, n, l, l) = -Eigen::MatrixXd::Identity(l, l);\n\n  std::cout << K << std::endl;\n\n  Eigen::LDLT<Eigen::MatrixXd> ldlt;\n  ldlt.compute(K);\n\n  MatrixXd L = ldlt.matrixL();\n  std::cout << L << std::endl;\n\n  VectorXd d = ldlt.vectorD();\n  std::cout << d << std::endl;\n}\n\nGTEST_TEST(A, C) {\n  int n = 3;\n  int l = 0;\n\n  MatrixXd H = Eigen::MatrixXd::Identity(n, n);\n  MatrixXd G = Eigen::MatrixXd::Random(l, n);\n\n  MatrixXd K(n + l, n + l);\n\n  K.block(0, 0, n, n) = H;\n  K.block(n, 0, l, n) = G;\n  K.block(n, n, l, l) = -Eigen::MatrixXd::Identity(l, l);\n\n  std::cout << K << std::endl;\n\n  Eigen::LDLT<Eigen::MatrixXd> ldlt;\n  ldlt.compute(K);\n\n  MatrixXd L = ldlt.matrixL();\n  std::cout << L << std::endl;\n\n  VectorXd d = ldlt.vectorD();\n  std::cout << d << std::endl;\n}\n\nGTEST_TEST(A, D) {\n  int nr = 4;\n  int nc = 1;\n\n  MatrixXd H(nr, nc);\n  H << 1, 2, 3, 4;\n\n  Eigen::Map<Eigen::MatrixXd> A(H.data(), nr, nc);\n\n  Eigen::VectorXd a = A;\n\n  std::cout << A << std::endl;\n  std::cout << a << std::endl;\n\n  const auto& AA = A;\n\n  std::cout << AA << std::endl;\n}\n\n}  // namespace test\n}  // namespace fbstab", "meta": {"hexsha": "2eace19f2dd5cc554210d7e07bfba64bdac10b08", "size": 1488, "ext": "cc", "lang": "C++", "max_stars_repo_path": "fbstab/test/eigen_tests.cc", "max_stars_repo_name": "tcunis/fbstab", "max_stars_repo_head_hexsha": "25d5259f683427867f140567d739a55ed7359aca", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2019-08-09T18:43:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-07T12:38:27.000Z", "max_issues_repo_path": "fbstab/test/eigen_tests.cc", "max_issues_repo_name": "tcunis/fbstab", "max_issues_repo_head_hexsha": "25d5259f683427867f140567d739a55ed7359aca", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2019-08-14T17:33:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-01T12:03:36.000Z", "max_forks_repo_path": "fbstab/test/eigen_tests.cc", "max_forks_repo_name": "tcunis/fbstab", "max_forks_repo_head_hexsha": "25d5259f683427867f140567d739a55ed7359aca", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-08-09T19:03:23.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-07T23:03:33.000Z", "avg_line_length": 18.3703703704, "max_line_length": 57, "alphanum_fraction": 0.563844086, "num_tokens": 537, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467548438126, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.7082689265919513}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_FUNCTION_ATAN2_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ATAN2_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-trigonometric\n    Function object implementing atan2 capabilities\n\n    quadrant aware atan2 function.\n\n    @par Semantic:\n\n    For every parameters @c x and @c y of same floating type\n\n    @code\n    auto r = atan2(y, x);\n    @endcode\n\n    @par Notes\n\n    - For any real arguments @c x and @c y not both equal to zero, <tt>atan2(y, x)</tt>\n    is the angle in radians between the positive x-axis of a plane and the point\n    given by the coordinates  <tt>(x, y)</tt>.\n\n    - It is also the angle in \\f$[-\\pi,\\pi[\\f$ for which\n    \\f$x/\\sqrt{x^2+y^2}\\f$ and \\f$y/\\sqrt{x^2+y^2}\\f$\n    are respectively the sine and the cosine.\n\n    - Following IEEE norms,  we should have:\n     -  If y is \\f$\\pm0\\f$ and x is negative or -0,\\f$\\pm\\pi\\f$ is returned\n     -  If y is \\f$\\pm0\\f$ and x is positive or +0, \\f$\\pm0\\f$ is returned\n     -  If y is \\f$\\pm\\infty\\f$ and x is finite, \\f$\\pm\\pi/2\\f$ is returned\n     -  If y is \\f$\\pm\\infty\\f$ and x is \\f$-\\infty\\f$,\\f$\\pm3\\pi/4\\f$ is returned\n     -  If y is \\f$\\pm\\infty\\f$ and x is \\f$+\\infty\\f$, \\f$\\pm\\pi/4\\f$ is returned\n     -  If x is \\f$\\pm0\\f$ and y is negative, \\f$-\\pi/2\\f$ is returned\n     -  If x is \\f$\\pm0\\f$ and y is positive, \\f$+\\pi/2\\f$  is returned\n     -  If x is \\f$-\\infty\\f$ and y is finite and positive, \\f$+\\pi\\f$ is returned\n     -  If x is \\f$-\\infty\\f$ and y is finite and negative, \\f$-\\pi\\f$ is returned\n     -  If x is \\f$+\\infty\\f$ and y is finite and positive, +0 is returned\n     -  If x is \\f$+\\infty\\f$ and y is finite and negative, -0 is returned\n     -  If either x is Nan or y is Nan, Nan is returned\n\n     The pedantic_ decorator ensures all these conditions,  but the regular version\n     will return a NaN if x and y are both either null or infinite, result which in fact\n      is not more absurd than the IEEE choices. It will be conforming in all other cases.\n\n    @par Decorators\n\n    - std_  provides access to std::atan2\n\n   -  pedantic_ ensures the respect of all IEEE limits\n\n  @see atan, atand, atanpi\n\n  **/\n  Value atan2(Value const &y, Value const &x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/atan2.hpp>\n#include <boost/simd/function/simd/atan2.hpp>\n\n#endif\n", "meta": {"hexsha": "929e4e0999a49f0d65496945ca163797411e51d4", "size": 2733, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/atan2.hpp", "max_stars_repo_name": "nickporubsky/boost-simd-clone", "max_stars_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-12T13:45:09.000Z", "max_issues_repo_path": "include/boost/simd/function/atan2.hpp", "max_issues_repo_name": "nickporubsky/boost-simd-clone", "max_issues_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_issues_repo_licenses": ["BSL-1.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": "include/boost/simd/function/atan2.hpp", "max_forks_repo_name": "nickporubsky/boost-simd-clone", "max_forks_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-11-17T15:30:36.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-01T02:06:25.000Z", "avg_line_length": 35.0384615385, "max_line_length": 100, "alphanum_fraction": 0.6037321625, "num_tokens": 815, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467580102418, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.7082689250402014}}
{"text": "//////////////////////////////////////////////////////////////////////////////\r\n//\r\n// (C) Copyright Stephen Cleary 2000.\r\n// (C) Copyright Ion Gaztanaga 2007-2008.\r\n//\r\n// Distributed under the Boost Software License, Version 1.0.\r\n//    (See accompanying file LICENSE_1_0.txt or copy at \r\n//    http://www.boost.org/LICENSE_1_0.txt)\r\n//\r\n// See http://www.boost.org/libs/interprocess for documentation.\r\n//\r\n// This file is a slightly modified file from Boost.Pool\r\n//\r\n//////////////////////////////////////////////////////////////////////////////\r\n\r\n#ifndef BOOST_INTERPROCESS_DETAIL_MATH_FUNCTIONS_HPP\r\n#define BOOST_INTERPROCESS_DETAIL_MATH_FUNCTIONS_HPP\r\n\r\n#include <climits>\r\n#include <boost/static_assert.hpp>\r\n\r\nnamespace boost {\r\nnamespace interprocess {\r\nnamespace detail {\r\n\r\n// Greatest common divisor and least common multiple\r\n\r\n//\r\n// gcd is an algorithm that calculates the greatest common divisor of two\r\n//  integers, using Euclid's algorithm.\r\n//\r\n// Pre: A > 0 && B > 0\r\n// Recommended: A > B\r\ntemplate <typename Integer>\r\ninline Integer gcd(Integer A, Integer B)\r\n{\r\n   do\r\n   {\r\n      const Integer tmp(B);\r\n      B = A % B;\r\n      A = tmp;\r\n   } while (B != 0);\r\n\r\n   return A;\r\n}\r\n\r\n//\r\n// lcm is an algorithm that calculates the least common multiple of two\r\n//  integers.\r\n//\r\n// Pre: A > 0 && B > 0\r\n// Recommended: A > B\r\ntemplate <typename Integer>\r\ninline Integer lcm(const Integer & A, const Integer & B)\r\n{\r\n   Integer ret = A;\r\n   ret /= gcd(A, B);\r\n   ret *= B;\r\n   return ret;\r\n}\r\n\r\ntemplate <typename Integer>\r\ninline Integer log2_ceil(const Integer & A)\r\n{\r\n   Integer i = 0;\r\n   Integer power_of_2 = 1;\r\n\r\n   while(power_of_2 < A){\r\n      power_of_2 <<= 1;\r\n      ++i;\r\n   }\r\n   return i;\r\n}\r\n\r\ntemplate <typename Integer>\r\ninline Integer upper_power_of_2(const Integer & A)\r\n{\r\n   Integer power_of_2 = 1;\r\n\r\n   while(power_of_2 < A){\r\n      power_of_2 <<= 1;\r\n   }\r\n   return power_of_2;\r\n}\r\n\r\n//This function uses binary search to discover the\r\n//highest set bit of the integer\r\ninline std::size_t floor_log2 (std::size_t x)\r\n{\r\n   const std::size_t Bits = sizeof(std::size_t)*CHAR_BIT;\r\n   const bool Size_t_Bits_Power_2= !(Bits & (Bits-1));\r\n   BOOST_STATIC_ASSERT(((Size_t_Bits_Power_2)== true));\r\n\r\n   std::size_t n = x;\r\n   std::size_t log2 = 0;\r\n   \r\n   for(std::size_t shift = Bits >> 1; shift; shift >>= 1){\r\n      std::size_t tmp = n >> shift;\r\n      if (tmp)\r\n         log2 += shift, n = tmp;\r\n   }\r\n\r\n   return log2;\r\n}\r\n\r\n} // namespace detail\r\n} // namespace interprocess\r\n} // namespace boost\r\n\r\n#endif\r\n", "meta": {"hexsha": "335ab4cccd82c96f1d472660de375adb70b95050", "size": 2560, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "windows/include/boost/interprocess/detail/math_functions.hpp", "max_stars_repo_name": "jaredhoberock/gotham", "max_stars_repo_head_hexsha": "e3551cc355646530574d086d7cc2b82e41e8f798", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-12-29T07:21:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-29T10:47:38.000Z", "max_issues_repo_path": "windows/include/boost/interprocess/detail/math_functions.hpp", "max_issues_repo_name": "jaredhoberock/gotham", "max_issues_repo_head_hexsha": "e3551cc355646530574d086d7cc2b82e41e8f798", "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": "windows/include/boost/interprocess/detail/math_functions.hpp", "max_forks_repo_name": "jaredhoberock/gotham", "max_forks_repo_head_hexsha": "e3551cc355646530574d086d7cc2b82e41e8f798", "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": 23.0630630631, "max_line_length": 79, "alphanum_fraction": 0.59140625, "num_tokens": 636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237605, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.7082598592714765}}
{"text": "/*\nHeader files to implement linear models\nX: mat type with shape (M, N), a dataset consisting of 'M' examples each of dimension of 'N'\ny: mat type with shape (M, K), the targets for each of the 'M' examples in 'X', where each target has dimension `K` \n\n1. Linear Regression\nTo apply Ordinary Least Squares with normal equation with formula:\n\\mathbf{theta}= \\left(\\mathbf{X}^\\top \\mathbf{X}\\right)^{-1} \\mathbf{X}^\\top \\mathbf{y}\n\n2. Ridge Regression\nTo apply Ridge regression with normal equation:\n \\mathbf{theta} \\left(\\mathbf{X}^\\top \\mathbf{X} +\n \\lambda \\mathbf{I} \\right)^{-1}\\mathbf{X}^\\top \\mathbf{y}\n \nwhere alpha is the paramater for L2 regulization, a greater value has a larger penalty\n\n3. Logistic Regression\nTo minimize the following loss function:\n\n- \\log (\\mathcal{L}(\\mathbf{theta})) = -\\frac{1}{M} \\left[\n        \\left(\n            \\sum_{i=0}^M \\y^((i)) \\log(\\h_theta(x^((i)))) +\n                (1-y^((i))) \\log(1-\\h_theta(x^((i))))\n        \\right) - R(\\mathbf{theta}, \\lambda)\n    \\right]\n\nWhere:\nR(mathbf{theta}, lambda) = {(lambda/2||\\mathbf{theta}||_2^2\\ :\\ \"penalty\" = 'l2'),\n(lambda||\\mathbf{theta}||_1:\\ \"penalty\" = 'l1'):}\n\nis a regularization penalty, '\\lambda' is a regularization weight, 'M' is the number of examples in y\nfit with gradient descent algo\n\n*/\n#include <iostream>\n#include <armadillo>\nusing namespace std;\nusing namespace arma;\n\n\n#ifndef LinearModels_HPP\n#define LinearModels_HPP\n\nclass LinearRegression {\nprivate:\n    //  Whether to fit intercept, with default value true\n    bool fit_intercept;\n    \npublic:\n    //  a vector to store coefficents of the results with defult shape of 100 X 1\n    vec theta; \n\n    //  constructors\n    LinearRegression();\n    LinearRegression(bool fit_intercept1);\n    LinearRegression(const LinearRegression& source);\n    ~LinearRegression();\n\n    //  Assignment operator\n    LinearRegression& operator = (const LinearRegression& source);\n\n    //  functions\n    const void fit(mat X, const mat& y);   // fit function to calculate the results and store to theta\n    const mat predict(mat X);   // return predicted values with trained model\n};\n\n\nclass RidgeRegression {\nprivate:\n    //  Whether to fit intercept, with default value true\n    bool fit_intercept;\n    //  Regulation paramater \n    double lambda;\n\npublic:\n    //  a vector to store coefficents of the results with defult shape of 100 X 1\n    vec theta;\n\n    //  constructors\n    RidgeRegression();\n    RidgeRegression(double lambda1, bool fit_intercept1=true);\n    RidgeRegression(const RidgeRegression& source);\n    ~RidgeRegression();\n\n    //  Assignment operator\n    RidgeRegression& operator = (const RidgeRegression& source);\n\n    //  functions\n    const void fit(mat X, const mat& y);    // fit function to calculate the results and store to theta\n    const mat predict(mat X);   // return predicted values with trained model\n};\n\n\n//  Logistic regression with gradient descent optimizer \nclass LogisticRegression {\nprivate:\n    //  regularization paramater\n    double lambda;\n    //  regularization type with l2 as default/\n    string penalty;\n    //  Whether to fit intercept, with default value true\n    bool fit_intercept;\n\npublic:\n    //  a vector to store coefficents of the results with defult shape of 100 X 1\n    vec theta;\n    //  constructors\n    LogisticRegression();\n    LogisticRegression(double lambda1 = 0, bool fit_intercept1 = true, string penalty = \"l2\");\n    LogisticRegression(const LogisticRegression& source);\n    ~LogisticRegression();\n\n    //  Assignment operator\n    LogisticRegression& operator = (const LogisticRegression& source);\n\n    //  functions\n    // fit function to calculate the results and store to theta. Apply gradient descent algo to minimize loss function\n    const void fit(mat X, const mat& y, double lr = 0.01, double tol = 1e-7, long max_iter = 1e7);\n    const mat predict(mat X);   // return predicted values with trained model\n    double _NLL(const mat& X, const mat& y, const mat& y_pred); // supplemental function to calculate negative log likelihood under current model\n    vec _NLL_grad(const mat& X, const mat& y, const mat& y_pred); // supplemental function to calculate Gradient of the penalized negative log likelihood wrt theta\n};\n\n//  supplemental functions\n\n//The logistic sigmoid function\nmat sigmoid(const mat& X);\n#endif;\n\n", "meta": {"hexsha": "a931972cb9a45c0e50b469d55fe5f1566aac174c", "size": 4328, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Machine Learning Algos/Machine Learning Algos/LinearModels/LinearModels.hpp", "max_stars_repo_name": "watermantle/ML_CPP", "max_stars_repo_head_hexsha": "76f82dad1eaea74098ad9f2b758bd0cd7a5e67d7", "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": "Machine Learning Algos/Machine Learning Algos/LinearModels/LinearModels.hpp", "max_issues_repo_name": "watermantle/ML_CPP", "max_issues_repo_head_hexsha": "76f82dad1eaea74098ad9f2b758bd0cd7a5e67d7", "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": "Machine Learning Algos/Machine Learning Algos/LinearModels/LinearModels.hpp", "max_forks_repo_name": "watermantle/ML_CPP", "max_forks_repo_head_hexsha": "76f82dad1eaea74098ad9f2b758bd0cd7a5e67d7", "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.2923076923, "max_line_length": 163, "alphanum_fraction": 0.6975508318, "num_tokens": 1095, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9728307700397332, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.7081969222705489}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\nusing namespace std;\nusing namespace Eigen;\n\nint main(void)\n{\n    // Try to know the solution of Null space\n    MatrixXf A(3,4);\n    VectorXf b = VectorXf::Zero(3);\n    A <<\n        1,-10,-24,-42,\n        1,-8,-18,-32,\n        -2,20,51,87;\n    // b << 3, 3, 4;\n    cout << \"Here is the matrix A:\\n\" << A << endl;\n    cout << \"Here is the vector b:\\n\" << b << endl;\n    VectorXf x = A.colPivHouseholderQr().solve(b);\n    cout << \"The solution is:\\n\" << x << endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "de46506682500f3b1c1bfd4139d2789c2c16bb39", "size": 523, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/solve_formula.cpp", "max_stars_repo_name": "RyodoTanaka/eigen_example", "max_stars_repo_head_hexsha": "55da46919e02d0eb7cbea9da97ffa0f9067a6d98", "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/solve_formula.cpp", "max_issues_repo_name": "RyodoTanaka/eigen_example", "max_issues_repo_head_hexsha": "55da46919e02d0eb7cbea9da97ffa0f9067a6d98", "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/solve_formula.cpp", "max_forks_repo_name": "RyodoTanaka/eigen_example", "max_forks_repo_head_hexsha": "55da46919e02d0eb7cbea9da97ffa0f9067a6d98", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-30T03:32:04.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-30T03:32:04.000Z", "avg_line_length": 22.7391304348, "max_line_length": 51, "alphanum_fraction": 0.5449330784, "num_tokens": 177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418241572634, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.7081640150262871}}
{"text": "#pragma once\n#include <Eigen/Dense>\n\n/*\nA convenience hull to solve dense matrix system by matrix decompositions.\n\nThe decomposition type is specified in the constructor.\nSupported options are:\n- LU: a classic LU decomposition\n- QR: a classic QR decomposition\n- LU2: a LU decomposition followed by a single refinement iteration (see\nhttps://en.wikipedia.org/wiki/Iterative_refinement)\n\nAfterwards, use `solve(A, b, x)` to solve the linear system A * x = b for x.\n\nAvailable matrix decomposition types in Eigen:\nhttps://eigen.tuxfamily.org/dox/group__TutorialLinearAlgebra.html\n*/\nclass MatrixSolver {\npublic:\n  // Available decomposition types\n  enum DecompositionType { LU,\n                           QR,\n                           LU2 };\n\n  // Constructor, takes decomposition type.\n  MatrixSolver(DecompositionType decompositionType);\n\n  // solve linear system A * x = b for x.\n  void solve(const Eigen::MatrixXd &A, const Eigen::VectorXd &b,\n             Eigen::VectorXd &x);\n\nprivate:\n  // Used type to compute decomposition\n  DecompositionType _decompositionType;\n};\n", "meta": {"hexsha": "9dc0128b01d4c18093ad3d0b6b597c447b8ee435", "size": 1073, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/MatrixSolver.hpp", "max_stars_repo_name": "kimkroener/testing-boost-exercise", "max_stars_repo_head_hexsha": "8e71e735624e59142303c1c25c2aed74fbd43e0b", "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/MatrixSolver.hpp", "max_issues_repo_name": "kimkroener/testing-boost-exercise", "max_issues_repo_head_hexsha": "8e71e735624e59142303c1c25c2aed74fbd43e0b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2022-01-29T01:07:41.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-15T16:49:23.000Z", "max_forks_repo_path": "src/MatrixSolver.hpp", "max_forks_repo_name": "kimkroener/testing-boost-exercise", "max_forks_repo_head_hexsha": "8e71e735624e59142303c1c25c2aed74fbd43e0b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-01T16:22:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-01T16:22:19.000Z", "avg_line_length": 29.0, "max_line_length": 76, "alphanum_fraction": 0.7148182665, "num_tokens": 234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896758909756, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.7081611373529842}}
{"text": "/**\n * @brief  Easing functions\n */\n\n#ifndef EASING_HPP\n#define EASING_HPP\n\n#include \"floating_point/tolerance_compare.hpp\"\n#include <boost/math/constants/constants.hpp>\n#include <cmath>\n#include <type_traits>\n\nnamespace easing {\n\nnamespace impl {\ntemplate <typename T, typename U, typename = std::void_t<>>\nclass has_in : public std::false_type {};\ntemplate <typename T, typename U>\nclass has_in<T, U, std::void_t<decltype(T::in(std::declval<U>()))>>\n    : public std::true_type {};\n} // namespace impl\n\ntemplate <typename Float = float> struct sine {\n  static_assert(std::is_floating_point_v<Float>,\n                \"only makes sence for floating point types.\");\n  static constexpr Float in(Float x) {\n    return 1.0 - std::cos((x * boost::math::constants::pi<Float>()) * 0.5);\n  }\n};\n\ntemplate <typename Float = float> struct quad {\n  static_assert(std::is_floating_point_v<Float>,\n                \"only makes sence for floating point types.\");\n  static constexpr Float in(Float x) { return x * x; }\n};\n\ntemplate <typename Float = float> struct cubic {\n  static_assert(std::is_floating_point_v<Float>,\n                \"only makes sence for floating point types.\");\n  static constexpr Float in(Float x) { return x * x * x; }\n};\n\ntemplate <typename Float = float> struct quart {\n  static_assert(std::is_floating_point_v<Float>,\n                \"only makes sence for floating point types.\");\n  static constexpr Float in(Float x) { return x * x * x * x; }\n};\n\ntemplate <typename Float = float> struct quint {\n  static_assert(std::is_floating_point_v<Float>,\n                \"only makes sence for floating point types.\");\n  static constexpr Float in(Float x) { return x * x * x * x * x; }\n};\n\ntemplate <typename Float = float> struct expo {\n  static_assert(std::is_floating_point_v<Float>,\n                \"only makes sence for floating point types.\");\n  static constexpr Float in(Float x) {\n    return tolerance_compare::float_eq(x, Float(0.0))\n               ? 0.0\n               : std::pow(2.0, 10.0 * x - 10.0);\n  }\n};\n\ntemplate <typename Float = float> struct circ {\n  static_assert(std::is_floating_point_v<Float>,\n                \"only makes sence for floating point types.\");\n  static constexpr Float in(Float x) {\n    return 1.0 - std::sqrt(1.0 - std::pow(x, 2.0));\n  }\n};\n\ntemplate <typename Float = float> struct back {\n  static_assert(std::is_floating_point_v<Float>,\n                \"only makes sence for floating point types.\");\n  static constexpr Float in(Float x) {\n    constexpr Float c1 = 1.70158;\n    constexpr Float c3 = c1 + 1.0;\n    return c3 * x * x * x - c1 * x * x;\n  }\n};\n\ntemplate <typename Float = float> struct elastic {\n  static_assert(std::is_floating_point_v<Float>,\n                \"only makes sence for floating point types.\");\n  static constexpr Float in(Float x) {\n    constexpr Float c4 = boost::math::constants::two_pi<Float>() / 3.0;\n    return tolerance_compare::float_eq(x, Float(0.0))\n               ? 0.0\n               : tolerance_compare::float_eq(x, Float(1.0))\n                     ? 1.0\n                     : -std::pow(2.0, 10.0 * x - 10.0) *\n                           std::sin((x * 10 - 10.75) * c4);\n  }\n};\n\ntemplate <typename Float = float> struct bounce {\n  static_assert(std::is_floating_point_v<Float>,\n                \"only makes sence for floating point types.\");\n  static constexpr Float out(Float x) {\n    constexpr Float n1 = 7.5625;\n    constexpr Float d1 = 2.75;\n\n    if (x < 1 / d1) {\n      return n1 * x * x;\n    } else if (x < 2 / d1) {\n      return n1 * (x - 1.5 / d1) * (x - 1.5 / d1) + 0.75;\n    } else if (x < 2.5 / d1) {\n      return n1 * (x - 2.25 / d1) * (x - 2.25 / d1) + 0.9375;\n    } else {\n      return n1 * (x - 2.625 / d1) * (x - 2.625 / d1) + 0.984375;\n    }\n  }\n};\n\ntemplate <typename ease_type, typename param_type = float> struct ease {\n  static_assert(std::is_floating_point_v<param_type>,\n                \"only makes sence for floating point types.\");\n\n  static constexpr param_type in(param_type x) {\n    if constexpr (impl::has_in<ease_type, param_type>::value) {\n      return ease_type::in(x);\n    } else {\n      return 1.0 - out(1.0 - x);\n    }\n  }\n\n  static constexpr param_type out(param_type x) {\n    if constexpr (impl::has_in<ease_type, param_type>::value) {\n      return 1.0 - in(1.0 - x);\n    } else {\n      return ease_type::out(x);\n    }\n  }\n\n  static constexpr param_type inout(param_type x) {\n    return (x < 0.5) ? in(2.0 * x) * 0.5 : 0.5 + out(2.0 * x - 1.0) * 0.5;\n  }\n};\n\ntemplate <typename Float = float> constexpr Float linear(Float x) {\n  static_assert(std::is_floating_point_v<Float>,\n                \"only makes sence for floating point types.\");\n  return x;\n}\n\ntemplate <typename Float = float> constexpr Float ease_in(Float x) {\n  return ease<quad<Float>, Float>::in(x);\n}\n\ntemplate <typename Float = float> constexpr Float ease_out(Float x) {\n  return ease<quad<Float>, Float>::out(x);\n}\n\ntemplate <typename Float = float> constexpr Float ease_inout(Float x) {\n  return ease<quad<Float>, Float>::inout(x);\n}\n\n} // namespace easing\n\n#endif\n", "meta": {"hexsha": "e199b600cdc7d6a6aaa83a28606b5dbfef7d41c8", "size": 5049, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/easing/easing.hpp", "max_stars_repo_name": "mnrn/game-memo", "max_stars_repo_head_hexsha": "8ed939b8ccc77ba9266beddd6214a5c0c5cc03c2", "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": "include/easing/easing.hpp", "max_issues_repo_name": "mnrn/game-memo", "max_issues_repo_head_hexsha": "8ed939b8ccc77ba9266beddd6214a5c0c5cc03c2", "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": "include/easing/easing.hpp", "max_forks_repo_name": "mnrn/game-memo", "max_forks_repo_head_hexsha": "8ed939b8ccc77ba9266beddd6214a5c0c5cc03c2", "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": 31.1666666667, "max_line_length": 75, "alphanum_fraction": 0.6213111507, "num_tokens": 1394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.7981867705385762, "lm_q1q2_score": 0.7081549647050289}}
{"text": "//============================================================================\n// Name        : Poisson-Gleichung.cpp\n// Author      : \n// Version     :\n// Copyright   : Your copyright notice\n// Description : Hello World in C++, Ansi-style\n//============================================================================\n\n#define _USE_MATH_DEFINES\n\n#include <iostream>\n#include <stdio.h>\n#include <time.h>\n#include <random>\n#include <complex>\n#include <cstdlib>\n#include <vector>\n#include <cmath>\n#include <sstream>\n#include <utility>\n#include <math.h>\n#include <string>\n#include <fstream>\n#include <Eigen/Dense>\n\nusing namespace std;\n\nconst double Delta = 0.05;\nconst double L = 1;\nconst int N = L / Delta;\nconst double eps = 10e-5;\n\ndouble diff_phi(double phi_1, double phi_2) {\n\treturn (phi_1 - phi_2) / 2;\n}\n\nvoid plot_E(Eigen::MatrixXd phi) {\n\n\tofstream E_Vektorfeld;\n\tE_Vektorfeld.open(\"Vektorfeld.txt\");\n\tE_Vektorfeld.precision(10);\n\n\tofstream abs_E_Vektorfeld;\n\tabs_E_Vektorfeld.open(\"Vektorfeld_Betrag.txt\");\n\tabs_E_Vektorfeld.precision(10);\n\n\tEigen::MatrixXd E_x(N + 1, N + 1);\n\tEigen::MatrixXd E_y(N + 1, N + 1);\n\tEigen::MatrixXd E_ges(N + 1, N + 1);\n\n\tfor (int i = 1; i < N; i++) {\n\t\tfor (int j = 1; j < N; j++) {\n\n\t\t\tE_x(i, j) = diff_phi(phi(i + 1, j), phi(i - 1, j));\n\t\t\tE_y(i, j) = diff_phi(phi(i, j + 1), phi(i, j - 1));\n\t\t\tE_ges(i, j) = sqrt(E_x(i, j) * E_x(i, j) + E_y(i, j) * E_y(i, j));\n\n\t\t}\n\t}\n\n\tfor (int i = 0; i <= N; i++) {\n\t\tfor (int j = 0; j <= N; j++) {\n\t\t\tif (i == 0 || j == 0 || i == N || j == N)\n\t\t\t\tabs_E_Vektorfeld << i * Delta << \"\\t\" << j * Delta << \"\\t\" << 0\n\t\t\t\t\t\t<< \"\\n\";\n\t\t\telse {\n\t\t\t\tE_Vektorfeld << i * Delta << \"\\t\" << j * Delta << \"\\t\"\n\t\t\t\t\t\t<< -E_x(i, j) << \"\\t\" << -E_y(i, j) << \"\\n\";\n\t\t\t\tabs_E_Vektorfeld << i * Delta << \"\\t\" << j * Delta << \"\\t\"\n\t\t\t\t\t\t<< E_ges(i, j) << \"\\n\";\n\t\t\t}\n\t\t}\n\t}\n\n\tE_Vektorfeld.close();\n}\n\nvoid Phi_ana(int n_sum) {\n\n\tofstream Poissongleichung_analytisch;\n\tPoissongleichung_analytisch.open(\"Poissongleichung_Analytisch.txt\");\n\tPoissongleichung_analytisch.precision(10);\n\n\tEigen::MatrixXd Phi(N + 1, N + 1);\n\n\tfor (int i = 0; i <= N; i++) {\n\t\tfor (int j = 0; j <= N; j++) {\n\t\t\tPhi(i, j) = 0;\n\t\t\tfor (int n = 1; n <= n_sum; n++) {\n\t\t\t\tPhi(i, j) += (2 * (1 - cos(n * M_PI)))\n\t\t\t\t\t\t/ (n * M_PI * sinh(n * M_PI))\n\t\t\t\t\t\t* sin(n * M_PI * i * Delta)\n\t\t\t\t\t\t* sinh(n * M_PI * j * Delta);\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (int i = 0; i <= N; i++) {\n\t\tfor (int j = 0; j <= N; j++) {\n\t\t\tPoissongleichung_analytisch << i * Delta << \"\\t\" << j * Delta\n\t\t\t\t\t<< \"\\t\" << Phi(i, j) << \"\\n\";\n\t\t}\n\t}\n\tPoissongleichung_analytisch.close();\n}\n\nEigen::MatrixXd Init_Rho() {\n\tEigen::MatrixXd rho(N, N);\n\n\trho(N/2,N/2) = 1.;\n\n\t//cout << rho << \"\\n\";\n\n\treturn rho;\n}\n\nEigen::MatrixXd Init_Phi() {\n\n\tEigen::MatrixXd Phi(N + 1, N + 1);\n\n\tfor (int i = 0; i <= N; i++) {\n\t\tfor (int j = 0; j <= N; j++) {\n\t\t\tif (j == N)\n\t\t\t\tPhi(i, j) = 0;\n\t\t\telse\n\t\t\t\tPhi(i, j) = 0;\n\t\t}\n\t}\n\n\treturn Phi;\n}\n\nEigen::MatrixXd Gauss_Seidel(Eigen::MatrixXd Phi, Eigen::MatrixXd rho) {\n\n\tfor (int j = 1; j < N; j++) {\n\t\tfor (int l = 1; l < N; l++) {\n\t\t\tPhi(j, l) = 0.25\n\t\t\t\t\t* ((Phi(j + 1, l) + Phi(j - 1, l) + Phi(j, l + 1)\n\t\t\t\t\t\t\t+ Phi(j, l - 1)) + rho(j, l));\n\t\t}\n\t}\n\treturn Phi;\n}\n\nvoid Poisson() {\n\n\tofstream Poissongleichung;\n\tPoissongleichung.open(\"Poissongleichung.txt\");\n\tPoissongleichung.precision(10);\n\n\tEigen::MatrixXd Phi = Init_Phi();\n\tEigen::MatrixXd Rho = Init_Rho();\n\n\tfor (int i = 0; i < 5000; i++) {\n\n\t\tPhi = Gauss_Seidel(Phi, Rho);\n\n\t}\n\n\tfor (int i = 0; i <= N; i++) {\n\t\tfor (int j = 0; j <= N; j++) {\n\t\t\tPoissongleichung << i * Delta << \"\\t\" << j * Delta << \"\\t\"\n\t\t\t\t\t<< Phi(i, j) << \"\\n\";\n\t\t}\n\t}\n\n\tplot_E(Phi);\n\n\tPoissongleichung.close();\n}\n\n\nvoid Poisson_2() {\n\n\tofstream Poissongleichung;\n\tPoissongleichung.open(\"Poissongleichung.txt\");\n\tPoissongleichung.precision(10);\n\n\tEigen::MatrixXd Phi1 = Init_Phi();\n\tEigen::MatrixXd Phi2(N+1,N+1);\n\tEigen::MatrixXd Rho = Init_Rho();\n\n\tint cnt = 0;\n\n\twhile (cnt < (N+1)*(N+1)) {\n\n\t\tcnt = 0;\n\n\t\tPhi2 = Phi1;\n\t\tPhi1 = Gauss_Seidel(Phi1, Rho);\n\n\t\tPhi2 = Phi2 - Phi1;\n\t\tfor(int i = 0; i <= N; i++) {\n\t\t\tfor(int j = 0; j <= N; j++) {\n\t\t\t\tif(abs(Phi2(i,j)) < eps) cnt += 1;\n\t\t\t}\n\t\t}\n\t\tcout << cnt << \"\\n\";\n\t}\n\n\tfor (int i = 0; i <= N; i++) {\n\t\tfor (int j = 0; j <= N; j++) {\n\t\t\tPoissongleichung << i * Delta << \"\\t\" << j * Delta << \"\\t\"\n\t\t\t\t\t<< Phi1(i, j) << \"\\n\";\n\t\t}\n\t}\n\n\tplot_E(Phi1);\n\n\tPoissongleichung.close();\n\n}\n\nint main() {\n\n\tPoisson_2();\n\t//Phi_ana(200);\n\n\treturn 0;\n}\n", "meta": {"hexsha": "842fcc88bd5100d30e258c787ba000a451eee602", "size": 4434, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Blatt_06/Abgabe_FelixMarcelRigo/Code/CP_06_02.cpp", "max_stars_repo_name": "KevSed/Computational_Physics", "max_stars_repo_head_hexsha": "6ebfcd07ae5ceb2bfe5b429e8d1425b6877037d1", "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": "Blatt_06/Abgabe_FelixMarcelRigo/Code/CP_06_02.cpp", "max_issues_repo_name": "KevSed/Computational_Physics", "max_issues_repo_head_hexsha": "6ebfcd07ae5ceb2bfe5b429e8d1425b6877037d1", "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": "Blatt_06/Abgabe_FelixMarcelRigo/Code/CP_06_02.cpp", "max_forks_repo_name": "KevSed/Computational_Physics", "max_forks_repo_head_hexsha": "6ebfcd07ae5ceb2bfe5b429e8d1425b6877037d1", "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": 20.0633484163, "max_line_length": 78, "alphanum_fraction": 0.5182679296, "num_tokens": 1655, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951552333004, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.708079389182089}}
{"text": "//\n// Copyright (c) 2019-2020 INRIA\n//\n\n#include <pinocchio/math/rpy.hpp>\n#include <pinocchio/math/quaternion.hpp>\n\n#include <boost/variant.hpp> // to avoid C99 warnings\n\n#include <boost/test/unit_test.hpp>\n#include <boost/utility/binary.hpp>\n\nBOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE)\n\nBOOST_AUTO_TEST_CASE(test_rpyToMatrix)\n{\n  const int n = 1e5;\n  for(int k = 0; k < n ; ++k)\n  {\n    double r = static_cast <double> (rand()) / (static_cast <double> (RAND_MAX/(2*M_PI))) - M_PI;\n    double p = static_cast <double> (rand()) / (static_cast <double> (RAND_MAX/M_PI)) - (M_PI/2);\n    double y = static_cast <double> (rand()) / (static_cast <double> (RAND_MAX/(2*M_PI))) - M_PI;\n    \n    Eigen::Matrix3d R = pinocchio::rpy::rpyToMatrix(r, p, y);\n    \n    Eigen::Matrix3d Raa = (Eigen::AngleAxisd(y, Eigen::Vector3d::UnitZ())\n                             * Eigen::AngleAxisd(p, Eigen::Vector3d::UnitY())\n                             * Eigen::AngleAxisd(r, Eigen::Vector3d::UnitX())\n                             ).toRotationMatrix();\n    \n    BOOST_CHECK(R.isApprox(Raa));\n    \n    Eigen::Vector3d v;\n    v << r, p, y;\n    \n    Eigen::Matrix3d Rv = pinocchio::rpy::rpyToMatrix(v);\n    \n    BOOST_CHECK(Rv.isApprox(Raa));\n    BOOST_CHECK(Rv.isApprox(R));\n  }\n}\n\nBOOST_AUTO_TEST_CASE(test_matrixToRpy)\n{\n  const int n = 1e6;\n  for(int k = 0; k < n ; ++k)\n  {\n    Eigen::Quaterniond quat;\n    pinocchio::quaternion::uniformRandom(quat);\n    const Eigen::Matrix3d R = quat.toRotationMatrix();\n\n    const Eigen::Vector3d v = pinocchio::rpy::matrixToRpy(R);\n    Eigen::Matrix3d Rprime = pinocchio::rpy::rpyToMatrix(v);\n\n    BOOST_CHECK(Rprime.isApprox(R));\n    BOOST_CHECK(-M_PI <= v[0] && v[0] <= M_PI);\n    BOOST_CHECK(-M_PI/2 <= v[1] && v[1] <= M_PI/2);\n    BOOST_CHECK(-M_PI <= v[2] && v[2] <= M_PI);\n  }\n\n  const int n2 = 1e3;\n\n  // Test singular case theta = pi/2\n  for(int k = 0; k < n2 ; ++k)\n  {\n    double r = static_cast <double> (rand()) / (static_cast <double> (RAND_MAX/(2*M_PI))) - M_PI;\n    double y = static_cast <double> (rand()) / (static_cast <double> (RAND_MAX/(2*M_PI))) - M_PI;\n    Eigen::Matrix3d Rp;\n    Rp <<  0.0, 0.0, 1.0,\n           0.0, 1.0, 0.0,\n          -1.0, 0.0, 0.0;\n    const Eigen::Matrix3d R = Eigen::AngleAxisd(y, Eigen::Vector3d::UnitZ()).toRotationMatrix()\n                            * Rp\n                            * Eigen::AngleAxisd(r, Eigen::Vector3d::UnitX()).toRotationMatrix();\n\n    const Eigen::Vector3d v = pinocchio::rpy::matrixToRpy(R);\n    Eigen::Matrix3d Rprime = pinocchio::rpy::rpyToMatrix(v);\n\n    BOOST_CHECK(Rprime.isApprox(R));\n    BOOST_CHECK(-M_PI <= v[0] && v[0] <= M_PI);\n    BOOST_CHECK(-M_PI/2 <= v[1] && v[1] <= M_PI/2);\n    BOOST_CHECK(-M_PI <= v[2] && v[2] <= M_PI);\n  }\n\n  // Test singular case theta = -pi/2\n  for(int k = 0; k < n2 ; ++k)\n  {\n    double r = static_cast <double> (rand()) / (static_cast <double> (RAND_MAX/(2*M_PI))) - M_PI;\n    double y = static_cast <double> (rand()) / (static_cast <double> (RAND_MAX/(2*M_PI))) - M_PI;\n    Eigen::Matrix3d Rp;\n    Rp << 0.0, 0.0, -1.0,\n          0.0, 1.0,  0.0,\n          1.0, 0.0,  0.0;\n    const Eigen::Matrix3d R = Eigen::AngleAxisd(y, Eigen::Vector3d::UnitZ()).toRotationMatrix()\n                            * Rp\n                            * Eigen::AngleAxisd(r, Eigen::Vector3d::UnitX()).toRotationMatrix();\n\n    const Eigen::Vector3d v = pinocchio::rpy::matrixToRpy(R);\n    Eigen::Matrix3d Rprime = pinocchio::rpy::rpyToMatrix(v);\n\n    BOOST_CHECK(Rprime.isApprox(R));\n    BOOST_CHECK(-M_PI <= v[0] && v[0] <= M_PI);\n    BOOST_CHECK(-M_PI/2 <= v[1] && v[1] <= M_PI/2);\n    BOOST_CHECK(-M_PI <= v[2] && v[2] <= M_PI);\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "be299cd97c90fdaf9ef45c14254fe0b1c4d1826d", "size": 3675, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/rpy.cpp", "max_stars_repo_name": "ikalevatykh/pinocchio", "max_stars_repo_head_hexsha": "2c22ca240e78e5a6c20e7b2cb6c44e7a45658d38", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unittest/rpy.cpp", "max_issues_repo_name": "ikalevatykh/pinocchio", "max_issues_repo_head_hexsha": "2c22ca240e78e5a6c20e7b2cb6c44e7a45658d38", "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": "unittest/rpy.cpp", "max_forks_repo_name": "ikalevatykh/pinocchio", "max_forks_repo_head_hexsha": "2c22ca240e78e5a6c20e7b2cb6c44e7a45658d38", "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": 33.7155963303, "max_line_length": 97, "alphanum_fraction": 0.5806802721, "num_tokens": 1235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505248181417, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.7080360269263073}}
{"text": "//  (C) Copyright Raffi Enficiaud 2014.\r\n//  Distributed under the Boost Software License, Version 1.0.\r\n//  (See accompanying file LICENSE_1_0.txt or copy at\r\n//  http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//  See http://www.boost.org/libs/test for the library home page.\r\n\r\n//[example_code\r\n#define BOOST_TEST_MODULE dataset_example63\r\n#include <boost/test/included/unit_test.hpp>\r\n#include <boost/test/data/test_case.hpp>\r\n#include <boost/test/data/monomorphic.hpp>\r\n\r\nnamespace bdata = boost::unit_test::data;\r\n\r\n\r\nBOOST_DATA_TEST_CASE( \r\n  test1, \r\n  bdata::random(1, 17) ^ bdata::xrange(7), \r\n  random_sample, index )\r\n{\r\n  std::cout << \"test 1: \" << random_sample \r\n            << \", \" << index << std::endl;\r\n  BOOST_TEST((random_sample <= 17 && random_sample >= 1));\r\n}\r\n\r\nBOOST_DATA_TEST_CASE( \r\n  test2, \r\n  bdata::random( (bdata::distribution=std::uniform_real_distribution<float>(1, 2)) ) \r\n      ^ bdata::xrange(7),\r\n  random_sample, index )\r\n{\r\n  std::cout << \"test 2: \" << random_sample \r\n            << \", \" << index << std::endl;\r\n  BOOST_TEST(random_sample < 1.7); // 30% chance of failure\r\n}\r\n//]\r\n", "meta": {"hexsha": "4857f49ebc512a92666560e1f45e1220ca247040", "size": 1116, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/test/doc/examples/dataset_example63.run-fail.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/test/doc/examples/dataset_example63.run-fail.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/test/doc/examples/dataset_example63.run-fail.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": 29.3684210526, "max_line_length": 86, "alphanum_fraction": 0.6460573477, "num_tokens": 314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026573249612, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.7080140867925679}}
{"text": "//// Copyright (c) 2018 Silvio Mayolo\n//// See LICENSE.txt for licensing details\n\n#include \"catch2/catch.hpp\"\n#include \"Number.hpp\"\n#include <boost/optional.hpp>\n#include <boost/optional/optional_io.hpp>\n#include <string>\n#include <complex>\n#include <limits>\n\nTEST_CASE( \"Number construction\", \"[number]\" ) {\n  REQUIRE( Number((Number::smallint)0).hierarchyLevel() == Number::SMALLINT );\n  REQUIRE( Number((Number::bigint)10).hierarchyLevel() == Number::BIGINT );\n  REQUIRE( Number( Number::ratio(1, 2) ).hierarchyLevel() == Number::RATIO );\n  REQUIRE( Number(3.0).hierarchyLevel() == Number::FLOATING );\n  REQUIRE( Number(1+1i).hierarchyLevel() == Number::COMPLEX );\n\n  Number a { (Number::smallint)10 };\n  Number b = a;\n\n  REQUIRE( a == b );\n\n}\n\nTEST_CASE( \"Number equality and comparison\", \"[number]\" ) {\n\n  Number smallZero { (Number::smallint)0 };\n  Number   bigZero { (Number::bigint)  0 };\n\n  Number   intOne { (Number::bigint) 1  };\n  Number ratioOne { Number::ratio(1, 1) };\n\n  Number floatingOne { 1.0 };\n\n  REQUIRE( smallZero == smallZero );\n  REQUIRE(   bigZero ==   bigZero );\n  REQUIRE( smallZero ==   bigZero );\n  REQUIRE( smallZero !=    intOne );\n  REQUIRE(  ratioOne ==    intOne );\n  REQUIRE(  ratioOne ==  ratioOne );\n\n  REQUIRE(   smallZero <      intOne );\n  REQUIRE(     bigZero <      intOne );\n  REQUIRE(   smallZero <    ratioOne );\n  REQUIRE(      intOne >   smallZero );\n  REQUIRE(     bigZero < floatingOne );\n  REQUIRE(         0.0 < floatingOne );\n  REQUIRE( floatingOne <         2.0 );\n\n}\n\nTEST_CASE( \"Number addition and subtraction\", \"[number]\" ) {\n\n  Number    small { (Number::smallint)1 };\n  Number      big { (Number::bigint)  1 };\n  Number    ratio { Number::ratio(1, 1) };\n  Number floating {                1.0  };\n  Number  complex {          1.0 + 0.0i };\n\n  SECTION( \"Addition and subtraction behave correctly\" ) {\n    REQUIRE( small + small == 2l );\n    REQUIRE( small +   big == 2l );\n    REQUIRE( small + ratio == 2l );\n    REQUIRE(   big +   big == 2l );\n    REQUIRE(   big + ratio == 2l );\n    REQUIRE( ratio + ratio == 2l );\n    REQUIRE( small - small == 0l );\n    REQUIRE( small -   big == 0l );\n    REQUIRE( small - ratio == 0l );\n    REQUIRE(   big -   big == 0l );\n    REQUIRE(   big - ratio == 0l );\n    REQUIRE( ratio - ratio == 0l );\n  }\n\n  SECTION( \"Negation behaves correctly\" ) {\n    REQUIRE( -small == -1l );\n    REQUIRE( -  big == -1l );\n    REQUIRE( -ratio == -1l );\n  }\n\n  SECTION( \"Addition and subtraction coerce to the larger type\" ) {\n    REQUIRE( (   small +    small).hierarchyLevel() == Number::SMALLINT );\n    REQUIRE( (   small +      big).hierarchyLevel() == Number::BIGINT   );\n    REQUIRE( (   small +    ratio).hierarchyLevel() == Number::RATIO    );\n    REQUIRE( (   small + floating).hierarchyLevel() == Number::FLOATING );\n    REQUIRE( (   small +  complex).hierarchyLevel() == Number::COMPLEX  );\n    REQUIRE( (   small -    small).hierarchyLevel() == Number::SMALLINT );\n    REQUIRE( (   small -      big).hierarchyLevel() == Number::BIGINT   );\n    REQUIRE( (   small -    ratio).hierarchyLevel() == Number::RATIO    );\n    REQUIRE( (   small - floating).hierarchyLevel() == Number::FLOATING );\n    REQUIRE( (   small -  complex).hierarchyLevel() == Number::COMPLEX  );\n  }\n\n  SECTION( \"Overflows are detected\" ) {\n    Number maximum { std::numeric_limits<Number::smallint>::max() };\n    REQUIRE( (maximum - small).hierarchyLevel() == Number::SMALLINT );\n    REQUIRE( (maximum + small).hierarchyLevel() == Number::BIGINT   );\n  }\n\n}\n\nTEST_CASE( \"Number multiplication\", \"[number]\" ) {\n\n  Number    small { (Number::smallint)2 };\n  Number      big { (Number::bigint)  2 };\n  Number    ratio { Number::ratio(2, 1) };\n  Number floating {                2.0  };\n  Number  complex {          2.0 + 0.0i };\n\n  SECTION( \"Multiplication behaves correctly\" ) {\n    REQUIRE( small * small == 4l );\n    REQUIRE( small *   big == 4l );\n    REQUIRE( small * ratio == 4l );\n    REQUIRE(   big *   big == 4l );\n    REQUIRE(   big * ratio == 4l );\n    REQUIRE( ratio * ratio == 4l );\n  }\n\n  SECTION( \"Multiplication coerces to the larger type\" ) {\n    REQUIRE( (   small *    small).hierarchyLevel() == Number::SMALLINT );\n    REQUIRE( (   small *      big).hierarchyLevel() == Number::BIGINT   );\n    REQUIRE( (   small *    ratio).hierarchyLevel() == Number::RATIO    );\n    REQUIRE( (   small * floating).hierarchyLevel() == Number::FLOATING );\n    REQUIRE( (   small *  complex).hierarchyLevel() == Number::COMPLEX  );\n  }\n\n  SECTION( \"Overflows are detected\" ) {\n    Number maximum { std::numeric_limits<Number::smallint>::max() };\n    Number one { (Number::smallint)1 };\n    REQUIRE( (maximum *   one).hierarchyLevel() == Number::SMALLINT );\n    REQUIRE( (maximum * small).hierarchyLevel() == Number::BIGINT   );\n  }\n\n}\n\nTEST_CASE( \"Numerical division and reciprocation\", \"[number]\" ) {\n\n  Number    smallOne { (Number::smallint)1 };\n  Number      bigOne { (Number::bigint)  1 };\n  Number    ratioOne { Number::ratio(1, 1) };\n  Number floatingOne {                1.0  };\n  Number  complexOne {          1.0 + 0.0i };\n\n  Number    smallTwo { (Number::smallint)2 };\n  Number      bigTwo { (Number::bigint)  2 };\n  Number    ratioTwo { Number::ratio(2, 1) };\n  Number floatingTwo {                2.0  };\n  Number  complexTwo {          2.0 + 0.0i };\n\n  SECTION( \"Division and reciprocation behave correctly\" ) {\n    REQUIRE( (smallOne / smallTwo) == Number::ratio(1, 2) );\n    REQUIRE( (  bigOne / smallTwo) == Number::ratio(1, 2) );\n    REQUIRE( (  bigOne /   bigTwo) == Number::ratio(1, 2) );\n    REQUIRE( (smallOne /   bigTwo) == Number::ratio(1, 2) );\n    REQUIRE( (  bigTwo / smallOne) == Number::ratio(2, 1) );\n    REQUIRE( (ratioTwo / ratioOne) == Number::ratio(2, 1) );\n  }\n\n  SECTION( \"Reciprocation widens appropriately\" ) {\n    REQUIRE(    smallOne.recip().hierarchyLevel() == Number::RATIO    );\n    REQUIRE(      bigOne.recip().hierarchyLevel() == Number::RATIO    );\n    REQUIRE(    ratioOne.recip().hierarchyLevel() == Number::RATIO    );\n    REQUIRE( floatingOne.recip().hierarchyLevel() == Number::FLOATING );\n    REQUIRE(  complexOne.recip().hierarchyLevel() == Number::COMPLEX  );\n  }\n\n  SECTION( \"Division widens appropriately\" ) {\n    REQUIRE( (   smallOne /    smallOne).hierarchyLevel() == Number::RATIO    );\n    REQUIRE( (   smallOne /      bigOne).hierarchyLevel() == Number::RATIO    );\n    REQUIRE( (   smallOne /    ratioOne).hierarchyLevel() == Number::RATIO    );\n    REQUIRE( (   smallOne / floatingOne).hierarchyLevel() == Number::FLOATING );\n    REQUIRE( (   smallOne /  complexOne).hierarchyLevel() == Number::COMPLEX  );\n  }\n\n}\n\nTEST_CASE( \"Numerical modulo\", \"[number]\" ) {\n\n  Number    small { (Number::smallint)3 };\n  Number      big { (Number::bigint)  3 };\n  Number    ratio { Number::ratio(3, 1) };\n  Number floating {                3.0  };\n  Number  complex {          3.0 + 0.0i };\n\n  SECTION( \"Modulo behaves correctly\" ) {\n    REQUIRE( (small % 2l) == 1l );\n    REQUIRE( (  big % 2l) == 1l );\n    REQUIRE( (ratio % 2l) == 1l );\n  }\n\n  SECTION( \"Modulo widens appropriately\" ) {\n    REQUIRE( (   small %    small).hierarchyLevel() == Number::SMALLINT );\n    REQUIRE( (   small %      big).hierarchyLevel() == Number::BIGINT   );\n    REQUIRE( (   small %    ratio).hierarchyLevel() == Number::RATIO    );\n    REQUIRE( (   small % floating).hierarchyLevel() == Number::FLOATING );\n    REQUIRE( (   small %  complex).hierarchyLevel() == Number::COMPLEX  );\n  }\n\n  SECTION( \"Modulo behaves correctly given negative numbers\" ) {\n    REQUIRE( ( small %  2l) ==  1l );\n    REQUIRE( ( small % -2l) == -1l );\n    REQUIRE( (-small %  2l) ==  1l );\n    REQUIRE( (-small % -2l) == -1l );\n    REQUIRE( (   big %  2l) ==  1l );\n    REQUIRE( (   big % -2l) == -1l );\n    REQUIRE( (-  big %  2l) ==  1l );\n    REQUIRE( (-  big % -2l) == -1l );\n    REQUIRE( ( ratio %  2l) ==  1l );\n    REQUIRE( ( ratio % -2l) == -1l );\n    REQUIRE( (-ratio %  2l) ==  1l );\n    REQUIRE( (-ratio % -2l) == -1l );\n  }\n\n  SECTION( \"Modulo handles rational results\" ) {\n    Number a { Number::ratio(3, 2) };\n    Number b { 2l };\n    REQUIRE( b % a == Number::ratio(1, 2) );\n  }\n\n}\n\n\nTEST_CASE( \"Exponents\", \"[number]\" ) {\n\n  Number    small { (Number::smallint)3 };\n  Number      big { (Number::bigint)  3 };\n  Number    ratio { Number::ratio(3, 1) };\n  Number floating {                3.0  };\n  Number  complex {          3.0 + 0.0i };\n\n  SECTION( \"Exponents behave correctly\" ) {\n    REQUIRE( (small.pow(small)) == 27l );\n    REQUIRE( (  big.pow(  big)) == 27l );\n    REQUIRE( (ratio.pow(small)) == 27l );\n  }\n\n  SECTION( \"Exponentiation respects the convoluted casting rules\" ) {\n    REQUIRE( (   small.pow(     small)).hierarchyLevel() == Number::BIGINT   );\n    REQUIRE( (   small.pow(       big)).hierarchyLevel() == Number::BIGINT   );\n    REQUIRE( (   small.pow(     ratio)).hierarchyLevel() == Number::FLOATING );\n    REQUIRE( (   small.pow(  floating)).hierarchyLevel() == Number::FLOATING );\n    REQUIRE( (   small.pow(   complex)).hierarchyLevel() == Number::COMPLEX  );\n    REQUIRE( (     big.pow(     small)).hierarchyLevel() == Number::BIGINT   );\n    REQUIRE( (     big.pow(       big)).hierarchyLevel() == Number::BIGINT   );\n    REQUIRE( (     big.pow(     ratio)).hierarchyLevel() == Number::FLOATING );\n    REQUIRE( (     big.pow(  floating)).hierarchyLevel() == Number::FLOATING );\n    REQUIRE( (     big.pow(   complex)).hierarchyLevel() == Number::COMPLEX  );\n    REQUIRE( (   ratio.pow(     small)).hierarchyLevel() == Number::RATIO    );\n    REQUIRE( (   ratio.pow(       big)).hierarchyLevel() == Number::RATIO    );\n    REQUIRE( (   ratio.pow(     ratio)).hierarchyLevel() == Number::FLOATING );\n    REQUIRE( (   ratio.pow(  floating)).hierarchyLevel() == Number::FLOATING );\n    REQUIRE( (   ratio.pow(   complex)).hierarchyLevel() == Number::COMPLEX  );\n    REQUIRE( (floating.pow(     small)).hierarchyLevel() == Number::FLOATING );\n    REQUIRE( (floating.pow(       big)).hierarchyLevel() == Number::FLOATING );\n    REQUIRE( (floating.pow(     ratio)).hierarchyLevel() == Number::FLOATING );\n    REQUIRE( (floating.pow(  floating)).hierarchyLevel() == Number::FLOATING );\n    REQUIRE( (floating.pow(   complex)).hierarchyLevel() == Number::COMPLEX  );\n    REQUIRE( ( complex.pow(     small)).hierarchyLevel() == Number::COMPLEX  );\n    REQUIRE( ( complex.pow(       big)).hierarchyLevel() == Number::COMPLEX  );\n    REQUIRE( ( complex.pow(     ratio)).hierarchyLevel() == Number::COMPLEX  );\n    REQUIRE( ( complex.pow(  floating)).hierarchyLevel() == Number::COMPLEX  );\n    REQUIRE( ( complex.pow(   complex)).hierarchyLevel() == Number::COMPLEX  );\n    REQUIRE( (   small.pow(-    small)).hierarchyLevel() == Number::RATIO    );\n    REQUIRE( (   small.pow(-      big)).hierarchyLevel() == Number::RATIO    );\n    REQUIRE( (   small.pow(-    ratio)).hierarchyLevel() == Number::FLOATING );\n    REQUIRE( (   small.pow(- floating)).hierarchyLevel() == Number::FLOATING );\n    REQUIRE( (     big.pow(-    small)).hierarchyLevel() == Number::RATIO    );\n    REQUIRE( (     big.pow(-      big)).hierarchyLevel() == Number::RATIO    );\n    REQUIRE( (     big.pow(-    ratio)).hierarchyLevel() == Number::FLOATING );\n    REQUIRE( (     big.pow(- floating)).hierarchyLevel() == Number::FLOATING );\n    REQUIRE( (   ratio.pow(-    small)).hierarchyLevel() == Number::RATIO    );\n    REQUIRE( (   ratio.pow(-      big)).hierarchyLevel() == Number::RATIO    );\n    REQUIRE( (   ratio.pow(-    ratio)).hierarchyLevel() == Number::FLOATING );\n    REQUIRE( (   ratio.pow(- floating)).hierarchyLevel() == Number::FLOATING );\n    REQUIRE( (floating.pow(-    small)).hierarchyLevel() == Number::FLOATING );\n    REQUIRE( (floating.pow(-      big)).hierarchyLevel() == Number::FLOATING );\n    REQUIRE( (floating.pow(-    ratio)).hierarchyLevel() == Number::FLOATING );\n    REQUIRE( (floating.pow(- floating)).hierarchyLevel() == Number::FLOATING );\n    REQUIRE( ( complex.pow(-    small)).hierarchyLevel() == Number::COMPLEX  );\n    REQUIRE( ( complex.pow(-      big)).hierarchyLevel() == Number::COMPLEX  );\n    REQUIRE( ( complex.pow(-    ratio)).hierarchyLevel() == Number::COMPLEX  );\n    REQUIRE( ( complex.pow(- floating)).hierarchyLevel() == Number::COMPLEX  );\n    REQUIRE( ( complex.pow(   complex)).hierarchyLevel() == Number::COMPLEX  );\n  }\n\n}\n\n// We could test the bitwise operators and trig functions here (also,\n// log). But what is there really to test? They literally just\n// delegate down to the C++ system calls.\n\nTEST_CASE( \"Floor function\", \"[number]\" ) {\n\n  Number    small { (Number::smallint)3 };\n  Number      big { (Number::bigint)  3 };\n  Number    ratio { Number::ratio(7, 2) };\n  Number floating {                3.5  };\n\n  SECTION( \"Floor behaves correctly\" ) {\n    REQUIRE(    small.floor() == 3l );\n    REQUIRE(      big.floor() == 3l );\n    REQUIRE(    ratio.floor() == 3l );\n    REQUIRE( floating.floor() == 3l );\n  }\n\n  SECTION( \"Floor can narrow the type\" ) {\n    REQUIRE(   small.floor().hierarchyLevel() == Number::SMALLINT );\n    REQUIRE(     big.floor().hierarchyLevel() == Number::BIGINT   );\n    REQUIRE(   ratio.floor().hierarchyLevel() == Number::BIGINT   );\n    REQUIRE(floating.floor().hierarchyLevel() == Number::BIGINT   );\n  }\n\n}\n\nTEST_CASE( \"Parts of complex numbers\", \"[number]\" ) {\n\n  Number complex0 { 1 + 2i };\n  Number complex1 = complexNumber(1l, 2l);\n\n  REQUIRE( complex0 == complex1 );\n  REQUIRE( complex0.realPart() == 1l );\n  REQUIRE( complex0.imagPart() == 2l );\n  REQUIRE( complex1.realPart() == 1l );\n  REQUIRE( complex1.imagPart() == 2l );\n\n  REQUIRE( complex0.realPart().hierarchyLevel() == Number::FLOATING );\n  REQUIRE( complex0.imagPart().hierarchyLevel() == Number::FLOATING );\n  REQUIRE( complex1.realPart().hierarchyLevel() == Number::FLOATING );\n  REQUIRE( complex1.imagPart().hierarchyLevel() == Number::FLOATING );\n\n}\n\n// Constants like epsilon, infinity, NaN could be tested for certain\n// properties?\n\nTEST_CASE( \"Parsing integers\", \"[number]\" ) {\n\n  REQUIRE( parseInteger(\"D300\") == Number(300l) );\n  REQUIRE( parseInteger(\"X12C\") == Number(300l) );\n  REQUIRE( parseInteger(\"B100101100\") == Number(300l) );\n  REQUIRE( parseInteger(\"O454\") == Number(300l) );\n  REQUIRE( parseInteger(\"B112\") == boost::none );\n  REQUIRE( parseInteger(\"D+300\") == Number(300l) );\n  REQUIRE( parseInteger(\"X+12C\") == Number(300l) );\n  REQUIRE( parseInteger(\"B+100101100\") == Number(300l) );\n  REQUIRE( parseInteger(\"O+454\") == Number(300l) );\n  REQUIRE( parseInteger(\"B+112\") == boost::none );\n  REQUIRE( parseInteger(\"D-300\") == Number(-300l) );\n  REQUIRE( parseInteger(\"X-12C\") == Number(-300l) );\n  REQUIRE( parseInteger(\"B-100101100\") == Number(-300l) );\n  REQUIRE( parseInteger(\"O-454\") == Number(-300l) );\n  REQUIRE( parseInteger(\"B-112\") == boost::none );\n\n}\n", "meta": {"hexsha": "fdba8f415568e8ae229698ddca5873f760d8ee41", "size": 14820, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_Number.cpp", "max_stars_repo_name": "Mercerenies/latitude", "max_stars_repo_head_hexsha": "29b1697f1f615d52480197a52e20ff8c1872f07d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-09-02T18:19:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-26T23:33:32.000Z", "max_issues_repo_path": "test/test_Number.cpp", "max_issues_repo_name": "Mercerenies/latitude", "max_issues_repo_head_hexsha": "29b1697f1f615d52480197a52e20ff8c1872f07d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 45.0, "max_issues_repo_issues_event_min_datetime": "2017-11-28T15:13:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-19T18:45:46.000Z", "max_forks_repo_path": "test/test_Number.cpp", "max_forks_repo_name": "Mercerenies/proto-lang", "max_forks_repo_head_hexsha": "29b1697f1f615d52480197a52e20ff8c1872f07d", "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.6292134831, "max_line_length": 80, "alphanum_fraction": 0.5925775978, "num_tokens": 4289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916205190225, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.7078890340473036}}
{"text": "/*\n * Copyright Nick Thompson, 2020\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#include <iostream>\n#include <boost/core/demangle.hpp>\n#include <boost/hana/for_each.hpp>\n#include <boost/hana/ext/std/integer_sequence.hpp>\n\n#include <boost/multiprecision/float128.hpp>\n#include <boost/math/special_functions/daubechies_wavelet.hpp>\n#include <quicksvg/graph_fn.hpp>\n#include <quicksvg/ulp_plot.hpp>\n\n\nusing boost::multiprecision::float128;\nconstexpr const int GRAPH_WIDTH = 700;\n\ntemplate<typename Real, int p>\nvoid plot_psi(int grid_refinements = -1)\n{\n    auto psi = boost::math::daubechies_wavelet<Real, p>();\n    if (grid_refinements >= 0)\n    {\n        psi = boost::math::daubechies_wavelet<Real, p>(grid_refinements);\n    }\n    auto [a, b] = psi.support();\n    std::string title = \"Daubechies \" + std::to_string(p) + \" wavelet\";\n    title = \"\";\n    std::string filename = \"daubechies_\" + std::to_string(p) + \"_wavelet.svg\";\n    int samples = 1024;\n    quicksvg::graph_fn daub(a, b, title, filename, samples, GRAPH_WIDTH);\n    daub.set_gridlines(8, 2*p-1);\n    daub.set_stroke_width(1);\n    daub.add_fn(psi);\n    daub.write_all();\n}\n\ntemplate<typename Real, int p>\nvoid plot_dpsi(int grid_refinements = -1)\n{\n    auto psi = boost::math::daubechies_wavelet<Real, p>();\n    if (grid_refinements >= 0)\n    {\n        psi = boost::math::daubechies_wavelet<Real, p>(grid_refinements);\n    }\n    auto [a, b] = psi.support();\n    std::string title = \"Daubechies \" + std::to_string(p) + \" wavelet derivative\";\n    title = \"\";\n    std::string filename = \"daubechies_\" + std::to_string(p) + \"_wavelet_prime.svg\";\n    int samples = 1024;\n    quicksvg::graph_fn daub(a, b, title, filename, samples, GRAPH_WIDTH);\n    daub.set_stroke_width(1);\n    daub.set_gridlines(8, 2*p-1);\n    auto dpsi = [psi](Real x)->Real { return psi.prime(x); };\n    daub.add_fn(dpsi);\n    daub.write_all();\n}\n\ntemplate<typename Real, int p>\nvoid plot_convergence()\n{\n    auto psi1 = boost::math::daubechies_wavelet<Real, p>(1);\n    auto [a, b] = psi1.support();\n    std::string title = \"Daubechies \" + std::to_string(p) + \" wavelet at  1 (orange), 2 (red), and 21 (blue) grid refinements\";\n    title = \"\";\n    std::string filename = \"daubechies_\" + std::to_string(p) + \"_wavelet_convergence.svg\";\n\n    quicksvg::graph_fn daub(a, b, title, filename, 1024, GRAPH_WIDTH);\n    daub.set_stroke_width(1);\n    daub.set_gridlines(8, 2*p-1);\n\n    daub.add_fn(psi1, \"orange\");\n    auto psi2 = boost::math::daubechies_wavelet<Real, p>(2);\n    daub.add_fn(psi2, \"red\");\n\n    auto psi21 = boost::math::daubechies_wavelet<Real, p>(21);\n    daub.add_fn(psi21);\n\n    daub.write_all();\n}\n\ntemplate<typename Real, int p>\nvoid plot_condition_number()\n{\n    using std::abs;\n    using std::log;\n    static_assert(p >= 3, \"p = 2 is not differentiable, so condition numbers cannot be effectively evaluated.\");\n    auto phi = boost::math::daubechies_wavelet<Real, p>();\n    Real a = phi.support().first + 1000*std::sqrt(std::numeric_limits<Real>::epsilon());\n    Real b = phi.support().second - 1000*std::sqrt(std::numeric_limits<Real>::epsilon());\n    std::string title = \"log10 of condition number of function evaluation for Daubechies \" + std::to_string(p) + \" wavelet function.\";\n    title = \"\";\n    std::string filename = \"daubechies_\" + std::to_string(p) + \"_wavelet_condition_number.svg\";\n\n\n    quicksvg::graph_fn daub(a, b, title, filename, 2048, GRAPH_WIDTH);\n    daub.set_stroke_width(1);\n    daub.set_gridlines(8, 2*p-1);\n\n    auto cond = [&phi](Real x)\n    {\n        Real y = phi(x);\n        Real dydx = phi.prime(x);\n        Real z = abs(x*dydx/y);\n        using std::isnan;\n        if (z==0)\n        {\n            return Real(-1);\n        }\n        if (isnan(z))\n        {\n            // Graphing libraries don't like nan's:\n            return Real(1);\n        }\n        return log10(z);\n    };\n    daub.add_fn(cond);\n    daub.write_all();\n}\n\ntemplate<typename CoarseReal, typename PreciseReal, int p, class PsiPrecise>\nvoid do_ulp(int coarse_refinements, PsiPrecise psi_precise)\n{\n    auto psi_coarse = boost::math::daubechies_wavelet<CoarseReal, p>(coarse_refinements);\n\n    std::string title = std::to_string(p) + \" vanishing moment ULP plot at \" + std::to_string(coarse_refinements) + \" refinements and \" + boost::core::demangle(typeid(CoarseReal).name()) + \" precision\";\n    title = \"\";\n\n    std::string filename = \"daubechies_\" + std::to_string(p) + \"_wavelet_\" + boost::core::demangle(typeid(CoarseReal).name()) + \"_\" + std::to_string(coarse_refinements) + \"_refinements.svg\";\n    int samples = 20000;\n    int clip = 20;\n    int horizontal_lines = 8;\n    int vertical_lines = 2*p - 1;\n    quicksvg::ulp_plot<decltype(psi_coarse), CoarseReal, decltype(psi_precise), PreciseReal>(psi_coarse, psi_precise, CoarseReal(psi_coarse.support().first), psi_coarse.support().second, title, filename, samples, GRAPH_WIDTH, clip, horizontal_lines, vertical_lines);\n}\n\n\nint main()\n{\n    boost::hana::for_each(std::make_index_sequence<18>(), [&](auto i){ plot_psi<double, i+2>(); });\n    boost::hana::for_each(std::make_index_sequence<17>(), [&](auto i){ plot_dpsi<double, i+3>(); });\n    boost::hana::for_each(std::make_index_sequence<17>(), [&](auto i){ plot_condition_number<double, i+3>(); });\n    boost::hana::for_each(std::make_index_sequence<18>(), [&](auto i){ plot_convergence<double, i+2>(); });\n\n    using PreciseReal = float128;\n    using CoarseReal = double;\n    int precise_refinements = 22;\n    constexpr const int p = 9;\n    std::cout << \"Computing precise wavelet function in \" << boost::core::demangle(typeid(PreciseReal).name()) << \" precision.\\n\";\n    auto phi_precise = boost::math::daubechies_wavelet<PreciseReal, p>(precise_refinements);\n    std::cout << \"Beginning comparison with functions computed in \" << boost::core::demangle(typeid(CoarseReal).name()) << \" precision.\\n\";\n    for (int i = 7; i <= precise_refinements-1; ++i)\n    {\n        std::cout << \"\\tCoarse refinement \" << i << \"\\n\";\n        do_ulp<CoarseReal, PreciseReal, p>(i, phi_precise);\n    }\n}\n", "meta": {"hexsha": "4d898ea4ef9d8f64a46cebcd1c6302bdee8c7a85", "size": 6182, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/daubechies_wavelets/daubechies_wavelet_plots.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": "3rdparty/boost_1_73_0/libs/math/example/daubechies_wavelets/daubechies_wavelet_plots.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "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": "3rdparty/boost_1_73_0/libs/math/example/daubechies_wavelets/daubechies_wavelet_plots.cpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_forks_repo_licenses": ["MIT"], "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": 38.397515528, "max_line_length": 266, "alphanum_fraction": 0.6586865092, "num_tokens": 1805, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.8198933425148214, "lm_q1q2_score": 0.7078890272366734}}
{"text": "/** Test cases for Segment class.\n *\n */\n\n#include \"utils/random.h\"\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE RandomTest\n#include <boost/test/unit_test.hpp>\n\n#include <iostream>\n#include <random>\n#include <map>\n#include <string>\n#include <iomanip>\n\nusing namespace utils::random;\nusing namespace std;\n\nbool print_histogram = true;\n\nvoid printBannerTestCase(string testName)\n{\n\tint N = 50;\n\tcout << \"\\n\";\n\tfor (int i = 1; i<=N; i++){\n\t\tcout << \"*\" ;\n\t}\n\tcout << \"\\n\" ;\n\tint dashNo = ( N - testName.length() - 2 )  /  2;\n\tfor (int i = 1; i<=dashNo; i++){\n\t\tcout << \"-\" ;\n\t}\n\tcout << \" \" << testName ;\n\n\tfor (int i = 1; i <= N-2*dashNo-testName.length()-1; i++){\n\t\t\tcout << \" \" ;\n\t}\n\tfor (int i = 1; i<=dashNo; i++){\n\t\t\tcout << \"-\" ;\n\t}\n\tcout << \"\\n\";\n\tfor (int i = 1; i<=N; i++){\n\t\t\tcout << \"*\" ;\n\t}\n\tcout << \"\\n\\n\";\n}\n\nBOOST_AUTO_TEST_CASE(Generate_Normal_Distribution)\n{\n\tprintBannerTestCase( \"Testing Normal Distribution\" );\n    int N = 1000000;\n    double expmean = 0;\n    double sigma = 1;\n    vector<double> vs(N);\n    genNormalDist(vs, sigma, expmean);\n    \n    double foundMean = 0;\n    for (auto v : vs) {\n    \tfoundMean += v;\n    }\n    foundMean = foundMean/N;\n    BOOST_CHECK(abs(foundMean - expmean ) < 0.1*abs(foundMean-sigma));\n    cout << \"Expected Mean: \" << expmean << endl;\n    cout << \"Generated Mean: \" << foundMean << endl;\n}\n\nBOOST_AUTO_TEST_CASE(Gaussian_Random_Distribution)\n{\n\tprintBannerTestCase( \"Testing Gaussian Random Distribution\" );\n\tint N = 1000000;\n\tstd::map<int, int> hist;\n\tdouble sigma, expmean, min, max, foundMean;\n\tsigma = 2;\n\tmax = 12;\n\tmin = -2;\n\texpmean = 5;\n\tfoundMean = 0;\n\tbool reset = false;\n\n\tfor( int n=0; n<N; n++ ){\n\t\tdouble number = getGaussianRand(sigma, expmean, min, max, reset );\n\t\tfoundMean += number;\n\t\t++hist[std::round( number)];\n\t}\n\tfoundMean = foundMean/double(N);\n\t//checking mean\n\tif ( expmean!=0 ){\n\t\tBOOST_CHECK_CLOSE( foundMean,  expmean, 1);\n\t}\n\tBOOST_CHECK(abs( expmean - abs(foundMean) ) < 0.1*sigma);\n\t//checking minimum\n\tBOOST_CHECK(hist.begin()->first >= min);\n\t//checking maximum\n\tBOOST_CHECK(hist.rbegin()->first <= max );\n\tif( print_histogram ){\n\t\tcout << \"Histogram : \" << endl;\n\t\tfor(auto p : hist) {\n\t\t\t\tstd::cout << std::fixed << std::setprecision(1) << std::setw(2)\n\t\t\t\t\t\t  << p.first << ' ' << std::string(p.second/4000, '*') << '\\n';\n\t\t}\n\t\tcout << \"\\n\";\n\t}\n\tcout << \"Expected Mean: \" << expmean << endl;\n\tcout << \"Generated Mean: \" << foundMean << endl;\n}\n\nBOOST_AUTO_TEST_CASE(Uniform_Random_Distribution)\n{\n\tprintBannerTestCase( \"Testing Uniform Random Distribution\" );\n\tint N = 1000000;\n\tstd::map<int, int> hist;\n\tdouble expmean, min, max, foundMean;\n\tmin = -2;\n\tmax = 12;\n\texpmean = (min + max)/2;\n\tfoundMean = 0;\n\tbool reset = false;\n\n\tfor( int n=0; n<N; n++ ){\n\t\tdouble number = getUniformRand(min, max, reset );\n\t\tfoundMean += number;\n\t\t++hist[std::round( number)];\n\t}\n\tfoundMean = foundMean/double(N);\n\t//checking mean\n\tif ( expmean!=0 ){\n\t\t\tBOOST_CHECK_CLOSE( foundMean,  expmean, 1);\n\t}\n\tBOOST_CHECK(abs( expmean - abs(foundMean) ) < 0.1*abs(abs(min)-abs(expmean)));\n\t//checking minimum\n\tBOOST_CHECK(hist.begin()->first >= min);\n\t//checking maximum\n\tBOOST_CHECK(hist.rbegin()->first <= max );\n\tif( print_histogram ){\n\t\tcout << \"Histogram : \" << endl;\n\t\tfor(auto p : hist) {\n\t\t\t\tstd::cout << std::fixed << std::setprecision(1) << std::setw(2)\n\t\t\t\t\t\t  << p.first << ' ' << std::string(p.second/4000, '*') << '\\n';\n\t\t}\n\t\tcout << \"\\n\";\n\t}\n\tcout << \"Expected Mean: \" << expmean << endl;\n\tcout << \"Generated Mean: \" << foundMean << endl;\n}\n\n\n\n\n", "meta": {"hexsha": "2edff7f97df5ffee2fd982fc0e8b56afe0964f88", "size": 3542, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/tests/test_random.cpp", "max_stars_repo_name": "mirzaelahi/quest", "max_stars_repo_head_hexsha": "c433175802014386c2b1bf3c8932cd66b0d37c8e", "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": "lib/tests/test_random.cpp", "max_issues_repo_name": "mirzaelahi/quest", "max_issues_repo_head_hexsha": "c433175802014386c2b1bf3c8932cd66b0d37c8e", "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": "lib/tests/test_random.cpp", "max_forks_repo_name": "mirzaelahi/quest", "max_forks_repo_head_hexsha": "c433175802014386c2b1bf3c8932cd66b0d37c8e", "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": 23.6133333333, "max_line_length": 79, "alphanum_fraction": 0.6098249577, "num_tokens": 1061, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916064586998, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.7078890244191703}}
{"text": "//  (C) Copyright John Maddock 2015.\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#include <pch.hpp>\n\n#ifndef BOOST_NO_CXX11_HDR_TUPLE\n\n#define BOOST_TEST_MAIN\n#include <boost/test/unit_test.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/math/tools/roots.hpp>\n#include <boost/test/results_collector.hpp>\n#include <boost/test/unit_test.hpp>\n#include <boost/math/special_functions/cbrt.hpp>\n#include <iostream>\n#include <iomanip>\n#include <tuple>\n\n// No derivatives - using TOMS748 internally.\nstruct cbrt_functor_noderiv\n{ //  cube root of x using only function - no derivatives.\n   cbrt_functor_noderiv(double to_find_root_of) : a(to_find_root_of)\n   { // Constructor just stores value a to find root of.\n   }\n   double operator()(double x)\n   {\n      double fx = x*x*x - a; // Difference (estimate x^3 - a).\n      return fx;\n   }\nprivate:\n   double a; // to be 'cube_rooted'.\n}; // template <class T> struct cbrt_functor_noderiv\n\n// Using 1st derivative only Newton-Raphson\nstruct cbrt_functor_deriv\n{ // Functor also returning 1st derviative.\n   cbrt_functor_deriv(double const& to_find_root_of) : a(to_find_root_of)\n   { // Constructor stores value a to find root of,\n      // for example: calling cbrt_functor_deriv<double>(x) to use to get cube root of x.\n   }\n   std::pair<double, double> operator()(double const& x)\n   { // Return both f(x) and f'(x).\n      double fx = x*x*x - a; // Difference (estimate x^3 - value).\n      double dx = 3 * x*x; // 1st derivative = 3x^2.\n      return std::make_pair(fx, dx); // 'return' both fx and dx.\n   }\nprivate:\n   double a; // to be 'cube_rooted'.\n};\n// Using 1st and 2nd derivatives with Halley algorithm.\nstruct cbrt_functor_2deriv\n{ // Functor returning both 1st and 2nd derivatives.\n   cbrt_functor_2deriv(double const& to_find_root_of) : a(to_find_root_of)\n   { // Constructor stores value a to find root of, for example:\n      // calling cbrt_functor_2deriv<double>(x) to get cube root of x,\n   }\n   std::tuple<double, double, double> operator()(double const& x)\n   { // Return both f(x) and f'(x) and f''(x).\n      double fx = x*x*x - a; // Difference (estimate x^3 - value).\n      double dx = 3 * x*x; // 1st derivative = 3x^2.\n      double d2x = 6 * x; // 2nd derivative = 6x.\n      return std::make_tuple(fx, dx, d2x); // 'return' fx, dx and d2x.\n   }\nprivate:\n   double a; // to be 'cube_rooted'.\n};\n\nBOOST_AUTO_TEST_CASE( test_main )\n{\n   int newton_limits = static_cast<int>(std::numeric_limits<double>::digits * 0.6);\n\n   double arg = 1e-50;\n   while(arg < 1e50)\n   {\n      double result = boost::math::cbrt(arg);\n      //\n      // Start with a really bad guess 5 times below the result:\n      //\n      double guess = result / 5;\n      boost::uintmax_t iters = 1000;\n      // TOMS algo first:\n      std::pair<double, double> r = boost::math::tools::bracket_and_solve_root(cbrt_functor_noderiv(arg), guess, 2.0, true, boost::math::tools::eps_tolerance<double>(), iters);\n      BOOST_CHECK_CLOSE_FRACTION((r.first + r.second) / 2, result, std::numeric_limits<double>::epsilon() * 4);\n      BOOST_CHECK_LE(iters, 14);\n      // Newton next:\n      iters = 1000;\n      double dr = boost::math::tools::newton_raphson_iterate(cbrt_functor_deriv(arg), guess, guess / 2, result * 10, newton_limits, iters);\n      BOOST_CHECK_CLOSE_FRACTION(dr, result, std::numeric_limits<double>::epsilon() * 2);\n      BOOST_CHECK_LE(iters, 12);\n      // Halley next:\n      iters = 1000;\n      dr = boost::math::tools::halley_iterate(cbrt_functor_2deriv(arg), guess, result / 10, result * 10, newton_limits, iters);\n      BOOST_CHECK_CLOSE_FRACTION(dr, result, std::numeric_limits<double>::epsilon() * 2);\n      BOOST_CHECK_LE(iters, 7);\n      // Schroder next:\n      iters = 1000;\n      dr = boost::math::tools::schroder_iterate(cbrt_functor_2deriv(arg), guess, result / 10, result * 10, newton_limits, iters);\n      BOOST_CHECK_CLOSE_FRACTION(dr, result, std::numeric_limits<double>::epsilon() * 2);\n      BOOST_CHECK_LE(iters, 11);\n      //\n      // Over again with a bad guess 5 times larger than the result:\n      //\n      iters = 1000;\n      guess = result * 5;\n      r = boost::math::tools::bracket_and_solve_root(cbrt_functor_noderiv(arg), guess, 2.0, true, boost::math::tools::eps_tolerance<double>(), iters);\n      BOOST_CHECK_CLOSE_FRACTION((r.first + r.second) / 2, result, std::numeric_limits<double>::epsilon() * 4);\n      BOOST_CHECK_LE(iters, 14);\n      // Newton next:\n      iters = 1000;\n      dr = boost::math::tools::newton_raphson_iterate(cbrt_functor_deriv(arg), guess, result / 10, result * 10, newton_limits, iters);\n      BOOST_CHECK_CLOSE_FRACTION(dr, result, std::numeric_limits<double>::epsilon() * 2);\n      BOOST_CHECK_LE(iters, 12);\n      // Halley next:\n      iters = 1000;\n      dr = boost::math::tools::halley_iterate(cbrt_functor_2deriv(arg), guess, result / 10, result * 10, newton_limits, iters);\n      BOOST_CHECK_CLOSE_FRACTION(dr, result, std::numeric_limits<double>::epsilon() * 2);\n      BOOST_CHECK_LE(iters, 7);\n      // Schroder next:\n      iters = 1000;\n      dr = boost::math::tools::schroder_iterate(cbrt_functor_2deriv(arg), guess, result / 10, result * 10, newton_limits, iters);\n      BOOST_CHECK_CLOSE_FRACTION(dr, result, std::numeric_limits<double>::epsilon() * 2);\n      BOOST_CHECK_LE(iters, 11);\n      //\n      // A much better guess, 1% below result:\n      //\n      iters = 1000;\n      guess = result * 0.9;\n      r = boost::math::tools::bracket_and_solve_root(cbrt_functor_noderiv(arg), guess, 2.0, true, boost::math::tools::eps_tolerance<double>(), iters);\n      BOOST_CHECK_CLOSE_FRACTION((r.first + r.second) / 2, result, std::numeric_limits<double>::epsilon() * 4);\n      BOOST_CHECK_LE(iters, 12);\n      // Newton next:\n      iters = 1000;\n      dr = boost::math::tools::newton_raphson_iterate(cbrt_functor_deriv(arg), guess, result / 10, result * 10, newton_limits, iters);\n      BOOST_CHECK_CLOSE_FRACTION(dr, result, std::numeric_limits<double>::epsilon() * 2);\n      BOOST_CHECK_LE(iters, 5);\n      // Halley next:\n      iters = 1000;\n      dr = boost::math::tools::halley_iterate(cbrt_functor_2deriv(arg), guess, result / 10, result * 10, newton_limits, iters);\n      BOOST_CHECK_CLOSE_FRACTION(dr, result, std::numeric_limits<double>::epsilon() * 2);\n      BOOST_CHECK_LE(iters, 3);\n      // Schroder next:\n      iters = 1000;\n      dr = boost::math::tools::schroder_iterate(cbrt_functor_2deriv(arg), guess, result / 10, result * 10, newton_limits, iters);\n      BOOST_CHECK_CLOSE_FRACTION(dr, result, std::numeric_limits<double>::epsilon() * 2);\n      BOOST_CHECK_LE(iters, 4);\n      //\n      // A much better guess, 1% above result:\n      //\n      iters = 1000;\n      guess = result * 1.1;\n      r = boost::math::tools::bracket_and_solve_root(cbrt_functor_noderiv(arg), guess, 2.0, true, boost::math::tools::eps_tolerance<double>(), iters);\n      BOOST_CHECK_CLOSE_FRACTION((r.first + r.second) / 2, result, std::numeric_limits<double>::epsilon() * 4);\n      BOOST_CHECK_LE(iters, 12);\n      // Newton next:\n      iters = 1000;\n      dr = boost::math::tools::newton_raphson_iterate(cbrt_functor_deriv(arg), guess, result / 10, result * 10, newton_limits, iters);\n      BOOST_CHECK_CLOSE_FRACTION(dr, result, std::numeric_limits<double>::epsilon() * 2);\n      BOOST_CHECK_LE(iters, 5);\n      // Halley next:\n      iters = 1000;\n      dr = boost::math::tools::halley_iterate(cbrt_functor_2deriv(arg), guess, result / 10, result * 10, newton_limits, iters);\n      BOOST_CHECK_CLOSE_FRACTION(dr, result, std::numeric_limits<double>::epsilon() * 2);\n      BOOST_CHECK_LE(iters, 3);\n      // Schroder next:\n      iters = 1000;\n      dr = boost::math::tools::schroder_iterate(cbrt_functor_2deriv(arg), guess, result / 10, result * 10, newton_limits, iters);\n      BOOST_CHECK_CLOSE_FRACTION(dr, result, std::numeric_limits<double>::epsilon() * 2);\n      BOOST_CHECK_LE(iters, 4);\n\n      arg *= 3.5;\n   }\n}\n\n#else\n\nint main() { return 0; }\n\n#endif\n", "meta": {"hexsha": "643b9165821440b6d9635c211857a8f772b8a8f0", "size": 8120, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "deps/boost/libs/math/test/test_root_iterations.cpp", "max_stars_repo_name": "alexhenrie/poedit", "max_stars_repo_head_hexsha": "b9b31a111d9e8a84cf1e698aff2c922a79bdd859", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11356.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T19:42:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:55:25.000Z", "max_issues_repo_path": "deps/boost/libs/math/test/test_root_iterations.cpp", "max_issues_repo_name": "alexhenrie/poedit", "max_issues_repo_head_hexsha": "b9b31a111d9e8a84cf1e698aff2c922a79bdd859", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2402.0, "max_issues_repo_issues_event_min_datetime": "2017-12-08T22:31:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:25:52.000Z", "max_forks_repo_path": "deps/boost/libs/math/test/test_root_iterations.cpp", "max_forks_repo_name": "alexhenrie/poedit", "max_forks_repo_head_hexsha": "b9b31a111d9e8a84cf1e698aff2c922a79bdd859", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 44.861878453, "max_line_length": 176, "alphanum_fraction": 0.6668719212, "num_tokens": 2411, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563335, "lm_q2_score": 0.8006920092299293, "lm_q1q2_score": 0.7078431936318835}}
{"text": "/**\n * @brief Functions to compute gradients using finite difference.\n *\n * Based on the functions in https://github.com/PatWie/CppNumericalSolvers\n * and rewritten to use Eigen\n */\n#pragma once\n\n#include <Eigen/Core>\n\nnamespace fd {\n\n/**\n * @brief Enumeration of available orders of accuracy for finite differences.\n *\n * The corresponding integer values are used internally and should be ignored.\n */\nenum AccuracyOrder {\n    SECOND, ///< @brief Second order accuracy.\n    FOURTH, ///< @brief Fourth order accuracy.\n    SIXTH,  ///< @brief Sixth order accuracy.\n    EIGHTH  ///< @brief Eighth order accuracy.\n};\n\n/**\n * @brief Compute the gradient of a function using finite differences.\n *\n * @param[in]  x         Point at which to compute the gradient.\n * @param[in]  f         Compute the gradient of this function.\n * @param[out] grad      Computed gradient.\n * @param[in]  accuracy  Accuracy of the finite differences.\n * @param[in]  eps       Value of the finite difference step.\n */\nvoid finite_gradient(\n    const Eigen::VectorXd& x,\n    const std::function<double(const Eigen::VectorXd&)>& f,\n    Eigen::VectorXd& grad,\n    const AccuracyOrder accuracy = SECOND,\n    const double eps = 1.0e-8);\n\n/**\n * @brief Compute the jacobian of a function using finite differences.\n *\n * @param[in]  x         Point at which to compute the jacobian.\n * @param[in]  f         Compute the jacobian of this function.\n * @param[out] jac       Computed jacobian.\n * @param[in]  accuracy  Accuracy of the finite differences.\n * @param[in]  eps       Value of the finite difference step.\n */\nvoid finite_jacobian(\n    const Eigen::VectorXd& x,\n    const std::function<Eigen::VectorXd(const Eigen::VectorXd&)>& f,\n    Eigen::MatrixXd& jac,\n    const AccuracyOrder accuracy = SECOND,\n    const double eps = 1.0e-8);\n\n/**\n * @brief Compute the hessian of a function using finite differences.\n *\n * @param[in]  x         Point at which to compute the hessian.\n * @param[in]  f         Compute the hessian of this function.\n * @param[out] hess      Computed hessian.\n * @param[in]  accuracy  Accuracy of the finite differences.\n * @param[in]  eps       Value of the finite difference step.\n */\nvoid finite_hessian(\n    const Eigen::VectorXd& x,\n    const std::function<double(const Eigen::VectorXd&)>& f,\n    Eigen::MatrixXd& hess,\n    const AccuracyOrder accuracy = SECOND,\n    const double eps = 1.0e-5);\n\n/**\n * @brief Compare if two gradients are close enough.\n *\n * @param[in] x         The first gradient to compare.\n * @param[in] y         The second gradient to compare against.\n * @param[in] test_eps  Tolerance of equality.\n * @param[in] msg       Debug message header.\n *\n * @return A boolean for if x and y are close to the same value.\n */\nbool compare_gradient(\n    const Eigen::VectorXd& x,\n    const Eigen::VectorXd& y,\n    const double test_eps = 1e-4,\n    const std::string& msg = \"compare_gradient \");\n\n/**\n * @brief Compare if two jacobians are close enough.\n *\n * @param[in] x         The first jacobian to compare.\n * @param[in] y         The second jacobian to compare against.\n * @param[in] test_eps  Tolerance of equality.\n * @param[in] msg       Debug message header.\n *\n * @return A boolean for if x and y are close to the same value.\n */\nbool compare_jacobian(\n    const Eigen::MatrixXd& x,\n    const Eigen::MatrixXd& y,\n    const double test_eps = 1e-4,\n    const std::string& msg = \"compare_jacobian \");\n\n/**\n * @brief Compare if two hessians are close enough.\n *\n * @param[in] x         The first hessian to compare.\n * @param[in] y         The second hessian to compare against.\n * @param[in] test_eps  Tolerance of equality.\n * @param[in] msg       Debug message header.\n *\n * @return A boolean for if x and y are close to the same value.\n */\nbool compare_hessian(\n    const Eigen::MatrixXd& x,\n    const Eigen::MatrixXd& y,\n    const double test_eps = 1e-4,\n    const std::string& msg = \"compare_hessian \");\n\n} // namespace fd\n", "meta": {"hexsha": "4f58e0d1f2b1946cb51975de79ddfbf0108e842a", "size": 3949, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/finitediff.hpp", "max_stars_repo_name": "zfergus/finite-diff", "max_stars_repo_head_hexsha": "0cda5b2222e3671aa4882e050632dcd04aeea08d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2020-12-16T07:07:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-05T08:20:29.000Z", "max_issues_repo_path": "src/finitediff.hpp", "max_issues_repo_name": "zfergus/finite-diff", "max_issues_repo_head_hexsha": "0cda5b2222e3671aa4882e050632dcd04aeea08d", "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/finitediff.hpp", "max_forks_repo_name": "zfergus/finite-diff", "max_forks_repo_head_hexsha": "0cda5b2222e3671aa4882e050632dcd04aeea08d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-16T07:07:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-16T07:07:40.000Z", "avg_line_length": 32.368852459, "max_line_length": 78, "alphanum_fraction": 0.6659913902, "num_tokens": 967, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.82893881677331, "lm_q2_score": 0.8539127492339907, "lm_q1q2_score": 0.7078414239776685}}
{"text": "// root_finding_example.cpp\n\n// Copyright Paul A. Bristow 2010.\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 of finding roots using Newton-Raphson, Halley \n\n// Note that this file contains Quickbook mark-up as well as code\n// and comments, don't change any of the special comment mark-ups!\n\n//#ifdef _MSC_VER\n//#  pragma warning(disable: 4180) // qualifier has no effect (in Fusion).\n//#endif\n\n//#define BOOST_MATH_INSTRUMENT\n\n//[root_finding_example1\n/*`\nThis example demonstrates how to use the various tools for root finding \ntaking the simple cube root function (cbrt) as an example.\nIt shows how use of derivatives can improve the speed.\n(But is only a demonstration and does not try to make the ultimate improvements of 'real-life'\nimplementation of boost::math::cbrt; mainly by using a better computed initial 'guess'\nat `<boost/math/special_functions/cbrt.hpp>` ).\n\nFirst some includes that will be needed.\nUsing statements are provided to list what functions are being used in this example:\nyou can of course qualify the names in other ways.\n*/\n\n#include <boost/math/tools/roots.hpp>\nusing boost::math::policies::policy;\nusing boost::math::tools::newton_raphson_iterate;\nusing boost::math::tools::halley_iterate;\nusing boost::math::tools::eps_tolerance; // Binary functor for specified number of bits.\nusing boost::math::tools::bracket_and_solve_root;\nusing boost::math::tools::toms748_solve;\n\n#include <boost/math/tools/tuple.hpp>\n// using boost::math::tuple;\n// using boost::math::make_tuple;\n// using boost::math::tie;\n// which provide convenient aliases for various implementations,\n// including std::tr1, depending on what is available.\n\n//] [/root_finding_example1]\n\n#include <iostream>\nusing std::cout; using std::endl;\n#include <iomanip>\nusing std::setw; using std::setprecision;\n#include <limits>\nusing std::numeric_limits;\n\n//[root_finding_example2\n/*`\n\nLet's suppose we want to find the cube root of a number.\n\nThe equation we want to solve is:\n\n__spaces ['f](x) = x[cubed]\n\nWe will first solve this without using any information\nabout the slope or curvature of the cbrt function.\n\nWe then show how adding what we can know, for this function, about the slope,\nthe 1st derivation /f'(x)/, will speed homing in on the solution,\nand then finally how adding the curvature /f''(x)/ as well will improve even more.\n\nThe 1st and 2nd derivatives of x[cubed] are:\n\n__spaces ['f]\\'(x) = 2x[sup2]\n\n__spaces ['f]\\'\\'(x) = 6x\n*/\n\ntemplate <class T>\nstruct cbrt_functor_1\n{ //  cube root of x using only function - no derivatives.\n  cbrt_functor_1(T const& to_find_root_of) : value(to_find_root_of)\n  { // Constructor stores value to find root of. \n    // For example: calling cbrt_functor_<T>(x) to get cube root of x.\n  }\n  T operator()(T const& x)\n  { // Return both f(x)only.\n    T fx = x*x*x - value; // Difference (estimate x^3 - value).\n    return fx;\n  }\nprivate:\n  T value; // to be 'cube_rooted'.\n};\n\n/*`Implementing the cube root function itself is fairly trivial now:\nthe hardest part is finding a good approximation to begin with.\nIn this case we'll just divide the exponent by three.\n(There are better but more complex guess algorithms used in 'real-life'.)\n\nCube root function is 'Really Well Behaved' in that it is monotonic \nand has only one root (we leave negative values 'as an exercise for the student').\n*/\n\ntemplate <class T>\nT cbrt_1(T x)\n{ // return cube root of x using bracket_and_solve (no derivatives).\n  using namespace std;  // Help ADL of std functions.\n  using namespace boost::math;\n  int exponent;\n  frexp(x, &exponent); // Get exponent of z (ignore mantissa).\n  T guess = ldexp(1., exponent/3); // Rough guess is to divide the exponent by three.\n  T factor = 2; // To multiply \n  int digits = std::numeric_limits<T>::digits; // Maximum possible binary digits accuracy for type T.\n  // digits used to control how accurate to try to make the result.\n  int get_digits = (digits * 3) /4; // Near maximum (3/4) possible accuracy.\n  //cout  << \", std::numeric_limits<\" << typeid(T).name()  << \">::digits = \" << digits \n  //   << \", accuracy \" << get_digits << \" bits.\"<< endl;\n\n  //boost::uintmax_t maxit = (std::numeric_limits<boost::uintmax_t>::max)();\n  // (std::numeric_limits<boost::uintmax_t>::max)() = 18446744073709551615 \n  // which is more than we might wish to wait for!!!  \n  // so we can choose some reasonable estimate of how many iterations may be needed.\n  const boost::uintmax_t maxit = 10;\n  boost::uintmax_t it = maxit; // Initally our chosen max iterations, but updated with actual.\n  // We could also have used a maximum iterations provided by any policy:\n  // boost::uintmax_t max_it = policies::get_max_root_iterations<Policy>();\n  bool is_rising = true; // So if result if guess^3 is too low, try increasing guess.\n  eps_tolerance<double> tol(get_digits);\n  std::pair<T, T> r = \n    bracket_and_solve_root(cbrt_functor_1<T>(x), guess, factor, is_rising, tol, it);\n\n  // Can show how many iterations (this information is lost outside cbrt_1).\n  cout << \"Iterations \" << maxit << endl;\n  if(it >= maxit)\n  { // \n    cout << \"Unable to locate solution in chosen iterations:\"\n      \" Current best guess is between \" << r.first << \" and \" << r.second << endl;\n  }\n  return r.first + (r.second - r.first)/2;  // Midway between brackets.\n} // T cbrt_1(T x)\n\n\n//[root_finding_example2\n/*`\nWe now solve the same problem, but using more information about the function,\nto show how this can speed up finding the best estimate of the root.\n\nFor this function, the 1st differential (the slope of the tangent to a curve at any point) is known.\n\n[@http://en.wikipedia.org/wiki/Derivative#Derivatives_of_elementary_functions derivatives]\ngives some reminders.\n\nUsing the rule that the derivative of x^n for positive n (actually all nonzero n) is nx^n-1,\nallows use to get the 1st differential as 3x^2.\n\nTo see how this extra information is used to find the root, view this demo:\n[@http://en.wikipedia.org/wiki/Newton%27s_methodNewton Newton-Raphson iterations].\n\nWe need to define a different functor that returns\nboth the evaluation of the function to solve, along with its first derivative:\n\nTo \\'return\\' two values, we use a pair of floating-point values:\n*/\ntemplate <class T>\nstruct cbrt_functor_2\n{ // Functor also returning 1st derviative.\n  cbrt_functor_2(T const& to_find_root_of) : value(to_find_root_of)\n  { // Constructor stores value to find root of,\n    // for example: calling cbrt_functor_2<T>(x) to use to get cube root of x.\n  }\n  std::pair<T, T> operator()(T const& x)\n  { // Return both f(x) and f'(x).\n    T fx = x*x*x - value; // Difference (estimate x^3 - value).\n    T dx =  3 * x*x; // 1st derivative = 3x^2.\n    return std::make_pair(fx, dx); // 'return' both fx and dx.\n  }\nprivate:\n  T value; // to be 'cube_rooted'.\n}; // cbrt_functor_2\n\n/*`Our cube root function is now:*/\n\ntemplate <class T>\nT cbrt_2(T x)\n{ // return cube root of x using 1st derivative and Newton_Raphson.\n  int exponent;\n  frexp(x, &exponent); // Get exponent of z (ignore mantissa).\n  T guess = ldexp(1., exponent/3); // Rough guess is to divide the exponent by three.\n  T min = ldexp(0.5, exponent/3); // Minimum possible value is half our guess.\n  T max = ldexp(2., exponent/3);// Maximum possible value is twice our guess.\n  int digits = std::numeric_limits<T>::digits; // Maximum possible binary digits accuracy for type T.\n  // digits used to control how accurate to try to make the result.\n  int get_digits = (digits * 3) /4; // Near maximum (3/4) possible accuracy.\n\n  //boost::uintmax_t maxit = (std::numeric_limits<boost::uintmax_t>::max)();\n  // the default (std::numeric_limits<boost::uintmax_t>::max)() = 18446744073709551615 \n  // which is more than we might wish to wait for!!!  so we can reduce it\n  boost::uintmax_t maxit = 10;\n  //cout << \"Max Iterations \" << maxit << endl; //\n  T result = newton_raphson_iterate(cbrt_functor_2<T>(x), guess, min, max, get_digits, maxit);\n  // Can show how many iterations (updated by newton_raphson_iterate) but lost on exit.\n  // cout << \"Iterations \" << maxit << endl;\n  return result;\n}\n\n/*`\nFinally need to define yet another functor that returns\nboth the evaluation of the function to solve, \nalong with its first and second derivatives:\n\nf''(x) = 3 * 3x\n\nTo \\'return\\' three values, we use a tuple of three floating-point values:\n*/\n\ntemplate <class T>\nstruct cbrt_functor_3\n{ // Functor returning both 1st and 2nd derivatives.\n  cbrt_functor_3(T const& to_find_root_of) : value(to_find_root_of)\n  { // Constructor stores value to find root of, for example:\n    //  calling cbrt_functor_3<T>(x) to get cube root of x,\n  }\n\n  // using boost::math::tuple; // to return three values.\n  boost::math::tuple<T, T, T> operator()(T const& x)\n  { // Return both f(x) and f'(x) and f''(x).\n    using boost::math::make_tuple;\n    T fx = x*x*x - value; // Difference (estimate x^3 - value).\n    T dx = 3 * x*x; // 1st derivative = 3x^2.\n    T d2x = 6 * x; // 2nd derivative = 6x.\n    return make_tuple(fx, dx, d2x); // 'return' fx, dx and d2x.\n  }\nprivate:\n  T value; // to be 'cube_rooted'.\n}; // struct cbrt_functor_3\n\n/*`Our cube function is now:*/\n\ntemplate <class T>\nT cbrt_3(T x)\n{ // return cube root of x using 1st and 2nd derivatives and Halley.\n  //using namespace std;  // Help ADL of std functions.\n  using namespace boost::math;\n  int exponent;\n  frexp(x, &exponent); // Get exponent of z (ignore mantissa).\n  T guess = ldexp(1., exponent/3); // Rough guess is to divide the exponent by three.\n  T min = ldexp(0.5, exponent/3); // Minimum possible value is half our guess.\n  T max = ldexp(2., exponent/3);// Maximum possible value is twice our guess.\n  int digits = std::numeric_limits<T>::digits; // Maximum possible binary digits accuracy for type T.\n  // digits used to control how accurate to try to make the result.\n  int get_digits = (digits * 3) /4; // Near maximum (3/4) possible accuracy.\n  //cout << \"Value \" << x << \", guess \" << guess \n  //  << \", min \" << min << \", max \" << max \n  //  << \", std::numeric_limits<\" << typeid(T).name()  << \">::digits = \" << digits \n  //   << \", accuracy \" << get_digits << \" bits.\"<< endl;\n\n  //boost::uintmax_t maxit = (std::numeric_limits<boost::uintmax_t>::max)();\n  // the default (std::numeric_limits<boost::uintmax_t>::max)() = 18446744073709551615 \n  // which is more than we might wish to wait for!!!  so we can reduce it\n  boost::uintmax_t maxit = 10;\n  //cout << \"Max Iterations \" << maxit << endl; //\n  T result = halley_iterate(cbrt_functor_3<T>(x), guess, min, max, digits, maxit);\n  // Can show how many iterations (updated by newton_raphson_iterate).\n  cout << \"Iterations \" << maxit << endl;\n  return result;\n} // cbrt_3(x)\n\n\nint main()\n{\n  cout << \"Cube Root finding (cbrt) Example.\" << endl;\n  cout.precision(std::numeric_limits<double>::max_digits10);\n  // Show all possibly significant decimal digits.\n  try\n  {\n\n    double v27 = 27; // that has an exact integer cube root.\n    double v28 = 28; // whose cube root is not exactly representable.\n\n    // Using bracketing:\n    double r = cbrt_1(v27);\n    cout << \"cbrt_1(\" << v27 << \") = \" << r << endl;\n    r = cbrt_1(v28);\n    cout << \"cbrt_1(\" << v28 << \") = \" << r << endl;\n\n    // Using 1st differential Newton-Raphson:\n    r = cbrt_2(v27);\n    cout << \"cbrt_1(\" << v27 << \") = \" << r << endl;\n    r = cbrt_2(v28);\n    cout << \"cbrt_2(\" << v28 << \") = \" << r << endl;\n\n    // Using Halley with 1st and 2nd differentials.\n    r = cbrt_3(v27);\n    cout << \"cbrt_3(\" << v27 << \") = \" << r << endl;\n    r = cbrt_3(v28);\n    cout << \"cbrt_3(\" << v28 << \") = \" << r << endl;\n\n\n\n    //] [/root_finding_example2]\n  }\n  catch(const std::exception& e)\n  { // Always useful to include try & catch blocks because default policies \n    // are to throw exceptions on arguments that cause errors like underflow, overflow. \n    // Lacking try & catch blocks, the program will abort without a message below,\n    // which may give some helpful clues as to the cause of the exception.\n    std::cout <<\n      \"\\n\"\"Message from thrown exception was:\\n   \" << e.what() << std::endl;\n  }\n  return 0;\n}  // int main()\n\n//[root_finding_example_output\n/*`\nNormal output is: \n\n[pre\n  root_finding_example.cpp\n  Generating code\n  Finished generating code\n  root_finding_example.vcxproj -> J:\\Cpp\\MathToolkit\\test\\Math_test\\Release\\root_finding_example.exe\n  Cube Root finding (cbrt) Example.\n  Iterations 10\n  cbrt_1(27) = 3\n  Iterations 10\n  Unable to locate solution in chosen iterations: Current best guess is between 3.0365889718756613 and 3.0365889718756627\n  cbrt_1(28) = 3.0365889718756618\n  cbrt_1(27) = 3\n  cbrt_2(28) = 3.0365889718756627\n  Iterations 4\n  cbrt_3(27) = 3\n  Iterations 5\n  cbrt_3(28) = 3.0365889718756627\n\n] [/pre]\n\nto get some (much!) diagnostic output we can add\n\n#define BOOST_MATH_INSTRUMENT\n\n[pre\n\n]\n*/\n//] [/root_finding_example_output]\n", "meta": {"hexsha": "5829d981c1c7aa6386cea1d8a8502e53bf2dcc11", "size": 13019, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/math/example/root_finding_example.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2016-04-12T16:29:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-28T11:01:57.000Z", "max_issues_repo_path": "boost/libs/math/example/root_finding_example.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-10-31T19:35:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-04T17:11:27.000Z", "max_forks_repo_path": "boost/libs/math/example/root_finding_example.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-09-09T02:38:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-30T00:24:24.000Z", "avg_line_length": 37.3037249284, "max_line_length": 121, "alphanum_fraction": 0.6892234427, "num_tokens": 3725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.8539127529517043, "lm_q1q2_score": 0.7078414126250645}}
{"text": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union\u2019s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n\n#include \"../util/AlgorithmUtils.hpp\"\n#include \"../util/FluidEigenMappings.hpp\"\n#include \"../../data/TensorTypes.hpp\"\n#include <Eigen/Core>\n#include <cassert>\n#include <cmath>\n\nnamespace fluid {\nnamespace algorithm {\n\nclass Normalization\n{\npublic:\n  using ArrayXd = Eigen::ArrayXd;\n  using ArrayXXd = Eigen::ArrayXXd;\n\n  void init(double min, double max, RealMatrixView in)\n  {\n    using namespace Eigen;\n    using namespace _impl;\n    mMin = min;\n    mMax = max;\n    ArrayXXd input = asEigen<Array>(in);\n    mDataMin = input.colwise().minCoeff();\n    mDataMax = input.colwise().maxCoeff();\n    mDataRange = mDataMax - mDataMin;\n    mInitialized = true;\n  }\n\n  void init(double min, double max, RealVectorView dataMin,\n            RealVectorView dataMax)\n  {\n    using namespace Eigen;\n    using namespace _impl;\n    mMin = min;\n    mMax = max;\n    mDataMin = asEigen<Array>(dataMin);\n    mDataMax = asEigen<Array>(dataMax);\n    mDataRange = mDataMax - mDataMin;\n    mDataRange = mDataRange.max(epsilon);\n    mInitialized = true;\n  }\n\n  void processFrame(const RealVectorView in, RealVectorView out,\n                    bool inverse = false) const\n  {\n    using namespace Eigen;\n    using namespace _impl;\n    ArrayXd input = asEigen<Array>(in);\n    ArrayXd result;\n    if (!inverse)\n    {\n      result = (input - mDataMin) / mDataRange.max(epsilon);\n      result = mMin + (result * (mMax - mMin));\n    }\n    else\n    {\n      result = (input - mMin) / std::max((mMax - mMin), epsilon);\n      result = mDataMin + (result * mDataRange);\n    }\n    out = asFluid(result);\n  }\n\n  void process(const RealMatrixView in, RealMatrixView out,\n               bool inverse = false) const\n  {\n    using namespace Eigen;\n    using namespace _impl;\n    ArrayXXd input = asEigen<Array>(in);\n    ArrayXXd result;\n    if (!inverse)\n    {\n      result = (input.rowwise() - mDataMin.transpose());\n      result = result.rowwise() / mDataRange.transpose().max(epsilon);\n      result = mMin + (result * (mMax - mMin));\n    }\n    else\n    {\n      result = input - mMin;\n      result = result / std::max((mMax - mMin), epsilon);\n      result = (result.rowwise() * mDataRange.transpose());\n      result = (result.rowwise() + mDataMin.transpose());\n    }\n    out = asFluid(result);\n  }\n\n  void setMin(double min) { mMin = min; }\n  void setMax(double max) { mMax = max; }\n  bool initialized() const { return mInitialized; }\n\n  double getMin() const { return mMin; }\n  double getMax() const { return mMax; }\n\n  void getDataMin(RealVectorView out) const\n  {\n    using namespace _impl;\n    out = asFluid(mDataMin);\n  }\n\n  void getDataMax(RealVectorView out) const\n  {\n    using namespace _impl;\n    out = asFluid(mDataMax);\n  }\n\n  index dims() const { return mDataMin.size(); }\n  index size() const { return 1; }\n\n  void clear()\n  {\n    mMin = 0;\n    mMax = 1.0;\n    mDataMin.setZero();\n    mDataMax.setZero();\n    mDataRange.setZero();\n    mInitialized = false;\n  }\n\n  double  mMin{0.0};\n  double  mMax{1.0};\n  ArrayXd mDataMin;\n  ArrayXd mDataMax;\n  ArrayXd mDataRange;\n  bool    mInitialized{false};\n};\n}; // namespace algorithm\n}; // namespace fluid\n", "meta": {"hexsha": "38d0225fed60ddcde340d2574427c1e169089695", "size": 3546, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/public/Normalization.hpp", "max_stars_repo_name": "chriskiefer/flucoma-core", "max_stars_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2020-05-11T15:42:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T01:51:36.000Z", "max_issues_repo_path": "include/algorithms/public/Normalization.hpp", "max_issues_repo_name": "chriskiefer/flucoma-core", "max_issues_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 90.0, "max_issues_repo_issues_event_min_datetime": "2020-05-13T20:25:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T18:05:35.000Z", "max_forks_repo_path": "include/algorithms/public/Normalization.hpp", "max_forks_repo_name": "chriskiefer/flucoma-core", "max_forks_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2020-05-11T15:15:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-15T12:15:36.000Z", "avg_line_length": 25.3285714286, "max_line_length": 74, "alphanum_fraction": 0.6497461929, "num_tokens": 922, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582497090321, "lm_q2_score": 0.7606506418255927, "lm_q1q2_score": 0.7077536648330929}}
{"text": "#ifndef _NAIVE_BAYES_\n#define _NAIVE_BAYES_ 1\n\n#include <string>\n#include <vector>\n#include <Eigen/Dense>\n#include <cmath>\n#include <exception>\n#include <algorithm>\n\n#define PI 3.141592653589793238462643383279502884L\n\n#define _l_ std::cout<<__LINE__<<std::endl;\n\n\ntypedef struct {\n  unsigned label;\n  Eigen::VectorXd features;\n} ClassificationObject;\n\ntypedef struct {\n  unsigned label;\n  double prior;\n  Eigen::VectorXd mean;\n  Eigen::MatrixXd covariance;\n  double covarianceDeterminant;\n  Eigen::MatrixXd covarianceInverse;\n} ClassInfo;\n\nClassInfo\nComputeClassInfo(\n    const std::vector<ClassificationObject>& data,\n    const unsigned classLabel,\n    const unsigned featureDim) {\n\n  ClassInfo classInfo;\n  classInfo.label = classLabel;\n  classInfo.mean.setZero(featureDim);\n  classInfo.covariance.setZero(featureDim, featureDim);\n\n  // compute mean and prior probability at once\n  std::vector<ClassificationObject> subset;\n  for (const ClassificationObject& classificationObject : data) {\n    if (classificationObject.label == classLabel) {\n      classInfo.mean += classificationObject.features;\n      subset.push_back(classificationObject);\n    }\n  }\n  classInfo.mean /= subset.size();\n  classInfo.prior = (double) subset.size() / (double) data.size();\n\n  // covariance matrix\n  // Note: I use a nifty trick that is simpler in code (not sure if\n  //       simpler computationally). Let $P_i = x_i - mu$, where $i$\n  //       corresponds to a particular observation vector. Then\n  //       $A$ is the concatenation of all the $P_i$ as column\n  //       vectors ($A = [P_1 ... P_m]$). Then\n  //       $\\frac{1}{m} * A * A^t$ results in the same computations\n  //       that create the covariance matrix as more traditional\n  //       formulae.\n  Eigen::MatrixXd A(featureDim, subset.size());\n  for (unsigned j = 0; j < subset.size(); ++j) {\n    A.col(j) = subset[j].features - classInfo.mean;\n  }\n\n  classInfo.covariance = A * A.transpose();\n  classInfo.covariance /= (double) subset.size();\n\n  classInfo.covarianceDeterminant = classInfo.covariance.determinant();\n  classInfo.covarianceInverse = classInfo.covariance.inverse();\n\n  return classInfo;\n}\n\ndouble\nGaussianPdf(\n  const Eigen::VectorXd& testFeatureVector,\n  const ClassInfo& classSummary) {\n\n  const Eigen::VectorXd& x = testFeatureVector;\n  const Eigen::VectorXd& mu = classSummary.mean;\n  const double& sigmaDet = classSummary.covarianceDeterminant;\n  const Eigen::MatrixXd& sigmaInv = classSummary.covarianceInverse;\n\n  double scalingFactor = 1.0 / sqrt(pow(2.0 * PI, mu.size()) * sigmaDet);\n  double exponent = -0.5 * (((x - mu).transpose() * sigmaInv).dot((x - mu)));\n\n  return scalingFactor * exp(exponent);\n}\n\nunsigned\nClassifyObject(const ClassificationObject& object, const std::vector<ClassInfo>& classSummaries) {\n  unsigned mostLikelyClass = 0;\n  double highestProbability = classSummaries.front().label;\n\n  for (const ClassInfo& classSummary : classSummaries) {\n    double probability = GaussianPdf(object.features, classSummary) * classSummary.prior;\n    if (probability > highestProbability) {\n      mostLikelyClass = classSummary.label;\n      highestProbability = probability;\n    }\n  }\n\n  return mostLikelyClass;\n}\n\n#endif //_NAIVE_BAYES_", "meta": {"hexsha": "071f21b5e8d9e80568204beb5dec370c0ceb333e", "size": 3218, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "STAT775/HW03/naive_bayes.cpp", "max_stars_repo_name": "T-R0D/Past-Courses", "max_stars_repo_head_hexsha": "0edc83a7bf09515f0d01d23a26df2ff90c0f458a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2017-03-13T17:32:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-27T16:51:22.000Z", "max_issues_repo_path": "STAT775/HW03/naive_bayes.cpp", "max_issues_repo_name": "T-R0D/Past-Courses", "max_issues_repo_head_hexsha": "0edc83a7bf09515f0d01d23a26df2ff90c0f458a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-29T19:54:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-29T19:54:52.000Z", "max_forks_repo_path": "STAT775/HW03/naive_bayes.cpp", "max_forks_repo_name": "T-R0D/Past-Courses", "max_forks_repo_head_hexsha": "0edc83a7bf09515f0d01d23a26df2ff90c0f458a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2016-10-18T03:31:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-29T13:23:10.000Z", "avg_line_length": 30.0747663551, "max_line_length": 98, "alphanum_fraction": 0.7156619018, "num_tokens": 809, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765210631689, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.7077186564715536}}
{"text": "#include <iostream>\n#include <cmath>\nusing namespace std; \n#include <Eigen/Core>\n#include <Eigen/Geometry>\n \n// \u674e\u7fa4\u674e\u4ee3\u6570 \u5e93 \n#include \"sophus/so3.hpp\"\n#include \"sophus/se3.hpp\"\n\n#include<stdio.h>\n#include\"mex.h\"\n\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]){\n    // nlhs represent the number of parameters of the output\n    // plhs is a array of the mxarray pointers, each pointing to the output\n    // nrhs represents the number of parameters of the input\n    // prhs is a array of the mxarray pointers, each pointing to the input\n\n    // prhs[0], 6x1 matrix\n    // prhs[1], Mx1 cell, each cell with NX3 points\n    // prhs[2], Mx1 cell, each cell with PXQ single matrix\n    // prhs[3], 1x2, or 1x3, or 1x4, or 1x5 matrix\n    // prhs[4], 3x3 matrix\n    // prhs[5], 1x2 matrix\n\n    if(nrhs < 1){\n        mexErrMsgIdAndTxt( \"euler2se3Mex:invalidNumInputs\", \"at least 1 input arguments required\");\n        return;\n    }\n\n    // get the euler transformation\n    const size_t *dimArrayOfEulerTransformation = mxGetDimensions(prhs[0]);\n    size_t sizeRowsEulerTransformation = *(dimArrayOfEulerTransformation + 0);\n    size_t sizeColsEulerTransformation = *(dimArrayOfEulerTransformation + 1);\n    if(sizeRowsEulerTransformation != 6 || sizeColsEulerTransformation != 1){\n        mexErrMsgIdAndTxt( \"EdgeSE3ProjectDirectWithDirstortJacobian:invalidInputs\", \"the 1st param should be 6x1\");\n        return;\n    }\n    double *ptrEulerTransformation = (double *)(mxGetPr(prhs[0]));\n    Eigen::Matrix<double, 6, 1> eulerTransformation;\n    for(int i = 0; i < 6; i++){\n        eulerTransformation(i, 0) = *(ptrEulerTransformation + i);\n    }\n\n    // cout<<\"eulerTransformation = \"<<endl<<eulerTransformation<<endl;\n\n    Eigen::Matrix<double,6,1> se3;\n\n    Eigen::Matrix3d R = Eigen::Matrix3d::Identity();\n    Eigen::AngleAxisd rotation_Z_vector ( eulerTransformation(0,0), Eigen::Vector3d ( 0,0,1 ) );     //\u6cbf Z \u8f74\u65cb\u8f6c yaw\n    Eigen::AngleAxisd rotation_Y_vector ( eulerTransformation(1,0), Eigen::Vector3d ( 0,1,0 ) );      //\u6cbf Y \u8f74\u65cb\u8f6c pitch\n    Eigen::AngleAxisd rotation_X_vector ( eulerTransformation(2,0), Eigen::Vector3d ( 1,0,0 ) );      //\u6cbf X \u8f74\u65cb\u8f6c roll\n    R = rotation_Z_vector.toRotationMatrix() * rotation_Y_vector.toRotationMatrix() * rotation_X_vector.toRotationMatrix();\n\n    Eigen::Vector3d t(eulerTransformation(3,0), eulerTransformation(4,0), eulerTransformation(5,0));\n    Sophus::SE3<double> SE3_Rt(R, t);           // \u4eceR,t\u6784\u9020SE(3)\n\n    // cout<<\"SE3 = \"<<endl<<SE3_Rt.matrix()<<endl;\n\n    se3 = SE3_Rt.log();\n\n    // cout<<\"se3 = \"<<endl<<se3.matrix()<<endl;\n\n    // the se3 will be 6x1\n    size_t dimArrayOfSe3[2] = { 6, 1 };\n    plhs[0] = mxCreateNumericArray(2, dimArrayOfSe3, mxDOUBLE_CLASS, mxREAL);\n    double *ptrSe3 = (double *)mxGetData(plhs[0]);\n    for(int i = 0; i < 6; i++){\n        ptrSe3[i] = se3(i, 0);\n    }\n}", "meta": {"hexsha": "fbde3e70c5cca31326398d9f253c56de921ca331", "size": 2855, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "utils/optimization/cpp/euler2se3Mex.cpp", "max_stars_repo_name": "ccyinlu/multimodal_data_studio", "max_stars_repo_head_hexsha": "9b76f9033d46a5a812f2ee2babe1526c7d874111", "max_stars_repo_licenses": ["Xnet", "X11"], "max_stars_count": 37.0, "max_stars_repo_stars_event_min_datetime": "2019-03-14T01:18:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T00:07:58.000Z", "max_issues_repo_path": "utils/optimization/cpp/euler2se3Mex.cpp", "max_issues_repo_name": "yxw027/multimodal_data_studio", "max_issues_repo_head_hexsha": "975f0560e32d810fccb8690a36d157162d7da5ab", "max_issues_repo_licenses": ["Xnet", "X11"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-07-29T08:08:39.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-20T09:25:31.000Z", "max_forks_repo_path": "utils/optimization/cpp/euler2se3Mex.cpp", "max_forks_repo_name": "yxw027/multimodal_data_studio", "max_forks_repo_head_hexsha": "975f0560e32d810fccb8690a36d157162d7da5ab", "max_forks_repo_licenses": ["Xnet", "X11"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2019-07-16T06:06:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T23:53:56.000Z", "avg_line_length": 39.6527777778, "max_line_length": 123, "alphanum_fraction": 0.6665499124, "num_tokens": 905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122263731811, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.7076970902446548}}
{"text": "#include <vector>\n\n#include <NTL/ZZ.h>\n\n#include \"../src/elements/element.hpp\"\n#include \"../src/algorithms/utils.hpp\"\n\n/* Example: using the remainder tree algorithm to search for Wolstenholme primes.\n * Wolstenholme's theorem states that choose(2*p - 1, p - 1) = 1 (mod p^3) for prime p.\n * A Wolstenholme prime satisfies the same identity modulo p^4.\n *\n * Suppose we want to use the remainder tree algorithm to aid our search for Wolstenholme primes.\n * Let w_p = choose(2*p - 1, p - 1). We wish to find w_p (mod p^4) for primes p. Define R_1 = 1\n *\n * R_n = 4*n - 2\n *\n * Observe that w_p = ((4*p - 2)/p)*w_{p-1}. Therefore,\n * (R_1 * R_2 ... * R_p)/p! will be w_p\n * Remember the goal is to find w_p (R_p)!/p! (mod p^4). Unfortunately,\n * p! contains a single factor of p which has no inverse modulo p^4.\n *\n * In general to find (n/d) (mod m) where d and m are not coprime, use the following.\n * Suppose q_0*m + r_0 = n/d. For some q_0 and 0 <= r_0 < m.\n * Then multiplying gives q_0*m*d + r_0*d = n\n * If we compute n modulo (m*d), we get q_1*m*d + r_1 = n. Since 0 <= r_0 < m implies 0 <= r_0*d < m*d,\n * then r_1 = r_0*d. The goal is to find r_0, and we do so by computing r_1 and dividing by d.\n *\n * In our case, we should find (R_p)! (mod p^5) and then divide the output by p.\n * Then, reduce modulo p^4 and multiply by the modular inverse of (p-1)!.\n *\n * We will need to do remainder tree twice. The first time, set the multiplicands to be\n * A_0 = 1, and A_n = R_n. Set the moduli to be m_n = n^5 if n is prime, and m_n is 1 otherwise.\n * Then, for each index n in the output, divide the remainder by n, and then reduce modulo (n^4).\n *\n * The second remainder tree, set the multiplicands to be A_0 = A_1 = 1, and A_n = n - 1 and set the\n * moduli to be m_n = n^4 if n is prime, and m_n is 1 otherwise. Then, for each index in the output,\n * set each remainder to be its modular inverse, then multiply by the corresponding index from the first\n * remainder tree. The final vector will contain w_p (mod p^4) for primes p, as desired.\n */\n\n\nusing std::vector;\n\n// Like in the search for Wilson primes, we only need to be able to use integers. See\n// wilson.hpp for more explanation on how Elt works and how to wrap types.\nusing NTL::ZZ;\n\n//The convention here is to generate from lower bound---inclusive to upper---exclusive\nvector<Elt<ZZ>> gen_wolstenholme_numerator(long lower, long upper) {\n    vector<Elt<ZZ>> output(upper-lower);\n\n    for(long i = lower; i < upper; ++i) {\n        if(i <= 1){\n            output[i] = Elt<ZZ>(1);\n        }\n        else {\n            //If you worry that the initializer (4*n - 2) in this case will already overflow,\n            //Just initialize on i and do arithmetic there.\n            output[i-lower] = Elt<ZZ> (4*i - 2);\n        }\n    }\n    return output;\n}\n\nvector<Elt<ZZ>> gen_wolstenholme_denominator(long lower, long upper){\n    vector<Elt<ZZ>> output(upper-lower);\n\n    for(long i = lower; i < upper; ++i) {\n        if(i <= 1){\n            output[i] = Elt<ZZ>(1);\n        }\n        else {\n            output[i-lower] = Elt<ZZ> (i - 1);\n        }\n    }\n    return output;\n}\n\n\nvector<Elt<ZZ>> gen_fourth_prime_power(long lower, long upper) {\n    vector<Elt<ZZ>> output(upper-lower);\n    \n    for(long i = lower; i < upper; i++){\n        ZZ n(i);\n        if(ProbPrime(n)) { //Technically a sieve is faster & more correct, but shouldn't make a big difference.\n                            //This is just an example anyway.\n            NTL::power(n, n, 4);\n            output[i-lower] = Elt<ZZ>(n);\n        }\n        else{\n            output[i-lower] = Elt<ZZ>(1);\n        }\n    }\n    return output;\n}\n\n\nvector<Elt<ZZ>> gen_fifth_prime_power(long lower, long upper) {\n    vector<Elt<ZZ>> output(upper-lower);\n    \n    for(long i = lower; i < upper; i++){\n        ZZ n(i);\n        if(ProbPrime(n)) {\n            power(n, n, 5);\n            output[i-lower] = Elt<ZZ>(n);\n        }\n        else {\n            output[i-lower] = Elt<ZZ>(1);\n        }\n    }\n    return output;\n}\n\n\n//TODO: combine the above and actually write a search function that zips the outputs and finds XGCD etc.\n//TODO: explain how to modify calculate_factorial and compute V", "meta": {"hexsha": "1bb2fee71de971ddab3e2afa56e1cc3c35acdba5", "size": 4196, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "examples/wolstenholme.hpp", "max_stars_repo_name": "adienes/remainder-tree", "max_stars_repo_head_hexsha": "0aa76214ab6f2a4389ec45a239ea660749989a90", "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": "examples/wolstenholme.hpp", "max_issues_repo_name": "adienes/remainder-tree", "max_issues_repo_head_hexsha": "0aa76214ab6f2a4389ec45a239ea660749989a90", "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": "examples/wolstenholme.hpp", "max_forks_repo_name": "adienes/remainder-tree", "max_forks_repo_head_hexsha": "0aa76214ab6f2a4389ec45a239ea660749989a90", "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.1724137931, "max_line_length": 111, "alphanum_fraction": 0.6146329838, "num_tokens": 1250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.8128673178375734, "lm_q1q2_score": 0.7076800610294831}}
{"text": "\n#include \"SDL2/SDL.h\"\n#include <Eigen/Dense>\n#include \"stdio.h\"\n#include <iostream>\n#include <vector>\n#include <cmath>\n// SDL_Window *window;\n\n// lldb (print pow correctly): expr -l objective-c -- @import Darwin\n\nclass GlobalSettings\n{\n  public:\n  const static int ScreenResolutionX = 640;\n  const static int ScreenResolutionY = 480;\n};\n\nstruct Ray\n{\n  Eigen::Vector3d origin;\n  Eigen::Vector3d direction;\n};\n\nclass Object;\n\nstruct RayHitResult\n{\n  Eigen::Vector3d hitPosition;\n  bool hit;\n  Object* hitObject;\n};\n\nclass Object\n{\n  public:\n  Eigen::Vector3d color;\n\n  virtual RayHitResult raytrace(Ray ray) = 0;\n  virtual const Eigen::Vector3d normalAt(const Eigen::Vector3d pos) = 0;\n};\n\nclass Sphere : public Object\n{\n  float radii;\n  Eigen::Vector3d position;\n\n  public:\n  Sphere (double pRadii, Eigen::Vector3d pPosition, Eigen::Vector3d pColor)\n  {\n    radii = pRadii; // in meters\n    position = pPosition;\n    color = pColor;\n  }\n\n  virtual const Eigen::Vector3d normalAt(const Eigen::Vector3d pPos)\n  {\n    return pPos - position;\n  }\n\n  virtual RayHitResult raytrace(Ray ray)\n  {\n    // print the closest colision point\n    // see equation at https://en.wikipedia.org/wiki/Line%E2%80%93sphere_intersection\n    // - (l * ( o - c) ) +- sqrt( (l * ( o - c))^2 - (o-c)^2 + r^2 )\n    double l_o_c =\n      ray.direction.x() * ( ray.origin.x() - position.x() ) +\n      ray.direction.y() * ( ray.origin.y() - position.y() ) +\n      ray.direction.z() * ( ray.origin.z() - position.z() );\n\n    double sqrtValue =\n      pow( l_o_c, 2)\n      - ( pow(ray.origin.x() - position.x(), 2) +\n          pow(ray.origin.y() - position.y(), 2) +\n          pow(ray.origin.z() - position.z(), 2)\n        )\n      + pow(radii, 2);\n\n\n    RayHitResult hitResult;\n\n    if (sqrtValue < 0)\n    {\n      hitResult.hit = false;\n\n      return hitResult; //  missed the sphere\n    }\n    else\n    {\n      double t = - l_o_c - sqrtValue;\n\n      if (t < 0)\n      {\n        hitResult.hit = false;\n        return hitResult;\n      }\n\n      // ray equation\n      // R(t) = StartPos + Direction * t\n      Eigen::Vector3d hitPosition = ray.origin + ray.direction * t;\n\n      hitResult.hit = true;\n      hitResult.hitPosition = hitPosition;\n      return hitResult;\n    }\n  }\n};\n\nstruct Light\n{\n  Eigen::Vector3d pos;\n  Eigen::Vector3d color;\n  double intensity = 70;\n};\n\nclass World\n{\n  public:\n  std::vector<Object*> sceneObjects;\n  Light light;\n\n  void spawnObject()\n  {\n    light.pos = Eigen::Vector3d(0, -2, 0);\n    light.color = Eigen::Vector3d(255, 255, 255);\n\n    sceneObjects.push_back(new Sphere(0.5, Eigen::Vector3d(0.5, 0.8, -8), Eigen::Vector3d(100, 100, 0)));\n    sceneObjects.push_back(new Sphere(0.5, Eigen::Vector3d(1.9, 0.3, -9.8), Eigen::Vector3d(0, 100, 0)));\n    sceneObjects.push_back(new Sphere(0.5, Eigen::Vector3d(0.9, 0.8, -7.5), Eigen::Vector3d(0, 100, 55)));\n  }\n};\n\nclass Camera\n{\n  public:\n  Eigen::Vector3d pos;\n  Eigen::Vector3d dir;\n  double viewPlaceDist = -0.5;\n  double viewPlaneXsize;  // the size of the rendering place, in meters\n  double viewPlaneYsize;  // the size of the rendering place, in meters\n\n  Camera(double pScreenWidth, double pScreenHeight)\n  {\n    viewPlaneYsize = 0.1;\n    viewPlaneXsize = (pScreenWidth/pScreenHeight) * viewPlaneYsize;\n  }\n\n  Ray RayAtScreenSpace(double x, double y)\n  {\n    Ray ray;\n\n    ray.origin = Eigen::Vector3d(0, 0, 0.5); // TODO change this to use the camera position\n    ray.direction = Eigen::Vector3d(x * viewPlaneXsize, y * viewPlaneYsize, viewPlaceDist);\n    ray.direction.normalize();\n\n    return ray;\n  }\n};\n\nclass Renderer\n{\n  public:\n\n  SDL_Window *window;\n  int windowIndex;\n  SDL_Renderer* sdl_renderer;\n\n  World* world;\n\n  Renderer(SDL_Window *window, World *pWorld)\n  {\n    this->window = window;\n    world = pWorld;\n\n    windowIndex = -1; // the index of the rendering driver to initialize, or -1 to initialize the first one supporting the requested flags\n    int flags = 0;\n    sdl_renderer = SDL_CreateRenderer(window, windowIndex, flags);\n  }\n\n  void render()\n  {\n    SDL_SetRenderDrawColor(sdl_renderer, 255, 0, 0, 1); // If something is FULL red on the screen, it means that pixel was not rendered\n    SDL_RenderClear(sdl_renderer);\n    SDL_RenderPresent( sdl_renderer );\n\n    Camera camera(GlobalSettings::ScreenResolutionX, GlobalSettings::ScreenResolutionY);\n\n    double screenSpaceXRatio = 1.0 / GlobalSettings::ScreenResolutionX;\n    double screenSpaceYRatio = 1.0 / GlobalSettings::ScreenResolutionY;\n\n    for (int y = 0; y < GlobalSettings::ScreenResolutionY; ++y)\n    {\n      for (int x = 0; x < GlobalSettings::ScreenResolutionX; ++x)\n      {\n        double screenSpaceX = screenSpaceXRatio * x;\n        double screenSpaceY = screenSpaceYRatio * y;\n        Ray ray = camera.RayAtScreenSpace(screenSpaceX, screenSpaceY);\n\n        RayHitResult hitResult = findClosestHit(world->sceneObjects, ray);\n\n        if (hitResult.hit)\n        {\n          // calculating pixel color (SHADER!)\n          Eigen::Vector3d normal = hitResult.hitObject->normalAt(hitResult.hitPosition);\n\n          Eigen::Vector3d lightNormalToHitPos = world->light.pos - hitResult.hitPosition;\n          double distanceFromLight = lightNormalToHitPos.norm();\n          double lightAttenuation = (1/ (1 + 0.1 * distanceFromLight + 0.1 * distanceFromLight * distanceFromLight ));\n\n          lightNormalToHitPos.normalize();\n          double lightAngle = lightNormalToHitPos.dot(normal);\n\n          if (lightAngle > 0)\n          {\n            int r = hitResult.hitObject->color.x() * lightAngle * lightAttenuation * world->light.intensity;\n            int g = hitResult.hitObject->color.y() * lightAngle * lightAttenuation * world->light.intensity;\n            int b = hitResult.hitObject->color.z() * lightAngle * lightAttenuation * world->light.intensity;\n            SDL_SetRenderDrawColor(sdl_renderer, r, g, b, 1);\n          }\n          else\n          {\n            SDL_SetRenderDrawColor(sdl_renderer, 0, 0, 0, 1);\n          }\n        }\n        else\n        {\n          SDL_SetRenderDrawColor(sdl_renderer, 50, 50, 50, 1);\n        }\n\n        SDL_RenderDrawPoint(sdl_renderer, x, y);\n      }\n    }\n\n    SDL_RenderPresent( sdl_renderer );\n    std::cout << \"done\" << std::endl;\n  }\n\n  RayHitResult findClosestHit(std::vector<Object*> worldObjects, Ray ray)\n  {\n    RayHitResult closestHitResult;\n    closestHitResult.hitPosition = Eigen::Vector3d(9999, 9999, 9999);\n    closestHitResult.hit = false;\n    closestHitResult.hitObject = nullptr;\n\n    for (int i = 0; i < worldObjects.size(); ++i)\n    {\n      Object* sceneObject = world->sceneObjects[i];\n\n      RayHitResult hitResult;\n      hitResult = sceneObject->raytrace(ray);\n\n      if (hitResult.hit && hitResult.hitPosition.norm() < closestHitResult.hitPosition.norm())\n      {\n        closestHitResult = hitResult;\n        closestHitResult.hitObject = sceneObject;\n      }\n    }\n\n    return closestHitResult;\n  }\n};\n\nvoid waitUntilQuit()\n{\n  // A basic main loop to prevent blocking\n  bool is_running = true;\n  SDL_Event event;\n  while (is_running) {\n      while (SDL_PollEvent(&event)) {\n          if (event.type == SDL_QUIT) {\n              is_running = false;\n          }\n      }\n      SDL_Delay(16);\n  }\n}\n\nint main(int argc, char* argv[])\n{\n  SDL_Init(SDL_INIT_VIDEO);\n\n  SDL_Window* window = SDL_CreateWindow(\n      \"Raytracer\",\n      SDL_WINDOWPOS_CENTERED,\n      SDL_WINDOWPOS_CENTERED,\n      GlobalSettings::ScreenResolutionX,\n      GlobalSettings::ScreenResolutionY,\n      SDL_WINDOW_MAXIMIZED | SDL_WINDOW_SHOWN\n  );\n\n  if (window == NULL)\n  {\n      printf(\"Could not create window: %s\\n\", SDL_GetError());\n      return 1;\n  }\n\n  SDL_Delay(1);\n\n  World world;\n  world.spawnObject();\n\n  Renderer render(window, &world);\n  render.render();\n\n  waitUntilQuit();\n\n  SDL_DestroyWindow(window);\n  SDL_Quit();\n\n  return 0;\n}\n\n\n\n", "meta": {"hexsha": "5b8d4675b8c76ebf57cebe6aeb8d8c16c3fd89e3", "size": 7826, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "celsodantas/raytracer", "max_stars_repo_head_hexsha": "38153d9f7843aed7e4c42d2686ae8d8143b3d78e", "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": "celsodantas/raytracer", "max_issues_repo_head_hexsha": "38153d9f7843aed7e4c42d2686ae8d8143b3d78e", "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": "celsodantas/raytracer", "max_forks_repo_head_hexsha": "38153d9f7843aed7e4c42d2686ae8d8143b3d78e", "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.8444444444, "max_line_length": 138, "alphanum_fraction": 0.6399182213, "num_tokens": 2158, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107843878722, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.7075144618206118}}
{"text": "#include <iostream>\n#include <iomanip>\n#include <time.h>\n\n#include <boost/multiprecision/cpp_dec_float.hpp>\n\n#include \"../include/calcPI.h\"\n\n#include <omp.h>\n\nusing namespace boost::multiprecision;\n//namespace mp = boost::multiprecision; // mp::pow\n\nconst long long ACCUR = 100000; // \u041a\u043e\u043b-\u0432\u043e \u0437\u043d\u0430\u043a\u043e\u0432 \u043f\u043e\u0441\u043b\u0435 \u0437\u0430\u043f\u044f\u0442\u043e\u0439\nconst size_t DIGNUM = ACCUR+10;\n\ntypedef number< cpp_dec_float<DIGNUM> > cpp_dec_float_DIGNUM;\n\n\n/*\n\u041d\u0435\u044d\u0444\u0444\u0435\u043a\u0442\u0438\u0432\u043d\u0430\u044f \u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f \u044d\u0442\u043e\u0439 \u0444\u043e\u0440\u043c\u0443\u043b\u044b:\nhttps://i.imgur.com/dE8klLQ.png\n*/\nvoid calcPI()\n{\n    const cpp_dec_float_DIGNUM ONE = 1;\n    const cpp_dec_float_DIGNUM TWO = 2;\n    cpp_dec_float_DIGNUM pi;\n    cpp_dec_float_DIGNUM buff;\n    cpp_dec_float_DIGNUM a;\n    cpp_dec_float_DIGNUM b;\n    cpp_dec_float_DIGNUM diff;\n    cpp_dec_float_DIGNUM arith;\n    cpp_dec_float_DIGNUM geom;\n    cpp_dec_float_DIGNUM series;\n\n    buff = 10;\n    buff = pow(buff, -ACCUR);\n    const cpp_dec_float_DIGNUM epsilon = buff;\n\n    a = 1;\n\n    buff = sqrt(TWO);\n    b = ONE / buff;\n\n    diff = a - b;\n    series = 0;\n\n    size_t n = 0;\n    while(diff > epsilon)\n    {\n        ++n;\n        arith = (a + b) / TWO;\n        geom = sqrt(a*b);\n\n        a = arith;\n        b = geom;\n\n        buff = pow(TWO, n+1);\n        series += buff * (a*a - b*b);\n        \n        diff = a - b;\n    }\n\n    buff = 4;\n    pi = (buff*a*a) / (ONE - series);\n\n    //std::cout << \"n = \" << n << std::endl;\n    //std::cout << std::setprecision(std::numeric_limits<number< cpp_dec_float<ACCUR> >>::max_digits10) << \"pi = \" << pi << std::endl;\n}\n\n\n/*\n\u041d\u0435\u0442\u043e\u0447\u043d\u043e\u0435 \u0432\u044b\u0447\u0438\u0441\u043b\u0435\u043d\u0438\u0435 \u0447\u0438\u0441\u043b\u0430 pi, \u0441 \u043f\u043e\u043c\u043e\u0449\u044c\u044e \u044d\u0442\u043e\u0439 \u0444\u043e\u0440\u043c\u0443\u043b\u044b:\nhttps://i.imgur.com/gAMAToc.png\n*/\nvoid calcPI_mul(const unsigned threadNum)\n{\n    const size_t N = 100000000;\n    const size_t blocksize = 50000;\n    const unsigned REP_NUM = 50;\n\n\n    for(unsigned gi = 0; gi < REP_NUM; ++gi)\n    {\n\n        long double sum = 0;\n\n        #pragma omp parallel reduction (+: sum) num_threads(threadNum)\n        {\n            #pragma omp for schedule(dynamic, blocksize) nowait\n            for (size_t i = 0; i < N; ++i)\n            {\n                long double xi;\n                xi = (i + 0.5); xi /= N;\n                sum += (long double)4 / (1 + xi*xi);\n            }\n        }\n        sum /= N;\n        //std::cout << std::setprecision(80) << sum << std::endl;\n    }\n}\n", "meta": {"hexsha": "f80e5a599cea1e3f09a66c48ba911ff043cc9b1a", "size": 2277, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "func/calcPI.cpp", "max_stars_repo_name": "The220th/easybenchk", "max_stars_repo_head_hexsha": "01db67b6e86c0c2f81d5247b79533ada4e4cd221", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2022-01-21T20:45:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T13:18:50.000Z", "max_issues_repo_path": "func/calcPI.cpp", "max_issues_repo_name": "The220th/easybenchk", "max_issues_repo_head_hexsha": "01db67b6e86c0c2f81d5247b79533ada4e4cd221", "max_issues_repo_licenses": ["WTFPL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "func/calcPI.cpp", "max_forks_repo_name": "The220th/easybenchk", "max_forks_repo_head_hexsha": "01db67b6e86c0c2f81d5247b79533ada4e4cd221", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.1067961165, "max_line_length": 134, "alphanum_fraction": 0.5779534475, "num_tokens": 695, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620596782468, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.7074964364731372}}
{"text": "#include <iostream>\n#include <boost/multiprecision/float128.hpp>\n\nusing namespace std;\nusing namespace boost::multiprecision;\n\nclass Fibonacci{\n    float128 phi;\n    float128 a;\n    // Source : http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fibonacci/fibFormula.html\n    // Based on the source, we reduce the formula to on phi as 'V' contribute neglagible and its distance from zero keeps on increasing with sequence.\n\n    float128 even_sum(int num){\n\n        // Calculate the Gemotric Sum i.e. Sum = a * ((1+r**n)/(1-r))\n        // n = (1 + r **n )\n        float128 n = 1 - pow(phi,3*num);\n        // d = (1 - r)\n        float128 d = 1 - pow(phi,3);\n        // Gm of even number = a * (n/d)\n        float128 sum = a * (n/d);\n\n        return sum;\n    }\n\npublic:\n\n    Fibonacci(){\n        phi = (1+sqrt(5))/2;\n        a = pow(phi,3)/sqrt(5);\n    }\n\n    unsigned long long int get_even_sum(int limit){\n        int totalSum;\n        if(limit <= 2){\n            return 0;\n        }\n        totalSum = limit / 3;\n\n        return static_cast<unsigned long long int>(even_sum(totalSum)+1);\n    }\n};\n\n\nint main()\n{\n\n    Fibonacci obj;\n    int m_input;\n    cout<<\"Enter the Fibonacci Range : \";\n    cin>>m_input;\n    cout<<obj.get_even_sum(m_input);\n    return 0;\n}\n", "meta": {"hexsha": "7224deeb32c1f9a095bc1f466dd5a288a8426933", "size": 1261, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "raviy0807/Sum-of-Even-Fibonnaci-withoutloop-recursion", "max_stars_repo_head_hexsha": "a55a72387ef6c6f15203b7b3450a54150775d089", "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": "raviy0807/Sum-of-Even-Fibonnaci-withoutloop-recursion", "max_issues_repo_head_hexsha": "a55a72387ef6c6f15203b7b3450a54150775d089", "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": "raviy0807/Sum-of-Even-Fibonnaci-withoutloop-recursion", "max_forks_repo_head_hexsha": "a55a72387ef6c6f15203b7b3450a54150775d089", "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.9272727273, "max_line_length": 150, "alphanum_fraction": 0.5765265662, "num_tokens": 345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545333502202, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.7074550741038307}}
{"text": "#include <Eigen/Dense>\n#include <cassert>\n#include <iostream>\n\n// To disable assert*() calls, uncomment this line:\n// #define NDEBUG\n\n// This represents a triplet of indices as a column vector of nonnegative\n// integers:\n// [ i ]\n// [ j ]\n// [ k ]\ntypedef Eigen::Matrix<std::size_t, 3, 1> GridIndices;\n//\n// Returns the indices of the grid cell containing the point |p| for a grid with\n// lower corner |lc| and grid cell width (spacing) |dx|.\n//\n// If |dx| <= 0 or |p|'s location relative to |lc| would result in negative\n// indices being returned and assertions are on, then assertion failures will\n// crash this program.\ninline GridIndices floor(const Eigen::Vector3d& p, const Eigen::Vector3d& lc,\n                         double dx) {\n  // Ensure grid spacings are positive.\n  assert(dx > 0.0);\n\n  // Compute |p|'s location relative to |lc|.\n  // Dividing by |dx| yields a 3D vector indicating the number of grid\n  // cells (including fractions of grid cells, as the vector elements are\n  // floating-point values) away from |lc| that |p| is located.\n  Eigen::Vector3d p_lc_over_dx = (p - lc) / dx;\n\n  // Ensure we won't end up with negative indices.\n  assert(p_lc_over_dx[0] >= 0.0);\n  assert(p_lc_over_dx[1] >= 0.0);\n  assert(p_lc_over_dx[2] >= 0.0);\n\n  // Indices are valid. Construct and return them.\n  // This casts the elements of the vector above as nonnegative integers.\n  return p_lc_over_dx.cast<std::size_t>();\n}\n\nvoid print(const GridIndices& indices) {\n  std::cout << \"Indices: \" << std::endl;\n  std::cout << indices << std::endl;\n}\n\ninline Eigen::Vector3d weights(const Eigen::Vector3d& p,\n                               const Eigen::Vector3d& lc, double dx,\n                               const GridIndices& indices) {\n  return (p - lc) / dx - indices.cast<double>();\n}\n\nvoid PrintPointIndicesAndWeights(const Eigen::Vector3d& p,\n                                 const Eigen::Vector3d& lc, double dx) {\n  GridIndices p_indices = floor(p, lc, dx);\n  print(p_indices);\n  Eigen::Vector3d w = weights(p, lc, dx, p_indices);\n  std::cout << \"Weights = \" << std::endl;\n  std::cout << w << std::endl << std::endl;\n}\n\nint main(int argc, char** argv) {\n  // Let's have our grid's lower corner be at (3, 4, 5) with a grid spacing of\n  // 2. So, each grid cell will be a 2 x 2 x 2 cube.\n  Eigen::Vector3d lc(3, 4, 5);\n  double dx = 2.0;\n\n  // Expect (i, j, k) == (0, 3, 4), (w0, w1, w2) == (0.5, 0, 0.5)\n  Eigen::Vector3d p1(4, 10, 14);\n  PrintPointIndicesAndWeights(p1, lc, dx);\n\n  // Expect (i, j, k) == (3, 4, 16), (w0, w1, w2) == (0.5, 0.5, 0)\n  Eigen::Vector3d p2(10, 13, 37);\n  PrintPointIndicesAndWeights(p2, lc, dx);\n\n  // Expect (i, j, k) == (0, 0, 0), (w0, w1, w2) == (0, 0, 0)\n  Eigen::Vector3d p3(3, 4, 5);\n  PrintPointIndicesAndWeights(p3, lc, dx);\n  return 0;\n}\n", "meta": {"hexsha": "3455076e10c2c00f034624e6019fdd07291903d9", "size": 2783, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "incremental0/GridWeights.cpp", "max_stars_repo_name": "unusualinsights/flip_pic_examples", "max_stars_repo_head_hexsha": "3314dd4c67a681d2600feb342c88527e7618bc10", "max_stars_repo_licenses": ["BSD-4-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": "incremental0/GridWeights.cpp", "max_issues_repo_name": "unusualinsights/flip_pic_examples", "max_issues_repo_head_hexsha": "3314dd4c67a681d2600feb342c88527e7618bc10", "max_issues_repo_licenses": ["BSD-4-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": "incremental0/GridWeights.cpp", "max_forks_repo_name": "unusualinsights/flip_pic_examples", "max_forks_repo_head_hexsha": "3314dd4c67a681d2600feb342c88527e7618bc10", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.3580246914, "max_line_length": 80, "alphanum_fraction": 0.6248652533, "num_tokens": 879, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970654616711, "lm_q2_score": 0.8031738010682209, "lm_q1q2_score": 0.707433127036585}}
{"text": "//\n//  GivensQR.hpp\n//  IPC\n//\n//  Created by Minchen Li on 10/19/19.\n//\n\n#include \"Types.hpp\"\n\n#include <Eigen/Eigen>\n\nnamespace IPC {\n\ntemplate <int dim>\nclass GivensQR {\npublic:\n    static void compute(const Eigen::Matrix<double, dim, dim>& A,\n        Eigen::Matrix<double, dim, dim>& Q,\n        Eigen::Matrix<double, dim, dim>& R)\n    {\n        R = A;\n        Q.setIdentity();\n        for (int j = 0; j < dim; ++j) {\n            for (int i = dim - 1; i > j; --i) {\n                double a = R(i - 1, j), b = R(i, j);\n                double d = a * a + b * b;\n                double c = 1, s = 0;\n                double sqrtd = std::sqrt(d);\n                if (sqrtd) {\n                    double t = 1.0 / sqrtd;\n                    c = a * t;\n                    s = -b * t;\n                }\n\n                for (int k = 0; k < dim; ++k) {\n                    double tau1 = R(i - 1, k);\n                    double tau2 = R(i, k);\n                    R(i - 1, k) = c * tau1 - s * tau2;\n                    R(i, k) = s * tau1 + c * tau2;\n                }\n\n                for (int k = 0; k < dim; ++k) {\n                    double tau1 = Q(i - 1, k);\n                    double tau2 = Q(i, k);\n                    Q(i - 1, k) = c * tau1 - s * tau2;\n                    Q(i, k) = s * tau1 + c * tau2;\n                }\n            }\n        }\n        Q.transposeInPlace();\n    }\n};\n\n} // namespace IPC", "meta": {"hexsha": "b9a3839d36126db84b27de021f4edd2753a7f60c", "size": 1408, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Utils/GivensQR.hpp", "max_stars_repo_name": "vincentkslim/IPC", "max_stars_repo_head_hexsha": "eb702ead6f23a1dc0be39c9f5a0fd62c80abeb98", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 344.0, "max_stars_repo_stars_event_min_datetime": "2020-07-03T14:08:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T14:01:11.000Z", "max_issues_repo_path": "src/Utils/GivensQR.hpp", "max_issues_repo_name": "vincentkslim/IPC", "max_issues_repo_head_hexsha": "eb702ead6f23a1dc0be39c9f5a0fd62c80abeb98", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 25.0, "max_issues_repo_issues_event_min_datetime": "2020-07-05T15:56:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T20:56:39.000Z", "max_forks_repo_path": "src/Utils/GivensQR.hpp", "max_forks_repo_name": "vincentkslim/IPC", "max_forks_repo_head_hexsha": "eb702ead6f23a1dc0be39c9f5a0fd62c80abeb98", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 46.0, "max_forks_repo_forks_event_min_datetime": "2020-07-04T05:04:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T02:09:23.000Z", "avg_line_length": 26.0740740741, "max_line_length": 65, "alphanum_fraction": 0.3529829545, "num_tokens": 410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632288833652, "lm_q2_score": 0.7431680086124812, "lm_q1q2_score": 0.7073943002806969}}
{"text": "/**\n * \\copyright\n * Copyright (c) 2012-2019, OpenGeoSys Community (http://www.opengeosys.org)\n *            Distributed under a Modified BSD License.\n *              See accompanying file LICENSE.txt or\n *              http://www.opengeosys.org/project/license\n *\n */\n\n#include <gtest/gtest.h>\n\n#include <vector>\n#include <numeric>\n\n#include <Eigen/Sparse>\n\n\n/**\n * This test case checks if the internal Eigen::SparseMatrix compressed storage format\n * is a conventional CSR matrix. Currently this is the case, but it is not guaranteed\n * for all time.\n *\n * Cf. section \"Sparse matrix format\" on page\n * http://eigen.tuxfamily.org/dox/group__TutorialSparse.html\n */\nTEST(MathLibEigen, Eigen2CSR)\n{\n    const int nrows = 16;\n    const int ncols = nrows;\n\n    Eigen::SparseMatrix<double, Eigen::RowMajor> mat(nrows, ncols);\n\n    // set up sparsity pattern\n    std::vector<int> pat(nrows);\n    for (std::size_t i=0; i<nrows; ++i)\n    {\n        if (i==0 || i==nrows-1) {\n            pat[i] = 2;\n        } else {\n            pat[i] = 3;\n        }\n    }\n\n    // CSR representation of the matrix\n    std::vector<double> values;\n    std::vector<int> ia(nrows+1); // row offsets\n    std::vector<int> ja;          // column indices\n\n    std::partial_sum(pat.begin(), pat.end(), ia.begin()+1);\n\n    const int nnz = ia.back();\n    values.reserve(nnz);\n    ja.reserve(nnz);\n\n    mat.reserve(pat);\n\n    // init matrix, build CSR matrix in parallel\n    for (int row=0; row<nrows; ++row) {\n        for (int col = -1; col<=1; ++col) {\n            int cidx = row + col;\n            if (cidx < 0 || cidx >= ncols) continue;\n\n            const double val = (col == 0) ? 2.0 : -1.0;\n            values.push_back(val);\n            mat.coeffRef(row, cidx) = val;\n            ja.push_back(cidx);\n        }\n    }\n\n    // change matrix\n    for (int row=0; row<nrows; ++row) {\n        for (int col = -1; col<=1; ++col) {\n            int cidx = row + col;\n            if (cidx < 0 || cidx >= ncols) continue;\n\n            mat.coeffRef(row, cidx) = 4.0 * mat.coeff(row, cidx);\n        }\n    }\n    // adapt entries of CSR matrix\n    for (auto& v : values) v *= 4.0;\n\n    mat.makeCompressed();\n\n    ASSERT_EQ(nnz, mat.nonZeros());\n    ASSERT_EQ(nnz, values.size());\n    ASSERT_EQ(nnz, ja.size());\n\n    int* ptr = mat.outerIndexPtr();\n    int* col = mat.innerIndexPtr();\n    double* data = mat.valuePtr();\n\n    for (int r=0; r<(int) nrows; ++r) {\n        EXPECT_EQ(ia[r], ptr[r]);\n    }\n\n    for (int i=0; i<nnz; ++i) {\n        EXPECT_EQ(values[i], data[i]);\n        EXPECT_EQ(ja[i], col[i]);\n    }\n}\n\n", "meta": {"hexsha": "a70ad78a02f56ab2dc059fb5ff28c726342cec51", "size": 2572, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tests/MathLib/TestEigenCSR.cpp", "max_stars_repo_name": "mjamoein/ogs", "max_stars_repo_head_hexsha": "52e4d1bcf3bc21a44ee7710fc9900d8729334ad4", "max_stars_repo_licenses": ["BSD-4-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": "Tests/MathLib/TestEigenCSR.cpp", "max_issues_repo_name": "mjamoein/ogs", "max_issues_repo_head_hexsha": "52e4d1bcf3bc21a44ee7710fc9900d8729334ad4", "max_issues_repo_licenses": ["BSD-4-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": "Tests/MathLib/TestEigenCSR.cpp", "max_forks_repo_name": "mjamoein/ogs", "max_forks_repo_head_hexsha": "52e4d1bcf3bc21a44ee7710fc9900d8729334ad4", "max_forks_repo_licenses": ["BSD-4-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.2156862745, "max_line_length": 86, "alphanum_fraction": 0.5548211509, "num_tokens": 729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.7073851375544337}}
{"text": "#include <catch.hpp>\n#include <random>\n#include <vector>\n#include <Eigen/Core>\n#include <torch/torch.h>\n\n#include <renderer_utils.cuh>\n#include <losses.h>\n#include \"check_adjoint.h\"\n#include \"test_utils.h\"\n\n//namespace std {\n//\ttemplate < class T >\n//\tinline std::ostream& operator << (std::ostream& os, const std::vector<T>& v)\n//\t{\n//\t\tos << \"[\";\n//\t\tfor (typename std::vector<T>::const_iterator ii = v.begin(); ii != v.end(); ++ii)\n//\t\t{\n//\t\t\tos << \" \" << *ii;\n//\t\t}\n//\t\tos << \" ]\";\n//\t\treturn os;\n//\t}\n//}\n\t\nTEST_CASE(\"LogSumExp-double\", \"[math]\")\n{\n\tstd::default_random_engine rnd(42);\n\tstd::uniform_real_distribution<double> distr(-5, +5);\n\n\tfor (int N=1; N<=10; ++N)\n\t{\n\t\tDYNAMIC_SECTION(\"N=\" << N)\n\t\t{\n\t\t\tstd::vector<double> values(N);\n\t\t\tfor (int i = 0; i < N; ++i) values[i] = distr(rnd);\n\n\t\t\tconst auto valuesLambda = [values](int i) {return values[i]; };\n\t\t\tdouble resultActual = kernel::logSumExp<double>(N, valuesLambda);\n\n\t\t\t//naive\n\t\t\tdouble resultExpected = 0;\n\t\t\tfor (int i = 0; i < N; ++i) resultExpected += rexp(values[i]);\n\t\t\tresultExpected = rlog(resultExpected);\n\n\t\t\tREQUIRE(resultActual == Approx(resultExpected));\n\t\t}\n\t}\n}\nTEST_CASE(\"LogSumExp-double4\", \"[math]\")\n{\n\tstd::default_random_engine rnd(42);\n\tstd::uniform_real_distribution<double> distr(-5, +5);\n\n\tfor (int N = 1; N <= 10; ++N)\n\t{\n\t\tDYNAMIC_SECTION(\"N=\" << N)\n\t\t{\n\t\t\tstd::vector<double4> values(N);\n\t\t\tfor (int i = 0; i < N; ++i) {\n\t\t\t\tvalues[i] = make_double4(\n\t\t\t\t\tdistr(rnd), distr(rnd), \n\t\t\t\t\tdistr(rnd), distr(rnd));\n\t\t\t}\n\n\t\t\tconst auto valuesLambda = [values](int i) {return values[i]; };\n\t\t\tdouble4 resultActual = kernel::logSumExp<double4>(N, valuesLambda);\n\n\t\t\t//naive\n\t\t\tdouble4 resultExpected = make_double4(0);\n\t\t\tfor (int i = 0; i < N; ++i) resultExpected += rexp(values[i]);\n\t\t\tresultExpected = rlog(resultExpected);\n\n\t\t\tREQUIRE(resultActual.x == Approx(resultExpected.x));\n\t\t\tREQUIRE(resultActual.y == Approx(resultExpected.y));\n\t\t\tREQUIRE(resultActual.z == Approx(resultExpected.z));\n\t\t\tREQUIRE(resultActual.w == Approx(resultExpected.w));\n\t\t}\n\t}\n}\n\nTEST_CASE(\"LogSumExp-scaling-double\", \"[math]\")\n{\n\tstd::default_random_engine rnd(42);\n\tstd::uniform_real_distribution<double> distr(-5, +5);\n\n\tfor (int N = 1; N <= 10; ++N)\n\t{\n\t\tDYNAMIC_SECTION(\"N=\" << N)\n\t\t{\n\t\t\tstd::vector<double> values(N);\n\t\t\tstd::vector<double> scaling(N);\n\t\t\tfor (int i = 0; i < N; ++i) {\n\t\t\t\tvalues[i] = distr(rnd);\n\t\t\t\tscaling[i] = fabs(distr(rnd));\n\t\t\t}\n\t\t\tINFO(\"values: \" << values);\n\t\t\tINFO(\"scaling: \" << scaling);\n\n\t\t\tconst auto valuesLambda = [values](int i) {return values[i]; };\n\t\t\tconst auto scalingLambda = [scaling](int i) {return scaling[i]; };\n\t\t\tdouble resultActual = kernel::logSumExpWithScaling<double>(\n\t\t\t\tN, valuesLambda, scalingLambda);\n\n\t\t\t//naive\n\t\t\tdouble resultExpected = 0;\n\t\t\tfor (int i = 0; i < N; ++i) \n\t\t\t\tresultExpected += scaling[i] * rexp(values[i]);\n\t\t\tresultExpected = rlog(resultExpected);\n\n\t\t\tREQUIRE(resultActual == Approx(resultExpected));\n\t\t}\n\t}\n}\nTEST_CASE(\"LogSumExp-scaling-double4\", \"[math]\")\n{\n\tstd::default_random_engine rnd(42);\n\tstd::uniform_real_distribution<double> distr(-5, +5);\n\n\tfor (int N = 1; N <= 10; ++N)\n\t{\n\t\tDYNAMIC_SECTION(\"N=\" << N)\n\t\t{\n\t\t\tstd::vector<double4> values(N);\n\t\t\tstd::vector<double> scaling(N);\n\t\t\tfor (int i = 0; i < N; ++i) {\n\t\t\t\tvalues[i] = make_double4(\n\t\t\t\t\tdistr(rnd), distr(rnd),\n\t\t\t\t\tdistr(rnd), distr(rnd));\n\t\t\t\tscaling[i] = fabs(distr(rnd));\n\t\t\t}\n\n\t\t\tconst auto valuesLambda = [values](int i) {return values[i]; };\n\t\t\tconst auto scalingLambda = [scaling](int i) {return scaling[i]; };\n\t\t\tdouble4 resultActual = kernel::logSumExpWithScaling<double4>(\n\t\t\t\tN, valuesLambda, scalingLambda);\n\n\t\t\t//naive\n\t\t\tdouble4 resultExpected = make_double4(0);\n\t\t\tfor (int i = 0; i < N; ++i) \n\t\t\t\tresultExpected += scaling[i] * rexp(values[i]);\n\t\t\tresultExpected = rlog(resultExpected);\n\n\t\t\tREQUIRE(resultActual.x == Approx(resultExpected.x));\n\t\t\tREQUIRE(resultActual.y == Approx(resultExpected.y));\n\t\t\tREQUIRE(resultActual.z == Approx(resultExpected.z));\n\t\t\tREQUIRE(resultActual.w == Approx(resultExpected.w));\n\t\t}\n\t}\n}\n\nTEST_CASE(\"LogMSE-double\", \"[math]\")\n{\n\tstd::default_random_engine rnd(42);\n\tstd::uniform_real_distribution<double> distr(-5, +5);\n\n\tfor (int i = 1; i <= 50; ++i)\n\t{\n\t\tINFO(\"i: \" << i);\n\t\tdouble logX = distr(rnd);\n\t\tdouble logY = distr(rnd);\n\t\tdouble x = exp(logX), y = exp(logY);\n\t\tINFO(\"x=\" << x << \", y=\" << y);\n\n\t\tdouble mseExpected = (x - y) * (x - y);\n\n\t\tdouble mseActualLog = kernel::logMSE(logX, logY);\n\t\tdouble mseActual = exp(mseActualLog);\n\n\t\tREQUIRE(mseActual == Approx(mseExpected));\n\t}\n}\n\nTEST_CASE(\"LogL1-double\", \"[math]\")\n{\n\tstd::default_random_engine rnd(42);\n\tstd::uniform_real_distribution<double> distr(-5, +5);\n\n\tfor (int i = 1; i <= 50; ++i)\n\t{\n\t\tINFO(\"i: \" << i);\n\t\tdouble logX = distr(rnd);\n\t\tdouble logY = distr(rnd);\n\t\tdouble x = exp(logX), y = exp(logY);\n\t\tINFO(\"x=\" << x << \", y=\" << y);\n\n\t\tdouble l1Expected = fabs(x - y);\n\n\t\tdouble l1ActualLog = kernel::logL1(logX, logY);\n\t\tdouble l1Actual = exp(l1ActualLog);\n\n\t\tREQUIRE(l1Actual == Approx(l1Expected));\n\t}\n}\n\n\nTEST_CASE(\"Adjoint-LogMSE\", \"[adjoint]\")\n{\n\ttypedef empty TmpStorage_t;\n\ttypedef Eigen::VectorXd Vector_t;\n\n\tauto forward = [](const Vector_t& x, TmpStorage_t* tmp) -> Vector_t\n\t{\n\t\tdouble logX = x[0], logY = x[1];\n\t\tdouble res = kernel::logMSE(logX, logY);\n\t\tVector_t rese(1);\n\t\trese[0] = res;\n\t\treturn rese;\n\t};\n\tauto adjoint = [](const Vector_t& x, const Vector_t& e, const Vector_t& g,\n\t\tVector_t& z, const TmpStorage_t& tmp)\n\t{\n\t\tdouble logX = x[0], logY = x[1];\n\t\tdouble adjOut = g[0];\n\t\tdouble adjLogX, adjLogY;\n\t\tkernel::adjLogMSE(logX, logY, adjOut, adjLogX, adjLogY);\n\t\tz[0] = adjLogX;\n\t\tz[1] = adjLogY;\n\t};\n\n\tstd::default_random_engine rnd(42);\n\tstd::uniform_real_distribution<double> distr(-5, +5);\n\tint N = 20;\n\tfor (int i = 0; i < N; ++i)\n\t{\n\t\tINFO(\"N=\" << i);\n\t\tVector_t x(2);\n\t\tfor (int j = 0; j < 2; ++j) x[j] = distr(rnd);\n\n\t\tcheckAdjoint<Vector_t, TmpStorage_t>(x, forward, adjoint,\n\t\t\t1e-5, 1e-5, 1e-6);\n\t}\n}\n\nTEST_CASE(\"Adjoint-Log1\", \"[adjoint]\")\n{\n\ttypedef empty TmpStorage_t;\n\ttypedef Eigen::VectorXd Vector_t;\n\n\tauto forward = [](const Vector_t& x, TmpStorage_t* tmp) -> Vector_t\n\t{\n\t\tdouble logX = x[0], logY = x[1];\n\t\tdouble res = kernel::logL1(logX, logY);\n\t\tVector_t rese(1);\n\t\trese[0] = res;\n\t\treturn rese;\n\t};\n\tauto adjoint = [](const Vector_t& x, const Vector_t& e, const Vector_t& g,\n\t\tVector_t& z, const TmpStorage_t& tmp)\n\t{\n\t\tdouble logX = x[0], logY = x[1];\n\t\tdouble adjOut = g[0];\n\t\tdouble adjLogX, adjLogY;\n\t\tkernel::adjLogL1(logX, logY, adjOut, adjLogX, adjLogY);\n\t\tz[0] = adjLogX;\n\t\tz[1] = adjLogY;\n\t};\n\n\tstd::default_random_engine rnd(42);\n\tstd::uniform_real_distribution<double> distr(-5, +5);\n\tint N = 20;\n\tfor (int i = 0; i < N; ++i)\n\t{\n\t\tINFO(\"N=\" << i);\n\t\tVector_t x(2);\n\t\tfor (int j = 0; j < 2; ++j) x[j] = distr(rnd);\n\n\t\tcheckAdjoint<Vector_t, TmpStorage_t>(x, forward, adjoint,\n\t\t\t1e-5, 1e-5, 1e-6);\n\t}\n}\n\nTEST_CASE(\"Adjoint-LogMSE-Full\", \"[adjoint]\")\n{\n\ttorch::Tensor logX = torch::randn({ 4,5 },\n\t\tat::TensorOptions().dtype(c10::kDouble).device(c10::kCUDA))\n\t\t.requires_grad_(true);\n\ttorch::Tensor logY = torch::randn({ 4,5 },\n\t\tat::TensorOptions().dtype(c10::kDouble).device(c10::kCUDA))\n\t\t.requires_grad_(true);\n\n\ttorch::Tensor out = renderer::logMSE(logX, logY);\n\ttorch::Tensor grad_out = torch::rand_like(out);\n\tauto grad_inputs = torch::autograd::grad(\n\t\t{ out }, { logX, logY }, { grad_out });\n\ttorch::Tensor grad_logX = grad_inputs[0];\n\ttorch::Tensor grad_logY = grad_inputs[1];\n\n\tstd::cout << \"grad_logX:\\n\" << grad_logX << std::endl;\n}\n\n", "meta": {"hexsha": "323695eceedbfdf3eaf8623e53e318cddcf55302", "size": 7557, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittests/testMath.cpp", "max_stars_repo_name": "shamanDevel/DiffDVR", "max_stars_repo_head_hexsha": "99fbe9f114d0097daf402bde2ae35f18dade335d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2021-08-02T04:51:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-14T18:02:27.000Z", "max_issues_repo_path": "unittests/testMath.cpp", "max_issues_repo_name": "shamanDevel/DiffDVR", "max_issues_repo_head_hexsha": "99fbe9f114d0097daf402bde2ae35f18dade335d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-11-04T14:23:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-28T10:30:13.000Z", "max_forks_repo_path": "unittests/testMath.cpp", "max_forks_repo_name": "shamanDevel/DiffDVR", "max_forks_repo_head_hexsha": "99fbe9f114d0097daf402bde2ae35f18dade335d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-07-16T10:23:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T02:51:43.000Z", "avg_line_length": 25.8801369863, "max_line_length": 85, "alphanum_fraction": 0.6282916501, "num_tokens": 2456, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894717137996, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.7073582106319929}}
{"text": "/***************************************************************************\n * tiny.cpp    Blitz++ TinyVector<T,N> ray reflection example\n *\n * This example illustrates the TinyVector<T,N> class.  TinyVectors can be\n * used for small vectors whose sizes are known at compile time.  Most\n * operations on TinyVectors have their loops unravelled inline using template \n * metaprograms.\n *\n * The routine reflect(..) calculates the reflection of a monochrome ray \n * of light bouncing off a perfectly reflective, smooth surface.  \n ****************************************************************************/\n\n#include <blitz/array.h>\n#include <blitz/tinyvec2.h>\n\nBZ_USING_NAMESPACE(blitz)\n\nvoid reflect(TinyVector<double,3>& reflection, const TinyVector<double,3>& ray,\n    const TinyVector<double,3>& surfaceNormal)\n{\n    // The surface normal must be unit length to use this equation.\n\n    reflection = ray - 2 * dot(ray,surfaceNormal) * surfaceNormal;\n}\n\nint main()\n{\n    TinyVector<double,3> x, y, z;\n\n    // y will be the incident ray\n    y[0] = 1;\n    y[1] = 0;\n    y[2] = -1;\n\n    // z is the surface normal \n    z[0] = 0;\n    z[1] = 0;\n    z[2] = 1;\n\n    reflect(x, y, z);\n\n    cout << \"Reflected ray is: [ \" << x[0] << \" \" << x[1] << \" \" << x[2]\n         << \" ]\" << endl;\n}\n\n// Here's the assembly generated for reflect() using KCC +K3 -O2 on an\n// IBM RS/6000:\n\n// .reflect__(mangled-name)\n//        lfd     fp0,16(r4)\n//        lfd     fp1,16(r5)\n//        lfd     fp3,8(r4)\n//        fm      fp1,fp0,fp1\n//        lfd     fp0,8(r5)\n//        lfd     fp2,0(r4)\n//        fma     fp0,fp3,fp0,fp1\n//        lfd     fp1,0(r5)\n//        fma     fp0,fp2,fp1,fp0\n//        fa      fp0,fp0,fp0\n//        fnms    fp1,fp1,fp0,fp2\n//        stfd    fp1,0(r3)\n//        lfd     fp1,8(r4)\n//        lfd     fp2,8(r5)\n//        fnms    fp1,fp0,fp2,fp1\n//        stfd    fp1,8(r3)\n//        lfd     fp1,16(r4)\n//        lfd     fp2,16(r5)\n//        fnms    fp0,fp0,fp2,fp1\n//        stfd    fp0,16(r3)\n//        bcr     BO_ALWAYS,CR0_LT\n\n", "meta": {"hexsha": "8703550af15ec3c2bf8e6f4ea9ca8d86ef66eb2c", "size": 2035, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/examples/tiny.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/tiny.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/tiny.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": 28.2638888889, "max_line_length": 79, "alphanum_fraction": 0.512039312, "num_tokens": 642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894689081711, "lm_q2_score": 0.7905303162021596, "lm_q1q2_score": 0.707358201790339}}
{"text": "//  (C) Copyright John Maddock 2018.\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#include <boost/math/tools/fraction.hpp>\r\n#include <iostream>\r\n#include <complex>\r\n\r\n//[golden_ratio_1\r\ntemplate <class T>\r\nstruct golden_ratio_fraction\r\n{\r\n   typedef T result_type;\r\n\r\n   result_type operator()()\r\n   {\r\n      return 1;\r\n   }\r\n};\r\n//]\r\n\r\n//[cf_tan_fraction\r\ntemplate <class T>\r\nstruct tan_fraction\r\n{\r\nprivate:\r\n   T a, b;\r\npublic:\r\n   tan_fraction(T v)\r\n      : a(-v * v), b(-1)\r\n   {}\r\n\r\n   typedef std::pair<T, T> result_type;\r\n\r\n   std::pair<T, T> operator()()\r\n   {\r\n      b += 2;\r\n      return std::make_pair(a, b);\r\n   }\r\n};\r\n//]\r\n//[cf_tan\r\ntemplate <class T>\r\nT tan(T a)\r\n{\r\n   tan_fraction<T> fract(a);\r\n   return a / continued_fraction_b(fract, std::numeric_limits<T>::epsilon());\r\n}\r\n//]\r\n//[cf_expint_fraction\r\ntemplate <class T>\r\nstruct expint_fraction\r\n{\r\n   typedef std::pair<T, T> result_type;\r\n   expint_fraction(unsigned n_, T z_) : b(z_ + T(n_)), i(-1), n(n_) {}\r\n   std::pair<T, T> operator()()\r\n   {\r\n      std::pair<T, T> result = std::make_pair(-static_cast<T>((i + 1) * (n + i)), b);\r\n      b += 2;\r\n      ++i;\r\n      return result;\r\n   }\r\nprivate:\r\n   T b;\r\n   int i;\r\n   unsigned n;\r\n};\r\n//]\r\n//[cf_expint\r\ntemplate <class T>\r\ninline std::complex<T> expint_as_fraction(unsigned n, std::complex<T> const& z)\r\n{\r\n   boost::uintmax_t max_iter = 1000;\r\n   expint_fraction<std::complex<T> > f(n, z);\r\n   std::complex<T> result = boost::math::tools::continued_fraction_b(\r\n      f,\r\n      std::complex<T>(std::numeric_limits<T>::epsilon()),\r\n      max_iter);\r\n   result = exp(-z) / result;\r\n   return result;\r\n}\r\n//]\r\n//[cf_upper_gamma_fraction\r\ntemplate <class T>\r\nstruct upper_incomplete_gamma_fract\r\n{\r\nprivate:\r\n   typedef typename T::value_type scalar_type;\r\n   T z, a;\r\n   int k;\r\npublic:\r\n   typedef std::pair<T, T> result_type;\r\n\r\n   upper_incomplete_gamma_fract(T a1, T z1)\r\n      : z(z1 - a1 + scalar_type(1)), a(a1), k(0)\r\n   {\r\n   }\r\n\r\n   result_type operator()()\r\n   {\r\n      ++k;\r\n      z += scalar_type(2);\r\n      return result_type(scalar_type(k) * (a - scalar_type(k)), z);\r\n   }\r\n};\r\n//]\r\n//[cf_gamma_Q\r\ntemplate <class T>\r\ninline std::complex<T> gamma_Q_as_fraction(const std::complex<T>& a, const std::complex<T>& z)\r\n{\r\n   upper_incomplete_gamma_fract<std::complex<T> > f(a, z);\r\n   std::complex<T> eps(std::numeric_limits<T>::epsilon());\r\n   return pow(z, a) / (exp(z) *(z - a + T(1) + boost::math::tools::continued_fraction_a(f, eps)));\r\n}\r\n//]\r\n\r\n\r\nint main()\r\n{\r\n   using namespace boost::math::tools;\r\n\r\n   //[cf_gr\r\n   golden_ratio_fraction<double> func;\r\n   double gr = continued_fraction_a(\r\n      func,\r\n      std::numeric_limits<double>::epsilon());\r\n   std::cout << \"The golden ratio is: \" << gr << std::endl;\r\n   //]\r\n\r\n   std::cout << tan(0.5) << std::endl;\r\n\r\n   std::complex<double> arg(3, 2);\r\n   std::cout << expint_as_fraction(5, arg) << std::endl;\r\n\r\n   std::complex<double> a(3, 3), z(3, 2);\r\n   std::cout << gamma_Q_as_fraction(a, z) << std::endl;\r\n\r\n   return 0;\r\n}\r\n", "meta": {"hexsha": "da4df4c63140e8ac8cd8ef767f4686a95f57ae1f", "size": 3182, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/libs/math/example/continued_fractions.cpp", "max_stars_repo_name": "Jackarain/tinyrpc", "max_stars_repo_head_hexsha": "07060e3466776aa992df8574ded6c1616a1a31af", "max_stars_repo_licenses": ["BSL-1.0"], "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": "third_party/boost/libs/math/example/continued_fractions.cpp", "max_issues_repo_name": "avplayer/cxxrpc", "max_issues_repo_head_hexsha": "7049b4079fac78b3828e68f787d04d699ce52f6d", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "third_party/boost/libs/math/example/continued_fractions.cpp", "max_forks_repo_name": "avplayer/cxxrpc", "max_forks_repo_head_hexsha": "7049b4079fac78b3828e68f787d04d699ce52f6d", "max_forks_repo_licenses": ["BSL-1.0"], "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": 22.5673758865, "max_line_length": 99, "alphanum_fraction": 0.5920804525, "num_tokens": 922, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.7073581907106941}}
{"text": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union\u2019s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n\n#include \"AlgorithmUtils.hpp\"\n#include <Eigen/Core>\n#include <cassert>\n#include <cmath>\n#include <map>\n\nnamespace fluid {\nnamespace algorithm {\n\nclass DistanceFuncs\n{\n\npublic:\n  enum class Distance {\n    kManhattan,\n    kEuclidean,\n    kSqEuclidean,\n    kMax,\n    kMin,\n    kKL,\n    kCosine\n  };\n\n  using ArrayXcd = Eigen::ArrayXcd;\n  using ArrayXd = Eigen::ArrayXd;\n  using MatrixXd = Eigen::MatrixXd;\n  using DistanceFuncsMap =\n      std::map<Distance, std::function<double(ArrayXd, ArrayXd)>>;\n\n  static DistanceFuncsMap& map()\n  {\n    static DistanceFuncsMap _funcs = {\n        {Distance::kManhattan,\n         [](ArrayXd x, ArrayXd y) { return (x - y).abs().sum(); }},\n        {Distance::kEuclidean,\n         [](ArrayXd x, ArrayXd y) {\n           return std::sqrt((x - y).square().sum());\n         }},\n        {Distance::kSqEuclidean,\n         [](ArrayXd x, ArrayXd y) { return (x - y).square().sum(); }},\n        {Distance::kMax,\n         [](ArrayXd x, ArrayXd y) { return (x - y).abs().maxCoeff(); }},\n        {Distance::kMin,\n         [](ArrayXd x, ArrayXd y) { return (x - y).abs().minCoeff(); }},\n        {Distance::kKL,\n         [](ArrayXd x, ArrayXd y) {\n           auto   logX = x.max(epsilon).log(), logY = y.max(epsilon).log();\n           double d1 = (x * (logX - logY)).sum();\n           double d2 = (y * (logY - logX)).sum();\n           return d1 + d2;\n         }},\n        {Distance::kCosine, [](ArrayXd x, ArrayXd y) {\n           double norm = x.matrix().norm() * y.matrix().norm();\n           double dot = x.matrix().dot(y.matrix());\n           return dot / norm;\n         }}};\n    return _funcs;\n  }\n};\n\nEigen::MatrixXd DistanceMatrix(Eigen::Ref<Eigen::MatrixXd> X, index distance)\n{\n  auto            dist = static_cast<DistanceFuncs::Distance>(distance);\n  Eigen::MatrixXd D = Eigen::MatrixXd::Zero(X.rows(), X.rows());\n  for (index i = 0; i < X.rows(); i++)\n  {\n    for (index j = 0; j < X.rows(); j++)\n    {\n      D(i, j) = DistanceFuncs::map()[dist](X.row(i).array(), X.row(j).array());\n    }\n  }\n  return D;\n}\n\ntemplate <typename Derived>\nEigen::MatrixXd DistanceMatrix(const Eigen::PlainObjectBase<Derived>& X,\n                               const Eigen::PlainObjectBase<Derived>& Y,\n                               index                                  distance)\n{\n  auto            dist = static_cast<DistanceFuncs::Distance>(distance);\n  Eigen::MatrixXd D = Eigen::MatrixXd::Zero(X.rows(), Y.rows());\n  for (index i = 0; i < X.rows(); i++)\n  {\n    for (index j = 0; j < Y.rows(); j++)\n    {\n      D(i, j) = DistanceFuncs::map()[dist](X.row(i).array(), Y.row(j).array());\n    }\n  }\n  return D;\n}\n\n\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "69551c96c63e32b5e43be8e616df389ae7021ceb", "size": 3096, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/util/DistanceFuncs.hpp", "max_stars_repo_name": "elgiano/flucoma-core", "max_stars_repo_head_hexsha": "d34a04e7a68f24eaf09b24df57020d45664061fc", "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": "include/algorithms/util/DistanceFuncs.hpp", "max_issues_repo_name": "elgiano/flucoma-core", "max_issues_repo_head_hexsha": "d34a04e7a68f24eaf09b24df57020d45664061fc", "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": "include/algorithms/util/DistanceFuncs.hpp", "max_forks_repo_name": "elgiano/flucoma-core", "max_forks_repo_head_hexsha": "d34a04e7a68f24eaf09b24df57020d45664061fc", "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": 28.9345794393, "max_line_length": 79, "alphanum_fraction": 0.5765503876, "num_tokens": 827, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308128813471, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.7073486108699494}}
{"text": "//GlobalFunctions.cpp\n\n//Modification Date: 6/22/15\n\n#include <boost/math/distributions/normal.hpp>\n#include <cmath>\n#include <stdio.h>\n#include <iostream>\n#include <vector>\n#include \"GlobalFunctions.hpp\"\nusing namespace std;\n\n\ndouble CallPrice(double S, double K, double T, double r, double sig, double b) {\n\tdouble tmp = sig * sqrt(T);\n\n\tdouble d1 = (log(S / K) + (b + (sig*sig)*0.5) * T) / tmp;\n\tdouble d2 = d1 - tmp;\n\n\treturn (S * exp((b - r)*T) * N(d1)) - (K * exp(-r * T)* N(d2));\n}\n\ndouble CallPricePCP(double P, double S, double K, double T, double r, double b) {\n\treturn P + S*exp((b-r)*T) - K*exp(-r*T);\n}\n\n\n\ndouble PutPrice(double S, double K, double T, double r, double sig, double b){\n\tdouble tmp = sig * sqrt(T);\n\n\tdouble d1 = (log(S / K) + (b + (sig*sig)*0.5) * T) / tmp;\n\tdouble d2 = d1 - tmp;\n\n\treturn (K * exp(-r*T) * N(-d2)) - (S * exp((b - r) * T) * N(-d1));\n}\n\ndouble PutPricePCP(double C, double S, double K, double T, double r, double b) {\n\treturn C - S*exp((b - r)*T) + K*exp(-r*T);\n}\n\n\nstd::vector<double> MeshArray(double LowerLimit, double UpperLimit, int Num)\t\t\t//N - amount of steps\n{\n\tvector<double> mesh;\n\tmesh.reserve(Num+1);\n\tdouble h = (UpperLimit - LowerLimit) / Num;\n\t\n\tfor (double x = LowerLimit; x <= UpperLimit; x += h)\n\t{\n\t\tmesh.push_back(x); \t\t\n\t}\n\treturn mesh;\n}\n\nvoid PrintVector (const vector<double>& V)\n{\n\tfor (vector<double>::const_iterator it = V.begin(); it != V.end(); ++it)\n\t\tcout << *it << \", \";\n}\n\ndouble N(double x) {\n\tboost::math::normal_distribution<> myNormal(0.0, 1.0);\n\treturn boost::math::cdf(myNormal, x);\n}\n\ndouble n(double x) {\n\tboost::math::normal_distribution<> myNormal(0.0, 1.0);\n\treturn boost::math::pdf(myNormal, x);\n}\n\ndouble CallDelta(double S, double K, double T, double r, double sig, double b)\n{\n\tdouble tmp = sig * sqrt(T);\n\n\tdouble d1 = (log(S / K) + (b + (sig*sig)*0.5) * T) / tmp;\n\n\treturn exp((b - r)*T) * N(d1);\n}\n\ndouble PutDelta(double S, double K, double T, double r, double sig, double b)\n{\n\tdouble tmp = sig * sqrt(T);\n\n\tdouble d1 = (log(S / K) + (b + (sig*sig)*0.5) * T) / tmp;\n\n\treturn exp((b - r)*T) * (N(d1) - 1.0);\n}\n\ndouble GammaGF(double S, double K, double T, double r, double sig, double b) {\n\tdouble tmp = sig * sqrt(T);\n\n\tdouble d1 = (log(S / K) + (b + (sig*sig)*0.5) * T) / tmp;\n\n\treturn n(d1)*exp((b - r)*T) / (S*tmp);\n}\n\ndouble VegaGF(double S, double K, double T, double r, double sig, double b) {\n\tdouble tmp = sig * sqrt(T);\n\n\tdouble d1 = (log(S / K) + (b + (sig*sig)*0.5) * T) / tmp;\n\n\treturn S*sqrt(T)*exp((b - r)*T)*n(d1);\n}\n\ndouble CallTheta(double S, double K, double T, double r, double sig, double b) {\n\tdouble tmp = sig * sqrt(T);\n\n\tdouble d1 = (log(S / K) + (b + (sig*sig)*0.5) * T) / tmp;\n\tdouble d2 = d1 - tmp;\n\n\treturn -S*sig*exp((b - r)*T)*n(d1) / (2 * sqrt(T)) - (b - r)*S*exp((b - r)*T)*N(d1) - r*K*exp(-r*T)*N(d2);\n}\n\ndouble PutTheta(double S, double K, double T, double r, double sig, double b) {\n\tdouble tmp = sig * sqrt(T);\n\n\tdouble d1 = (log(S / K) + (b + (sig*sig)*0.5) * T) / tmp;\n\tdouble d2 = d1 - tmp;\n\n\treturn -S*sig*exp((b - r)*T)*n(d1) / (2 * sqrt(T)) - (b - r)*S*exp((b - r)*T)*N(-d1) + r*K*exp(-r*T)*N(-d2);\n}\n\ndouble CallRho(double S, double K, double T, double r, double sig, double b) {\n\tdouble tmp = sig * sqrt(T);\n\n\tdouble d1 = (log(S / K) + (b + (sig*sig)*0.5) * T) / tmp;\n\tdouble d2 = d1 - tmp;\n\n\treturn 0.01*K*T*exp(- r*T)*N(d2);\n}\n\ndouble PutRho(double S, double K, double T, double r, double sig, double b) {\n\tdouble tmp = sig * sqrt(T);\n\n\tdouble d1 = (log(S / K) + (b + (sig*sig)*0.5) * T) / tmp;\n\tdouble d2 = d1 - tmp;\n\n\treturn -0.01*K*T*exp(- r*T)*N(-d2);\n}\n\ndouble CallDelta(double S, double h, double K, double T, double r, double sig, double b) {\t\t//Delta Aproximation  using divided difference\n\treturn (CallPrice(S + h, K, T, r, sig, b) - CallPrice(S - h, K, T, r, sig, b)) / (2 * h);\n}\n\ndouble PutDelta(double S, double h, double K, double T, double r, double sig, double b) {\t\t//Delta Aproximation  using divided difference\n\treturn (PutPrice(S + h, K, T, r, sig, b) - PutPrice(S - h, K, T, r, sig, b)) / (2 * h);\n}\n\ndouble GammaGF(double S, double h, double K, double T, double r, double sig, double b) {\t\t//Gamma Aproximation  using divided difference\n\treturn (CallPrice(S + h, K, T, r, sig, b) - 2 * CallPrice(S, K, T, r, sig, b) + CallPrice(S - h, K, T, r, sig, b)) / (h * h);\n}\n\n\ndouble PerpetualCall(double S, double K, double r, double sig, double b)\n{ // Dividend q = r - b\n\n\tdouble sig2 = sig*sig;\t\t\t\t\t\t\t\t//sig to the second power defined for convenience\n\tdouble fac = b / sig2 - 0.5; fac *= fac;\t\t\t//fac to the second power defined for convenience\n\tdouble y1 = 0.5 - b / sig2 + sqrt(fac + 2.0*r / sig2);\n\n\n\tif (1.0 == y1)\t\t\t\t\t\t\t\t//no need to calculate the function if y1 equals to 1,\n\t\treturn S;\n\n\tdouble fac2 = ((y1 - 1.0)*S) / (y1 * K);\n\tdouble c = K * pow(fac2, y1) / (y1 - 1.0);\n\n\treturn c;\n}\n\ndouble PerpetualPut(double S, double K, double r, double sig, double b)\n{\n\tdouble sig2 = sig*sig;\n\tdouble fac = b / sig2 - 0.5; fac *= fac;\n\tdouble y2 = 0.5 - b / sig2 - sqrt(fac + 2.0*r / sig2);\n\n\tif (0.0 == y2)\n\t\treturn S;\n\n\tdouble fac2 = ((y2 - 1.0)*S) / (y2 * K);\n\tdouble p = K * pow(fac2, y2) / (1.0 - y2);\n\n\treturn p;\n}\n", "meta": {"hexsha": "4457490343a4909f8e5b1c14cf1d588a4ff669f6", "size": 5183, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "GlobalFunctions.cpp", "max_stars_repo_name": "IlyaKul/OptionPricers", "max_stars_repo_head_hexsha": "4907e77994e75697ba7673673536c0312cd1e063", "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": "GlobalFunctions.cpp", "max_issues_repo_name": "IlyaKul/OptionPricers", "max_issues_repo_head_hexsha": "4907e77994e75697ba7673673536c0312cd1e063", "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": "GlobalFunctions.cpp", "max_forks_repo_name": "IlyaKul/OptionPricers", "max_forks_repo_head_hexsha": "4907e77994e75697ba7673673536c0312cd1e063", "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.8655913978, "max_line_length": 138, "alphanum_fraction": 0.5913563573, "num_tokens": 1863, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813453, "lm_q2_score": 0.7879311931529758, "lm_q1q2_score": 0.707322126911085}}
{"text": "#include <Eigen/Core>\n#include <iostream>\n#include <mathtoolbox/rbf-interpolation.hpp>\n#include <random>\n#include <vector>\n\nusing Eigen::MatrixXd;\nusing Eigen::Vector2d;\nusing Eigen::VectorXd;\n\nnamespace\n{\n    std::random_device                     seed;\n    std::default_random_engine             engine(seed());\n    std::uniform_real_distribution<double> uniform_dist(-1.0, 1.0);\n\n    double CalcFunction(const Vector2d& x) { return std::sin(10.0 * x(0)) + std::sin(10.0 * x(1)); }\n} // namespace\n\nint main()\n{\n    // Generate scattered data (in this case, 500 data points in a 2-dimensional space)\n    constexpr int    number_of_samples = 500;\n    constexpr double noise_intensity   = 0.1;\n    Eigen::MatrixXd  X(2, number_of_samples);\n    Eigen::VectorXd  y(number_of_samples);\n    for (int i = 0; i < number_of_samples; ++i)\n    {\n        X.col(i) = Vector2d(uniform_dist(engine), uniform_dist(engine));\n        y(i)     = CalcFunction(X.col(i)) + noise_intensity * uniform_dist(engine);\n    }\n\n    // Define interpolation settings\n    const auto     kernel             = mathtoolbox::ThinPlateSplineRbfKernel();\n    constexpr bool use_regularization = true;\n\n    // Instantiate an interpolator\n    mathtoolbox::RbfInterpolator rbf_interpolator(kernel);\n\n    // Set data\n    rbf_interpolator.SetData(X, y);\n\n    // Calculate internal weights with or without regularization\n    rbf_interpolator.CalcWeights(use_regularization);\n\n    // Calculate and print interpolated values on randomly sampled points in CSV format\n    constexpr int number_of_test_samples = 100;\n    std::cout << \"x(0),x(1),y\" << std::endl;\n    for (int i = 0; i < number_of_test_samples; ++i)\n    {\n        const Vector2d x = Vector2d(uniform_dist(engine), uniform_dist(engine));\n        const double   y = rbf_interpolator.CalcValue(x);\n\n        std::cout << x(0) << \",\" << x(1) << \",\" << y << std::endl;\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "cc2b6c035bf03e3c97742c05805cf6c0bcceab69", "size": 1903, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/rbf-interpolation/main.cpp", "max_stars_repo_name": "amazing89/mathtoolbox", "max_stars_repo_head_hexsha": "8904bb06ced2ac501594f9574ef1ba3454b8e38e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-02-01T03:39:24.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-01T03:39:24.000Z", "max_issues_repo_path": "examples/rbf-interpolation/main.cpp", "max_issues_repo_name": "amazing89/mathtoolbox", "max_issues_repo_head_hexsha": "8904bb06ced2ac501594f9574ef1ba3454b8e38e", "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": "examples/rbf-interpolation/main.cpp", "max_forks_repo_name": "amazing89/mathtoolbox", "max_forks_repo_head_hexsha": "8904bb06ced2ac501594f9574ef1ba3454b8e38e", "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.2542372881, "max_line_length": 100, "alphanum_fraction": 0.6558066211, "num_tokens": 491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333484, "lm_q2_score": 0.7879311931529758, "lm_q1q2_score": 0.7073221182848168}}
{"text": "/* Functions-3.hpp (exercise 1.5.3)\nDescription:\n\t* Functions for exercise 1.5.3.\nFunctions:\n\t*tuple<double,double,double,double,double> GetStatisticalPRoperties(const Container&): calculate the mean, mean deviation, range, variance and standard deviation of passed dataset stored in STL container. \n\t*Type median(const Container<Type, Alloc>&): calculate median of dataset stored in passed sorted STL container.\n\t*Type mode(const Container<Type, Alloc>&): calculate the mode of dataset stored in passed STL container. If multimodal, then return the smallest mode.\n*/\n\n\n#ifndef FUNCTIONS3_HPP\n#define FUNCTIONS3_HPP\n\n#ifndef _SILENCE_ALL_CXX17_DEPRECATION_WARNINGS\n\t#define _SILENCE_ALL_CXX17_DEPRECATION_WARNINGS\n#endif\n\n\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/range/numeric.hpp>\n#include <memory>\n#include <numeric>\n#include <set>\n#include <tuple>\n#include \"Exception.hpp\"\n#include \"SizeExcept.hpp\"\n\n/* 1.5.3: */\n// a) Create a function that returns statistical properties of dataset implemented in a boost::vector:\ntemplate<typename Container>\nstd::tuple<double, double, double, double, double> GetStatisticalProperties(const Container &values)\n{\n\tstd::size_t numElements = values.size();\n\tdouble mean, meanDev = 0, range, var, stdDev;\n\tif (numElements > 0)\n\t{\n\t\t// Calculate mean:\n\t\tmean = std::accumulate(values.begin(), values.end(), 0.0L, [&](double first, double second) { return first + second; }) / (double)numElements;\n\t\t// Calculate mean deviation:\n\t\tstd::for_each(values.begin(), values.end(), [&](double element) { meanDev += std::abs(element - mean) / (double)numElements; });\n\t\t// meanDev = std::accumulate(values.begin(), values.end(), 0.0L, [&](double first, double second) { return std::abs(first - mean) + second; }) / (double)numElements;\n\t\t// Calculate range:\n\t\trange = (double) *std::max_element(values.begin(), values.end()) - (double) *std::min_element(values.begin(), values.end());\n\t\t// Calculate the variance (E[(x - mu)^2] = E(x^2) - E(x)^2).\n\t\tvar = boost::inner_product(values, values, 0.0L) / (double)numElements - mean * mean;\n\t\t// Calculate the standard deviation:\n\t\tstdDev = std::sqrt(var);\n\t}\n\telse\n\t{\n\t\tthrow Exceptions::SizeExcept(\"There must be at least one element in the passed vector.\");\n\t}\n\treturn std::make_tuple<double, double, double, double, double>(std::move(mean), std::move(meanDev), std::move(range), std::move(var), std::move(stdDev));\n}\n// b) Create a function that returns median and mode of dataset stored in boost::vector:\ntemplate<template<typename T, typename> class Container, class Type, class Alloc = std::allocator<Type>>\nType median(const Container<Type, Alloc> &values)\t\t\t\t\t\t\t\t\t\t\t/* Get median of elements in passed sorted container. */\n{\n\tif (values.size() % 2 == 0)\n\t{\n\t\treturn values[values.size() / 2]  / 2.0 + values[values.size() / 2 + 1] / 2.0;\n\t}\n\telse\n\t{\n\t\treturn values[values.size() / 2];\n\t}\n}\n\ntemplate<template<typename, typename> class Container, class Type, class Alloc = std::allocator<Type>>\nType mode(const Container<Type, Alloc> &values)\t\t\t\t\t\t\t\t\t\t\t\t/* Get mode of elements in passed container. */\n{\n\tstd::map<Type, std::size_t> uniqueCounts;\n\tstd::set<Type> modeSet;\n\tstd::size_t modeIndex = 0, maxFreq = 0;\n\tfor (auto elem = values.begin(); elem != values.end(); elem++)\n\t{\n\t\t// Add element to unique list if not present or increment frequency by 1:\n\t\tif (uniqueCounts.find(*elem) != uniqueCounts.end())\n\t\t{\n\t\t\tuniqueCounts[*elem]++;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tuniqueCounts.insert(std::pair<Type, std::size_t>(*elem, 1));\n\t\t}\n\t}\n\tif (uniqueCounts.size())\n\t{\n\t\t// Find the maximum frequency:\n\t\tstd::for_each(uniqueCounts.begin(), uniqueCounts.end(),\n\t\t[&](auto elem)\n\t\t{\n\t\t\tstd::size_t currFreq = std::get<1>(elem);\n\t\t\tif (maxFreq < currFreq)\n\t\t\t{\n\t\t\t\tmaxFreq = currFreq;\n\t\t\t}\n\t\t});\n\t\t// Put all uniques that share the maximum frequency into the mode-set:\n\t\tstd::for_each(uniqueCounts.begin(), uniqueCounts.end(),\n\t\t[&](auto elem)\n\t\t{\n\t\t\tif (std::get<1>(elem) == maxFreq)\n\t\t\t{\n\t\t\t\tmodeSet.emplace(std::get<0>(elem));\n\t\t\t}\n\t\t});\n\t\t// Return the first element in the set (std::set is in ascending order by default so first element is the smallest mode):\n\t\treturn *modeSet.begin();\n\t}\n\telse\n\t{\n\t\tthrow Exceptions::SizeExcept(\"There must be at least one element in container to calculate the mode. \");\n\t}\n}\n\n#endif", "meta": {"hexsha": "d681cc6e3a97aabb93c15dd9b937f4e102193624", "size": 4303, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Advanced C++ Course/Benjamin Rutan HW 1 Submission/1.5/1.5/Functions-3.hpp", "max_stars_repo_name": "BRutan/Cpp", "max_stars_repo_head_hexsha": "8acbc6c341f49d6d83168ccd5ba49bd6824214f9", "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": "Advanced C++ Course/Benjamin Rutan HW 1 Submission/1.5/1.5/Functions-3.hpp", "max_issues_repo_name": "BRutan/Cpp", "max_issues_repo_head_hexsha": "8acbc6c341f49d6d83168ccd5ba49bd6824214f9", "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": "Advanced C++ Course/Benjamin Rutan HW 1 Submission/1.5/1.5/Functions-3.hpp", "max_forks_repo_name": "BRutan/Cpp", "max_forks_repo_head_hexsha": "8acbc6c341f49d6d83168ccd5ba49bd6824214f9", "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.7777777778, "max_line_length": 206, "alphanum_fraction": 0.6941668603, "num_tokens": 1158, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952838963489, "lm_q2_score": 0.787931190663057, "lm_q1q2_score": 0.7073221138930611}}
{"text": "#include \"Classes.h\"\n#include <Eigen/Dense>\n#include <math.h>\nusing namespace Eigen;\n\nint Wireframe::normalise() {\n    double sumx = 0.0;\n    double sumy = 0.0;\n    double sumz = 0.0;\n    for(int i = 0; i < this->vertices.size(); i++) {\n        sumx += this->vertices[i].x;\n        sumy += this->vertices[i].y;\n        sumz += this->vertices[i].z;\n    }\n    sumx = sumx/(this->vertices.size());\n    sumy = sumy/(this->vertices.size());\n    sumz = sumz/(this->vertices.size());\n    for(int i = 0; i < this->edges.size(); i++) {\n        this->edges[i].p1.x -= sumx;\n        this->edges[i].p1.y -= sumy;\n        this->edges[i].p1.z -= sumz;\n        this->edges[i].p2.x -= sumx;\n        this->edges[i].p2.y -= sumy;\n        this->edges[i].p2.z -= sumz;\n    }\n    return 0;\n}\n\nWireframe* Wireframe::projectFrame() {\n    ///\n    /// Project the frame on xz plane\n    ///\n    double plane[4] = {0,0,1,0};\n    Wireframe* projected;\n    projected = new Wireframe;\n    for(int i = 0; i < this->edges.size(); i++) {\n        Edge edge;\n        edge.p1 = edges[i].p1.projectPoint(plane);\n        edge.p2 = edges[i].p2.projectPoint(plane);        \n        projected->edges.push_back(edge);\n    }\n    return projected;\n}\n\nint Wireframe::rotateFrame(int type) {\n    ///\n    /// Rotate the Wireframe by ten degrees\n    ///\n    Matrix3d rot;\n    double theta = 0.2;\n    double costheta = cos(theta);\n    double sintheta = sin(theta);    \n    if(type==1) {\n        rot << 1, 0, 0,\n            0, costheta, sintheta,\n            0, -sintheta, costheta;          \n    }\n    if(type==2) {\n        rot << costheta, 0, -sintheta,\n            0, 1, 0,\n            sintheta, 0, costheta;          \n    }\n    if(type==3) {\n        rot << 1, 0, 0,\n            0, costheta, -sintheta,\n            0, sintheta, costheta;          \n    }\n    if(type==4) {\n        rot << costheta, 0, sintheta,\n            0, 1, 0,\n            -sintheta, 0, costheta;             \n    }\n    for(int i = 0; i < this->edges.size(); i++) {\n        Vector3d p1(edges[i].p1.x,edges[i].p1.y,edges[i].p1.z);\n        Vector3d p2(edges[i].p2.x,edges[i].p2.y,edges[i].p2.z);\n        Vector3d p1new = rot*p1;\n        Vector3d p2new = rot*p2;\n        edges[i].p1.setCoordinates(p1new.x(),p1new.y(),p1new.z());\n        edges[i].p2.setCoordinates(p2new.x(),p2new.y(),p2new.z()); \n    }\n    return 0; \n}", "meta": {"hexsha": "bd005bfb2e670a8ca5df743a881426348e4e7523", "size": 2340, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Wireframe.cpp", "max_stars_repo_name": "DivyanshuSaxena/COP290-Assignment", "max_stars_repo_head_hexsha": "dbf06f0aa29de9c3d4250c232fb2dd14eabe1b52", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2018-03-04T18:44:22.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-04T23:07:12.000Z", "max_issues_repo_path": "src/Wireframe.cpp", "max_issues_repo_name": "DivyanshuSaxena/COP290-Assignment", "max_issues_repo_head_hexsha": "dbf06f0aa29de9c3d4250c232fb2dd14eabe1b52", "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/Wireframe.cpp", "max_forks_repo_name": "DivyanshuSaxena/COP290-Assignment", "max_forks_repo_head_hexsha": "dbf06f0aa29de9c3d4250c232fb2dd14eabe1b52", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-02-09T10:55:18.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-28T08:53:33.000Z", "avg_line_length": 28.5365853659, "max_line_length": 67, "alphanum_fraction": 0.505982906, "num_tokens": 759, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391685381605, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.7073190520966137}}
{"text": "#pragma once\n\n#include <iostream>\n#include <Eigen/Dense>\n\nclass EKF {\n\npublic: \n\n    EKF(const Eigen::MatrixXd& P0,\n        const Eigen::MatrixXd& Q,\n        const Eigen::MatrixXd& R,\n        const float& dt ) : initialized(false), P_post(P0), P_prio(P0), Q(Q), R(R), dt(dt)\n    {}\n\n    void init(const Eigen::VectorXd& x0) {\n        x_hat_prio = x0;\n        x_hat_post = x0;\n\n        I = Eigen::MatrixXd::Identity(x0.size(), x0.size());\n\n        initialized = true;\n    }\n\n\n    void prediction_update(const Eigen::VectorXd& U) {\n        if(!initialized) {\n            throw std::runtime_error(\"Filter is not initialized!\");\n        }\n\n        // Use the motion model to predict a-priori estimate\n        this->x_hat_prio = this->motion_model(this->x_hat_post, U, this->dt);\n        Eigen::MatrixXd jF = this->jacobian_F(this->x_hat_prio, U, this->dt);\n        P_prio = jF * P_post * jF.transpose() + Q;\n    }\n\n    void innovation_update(const Eigen::VectorXd& Z) {\n        Eigen::MatrixXd jH = this->jacobian_H(this->x_hat_prio);\n        Eigen::VectorXd z_predict = this->observation_model(this->x_hat_prio);\n\n        Eigen::MatrixXd K = P_prio * jH.transpose() * (jH * P_prio * jH.transpose() + R).inverse();\n        this->x_hat_post = this->x_hat_prio + K * (Z - z_predict);\n        P_post = (I - K * jH) * P_prio;\n    }\n\n    // Return the current state\n    Eigen::VectorXd get_state() {return x_hat_post;};\n\n    // Return the current state error covariance\n    Eigen::MatrixXd get_P() {return P_post;};        \n\n    // is the filter initialized?\n    bool initialized;\n\n    // // Motion model (user defined)\n    std::function<Eigen::VectorXd(const Eigen::VectorXd& x_hat_post, \n                                  const Eigen::VectorXd& u_measured, \n                                  const float& dt)> motion_model;\n\n    // Observation model (user defined)\n    std::function<Eigen::VectorXd(const Eigen::VectorXd&)> observation_model;\n\n    // Jacobian of the motion model\n    std::function<Eigen::MatrixXd(const Eigen::VectorXd& x_hat_prio,\n                                  const Eigen::VectorXd& u_measured, \n                                  const float& dt)> jacobian_F;\n    \n    // Jacobian of the observation model\n    std::function<Eigen::MatrixXd(const Eigen::VectorXd& x_hat_prio)> jacobian_H;\n\nprivate:\n    // Estimated states\n    Eigen::VectorXd x_hat_prio, x_hat_post;\n\n    float dt;\n\n    Eigen::MatrixXd P_post, P_prio, Q, R, I;\n\n\n};", "meta": {"hexsha": "927b53c6e1aaeec10380d8b623bf379fa2e7e486", "size": 2447, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ExtendedKalmanFilter/ekf.hpp", "max_stars_repo_name": "goksanisil23/lazy_minimal_robotics", "max_stars_repo_head_hexsha": "ee98a05ffbddfa62e7bb228ca121d0620874a271", "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": "ExtendedKalmanFilter/ekf.hpp", "max_issues_repo_name": "goksanisil23/lazy_minimal_robotics", "max_issues_repo_head_hexsha": "ee98a05ffbddfa62e7bb228ca121d0620874a271", "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": "ExtendedKalmanFilter/ekf.hpp", "max_forks_repo_name": "goksanisil23/lazy_minimal_robotics", "max_forks_repo_head_hexsha": "ee98a05ffbddfa62e7bb228ca121d0620874a271", "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.5875, "max_line_length": 99, "alphanum_fraction": 0.5999182673, "num_tokens": 617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.923039160069787, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.7073190308279381}}
{"text": "#pragma once\n\n#include <armadillo>\n#include \"estructura_capas_red.cpp\"\n\nusing namespace std;\nusing namespace arma;\n\nnamespace ic {\n\nvec sigmoid(const vec& v)\n{\n\treturn 2 / (1 + exp(-0.5 * v)) - 1;\n}\n\nvector<vec> salidaMulticapa(const vector<mat>& pesos,\n                            const vec& patron)\n{\n\t// Este multicapa va a tener salida lineal s\u00f3lo en la capa de salida.\n\t// En las dem\u00e1s capas se va a usar salida sigmoidea.\n\tvector<vec> ySalidas;\n\n\t// Calculo de la salida para la primer capa\n\t{\n\t\tvec v = pesos[0] * join_vert(vec{-1}, patron); // agrega entrada correspondiente al sesgo\n\n\t\tif (pesos.size() != 1) { // Si hay m\u00e1s de una capa, a la salida de la primera\n\t\t\tv = sigmoid(v);      // hay que aplicarle sigmoidea.\n\t\t}\n\n\t\tySalidas.push_back(v);\n\t}\n\n\t// Calculo de las salidas para las demas capas\n\tfor (unsigned int i = 1; i < pesos.size(); ++i) {\n\t\tvec v = pesos[i] * join_vert(vec{-1}, ySalidas[i - 1]); // agrega entrada correspondiente al sesgo\n\n\t\tif (i != pesos.size() - 1) { // Para todas las capas menos la \u00faltima, usar salida sigmoidea.\n\t\t\tv = sigmoid(v);\n\t\t}\n\n\t\tySalidas.push_back(v);\n\t}\n\n\treturn ySalidas;\n}\n\ndouble errorCuadraticoMulticapa(const vector<mat>& pesos,\n                                const mat& patrones,\n                                const mat& salidaDeseada)\n{\n\tdouble errorCuadraticoTotal = 0;\n\n\tfor (unsigned int n = 0; n < patrones.n_rows; ++n) {\n\t\tvector<vec> ySalidas = salidaMulticapa(pesos, patrones.row(n).t());\n\t\tconst vec salidaRed = ySalidas.back();\n\n\t\tconst double errorCuadraticoPatron = sum(pow(salidaDeseada.row(n).t() - salidaRed, 2));\n\t\terrorCuadraticoTotal += errorCuadraticoPatron;\n\t}\n\n\treturn errorCuadraticoTotal;\n}\n\ndouble errorRelativoPromedioMulticapa(const vector<mat>& pesos,\n                                      const mat& patrones,\n                                      const mat& salidaDeseada)\n{\n\tdouble sumaErroresRelativos = 0;\n\n\tfor (unsigned int n = 0; n < patrones.n_rows; ++n) {\n\t\tvector<vec> ySalidas = salidaMulticapa(pesos, patrones.row(n).t());\n\t\tconst vec salidaRed = ySalidas.back();\n\n\t\tdouble sumaParcial = 0;\n\n\t\tfor (unsigned int i = 0; i < salidaDeseada.n_cols; ++i) {\n\t\t\tconst double errorRelativoPatron = abs(salidaRed(i) - salidaDeseada(n, i)) / abs(salidaDeseada(n, i));\n\t\t\tsumaParcial += errorRelativoPatron;\n\t\t}\n\n\t\t// Promedio del error absoluto a lo largo de todas las salidas\n\t\t// de este patr\u00f3n.\n\t\tsumaErroresRelativos += sumaParcial / salidaDeseada.n_cols;\n\t}\n\n\t// Promedio del error a lo largo de todos los patrones\n\treturn sumaErroresRelativos / patrones.n_rows * 100;\n}\n\nvector<mat> epocaMulticapa(const mat& patrones,\n                           const mat& salidaDeseada,\n                           double tasaAprendizaje,\n                           double inercia,\n                           vector<mat> pesos)\n{\n\t//Entrenamiento\n\tvector<mat> deltaWOld;\n\tfor (unsigned int i = 0; i < pesos.size(); ++i)\n\t\tdeltaWOld.push_back(zeros(pesos[i].n_rows, pesos[i].n_cols));\n\n\tfor (unsigned int n = 0; n < patrones.n_rows; ++n) {\n\t\t// Calcular las salidas para cada capa\n\t\tconst vector<vec> ySalidas = salidaMulticapa(pesos, patrones.row(n).t());\n\n\t\t// Calculo del error\n\t\tconst vec error = salidaDeseada.row(n).t() - ySalidas.back();\n\n\t\t// Calculo retropropagacion\n\t\t// Calculo de gradiente error local instantaneo\n\t\tvector<vec> delta;\n\t\t// Tenemos tantos vectores de deltas como capas\n\t\tdelta.resize(ySalidas.size());\n\n\t\t// Delta de ultima capa\n\t\tdelta[delta.size() - 1] = error;\n\t\t// Deltas de las capas anteriores\n\t\tfor (int i = ySalidas.size() - 2; i >= 0; --i) {\n\t\t\t// No participan los pesos correspondientes al sesgo en el c\u00e1lculo de los deltas\n\t\t\tconst mat pesosAux = pesos[i + 1].tail_cols(pesos[i + 1].n_cols - 1);\n\t\t\tdelta[i] = pesosAux.t() * delta[i + 1];\n\t\t}\n\n\t\t// Actualizacion de pesos de todas las capas menos la primera.\n\t\t// Si la red tiene una sola capa, no se entra ac\u00e1.\n\t\tfor (int i = pesos.size() - 1; i >= 1; --i) {\n\t\t\tconst mat deltaWnuevo = tasaAprendizaje\n\t\t\t                            * delta[i]\n\t\t\t                            * join_horiz(vec{-1}, ySalidas[i - 1].t())\n\t\t\t                        + inercia * deltaWOld[i];\n\t\t\tpesos[i] += deltaWnuevo;\n\t\t\tdeltaWOld[i] = deltaWnuevo;\n\t\t}\n\n\t\t// Actualizaci\u00f3n de pesos de la primer capa\n\t\tconst mat deltaW = tasaAprendizaje\n\t\t                       * delta[0]\n\t\t                       * join_horiz(vec{-1}, patrones.row(n))\n\t\t                   + inercia * deltaWOld[0];\n\t\tpesos[0] += deltaW;\n\t\tdeltaWOld[0] = deltaW;\n\t}\n\n\treturn pesos;\n} // fin funcion Epoca\n\ntuple<vector<mat>, double, int> entrenarMulticapa(const EstructuraCapasRed& estructura,\n                                                  const mat& datos,\n                                                  int nEpocas,\n                                                  double tasaAprendizaje,\n                                                  double inercia,\n                                                  double tolErrorRelativoPromedio,\n                                                  bool monitoreo = false)\n{\n    mat partEntrenamiento;\n    mat partMonitoreo;\n\n    if (monitoreo) {\n        const int nEntrenamiento = datos.n_rows * 0.9;\n        partEntrenamiento = datos.head_rows(nEntrenamiento);\n        partMonitoreo = datos.tail_rows(datos.n_rows - nEntrenamiento);\n    }\n    else {\n        partEntrenamiento = datos;\n    }\n\n\tconst int nSalidas = estructura(estructura.n_elem - 1);\n    const int nEntradas = partEntrenamiento.n_cols - nSalidas;\n\tconst int nCapas = estructura.n_elem;\n\t// Vamos a tener tantas columnas en salidaDeseada\n\t// como neuronas en la capa de salida\n    const mat salidaDeseada = partEntrenamiento.tail_cols(nSalidas);\n\t// Extender la matriz de patrones con la entrada correspondiente al umbral\n    const mat patrones = partEntrenamiento.head_cols(nEntradas);\n\n\t// Inicializar pesos y tasa de error\n\tvector<mat> pesos;\n\n\t// La primer matriz matriz de pesos tiene tantas filas como neuronas en la primer capa\n\t// y tantas columnas como componentes tiene la entrada, m\u00e1s la entrada correspondiente\n\t// al sesgo.\n\tpesos.push_back(randu(estructura(0), nEntradas + 1) - 0.5);\n\n\tfor (int i = 1; i < nCapas; ++i) {\n\t\t// Las siguientes matrices de pesos tienen tantas filas como neuronas en dicha capa\n\t\t// y tantas columnas como entradas a esa capa, que van a ser las salidas de\n\t\t// la capa anterior mas la entrada correspondiente al sesgo.\n\t\t// Las salidas de la capa anterior es igual al nro de neuronas en la capa anterior.\n\t\tpesos.push_back(randu(estructura(i), estructura(i - 1) + 1) - 0.5);\n\t}\n\n\tdouble errorRelativoPromedio;\n    double menorErrorMonitoreo = numeric_limits<double>::max();\n    vector<mat> mejoresPesos = pesos;\n    //    int mejorEpoca = 0;\n\n\t// Ciclo de las epocas\n\tint epoca = 1;\n\tfor (; epoca <= nEpocas; ++epoca) {\n\t\t// Ciclo para una \u00e9poca\n\t\tpesos = epocaMulticapa(patrones,\n\t\t                       salidaDeseada,\n\t\t                       tasaAprendizaje,\n\t\t                       inercia,\n\t\t                       pesos);\n\n\t\terrorRelativoPromedio = errorRelativoPromedioMulticapa(pesos, patrones, salidaDeseada);\n        //        cout << epoca << \" Error cuadratico entrenamiento: \"\n        //             << errorCuadraticoMulticapa(pesos, patrones, salidaDeseada) << endl;\n\n        if (monitoreo) {\n            const double errorMonitoreo = errorCuadraticoMulticapa(pesos,\n                                                                   partMonitoreo.head_cols(nEntradas),\n                                                                   partMonitoreo.tail_cols(nSalidas));\n            //            cout << \"Error cuadratico monitoreo: \" << errorMonitoreo << endl;\n\n            if (errorMonitoreo < menorErrorMonitoreo) {\n                menorErrorMonitoreo = errorMonitoreo;\n                mejoresPesos = pesos;\n                //                mejorEpoca = epoca;\n            }\n        }\n\n        if (errorRelativoPromedio <= tolErrorRelativoPromedio)\n            break;\n    }\n    // Fin ciclo (epocas)\n\n    // Si el bucle anterior no cort\u00f3 por tolerancia de error,\n    // el for va a incrementar la variable una vez de m\u00e1s.\n    if (epoca > nEpocas)\n        epoca = nEpocas;\n\n    //    cout << \"Mejor epoca: \" << mejorEpoca << endl;\n\n    if (monitoreo)\n        return make_tuple(mejoresPesos, errorRelativoPromedio, epoca);\n    else\n        return make_tuple(pesos, errorRelativoPromedio, epoca);\n}\n\nstruct ParametrosMulticapa {\n\tEstructuraCapasRed estructuraRed;\n\tint nEpocas;\n\tdouble tasaAprendizaje;\n\tdouble inercia;\n\tdouble toleranciaError;\n};\n}\n\nistream& operator>>(istream& is, ic::ParametrosMulticapa& parametros)\n{\n\t// Formato:\n\t// estructura: [3 2 1]\n\t// n_epocas: 200\n\t// tasa_entrenamiento: 0.1\n\t// inercia: 0.5\n\t// parametro_sigmoidea: 1\n\t// tolerancia_error: 5\n\tstring str;\n\n\t// No chequeamos si la etiqueta de cada l\u00ednea est\u00e1 bien o no. No nos importa\n\tis >> str >> parametros.estructuraRed\n\t    >> str >> parametros.nEpocas\n\t    >> str >> parametros.tasaAprendizaje\n\t    >> str >> parametros.inercia\n\t    >> str >> parametros.toleranciaError;\n\n\t// Control b\u00e1sico de valores de par\u00e1metros\n\tif (parametros.nEpocas <= 0\n\t    || parametros.tasaAprendizaje <= 0\n\t    || parametros.toleranciaError <= 0\n\t    || parametros.toleranciaError >= 100)\n\t\tis.clear(ios::failbit);\n\n\treturn is;\n}\n", "meta": {"hexsha": "fd2b886e342a7cec1b36daad78346d48200f9b70", "size": 9300, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "guia2/mlp_salida_lineal.cpp", "max_stars_repo_name": "junrrein/ic2017", "max_stars_repo_head_hexsha": "e7ab09257093a56751c58a4633a049f7746f00e3", "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": "guia2/mlp_salida_lineal.cpp", "max_issues_repo_name": "junrrein/ic2017", "max_issues_repo_head_hexsha": "e7ab09257093a56751c58a4633a049f7746f00e3", "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": "guia2/mlp_salida_lineal.cpp", "max_forks_repo_name": "junrrein/ic2017", "max_forks_repo_head_hexsha": "e7ab09257093a56751c58a4633a049f7746f00e3", "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": 33.4532374101, "max_line_length": 105, "alphanum_fraction": 0.6135483871, "num_tokens": 2609, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777929, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.7072788861636322}}
{"text": "/**\n * \\file RobertBristowJohnsonFilter.hxx\n */\n\n#include \"RobertBristowJohnsonFilter.h\"\n\n#include <boost/math/constants/constants.hpp>\n\nnamespace ATK\n{\n  template<typename DataType>\n  RobertBristowJohnsonLowPassCoefficients<DataType>::RobertBristowJohnsonLowPassCoefficients(gsl::index nb_channels)\n    :Parent(nb_channels)\n  {\n  }\n\n  template <typename DataType>\n  void RobertBristowJohnsonLowPassCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n\n    CoeffDataType w0 = 2 * boost::math::constants::pi<CoeffDataType>() * cut_frequency / input_sampling_rate;\n    CoeffDataType cosw0 = std::cos(w0);\n    CoeffDataType alpha = std::sin(w0) / (2 * Q);\n\n    coefficients_in[2] = (1 - cosw0)/2 / (1 + alpha);\n    coefficients_in[1] = (1 - cosw0) / (1 + alpha);\n    coefficients_in[0] = (1 - cosw0) / 2 / (1 + alpha);\n    coefficients_out[1] = 2 * cosw0 / (1 + alpha);\n    coefficients_out[0] = (alpha - 1) / (1 + alpha);\n  }\n\n  template <typename DataType_>\n  void RobertBristowJohnsonLowPassCoefficients<DataType_>::set_Q(CoeffDataType Q)\n  {\n    if (Q <= 0)\n    {\n      throw std::out_of_range(\"Q must be positive\");\n    }\n    this->Q = Q;\n    setup();\n  }\n\n  template <typename DataType_>\n  typename RobertBristowJohnsonLowPassCoefficients<DataType_>::CoeffDataType RobertBristowJohnsonLowPassCoefficients<DataType_>::get_Q() const\n  {\n    return Q;\n  }\n\n  template<typename DataType>\n  RobertBristowJohnsonHighPassCoefficients<DataType>::RobertBristowJohnsonHighPassCoefficients(gsl::index nb_channels)\n    :Parent(nb_channels)\n  {\n  }\n\n  template <typename DataType>\n  void RobertBristowJohnsonHighPassCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n\n    CoeffDataType w0 = 2 * boost::math::constants::pi<CoeffDataType>() * cut_frequency / input_sampling_rate;\n    CoeffDataType cosw0 = std::cos(w0);\n    CoeffDataType alpha = std::sin(w0) / (2 * Q);\n\n    coefficients_in[2] = (1 + cosw0) / 2 / (1 + alpha);\n    coefficients_in[1] = -(1 + cosw0) / (1 + alpha);\n    coefficients_in[0] = (1 + cosw0) / 2 / (1 + alpha);\n    coefficients_out[1] = 2 * cosw0 / (1 + alpha);\n    coefficients_out[0] = (alpha - 1) / (1 + alpha);\n  }\n\n  template <typename DataType_>\n  void RobertBristowJohnsonHighPassCoefficients<DataType_>::set_Q(CoeffDataType Q)\n  {\n    if (Q <= 0)\n    {\n      throw std::out_of_range(\"Q must be positive\");\n    }\n    this->Q = Q;\n    setup();\n  }\n\n  template <typename DataType_>\n  typename RobertBristowJohnsonHighPassCoefficients<DataType_>::CoeffDataType RobertBristowJohnsonHighPassCoefficients<DataType_>::get_Q() const\n  {\n    return Q;\n  }\n\n  template<typename DataType>\n  RobertBristowJohnsonBandPassCoefficients<DataType>::RobertBristowJohnsonBandPassCoefficients(gsl::index nb_channels)\n    :Parent(nb_channels)\n  {\n  }\n\n  template <typename DataType>\n  void RobertBristowJohnsonBandPassCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n\n    CoeffDataType w0 = 2 * boost::math::constants::pi<CoeffDataType>() * cut_frequency / input_sampling_rate;\n    CoeffDataType cosw0 = std::cos(w0);\n    CoeffDataType alpha = std::sin(w0) / (2 * Q);\n\n    coefficients_in[2] = Q * alpha / (1 + alpha);\n    coefficients_in[1] = 0;\n    coefficients_in[0] = - Q * alpha / (1 + alpha);\n    coefficients_out[1] = 2 * cosw0 / (1 + alpha);\n    coefficients_out[0] = (alpha - 1) / (1 + alpha);\n  }\n\n  template <typename DataType_>\n  void RobertBristowJohnsonBandPassCoefficients<DataType_>::set_Q(CoeffDataType Q)\n  {\n    if (Q <= 0)\n    {\n      throw std::out_of_range(\"Q must be positive\");\n    }\n    this->Q = Q;\n    setup();\n  }\n\n  template <typename DataType_>\n  typename RobertBristowJohnsonBandPassCoefficients<DataType_>::CoeffDataType RobertBristowJohnsonBandPassCoefficients<DataType_>::get_Q() const\n  {\n    return Q;\n  }\n\n  template<typename DataType>\n  RobertBristowJohnsonBandPass2Coefficients<DataType>::RobertBristowJohnsonBandPass2Coefficients(gsl::index nb_channels)\n    :Parent(nb_channels)\n  {\n  }\n\n  template <typename DataType>\n  void RobertBristowJohnsonBandPass2Coefficients<DataType>::setup()\n  {\n    Parent::setup();\n\n    CoeffDataType w0 = 2 * boost::math::constants::pi<CoeffDataType>() * cut_frequency / input_sampling_rate;\n    CoeffDataType cosw0 = std::cos(w0);\n    CoeffDataType alpha = std::sin(w0) / (2 * Q);\n\n    coefficients_in[2] = alpha / (1 + alpha);\n    coefficients_in[1] = 0;\n    coefficients_in[0] = -alpha / (1 + alpha);\n    coefficients_out[1] = 2 * cosw0 / (1 + alpha);\n    coefficients_out[0] = (alpha - 1) / (1 + alpha);\n  }\n\n  template <typename DataType_>\n  void RobertBristowJohnsonBandPass2Coefficients<DataType_>::set_Q(CoeffDataType Q)\n  {\n    if (Q <= 0)\n    {\n      throw std::out_of_range(\"Q must be positive\");\n    }\n    this->Q = Q;\n    setup();\n  }\n\n  template <typename DataType_>\n  typename RobertBristowJohnsonBandPass2Coefficients<DataType_>::CoeffDataType RobertBristowJohnsonBandPass2Coefficients<DataType_>::get_Q() const\n  {\n    return Q;\n  }\n  \n  template<typename DataType>\n  RobertBristowJohnsonBandStopCoefficients<DataType>::RobertBristowJohnsonBandStopCoefficients(gsl::index nb_channels)\n  :Parent(nb_channels)\n  {\n  }\n  \n  template <typename DataType>\n  void RobertBristowJohnsonBandStopCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n    \n    CoeffDataType w0 = 2 * boost::math::constants::pi<CoeffDataType>() * cut_frequency / input_sampling_rate;\n    CoeffDataType cosw0 = std::cos(w0);\n    CoeffDataType alpha = std::sin(w0) / (2 * Q);\n    \n    coefficients_in[2] = 1 / (1 + alpha);\n    coefficients_in[1] = -2 * cosw0 / (1 + alpha);\n    coefficients_in[0] = 1 / (1 + alpha);\n    coefficients_out[1] = 2 * cosw0 / (1 + alpha);\n    coefficients_out[0] = (alpha - 1) / (1 + alpha);\n  }\n  \n  template <typename DataType_>\n  void RobertBristowJohnsonBandStopCoefficients<DataType_>::set_Q(CoeffDataType Q)\n  {\n    if (Q <= 0)\n    {\n      throw std::out_of_range(\"Q must be positive\");\n    }\n    this->Q = Q;\n    setup();\n  }\n  \n  template <typename DataType_>\n  typename RobertBristowJohnsonBandStopCoefficients<DataType_>::CoeffDataType RobertBristowJohnsonBandStopCoefficients<DataType_>::get_Q() const\n  {\n    return Q;\n  }\n\n  template<typename DataType>\n  RobertBristowJohnsonAllPassCoefficients<DataType>::RobertBristowJohnsonAllPassCoefficients(gsl::index nb_channels)\n    :Parent(nb_channels)\n  {\n  }\n\n  template <typename DataType>\n  void RobertBristowJohnsonAllPassCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n\n    CoeffDataType w0 = 2 * boost::math::constants::pi<CoeffDataType>() * cut_frequency / input_sampling_rate;\n    CoeffDataType cosw0 = std::cos(w0);\n    CoeffDataType alpha = std::sin(w0) / (2 * Q);\n\n    coefficients_in[2] = (1 - alpha) / (1 + alpha);\n    coefficients_in[1] = -2 * cosw0 / (1 + alpha);\n    coefficients_in[0] = 1;\n    coefficients_out[1] = 2 * cosw0 / (1 + alpha);\n    coefficients_out[0] = (alpha - 1) / (1 + alpha);\n  }\n\n  template <typename DataType_>\n  void RobertBristowJohnsonAllPassCoefficients<DataType_>::set_Q(CoeffDataType Q)\n  {\n    if (Q <= 0)\n    {\n      throw std::out_of_range(\"Q must be positive\");\n    }\n    this->Q = Q;\n    setup();\n  }\n\n  template <typename DataType_>\n  typename RobertBristowJohnsonAllPassCoefficients<DataType_>::CoeffDataType RobertBristowJohnsonAllPassCoefficients<DataType_>::get_Q() const\n  {\n    return Q;\n  }\n  \n  template<typename DataType>\n  RobertBristowJohnsonBandPassPeakCoefficients<DataType>::RobertBristowJohnsonBandPassPeakCoefficients(gsl::index nb_channels)\n  :Parent(nb_channels)\n  {\n  }\n  \n  template <typename DataType>\n  void RobertBristowJohnsonBandPassPeakCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n    \n    CoeffDataType w0 = 2 * boost::math::constants::pi<CoeffDataType>() * cut_frequency / input_sampling_rate;\n    CoeffDataType cosw0 = std::cos(w0);\n    CoeffDataType alpha = std::sin(w0) / (2 * Q);\n    \n    coefficients_in[2] = (1 + alpha * gain) / (1 + alpha / gain);\n    coefficients_in[1] = -2 * cosw0 / (1 + alpha / gain);\n    coefficients_in[0] = (1 - alpha * gain) / (1 + alpha / gain);\n    coefficients_out[1] = 2 * cosw0 / (1 + alpha / gain);\n    coefficients_out[0] = (alpha / gain - 1) / (1 + alpha / gain);\n  }\n  \n  template <typename DataType_>\n  void RobertBristowJohnsonBandPassPeakCoefficients<DataType_>::set_Q(CoeffDataType Q)\n  {\n    if (Q <= 0)\n    {\n      throw std::out_of_range(\"Q must be positive\");\n    }\n    this->Q = Q;\n    setup();\n  }\n  \n  template <typename DataType_>\n  typename RobertBristowJohnsonBandPassPeakCoefficients<DataType_>::CoeffDataType RobertBristowJohnsonBandPassPeakCoefficients<DataType_>::get_Q() const\n  {\n    return Q;\n  }\n  \n  template <typename DataType_>\n  void RobertBristowJohnsonBandPassPeakCoefficients<DataType_>::set_gain(CoeffDataType gain)\n  {\n    if (gain <= 0)\n    {\n      throw std::out_of_range(\"gain must be positive\");\n    }\n    this->gain = gain;\n    setup();\n  }\n  \n  template <typename DataType_>\n  typename RobertBristowJohnsonBandPassPeakCoefficients<DataType_>::CoeffDataType RobertBristowJohnsonBandPassPeakCoefficients<DataType_>::get_gain() const\n  {\n    return gain;\n  }\n  \n  template<typename DataType>\n  RobertBristowJohnsonLowShelvingCoefficients<DataType>::RobertBristowJohnsonLowShelvingCoefficients(gsl::index nb_channels)\n  :Parent(nb_channels)\n  {\n  }\n  \n  template <typename DataType>\n  void RobertBristowJohnsonLowShelvingCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n    \n    CoeffDataType w0 = 2 * boost::math::constants::pi<CoeffDataType>() * cut_frequency / input_sampling_rate;\n    CoeffDataType cosw0 = std::cos(w0);\n    CoeffDataType alpha = std::sin(w0) / (2 * Q);\n    CoeffDataType d = (gain + 1) + (gain - 1) * cosw0 + 2 * std::sqrt(gain) * alpha;\n\n    coefficients_in[2] = gain * ((gain + 1) - (gain - 1) * cosw0 + 2 * sqrt(gain) * alpha) / d;\n    coefficients_in[1] = 2 * gain * ((gain - 1) - (gain + 1) * cosw0) / d;\n    coefficients_in[0] = gain * ((gain + 1) - (gain - 1) * cosw0 - 2 * sqrt(gain) * alpha) / d;\n    coefficients_out[1] = 2 * ((gain - 1) + (gain + 1) * cosw0) / d;\n    coefficients_out[0] = -((gain + 1) + (gain - 1) * cosw0 - 2 * sqrt(gain) * alpha) / d;\n  }\n  \n  template <typename DataType_>\n  void RobertBristowJohnsonLowShelvingCoefficients<DataType_>::set_Q(CoeffDataType Q)\n  {\n    if (Q <= 0)\n    {\n      throw std::out_of_range(\"Q must be positive\");\n    }\n    this->Q = Q;\n    setup();\n  }\n  \n  template <typename DataType_>\n  typename RobertBristowJohnsonLowShelvingCoefficients<DataType_>::CoeffDataType RobertBristowJohnsonLowShelvingCoefficients<DataType_>::get_Q() const\n  {\n    return Q;\n  }\n  \n  template <typename DataType_>\n  void RobertBristowJohnsonLowShelvingCoefficients<DataType_>::set_gain(CoeffDataType gain)\n  {\n    if (gain <= 0)\n    {\n      throw std::out_of_range(\"gain must be positive\");\n    }\n    this->gain = gain;\n    setup();\n  }\n  \n  template <typename DataType_>\n  typename RobertBristowJohnsonLowShelvingCoefficients<DataType_>::CoeffDataType RobertBristowJohnsonLowShelvingCoefficients<DataType_>::get_gain() const\n  {\n    return gain;\n  }\n  \n  template<typename DataType>\n  RobertBristowJohnsonHighShelvingCoefficients<DataType>::RobertBristowJohnsonHighShelvingCoefficients(gsl::index nb_channels)\n  :Parent(nb_channels)\n  {\n  }\n  \n  template <typename DataType>\n  void RobertBristowJohnsonHighShelvingCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n    \n    CoeffDataType w0 = 2 * boost::math::constants::pi<CoeffDataType>() * cut_frequency / input_sampling_rate;\n    CoeffDataType cosw0 = std::cos(w0);\n    CoeffDataType alpha = std::sin(w0) / (2 * Q);\n    CoeffDataType d = (gain + 1) - (gain - 1) * cosw0 + 2 * std::sqrt(gain) * alpha;\n    \n    coefficients_in[2] = gain * ((gain + 1) + (gain - 1) * cosw0 + 2 * sqrt(gain) * alpha) / d;\n    coefficients_in[1] = -2 * gain * ((gain - 1) + (gain + 1) * cosw0) / d;\n    coefficients_in[0] = gain * ((gain + 1) + (gain - 1) * cosw0 - 2 * sqrt(gain) * alpha) / d;\n    coefficients_out[1] = -2 * ((gain - 1) - (gain + 1) * cosw0) / d;\n    coefficients_out[0] = -((gain + 1) - (gain - 1) * cosw0 - 2 * sqrt(gain) * alpha) / d;\n  }\n  \n  template <typename DataType_>\n  void RobertBristowJohnsonHighShelvingCoefficients<DataType_>::set_Q(CoeffDataType Q)\n  {\n    if (Q <= 0)\n    {\n      throw std::out_of_range(\"Q must be positive\");\n    }\n    this->Q = Q;\n    setup();\n  }\n  \n  template <typename DataType_>\n  typename RobertBristowJohnsonHighShelvingCoefficients<DataType_>::CoeffDataType RobertBristowJohnsonHighShelvingCoefficients<DataType_>::get_Q() const\n  {\n    return Q;\n  }\n  \n  template <typename DataType_>\n  void RobertBristowJohnsonHighShelvingCoefficients<DataType_>::set_gain(CoeffDataType gain)\n  {\n    if (gain <= 0)\n    {\n      throw std::out_of_range(\"gain must be positive\");\n    }\n    this->gain = gain;\n    setup();\n  }\n  \n  template <typename DataType_>\n  typename RobertBristowJohnsonHighShelvingCoefficients<DataType_>::CoeffDataType RobertBristowJohnsonHighShelvingCoefficients<DataType_>::get_gain() const\n  {\n    return gain;\n  }\n}\n", "meta": {"hexsha": "3c880c64e6530361cc2806b96c23d608800ab0f0", "size": 13029, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "ATK/EQ/RobertBristowJohnsonFilter.hxx", "max_stars_repo_name": "AudioTK/AudioTK", "max_stars_repo_head_hexsha": "dba42eea68534501efe74692b74edf4792cca231", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2021-02-04T10:47:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T03:45:00.000Z", "max_issues_repo_path": "ATK/EQ/RobertBristowJohnsonFilter.hxx", "max_issues_repo_name": "AudioTK/AudioTK", "max_issues_repo_head_hexsha": "dba42eea68534501efe74692b74edf4792cca231", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-02-01T15:45:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-13T19:39:05.000Z", "max_forks_repo_path": "ATK/EQ/RobertBristowJohnsonFilter.hxx", "max_forks_repo_name": "AudioTK/AudioTK", "max_forks_repo_head_hexsha": "dba42eea68534501efe74692b74edf4792cca231", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-04-12T03:28:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-17T00:47:11.000Z", "avg_line_length": 31.3951807229, "max_line_length": 155, "alphanum_fraction": 0.6804052498, "num_tokens": 3839, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768525822309, "lm_q2_score": 0.7490872131147276, "lm_q1q2_score": 0.7072708071882584}}
{"text": "// MomentTools.cpp\n//\n// Breannan Smith\n// Last updated: 09/14/2015\n\n#include \"MomentTools.h\"\n\n#include <iostream>\n\n#include <Eigen/Eigenvalues>\n\nstatic void diagonalizeInertiaTensor( const Matrix3s& I, Matrix3s& R0, Vector3s& I0 )\n{\n  // Inertia tensor should by symmetric\n  assert( ( I - I.transpose() ).lpNorm<Eigen::Infinity>() <= 1.0e-6 );\n  // Inertia tensor should have positive determinant\n  assert( I.determinant() > 0.0 );\n\n  // Compute the eigenvectors and eigenvalues of the input matrix\n  const Eigen::SelfAdjointEigenSolver<Matrix3s> es{ I };\n\n  // Check for errors\n  if( es.info() == Eigen::NumericalIssue )\n  {\n    std::cerr << \"Warning, failed to compute eigenvalues of inertia tensor due to Eigen::NumericalIssue\" << std::endl;\n  }\n  else if( es.info() == Eigen::NoConvergence )\n  {\n    std::cerr << \"Warning, failed to compute eigenvalues of inertia tensor due to Eigen::NoConvergence\" << std::endl;\n  }\n  else if( es.info() == Eigen::InvalidInput )\n  {\n    std::cerr << \"Warning, failed to compute eigenvalues of inertia tensor due to Eigen::InvalidInput\" << std::endl;\n  }\n  assert( es.info() == Eigen::Success );\n\n  // Save the eigenvectors and eigenvalues\n  I0 = es.eigenvalues();\n  assert( ( I0.array() > 0.0 ).all() );\n  assert( I0.x() <= I0.y() );\n  assert( I0.y() <= I0.z() );\n  R0 = es.eigenvectors();\n  assert( fabs( fabs( R0.determinant() ) - 1.0 ) <= 1.0e-6 );\n\n  // Ensure that we have an orientation preserving transform\n  if( R0.determinant() < 0.0 )\n  {\n    R0.col( 0 ) *= -1.0;\n  }\n}\n\nnamespace MomentTools\n{\n\n// TODO: most of this function can be vectorized\nvoid computeMoments( const Matrix3Xsc& vertices, const Matrix3Xuc& indices, scalar& mass, Vector3s& I, Vector3s& center, Matrix3s& R )\n{\n  assert( ( indices.array() < unsigned( vertices.cols() ) ).all() );\n\n  constexpr scalar oneDiv6{ 1.0 / 6.0 };\n  constexpr scalar oneDiv24{ 1.0 / 24.0 };\n  constexpr scalar oneDiv60{ 1.0 / 60.0 };\n  constexpr scalar oneDiv120{ 1.0 / 120.0 };\n\n  // order:  1, x, y, z, x^2, y^2, z^2, xy, yz, zx\n  VectorXs integral{ VectorXs::Zero( 10 ) };\n\n  for( int i = 0; i < indices.cols(); ++i )\n  {\n    // Copy the vertices of triangle i\n    const Vector3s v0{ vertices.col( indices( 0, i ) ) };\n    const Vector3s v1{ vertices.col( indices( 1, i ) ) };\n    const Vector3s v2{ vertices.col( indices( 2, i ) ) };\n\n    // Compute a normal for the current triangle\n    const Vector3s N{ ( v1 - v0 ).cross( v2 - v0 ) };\n\n    // Compute the integral terms\n    scalar tmp0{ v0.x() + v1.x() };\n    scalar tmp1{ v0.x() * v0.x() };\n    scalar tmp2{ tmp1 + v1.x() * tmp0 };\n    const scalar f1x{ tmp0 + v2.x() };\n    const scalar f2x{ tmp2 + v2.x() * f1x };\n    const scalar f3x{ v0.x() * tmp1 + v1.x() * tmp2 + v2.x() * f2x };\n    const scalar g0x{ f2x + v0.x() * ( f1x + v0.x() ) };\n    const scalar g1x{ f2x + v1.x() * ( f1x + v1.x() ) };\n    const scalar g2x{ f2x + v2.x() * ( f1x + v2.x() ) };\n\n    tmp0 = v0.y() + v1.y();\n    tmp1 = v0.y() * v0.y();\n    tmp2 = tmp1 + v1.y() * tmp0;\n    const scalar f1y{ tmp0 + v2.y() };\n    const scalar f2y{ tmp2 + v2.y() * f1y };\n    const scalar f3y{ v0.y() * tmp1 + v1.y() * tmp2 + v2.y() * f2y };\n    const scalar g0y{ f2y + v0.y() * ( f1y + v0.y() ) };\n    const scalar g1y{ f2y + v1.y() * ( f1y + v1.y() ) };\n    const scalar g2y{ f2y + v2.y() * ( f1y + v2.y() ) };\n\n    tmp0 = v0.z() + v1.z();\n    tmp1 = v0.z()*v0.z();\n    tmp2 = tmp1 + v1.z()*tmp0;\n    const scalar f1z{ tmp0 + v2.z() };\n    const scalar f2z{ tmp2 + v2.z() * f1z };\n    const scalar f3z{ v0.z() * tmp1 + v1.z() * tmp2 + v2.z() * f2z };\n    const scalar g0z{ f2z + v0.z() * ( f1z + v0.z() ) };\n    const scalar g1z{ f2z + v1.z() * ( f1z + v1.z() ) };\n    const scalar g2z{ f2z + v2.z() * ( f1z + v2.z() ) };\n\n    // Update integrals\n    integral(0) += N.x() * f1x;\n    integral(1) += N.x() * f2x;\n    integral(2) += N.y() * f2y;\n    integral(3) += N.z() * f2z;\n    integral(4) += N.x() * f3x;\n    integral(5) += N.y() * f3y;\n    integral(6) += N.z() * f3z;\n    integral(7) += N.x() * ( v0.y() * g0x + v1.y() * g1x + v2.y() * g2x );\n    integral(8) += N.y() * ( v0.z() * g0y + v1.z() * g1y + v2.z() * g2y );\n    integral(9) += N.z() * ( v0.x() * g0z + v1.x() * g1z + v2.x() * g2z );\n  }\n\n  integral(0) *= oneDiv6;\n  integral(1) *= oneDiv24;\n  integral(2) *= oneDiv24;\n  integral(3) *= oneDiv24;\n  integral(4) *= oneDiv60;\n  integral(5) *= oneDiv60;\n  integral(6) *= oneDiv60;\n  integral(7) *= oneDiv120;\n  integral(8) *= oneDiv120;\n  integral(9) *= oneDiv120;\n\n  // Mass\n  mass = integral(0);\n\n  // Center of mass\n  center = Vector3s{ integral(1), integral(2), integral(3) } / mass;\n\n  // Inertia relative to world origin\n  R(0,0) = integral(5) + integral(6);\n  R(0,1) = -integral(7);\n  R(0,2) = -integral(9);\n  R(1,0) = R(0,1);\n  R(1,1) = integral(4) + integral(6);\n  R(1,2) = -integral(8);\n  R(2,0) = R(0,2);\n  R(2,1) = R(1,2);\n  R(2,2) = integral(4) + integral(5);\n\n  // Comptue the inertia relative to the center of mass\n  R(0,0) -= mass * ( center.y() * center.y() + center.z() * center.z() );\n  R(0,1) += mass * center.x() * center.y();\n  R(0,2) += mass * center.z() * center.x();\n  R(1,0) = R(0,1);\n  R(1,1) -= mass * ( center.z() * center.z() + center.x() * center.x() );\n  R(1,2) += mass * center.y() * center.z();\n  R(2,0) = R(0,2);\n  R(2,1) = R(1,2);\n  R(2,2) -= mass * ( center.x() * center.x() + center.y() * center.y() );\n\n  // Diagonalize the inertia tensor\n  Matrix3s R0;\n  diagonalizeInertiaTensor( R, R0, I );\n  // Check that we actually diagonalized the inertia tensor\n  assert( ( R0 * I.asDiagonal() * R0.transpose() - R ).lpNorm<Eigen::Infinity>() <= 1.0e-9 );\n  assert( ( R0.transpose() * R * R0 - Matrix3s{ I.asDiagonal() } ).lpNorm<Eigen::Infinity>() <= 1.0e-9 );\n  R = R0;\n\n  // All inertias should be positive\n  assert( ( I.array() > 0.0 ).all() );\n  // Check that we have an orthonormal transformation\n  assert( ( R * R.transpose() - Matrix3s::Identity() ).lpNorm<Eigen::Infinity>() <= 1.0e-9 );\n  assert( fabs( R.determinant() - 1.0 ) <= 1.0e-9 );\n}\n\n}\n", "meta": {"hexsha": "50caa9451a6ea68525a54a8a3a49f6a9dd314445", "size": 6008, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rigidbody3d/Geometry/MomentTools.cpp", "max_stars_repo_name": "Lyestria/scisim", "max_stars_repo_head_hexsha": "e2c2abc8d38ea9b07717841782c5c723fce37ce5", "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": "rigidbody3d/Geometry/MomentTools.cpp", "max_issues_repo_name": "Lyestria/scisim", "max_issues_repo_head_hexsha": "e2c2abc8d38ea9b07717841782c5c723fce37ce5", "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": "rigidbody3d/Geometry/MomentTools.cpp", "max_forks_repo_name": "Lyestria/scisim", "max_forks_repo_head_hexsha": "e2c2abc8d38ea9b07717841782c5c723fce37ce5", "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": 33.9435028249, "max_line_length": 134, "alphanum_fraction": 0.5669107856, "num_tokens": 2267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037282594921, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.7072178666159094}}
{"text": "/**\n * @file tests/pca_test.cpp\n * @author Ajinkya Kale\n * @author Marcus Edel\n *\n * Test file for PCA class.\n *\n * mlpack is free software; you may redistribute it and/or modify it under the\n * terms of the 3-clause BSD license.  You should have received a copy of the\n * 3-clause BSD license along with mlpack.  If not, see\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n */\n#include <mlpack/core.hpp>\n#include <mlpack/methods/pca/pca.hpp>\n#include <mlpack/methods/pca/decomposition_policies/exact_svd_method.hpp>\n#include <mlpack/methods/pca/decomposition_policies/quic_svd_method.hpp>\n#include <mlpack/methods/pca/decomposition_policies/randomized_svd_method.hpp>\n#include <mlpack/methods/pca/decomposition_policies/randomized_block_krylov_method.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nBOOST_AUTO_TEST_SUITE(PCATest);\n\nusing namespace arma;\nusing namespace mlpack;\nusing namespace mlpack::pca;\nusing namespace mlpack::distribution;\n\n/*\n * Compare the output of the our PCA implementation with Armadillo's using the\n * specified decomposition policy.\n */\ntemplate<typename DecompositionPolicy>\nvoid ArmaComparisonPCA(\n    const bool scaleData = false,\n    const DecompositionPolicy& decomposition = DecompositionPolicy())\n{\n  arma::mat coeff, coeff1, score, score1;\n  arma::vec eigVal, eigVal1;\n\n  arma::mat data = arma::randu<arma::mat>(3, 1000);\n\n  PCA<DecompositionPolicy> pcaType(scaleData, decomposition);\n  pcaType.Apply(data, score1, eigVal1, coeff1);\n\n  princomp(coeff, score, eigVal, trans(data));\n\n  // Verify the PCA results based on the eigenvalues.\n  for (size_t i = 0; i < eigVal.n_elem; i++)\n  {\n    if (eigVal[i] == 0.0)\n      BOOST_REQUIRE_SMALL(eigVal1[i], 1e-15);\n    else\n      BOOST_REQUIRE_CLOSE(eigVal[i], eigVal1[i], 0.0001);\n  }\n}\n\n/*\n * Test that dimensionality reduction with PCA works the same way MATLAB does\n * (which should be correct!) using the specified decomposition policy.\n */\ntemplate<typename DecompositionPolicy>\nvoid PCADimensionalityReduction(\n    const bool scaleData = false,\n    const DecompositionPolicy& decomposition = DecompositionPolicy())\n{\n  // Fake, simple dataset.  The results we will compare against are from MATLAB.\n  mat data(\"1 0 2 3 9;\"\n           \"5 2 8 4 8;\"\n           \"6 7 3 1 8\");\n\n  // Now run PCA to reduce the dimensionality.\n  size_t trial = 0;\n  bool success = false;\n  double varRetained = 0.0;\n  while (trial < 3 && !success)\n  {\n    // In some cases the LU decomposition may fail.\n    try\n    {\n      PCA<DecompositionPolicy> p(scaleData, decomposition);\n      varRetained = p.Apply(data, 2); // Reduce to 2 dimensions.\n      success = true;\n    }\n    catch (std::logic_error&) { }\n\n    ++trial;\n  }\n\n  BOOST_REQUIRE_EQUAL(success, true);\n\n  // Compare with correct results.\n  mat correct(\"-1.53781086 -3.51358020 -0.16139887 -1.87706634  7.08985628;\"\n              \" 1.29937798  3.45762685 -2.69910005 -3.15620704  1.09830225\");\n\n  BOOST_REQUIRE_EQUAL(data.n_rows, correct.n_rows);\n  BOOST_REQUIRE_EQUAL(data.n_cols, correct.n_cols);\n\n  // If the eigenvectors are pointed opposite directions, they will cancel\n  // each other out in this summation.\n  for (size_t i = 0; i < data.n_rows; i++)\n  {\n    if (accu(abs(correct.row(i) + data.row(i))) < 0.001 /* arbitrary */)\n    {\n      // Flip Armadillo coefficients for this column.\n      data.row(i) *= -1;\n    }\n  }\n\n  for (size_t row = 0; row < 2; row++)\n    for (size_t col = 0; col < 5; col++)\n      BOOST_REQUIRE_CLOSE(data(row, col), correct(row, col), 1e-3);\n\n  // Check that the amount of variance retained is right.\n  BOOST_REQUIRE_CLOSE(varRetained, 0.904876047045906, 1e-5);\n}\n\n/**\n * Test that setting the variance retained parameter to perform dimensionality\n * reduction works using the specified decomposition policy.\n */\ntemplate<typename DecompositionPolicy>\nvoid PCAVarianceRetained()\n{\n    // Fake, simple dataset.\n  mat data(\"1 0 2 3 9;\"\n           \"5 2 8 4 8;\"\n           \"6 7 3 1 8\");\n\n  // The normalized eigenvalues:\n  //   0.616237391936100\n  //   0.288638655109805\n  //   0.095123952954094\n  // So if we keep one dimension, the actual variance retained is\n  //   0.616237391936100\n  // and if we keep two, the actual variance retained is\n  //   0.904876047045906\n  // and if we keep three, the actual variance retained is 1.\n  PCA<DecompositionPolicy> p;\n  arma::mat origData = data;\n  double varRetained = p.Apply(data, 0.1);\n\n  BOOST_REQUIRE_EQUAL(data.n_rows, 1);\n  BOOST_REQUIRE_EQUAL(data.n_cols, 5);\n  BOOST_REQUIRE_CLOSE(varRetained, 0.616237391936100, 1e-5);\n\n  data = origData;\n  varRetained = p.Apply(data, 0.5);\n\n  BOOST_REQUIRE_EQUAL(data.n_rows, 1);\n  BOOST_REQUIRE_EQUAL(data.n_cols, 5);\n  BOOST_REQUIRE_CLOSE(varRetained, 0.616237391936100, 1e-5);\n\n  data = origData;\n  varRetained = p.Apply(data, 0.7);\n\n  BOOST_REQUIRE_EQUAL(data.n_rows, 2);\n  BOOST_REQUIRE_EQUAL(data.n_cols, 5);\n  BOOST_REQUIRE_CLOSE(varRetained, 0.904876047045906, 1e-5);\n\n  data = origData;\n  varRetained = p.Apply(data, 0.904);\n\n  BOOST_REQUIRE_EQUAL(data.n_rows, 2);\n  BOOST_REQUIRE_EQUAL(data.n_cols, 5);\n  BOOST_REQUIRE_CLOSE(varRetained, 0.904876047045906, 1e-5);\n\n  data = origData;\n  varRetained = p.Apply(data, 0.905);\n\n  BOOST_REQUIRE_EQUAL(data.n_rows, 3);\n  BOOST_REQUIRE_EQUAL(data.n_cols, 5);\n  BOOST_REQUIRE_CLOSE(varRetained, 1.0, 1e-5);\n\n  data = origData;\n  varRetained = p.Apply(data, 1.0);\n\n  BOOST_REQUIRE_EQUAL(data.n_rows, 3);\n  BOOST_REQUIRE_EQUAL(data.n_cols, 5);\n  BOOST_REQUIRE_CLOSE(varRetained, 1.0, 1e-5);\n}\n\n/**\n * Compare the output of our exact PCA implementation with Armadillo's.\n */\nBOOST_AUTO_TEST_CASE(ArmaComparisonExactPCATest)\n{\n  ArmaComparisonPCA<ExactSVDPolicy>();\n}\n\n/**\n * Compare the output of our randomized block krylov PCA implementation with\n * Armadillo's.\n */\nBOOST_AUTO_TEST_CASE(ArmaComparisonRandomizedBlockKrylovPCATest)\n{\n  RandomizedBlockKrylovSVDPolicy decomposition(5);\n  ArmaComparisonPCA<RandomizedBlockKrylovSVDPolicy>(false, decomposition);\n}\n\n/**\n * Compare the output of our randomized-SVD PCA implementation with Armadillo's.\n */\nBOOST_AUTO_TEST_CASE(ArmaComparisonRandomizedPCATest)\n{\n  ArmaComparisonPCA<RandomizedSVDPolicy>();\n}\n\n/**\n * Test that dimensionality reduction with exact-svd PCA works the same way\n * MATLAB does (which should be correct!).\n */\nBOOST_AUTO_TEST_CASE(ExactPCADimensionalityReductionTest)\n{\n  PCADimensionalityReduction<ExactSVDPolicy>();\n}\n\n/**\n * Test that dimensionality reduction with randomized block krylov PCA works the\n * same way MATLAB does (which should be correct!).\n */\nBOOST_AUTO_TEST_CASE(RandomizedBlockKrylovPCADimensionalityReductionTest)\n{\n  RandomizedBlockKrylovSVDPolicy decomposition(5);\n  PCADimensionalityReduction<RandomizedBlockKrylovSVDPolicy>(false,\n      decomposition);\n}\n\n/**\n * Test that dimensionality reduction with randomized-svd PCA works the same way\n * MATLAB does (which should be correct!).\n */\nBOOST_AUTO_TEST_CASE(RandomizedPCADimensionalityReductionTest)\n{\n  PCADimensionalityReduction<RandomizedSVDPolicy>();\n}\n\n/**\n * Test that dimensionality reduction with QUIC-SVD PCA works the same way\n * as the Exact-SVD PCA method.\n */\nBOOST_AUTO_TEST_CASE(QUICPCADimensionalityReductionTest)\n{\n  arma::mat data, data1;\n  data::Load(\"test_data_3_1000.csv\", data);\n  data1 = data;\n\n  arma::mat backupData(data);\n\n  // It isn't guaranteed that the QUIC-SVD will match with the exact SVD method,\n  // starting with random samples. If this works 1 of 5 times, I'm fine with\n  // that. All I want to know is that the QUIC-SVD method is able to solve the\n  // task and is at least as good as the exact method (plus a little bit for\n  // noise).\n  size_t successes = 0;\n  for (size_t trial = 0; trial < 5; ++trial)\n  {\n    if (trial > 0)\n    {\n      data = backupData;\n      data1 = backupData;\n    }\n\n    PCA<ExactSVDPolicy> exactPCA;\n    const double varRetainedExact = exactPCA.Apply(data, 1);\n\n    PCA<QUICSVDPolicy> quicPCA;\n    const double varRetainedQUIC = quicPCA.Apply(data1, 1);\n\n    if (std::abs(varRetainedExact - varRetainedQUIC) < 0.2)\n    {\n      ++successes;\n      break;\n    }\n  }\n\n  BOOST_REQUIRE_GE(successes, 1);\n  BOOST_REQUIRE_EQUAL(data.n_rows, data1.n_rows);\n  BOOST_REQUIRE_EQUAL(data.n_cols, data1.n_cols);\n}\n\n/**\n * Test that setting the variance retained parameter to perform dimensionality\n * reduction works using the exact svd PCA method.\n */\nBOOST_AUTO_TEST_CASE(ExactPCAVarianceRetainedTest)\n{\n  PCAVarianceRetained<ExactSVDPolicy>();\n}\n\n/**\n * Test that scaling PCA works.\n */\nBOOST_AUTO_TEST_CASE(PCAScalingTest)\n{\n  // Generate an artificial dataset in 3 dimensions.\n  arma::mat data(3, 5000);\n\n  arma::vec mean(\"1.0 3.0 -12.0\");\n  arma::mat cov(\"1.0 0.9 0.0;\"\n                \"0.9 1.0 0.0;\"\n                \"0.0 0.0 12.0\");\n  GaussianDistribution g(mean, cov);\n\n  for (size_t i = 0; i < 5000; ++i)\n    data.col(i) = g.Random();\n\n  // Now get the principal components when we are scaling.\n  PCA<> p(true);\n  arma::mat transData;\n  arma::vec eigval;\n  arma::mat eigvec;\n\n  p.Apply(data, transData, eigval, eigvec);\n\n  // The first two components of the eigenvector with largest eigenvalue should\n  // be somewhere near sqrt(2) / 2.  The third component should be close to\n  // zero.  There is noise, of course...\n  BOOST_REQUIRE_CLOSE(std::abs(eigvec(0, 0)), sqrt(2) / 2, 0.35);\n  BOOST_REQUIRE_CLOSE(std::abs(eigvec(1, 0)), sqrt(2) / 2, 0.35);\n  BOOST_REQUIRE_SMALL(eigvec(2, 0), 0.1); // Large tolerance for noise.\n\n  // The second component should be focused almost entirely in the third\n  // dimension.\n  BOOST_REQUIRE_SMALL(eigvec(0, 1), 0.1);\n  BOOST_REQUIRE_SMALL(eigvec(1, 1), 0.1);\n  BOOST_REQUIRE_CLOSE(std::abs(eigvec(2, 1)), 1.0, 0.35);\n\n  // The third component should have the same absolute value characteristics as\n  // the first (plus 20% tolerance).\n  BOOST_REQUIRE_CLOSE(std::abs(eigvec(0, 0)), sqrt(2) / 2, 0.35);\n  BOOST_REQUIRE_CLOSE(std::abs(eigvec(1, 0)), sqrt(2) / 2, 0.35);\n  BOOST_REQUIRE_SMALL(eigvec(2, 0), 0.1); // Large tolerance for noise.\n\n  // The eigenvalues should sum to three.\n  BOOST_REQUIRE_CLOSE(accu(eigval), 3.0, 0.1); // 10% tolerance.\n}\n\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "6060e6838fb5391b83964ad89a2c21deb16c6f8e", "size": 10166, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/pca_test.cpp", "max_stars_repo_name": "KimSangYeon-DGU/mlpack", "max_stars_repo_head_hexsha": "defa29791f43d3372b019f552134abc39def234a", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "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/mlpack/tests/pca_test.cpp", "max_issues_repo_name": "KimSangYeon-DGU/mlpack", "max_issues_repo_head_hexsha": "defa29791f43d3372b019f552134abc39def234a", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "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/mlpack/tests/pca_test.cpp", "max_forks_repo_name": "KimSangYeon-DGU/mlpack", "max_forks_repo_head_hexsha": "defa29791f43d3372b019f552134abc39def234a", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-06-05T13:27:26.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-23T09:44:31.000Z", "avg_line_length": 29.7251461988, "max_line_length": 87, "alphanum_fraction": 0.7102105056, "num_tokens": 2955, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.7071937638585588}}
{"text": "#include <iostream>\n#include <fstream>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include \"ceres/ceres.h\"\n#include \"glog/logging.h\"\n\nusing ceres::AutoDiffCostFunction;\nusing ceres::CostFunction;\nusing ceres::Problem;\nusing ceres::Solve;\nusing ceres::Solver;\n\nconst double DT = 1.0 / 18;\n// const Eigen::Vector3d GRAVITY{0, 0, 0};\nconst Eigen::Vector3d GRAVITY{0, 0, -9.8};\n\nstruct State {\n  Eigen::Vector3d pos = Eigen::Vector3d::Random(); // position \n  Eigen::Vector3d vel = Eigen::Vector3d::Random(); // velocity\n  Eigen::Quaterniond q = Eigen::Quaterniond::UnitRandom(); // pose Qwr\n\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n};\n\nstruct Measurement{\n  Eigen::Matrix3d Rwr;\n  Eigen::Quaterniond qwr;\n  Eigen::Vector3d twr;\n  Eigen::Vector3d acc;\n  Eigen::Vector3d omega; \n\n  Measurement(Eigen::Matrix3d Rwr,                \n              Eigen::Quaterniond qwr,\n              Eigen::Vector3d twr,\n              Eigen::Vector3d acc,\n              Eigen::Vector3d omega)\n    : Rwr(Rwr), qwr(qwr), twr(twr), acc(acc), omega(omega) {}\n\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n};\n\nstruct PositionError {\n\tPositionError(const Eigen::Vector3d& pos_measured) \n\t\t: pos_measured_(pos_measured) {}\n\n\ttemplate <typename T>\n\tbool operator()(const T* const pos_hat_ptr,\n\t\t\t\t\t\t\t\t\tT* residuals_ptr) const {\n\t\tEigen::Matrix<T, 3, 1> pos_hat(pos_hat_ptr);\n\t\tEigen::Matrix<T, 3, 1> pos_delta = pos_hat - pos_measured_.template cast<T>();\t\n\n    for (int i = 0; i < 3; i++) {\n      residuals_ptr[i] = pos_delta[i];\n    }\n\t\treturn true;\n\t}\n\n\tstatic CostFunction* Create(const Eigen::Vector3d& pos_measured) {\n\t\treturn new AutoDiffCostFunction<PositionError, 3, 3>(\n\t\t\tnew PositionError(pos_measured)\n\t\t);\n\t}\n\nEIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\nprivate:\n\tconst Eigen::Vector3d pos_measured_;\n};\n\nstruct PoseError {\n  PoseError(const Eigen::Vector3d& pos_measured,\n            const Eigen::Quaterniond& q_measured)\n    : pos_measured_(pos_measured), q_measured_(q_measured) {}\n\n  template <typename T>\n  bool operator()(const T* const pos_hat_ptr,\n                  const T* const q_hat_ptr,\n                  T* residuals_ptr) const {   \n    Eigen::Matrix<T, 6, 1> residuals;\n    \n    Eigen::Matrix<T, 3, 1> pos_hat(pos_hat_ptr);\n    Eigen::Matrix<T, 3, 1> pos_delta;\n    residuals.template block<3, 1>(0, 0) = pos_hat - pos_measured_.template cast<T>();\n\n    Eigen::Quaternion<T> q_hat(q_hat_ptr);\n    Eigen::Quaternion<T> q_delta = q_measured_.conjugate().template cast<T>() * q_hat;\n    residuals.template block<3, 1>(3, 0) = q_delta.vec();\n    for (int i = 0; i < 6; i++) {\n      residuals_ptr[i] = residuals[i];\n    }\n    return true;\n  } \n  \n  static CostFunction* Create(const Eigen::Vector3d& pos_measured,\n                              const Eigen::Quaterniond& q_measured) {\n    return new AutoDiffCostFunction<PoseError, 6, 3, 4>(\n      new PoseError(pos_measured, q_measured));\n  }\n\nEIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\nprivate:\n  const Eigen::Vector3d pos_measured_;\n  const Eigen::Quaterniond q_measured_;\n};\n\n\nstruct PredictionError{\n  PredictionError(const Eigen::Vector3d& acc_measured,\n                  const Eigen::Vector3d& omega_measured)\n    : acc_measured_(acc_measured), omega_measured_(omega_measured) {}\n\n  template <typename T>\n  bool operator()(const T* const pos_b_ptr,\n                  const T* const vel_b_ptr,\n                  const T* const q_b_ptr,\n                  const T* const pos_e_ptr,\n                  const T* const vel_e_ptr,\n                  const T* const q_e_ptr,\n                  const T* const bias_ptr,\n                  T* residuals_ptr) const {\n    Eigen::Matrix<T, 9, 1> residuals;\n\n    // quat error\n    const Eigen::Quaternion<T> q_b(q_b_ptr);\n    const Eigen::Quaternion<T> q_e(q_e_ptr);\n    \n    Eigen::Quaternion<T> q_new;\n    Eigen::Quaternion<T> q_add; \n    \n    // // https://gamedev.stackexchange.com/questions/108920/applying-angular-velocity-to-quaternion \n    // Eigen::Quaternion<T> q_omega;\n    // // q_omega.w() = 0;\n    // q_omega.vec() = omega_measured_.template cast<T>() * DT * 0.5;\n    // q_add = q_omega * q_b;\n    // q_new.w() = q_b.w() + q_add.w();\n    // q_new.vec() = q_b.vec() + q_add.vec();\n\n    Eigen::Vector3d rotated = omega_measured_ * DT;\n    double angle = rotated.norm();\n    Eigen::Vector3d axis = rotated.normalized();\n    q_add = Eigen::AngleAxisd(angle, axis).template cast<T>();\n    q_new = q_b * q_add;\n  \n    Eigen::Quaternion<T> q_delta = q_e.conjugate() * q_new;\n    residuals.template block<3, 1>(6, 0) = q_delta.vec();\n\n    // vel error\n    const Eigen::Matrix<T, 3, 1> bias(bias_ptr);\n    const Eigen::Matrix<T, 3, 1> vel_b(vel_b_ptr);\n    const Eigen::Matrix<T, 3, 1> vel_e(vel_e_ptr);\n    residuals.template block<3, 1>(3, 0) = vel_b + (q_b * (acc_measured_.template cast<T>() - bias) - GRAVITY) * DT - vel_e;\n\n    // pos error\n    const Eigen::Matrix<T, 3, 1> pos_b(pos_b_ptr);\n    const Eigen::Matrix<T, 3, 1> pos_e(pos_e_ptr);\n    residuals.template block<3, 1>(0, 0) = pos_b + vel_b * DT - pos_e;\n\n    for (int i = 0; i < 9; i++) {\n      residuals_ptr[i] = residuals[i];\n    }\n    return true;\n  } \n  \n  static CostFunction* Create(const Eigen::Vector3d& acc_measured,\n                              const Eigen::Vector3d& omega_measured) {\n    return new AutoDiffCostFunction<PredictionError, 9, 3, 3, 4, 3, 3, 4, 3>(\n      new PredictionError(acc_measured, omega_measured));\n  }\n\nEIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\nprivate:\n  const Eigen::Vector3d acc_measured_;\n  const Eigen::Vector3d omega_measured_;\n};\n\nstruct OriPredictionError{\n  OriPredictionError(const Eigen::Vector3d& acc_measured,\n                  const Eigen::Vector3d& omega_measured)\n    : acc_measured_(acc_measured), omega_measured_(omega_measured) {}\n\n  template <typename T>\n  bool operator()(const T* const q_b_ptr,\n                  const T* const q_e_ptr,\n                  T* residuals_ptr) const {\n    Eigen::Matrix<T, 3, 1> residuals;\n\n    // quat error\n    const Eigen::Quaternion<T> q_b(q_b_ptr);\n    const Eigen::Quaternion<T> q_e(q_e_ptr);\n    \n    Eigen::Quaternion<T> q_new;\n    Eigen::Quaternion<T> q_add; \n    \n    // // https://gamedev.stackexchange.com/questions/108920/applying-angular-velocity-to-quaternion \n    // Eigen::Quaternion<T> q_omega;\n    // // q_omega.w() = 0;\n    // q_omega.vec() = omega_measured_.template cast<T>() * DT * 0.5;\n    // q_add = q_omega * q_b;\n    // q_new.w() = q_b.w() + q_add.w();\n    // q_new.vec() = q_b.vec() + q_add.vec();\n\n    Eigen::Vector3d rotated = omega_measured_ * DT;\n    double angle = rotated.norm();\n    Eigen::Vector3d axis = rotated.normalized();\n    q_add = Eigen::AngleAxisd(angle, axis).template cast<T>();\n    q_new = q_b * q_add;\n  \n    Eigen::Quaternion<T> q_delta = q_e.conjugate() * q_new;\n    residuals.template block<3, 1>(0, 0) = T(2.0) * q_delta.vec();\n\n    for (int i = 0; i < 3; i++) {\n      residuals_ptr[i] = residuals[i];\n    }\n    return true;\n  } \n  \n  static CostFunction* Create(const Eigen::Vector3d& acc_measured,\n                              const Eigen::Vector3d& omega_measured) {\n    return new AutoDiffCostFunction<OriPredictionError, 3, 4, 4>(\n      new OriPredictionError(acc_measured, omega_measured));\n  }\n\nEIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\nprivate:\n  const Eigen::Vector3d acc_measured_;\n  const Eigen::Vector3d omega_measured_;\n};\n\nstd::vector<Measurement, Eigen::aligned_allocator<Measurement>> readSensorData(std::string path) {\n  std::vector<Measurement, Eigen::aligned_allocator<Measurement>> ret;\n\n  std::ifstream csvFile;\n  csvFile.open(path);\n\n  std::string line;\n  while(std::getline(csvFile, line)) {\n    std::vector<double> row;\n    std::cout << \"line:\" << line << std::endl;\n    std::istringstream s(line);\n    std::string field;\n    while (std::getline(s, field,',')) {\n      // std::cout << \"field: \" << field << std::endl;\n      row.push_back(std::stod(field));\n    }  \n    Eigen::Matrix3d Rwr;\n    Eigen::Quaterniond qwr;\n    Eigen::Vector3d twr;\n    Eigen::Vector3d acc;\n    Eigen::Vector3d omega; \n    Rwr << row[0], row[1], row[2],\n          row[4], row[5], row[6],\n          row[8], row[9], row[10];\n    qwr = Rwr;\n    twr << row[3], row[7], row[11];\n    acc << row[16], row[17], row[18];\n    omega << row[19], row[20], row[21];\n    std::cout << \"Rwr: \" << Rwr << std::endl;\n    std::cout << \"qwr: \" << qwr.w() << \" \" << qwr.vec() << std::endl; \n    std::cout << \"twr: \" << twr << std::endl;\n    std::cout << \"acc: \" << acc << std::endl;\n    std::cout << \"omega: \" << omega << std::endl;\n    \n    ret.push_back(Measurement(Rwr, qwr, twr, acc, omega));\n  }\n\n  return ret;\n}\n\nvoid output_pose(const Eigen::Vector3d& pos, \n\t\t\t\t\t\t\t\t const Eigen::Quaterniond& q) {\n\tEigen::AngleAxisd ori(q);\n\n\tstd::cout << \"Location: \" << pos << std::endl;\n\tstd::cout << \"Orientation: \" << ori.angle() << \" * \" << std::endl << ori.axis() << std::endl;\n}\n\nvoid output_measurement(const Measurement& data) {\n  std::cout << \"\\nData State: \\n\" << \"R: \\n\" << data.Rwr << \"\\nt: \\n\" << data.twr \\\n            << \"\\nacc: \\n\" << data.acc << \"\\nomega: \\n\" << data.omega << std::endl;\n} \n\nvoid save_states(const std::string& filename, \n                 std::vector<State, Eigen::aligned_allocator<State>>& states) {\n  std::fstream outfile;\n  outfile.open(filename.c_str(), std::istream::out);\n\n  for (auto& state : states) {\n    Eigen::Matrix3d rot = state.q.matrix();\n    outfile << rot << \"\\n\" << state.pos.transpose() << \"\\n\" << state.vel.transpose() << \"\\n\\n\";\n  }\n} \n\n\ndouble abs_pos_error(const std::vector<State, Eigen::aligned_allocator<State>>& states,\n                     const std::vector<State, Eigen::aligned_allocator<State>>& gt_states) {\n  double err = 0.0;\n  std::cout << \"abs_pos_err by step: \";\n  for (int i = 0; i < states.size(); i++) {\n    double step_err = (states[i].pos - gt_states[i].pos).norm();\n    err += step_err;\n    std::cout << step_err << \" \";\n  }\n  std::cout << std::endl;\n  return err;\n}\n\nint main(int argc, char** argv) {\n  if(argc < 2) {\n    std::cout << \"missing arg for the csv file\" << std::endl;\n  }\n\n  std::string path = argv[1];\n  std::vector<Measurement, Eigen::aligned_allocator<Measurement>> data = readSensorData(path);    \n  \n  if (false) {\n    output_measurement(data[0]);\n    output_measurement(data[1]);\n\n    Eigen::Vector3d rotated = data[0].omega * DT;\n    double angle = rotated.norm();\n    Eigen::Vector3d axis = rotated.normalized();\n    Eigen::Quaterniond q_add(Eigen::AngleAxisd(angle, axis));\n    Eigen::Quaterniond q_new = data[0].qwr * q_add;\n    Eigen::Matrix3d R_new = q_new.normalized().toRotationMatrix();\n\n    std::cout << \"R_new: \\n\" << R_new << std::endl;\n    \n    Eigen::Vector3d vel_add = data[0].qwr * data[0].acc * DT;\n    std::cout << \"vel_new: \\n\" << vel_add << std::endl;\n    return 0;\n  }\n  \n  int cnt = data.size();\n  // int cnt = 3;\n\n  // Eigen::Vector3d bias = Eigen::Vector3d::Random();\n  Eigen::Vector3d bias;\n  bias << 0, 0, 0;\n  std::vector<State, Eigen::aligned_allocator<State>> states(cnt);\n  std::vector<State, Eigen::aligned_allocator<State>> gt_states(cnt);\n  std::cout << \"states size: \" << states.size() << std::endl;\n\n  for (int i = 0; i < gt_states.size(); i++) {\n    gt_states[i].pos = data[i].twr;\n    gt_states[i].vel = Eigen::Vector3d::Zero();\n    gt_states[i].q = data[i].qwr;\n  }\n\n  Problem problem;\n  \n  ceres::LossFunction* loss_function = nullptr;\n  ceres::LocalParameterization* quaternion_local_parameterization =\n      new ceres::EigenQuaternionParameterization;\n\n  for (int i = 0; i < cnt; i++) {\n    ceres::CostFunction* position_cost_function = PositionError::Create(data[i].twr);\n    problem.AddResidualBlock(position_cost_function,\n                             loss_function,\n                             states[i].pos.data());\n    // ceres::CostFunction* pos_cost_function = PoseError::Create(data[i].twr, data[i].qwr);\n    // problem.AddResidualBlock(pos_cost_function,\n    //                          loss_function,\n    //                          states[i].pos.data(),\n    //                          states[i].q.coeffs().data());\n    // problem.SetParameterization(states[i].q.coeffs().data(),\n    //                             quaternion_local_parameterization);      \n    if (i > 0) {\n      ceres::CostFunction* pred_cost_function = PredictionError::Create(data[i].acc, data[i].omega);\n      problem.AddResidualBlock(pred_cost_function,\n                               loss_function,\n                               states[i - 1].pos.data(),\n                               states[i - 1].vel.data(),\n                               states[i - 1].q.coeffs().data(),\n                               states[i].pos.data(),\n                               states[i].vel.data(),\n                               states[i].q.coeffs().data(),\n                               bias.data());\n      // ceres::CostFunction* pred_cost_function = OriPredictionError::Create(data[i].acc, data[i].omega);\n      // problem.AddResidualBlock(pred_cost_function,\n      //                          loss_function,\n      //                          states[i - 1].q.coeffs().data(),\n      //                          states[i].q.coeffs().data());\n      problem.SetParameterization(states[i - 1].q.coeffs().data(),\n                                  quaternion_local_parameterization);      \n      problem.SetParameterization(states[i].q.coeffs().data(),\n                                  quaternion_local_parameterization);      \n    }\n  } \n\n  // set bias to constant\n  // problem.SetParameterBlockConstant(bias.data());\n  // Eigen::Quaterniond q_noise(Eigen::AngleAxisd(0.1, Eigen::Vector3d::Random().normalized()));\n  // states[0].q = data[0].qwr * q_noise;\n  // states[0].q = data[0].qwr;\n  // problem.SetParameterBlockConstant(states[0].q.coeffs().data());\n\n  ceres::Solver::Options options;\n\toptions.max_num_iterations = 200;\n  options.linear_solver_type = ceres::DENSE_SCHUR;\n  // options.linear_solver_type = ceres::SPARSE_NORMAL_CHOLESKY;\n  options.minimizer_progress_to_stdout = true;\n\n  ceres::Solver::Summary summary;\n  ceres::Solve(options, &problem, &summary);\n  std::cout << summary.FullReport() << \"\\n\";\n  \n  if (false) {\n    output_measurement(data[0]);\n    output_measurement(data[1]);\n    output_measurement(data[2]);\n\n    for (int i = 0; i < states.size(); i++) {\n      std::cout << \"Estimated State:\" << i << \" \\n\" << \"R: \\n\" << states[i].q.matrix()\n                                              << \"\\nt: \\n\" << states[i].pos\n                                              << \"\\nvel: \\n\" << states[i].vel << std::endl;\n    }\n  }\n\n  std::string est_filename = \"./results/est_no_ori_measure_nofixfirst_states.txt\";\n  // std::string est_filename = \"./results/est_position_predic_ori_states.txt\";\n  save_states(est_filename, states);\n  std::string gt_filename = \"./results/gt_states.txt\";\n  save_states(gt_filename, gt_states);\n  \n  double err = abs_pos_error(states, gt_states); \n  std::cout << \"absolute position error: \" << err << std::endl;\n  return 0;\n}", "meta": {"hexsha": "f1f106d8c2b18b27268b195d2bae7c9b443c4d54", "size": 14893, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "experimental/solver.cpp", "max_stars_repo_name": "yimuw/expriment", "max_stars_repo_head_hexsha": "5c4185d969556e7ec007aceaf0eb82f7e79f8abb", "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": "experimental/solver.cpp", "max_issues_repo_name": "yimuw/expriment", "max_issues_repo_head_hexsha": "5c4185d969556e7ec007aceaf0eb82f7e79f8abb", "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": "experimental/solver.cpp", "max_forks_repo_name": "yimuw/expriment", "max_forks_repo_head_hexsha": "5c4185d969556e7ec007aceaf0eb82f7e79f8abb", "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": 34.3949191686, "max_line_length": 124, "alphanum_fraction": 0.6048479151, "num_tokens": 4145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.7853085708384736, "lm_q1q2_score": 0.7071937593337188}}
{"text": "#include <iostream>\n\n#include <Eigen/Dense>\n\n#include <cppmath/matrix/PseudoInverseSVD.hpp>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main()\n{\n    const MatrixXd::Index rows = 42;\n    const MatrixXd::Index cols = 7;\n\n    // Generate system of linear equations\n    MatrixXd A( rows, cols );\n    A.setRandom();\n    VectorXd x( cols );\n    x.setRandom();\n    VectorXd b = A * x;\n    cout << \"x:\" << endl << x << endl;\n    VectorXd diff;\n\n    // Method call #1\n    cppmath::PseudoInverseSVD< MatrixXd > pinv( A );\n    MatrixXd Ainv;\n    pinv.compute( &Ainv );\n    VectorXd xs1 = Ainv * b;\n    diff = x - xs1;\n    cout << \"xs1:\" << endl << xs1 << endl;\n    cout << \"x - xs1: \" << diff.squaredNorm() << endl;\n\n    // Methof call #2\n    const MatrixXd& Apinv = pinv.compute();\n    VectorXd xs2 = Apinv * b;\n    diff = x - xs2;\n    cout << \"xs2:\" << endl << xs2 << endl;\n    cout << \"x - xs2: \" << diff.squaredNorm() << endl;\n\n    // Operator call\n    VectorXd xs3 = pinv * b;\n    diff = x - xs3;\n    cout << \"xs3:\" << endl << xs3 << endl;\n    cout << \"x - xs3: \" << diff.squaredNorm() << endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "18c777a234ff1ef4141c8b976c96dc34f5ff74fa", "size": 1112, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/examples/matrix/PseudoInverseSvdExample.cpp", "max_stars_repo_name": "cpieloth/CppMath", "max_stars_repo_head_hexsha": "58d1c7f0ea07dab9f913b946a251a01b0827bb39", "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": "src/examples/matrix/PseudoInverseSvdExample.cpp", "max_issues_repo_name": "cpieloth/CppMath", "max_issues_repo_head_hexsha": "58d1c7f0ea07dab9f913b946a251a01b0827bb39", "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": "src/examples/matrix/PseudoInverseSvdExample.cpp", "max_forks_repo_name": "cpieloth/CppMath", "max_forks_repo_head_hexsha": "58d1c7f0ea07dab9f913b946a251a01b0827bb39", "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": 23.1666666667, "max_line_length": 54, "alphanum_fraction": 0.5575539568, "num_tokens": 348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096112990285, "lm_q2_score": 0.7718435030872967, "lm_q1q2_score": 0.7070932515969838}}
{"text": "// Header\n#include <polyvec/curve-tracer/curve_bezier.hpp>\n\n// C++ stl\n#include <cassert>\n#include <cstdio>\n#include <cstdlib>\n#include <limits>\n#include <stdexcept>\n\n// Eigen\n#include <Eigen/Core>\n\n// Polyvec\n#include <polyvec/geom.hpp>\n#include <polyvec/geometry/smooth_curve.hpp>\n#include <polyvec/geometry/line.hpp>\n\nnamespace polyvec {\n\n\t// Taken from https://github.com/inkscape/lib2geom: src/2geom/bezier.h\n\t// Compute the value of a Bernstein-Bezier polynomial.\n\t// This method uses a Horner-like fast evaluation scheme.\n\t// param t Time value\n\t// param control_points control points (one per column)\n\t//\n\ttemplate <typename Derived>\n\tEigen::Matrix<double, Derived::RowsAtCompileTime,1>\n\t\t_bezier_value_at(const Eigen::MatrixBase<Derived>& control_points, const double t) {\n\n\t\tassert_break(t <= 1.);\n\t\tassert_break(t >= 0);\n\n\t\tdouble u = 1.0 - t;\n\t\tint degree = control_points.cols() - 1;\n\n\t\tEigen::Matrix<double, Derived::RowsAtCompileTime, 1> ans;\n\t\t\n\t\tdouble bc = 1;\n\t\tdouble tn = 1;\n\n\t\tans = control_points.col(0) * u;\n\n\t\tfor (unsigned i = 1; i < degree; i++) {\n\t\t\ttn = tn * t;\n\t\t\tbc = bc * (degree - i + 1) / i;\n\t\t\tans = (ans + tn * bc * control_points.col(i)) * u;\n\t\t}\n\t\tans = (ans + tn * t * control_points.col(degree));\n\n\t\treturn ans;\n\t}\n\n\t// From https://github.com/inkscape/lib2geom/: src/2geom/bezier.cpp\n\tEigen::Matrix2Xd\n\t\t_derivative_bezier_curve(const Eigen::Matrix2Xd& control_points) {\n\t\tassert_break(control_points.cols() >= 2);\n\t\tEigen::Matrix2Xd ans(2, control_points.cols() - 1);\n\n\t\tconst int order = (int)control_points.cols() - 1;\n\n\t\tfor (unsigned i = 0; i < ans.cols(); ++i) {\n\t\t\tans.col(i) = order * (control_points.col(i + 1) - control_points.col(i));\n\t\t}\n\n\t\treturn ans;\n\t}\n\n\tEigen::Matrix3Xd\n\t\t_tesselate(const Eigen::Matrix2Xd& control_points, const int n_sampling) {\n\t\tEigen::Matrix3Xd ans(3, n_sampling);\n\n\t\tfor (int i = 0; i < n_sampling; ++i) {\n\t\t\tconst double t = 1. / (n_sampling - 1) * i;\n\t\t\tans.col(i) (0) = t;\n\t\t\tans.col(i).tail<2>() = _bezier_value_at(control_points, t);\n\t\t}\n\n\t\treturn ans;\n\t}\n\n\tconst std::vector<double>&\n\t\t_get_gauss_quad_locs() {\n\t\tstatic std::vector<double> ans;\n\t\tstatic bool is_init = false;\n\n\t\tif (!is_init) {\n\t\t\tans.resize(6);\n\t\t\tans[0] = -9.3246951420315202781230155449399e-01L;\n\t\t\tans[1] = -6.6120938646626451366139959501991e-01L;\n\t\t\tans[2] = -2.3861918608319690863050172168071e-01L;\n\t\t\tans[3] = -ans[2];\n\t\t\tans[4] = -ans[1];\n\t\t\tans[5] = -ans[0];\n\n\t\t\tfor (double& a : ans) {\n\t\t\t\ta = a / 2. + 0.5;\n\t\t\t}\n\n\t\t\tis_init = true;\n\t\t}\n\n\t\treturn ans;\n\t}\n\n\tconst std::vector<double>&\n\t\t_get_gauss_quad_weights() {\n\t\tstatic std::vector<double> ans;\n\t\tstatic bool is_init = false;\n\n\t\tif (!is_init) {\n\t\t\tans.resize(6);\n\t\t\tans[0] = 1.7132449237917034504029614217273e-01L;\n\t\t\tans[1] = 3.6076157304813860756983351383772e-01L;\n\t\t\tans[2] = 4.6791393457269104738987034398955e-01L;\n\t\t\tans[3] = ans[2];\n\t\t\tans[4] = ans[1];\n\t\t\tans[5] = ans[0];\n\n\t\t\tfor (double& a : ans) {\n\t\t\t\ta = a / 2.;\n\t\t\t}\n\n\t\t\tis_init = true;\n\t\t}\n\n\t\treturn ans;\n\t}\n\n// ===================================================================\n//                            Bezier Curve\n// ===================================================================\n\n    Eigen::Vector2d\n    BezierCurve::pos ( const double t ) const {\n        return _bezier_value_at ( _control_points_d0, t );\n    }\n\n    Eigen::Vector2d\n    BezierCurve::dposdt ( const double t ) const {\n        return _bezier_value_at ( _control_points_d1, t );\n    }\n\n    Eigen::Vector2d\n    BezierCurve::dposdtdt ( const double t ) const {\n        return _bezier_value_at ( _control_points_d2, t );\n    }\n\n\tEigen::Vector2d BezierCurve::dposdtdtdt(const double t) const\n\t{\n\t\treturn _bezier_value_at(_control_points_d3, t);\n\t}\n\n    Eigen::Matrix2Xd\n    BezierCurve::dposdparams ( const double t ) const {\n        const int n_points = n_control_points();\n\n        // Eigen::Matrix2Xd ans(2, n_points);\n\n        // Coefficient of bernstein monomials in a bernstein polynomial\n        const double b0[] = {1., 0., 0., 0.};\n        const double b1[] = {0., 1., 0., 0.};\n        const double b2[] = {0., 0., 1., 0.};\n        const double b3[] = {0., 0., 0., 1.};\n\n        // Value of derivatives\n\t\tEigen::MatrixXd control(4, 4);\n\t\tcontrol <<\n\t\t\t1., 0., 0., 0.,\n\t\t\t0., 1., 0., 0.,\n\t\t\t0., 0., 1., 0.,\n\t\t\t0., 0., 0., 1.;\n\n\t\tauto dxdp = _bezier_value_at(control, t);\n\n        Eigen::Matrix2Xd ans = Eigen::Matrix2Xd::Zero ( 2, n_points * 2 );\n        ans.row ( 0 ) << dxdp(0), 0, dxdp(1), 0, dxdp(2), 0, dxdp(3), 0;\n        ans.row ( 1 ) << 0, dxdp(0), 0, dxdp(1), 0, dxdp(2), 0, dxdp(3);\n\n        return ans;\n    }\n\n    Eigen::Matrix2Xd\n    BezierCurve::dposdtdparams ( const double t ) const {\n        const int order = 3;\n        const double drder = order;\n        const int n_points = n_control_points();\n\n        // Eigen::Matrix2Xd ans(2, n_points);\n\n        // Coefficient of bernstein monomials in a bernstein polynomial\n        const double b0_deriv[] = {-drder, 0., 0.};\n        const double b1_deriv[] = {drder, -drder, 0.};\n        const double b2_deriv[] = {0., drder, -drder};\n        const double b3_deriv[] = {0., 0., drder};\n\n\t\tEigen::MatrixXd control(4, 3);\n\t\tcontrol <<\n\t\t\t-drder, 0., 0.,\n\t\t\tdrder, -drder, 0.,\n\t\t\t0., drder, -drder,\n\t\t\t0., 0., drder;\n\n        // Value of derivatives\n\t\tauto dxdtdp = _bezier_value_at(control, t);        \n\n        Eigen::Matrix2Xd ans = Eigen::Matrix2Xd::Zero ( 2, n_points * 2 );\n        ans.row ( 0 ) << dxdtdp(0), 0, dxdtdp(1), 0, dxdtdp(2), 0, dxdtdp(3), 0;\n        ans.row ( 1 ) << 0, dxdtdp(0), 0, dxdtdp(1), 0, dxdtdp(2), 0, dxdtdp(3);\n\n        return ans;\n    }\n\n    Eigen::Matrix2Xd\n    BezierCurve::dposdtdtdparams ( const double t ) const {\n        const int order = 3;\n        const double drder = order*(order-1);\n        const int n_points = n_control_points();\n\n        // Eigen::Matrix2Xd ans(2, n_points);\n\n        // Coefficient of bernstein monomials in a bernstein polynomial\n\t\tEigen::MatrixXd control(4, 2);\n\t\tcontrol <<\n\t\t\tdrder, 0.,\n\t\t\t-2 * drder, drder,\n\t\t\tdrder, -2 * drder,\n\t\t\t0., drder;\n\n        // Value of derivatives\n\t\tauto dxdtdtdp = _bezier_value_at(control, t);\n\n        Eigen::Matrix2Xd ans = Eigen::Matrix2Xd::Zero ( 2, n_points * 2 );\n        ans.row ( 0 ) << dxdtdtdp(0), 0, dxdtdtdp(1), 0, dxdtdtdp(2), 0, dxdtdtdp(3), 0;\n        ans.row ( 1 ) << 0, dxdtdtdp(0), 0, dxdtdtdp(1), 0, dxdtdtdp(2), 0, dxdtdtdp(3);\n\n        return ans;\n    }\n\n\tEigen::Matrix2Xd BezierCurve::dposdtdtdtdparams(const double t) const\n\t{\n\t\tconst int order = 3;\n\t\tconst double factor = 6;\n\t\tconst int n_points = n_control_points();\n\n\t\t// Coefficient of bernstein monomials in a bernstein polynomial\n\t\tEigen::MatrixXd control(4, 1);\n\t\tcontrol <<\n\t\t\t-factor,\n\t\t\t3 * factor,\n\t\t\t-3 * factor,\n\t\t\tfactor;\n\n\t\t// Value of derivatives\n\t\tauto dxdtdp = _bezier_value_at(control, t);\t\t\n\n\t\tEigen::Matrix2Xd ans = Eigen::Matrix2Xd::Zero(2, n_points * 2);\n\t\tans.row(0) << dxdtdp(0), 0, dxdtdp(1), 0, dxdtdp(2), 0, dxdtdp(3), 0;\n\t\tans.row(1) << 0, dxdtdp(0), 0, dxdtdp(1), 0, dxdtdp(2), 0, dxdtdp(3);\n\n\t\treturn ans;\n\t}\n\n    double\n    BezierCurve::project ( const Eigen::Vector2d& point ) const {\n\n        // int closest_idx = -1;\n        double closest_t = -1;\n        double closest_dist2 = std::numeric_limits<double>::max();\n\n        // First find an initial guess for the closest point\n        for ( int i = 0; i < _tesselation.cols(); ++i ) {\n            double dist2 = ( point - _tesselation.col ( i ).tail<2>() ).squaredNorm();\n\n            if ( dist2 < closest_dist2 ) {\n                // closest_idx = i;\n                closest_t = _tesselation.col ( i ) ( 0 );\n                closest_dist2 = dist2;\n            }\n        }\n\n        // Now refine your guess using newton iterations\n        auto newton_iteration = [&] ( double guess ) -> double {\n            Eigen::Vector2d post, dert, der2t;\n            post = this->pos ( guess );\n            dert = this->dposdt ( guess );\n            der2t = this->dposdtdt ( guess );\n\n            double dot = dert.dot ( point - post );\n            double dotDer = der2t.dot ( point - post ) - dert.squaredNorm();\n\n            // Make sure the iteration does not make things worse\n            if ( dotDer >= -1e-30 ) {\n                return guess;\n            }\n\n            // Make sure the iteration does not shoot us out of the range\n            return std::max ( 0., std::min ( 1., guess - dot / dotDer ) );\n        };\n        closest_t = newton_iteration ( closest_t );\n        closest_t = newton_iteration ( closest_t );\n        closest_t = newton_iteration ( closest_t );\n        closest_t = newton_iteration ( closest_t );\n\n        return closest_t;\n    }\n\n    Eigen::VectorXd\n    BezierCurve::dtprojectdparams ( const double time, const Eigen::Vector2d& point ) const {\n        const int n_params = n_control_points() * 2;\n        const double tend = 1.;\n\n        return SmoothCurveUtil::projection_derivatives (\n                   n_params,\n                   time,\n                   tend,\n                   point,\n                   pos ( time ),\n                   dposdt ( time ),\n                   dposdtdt ( time ),\n                   dposdparams ( time ),\n                   dposdtdparams ( time ) );\n    }\n\n    Eigen::Matrix2Xd\n    BezierCurve::dposprojectdparams ( const double t, const Eigen::VectorXd& dtprojectdparams ) const {\n        return dposdparams ( t ) + dposdt ( t ) * dtprojectdparams.transpose();\n    }\n\n    Eigen::Matrix2Xd\n    BezierCurve::dposdtprojectdparams ( const double t, const Eigen::VectorXd& dtprojectdparams ) const {\n        return dposdtdparams ( t ) + dposdtdt ( t ) * dtprojectdparams.transpose();\n    }\n\n\n    void\n    BezierCurve::set_control_points ( const Eigen::Matrix2Xd& control_points_d0_in ) {\n        assert_break ( control_points_d0_in.cols() == n_control_points() );\n        _control_points_d0 = control_points_d0_in;\n        _control_points_d1 = _derivative_bezier_curve ( _control_points_d0 );\n        _control_points_d2 = _derivative_bezier_curve ( _control_points_d1 );\n\t\t_control_points_d3 = _derivative_bezier_curve ( _control_points_d2 );\n        _tesselation = _tesselate ( _control_points_d0, _n_tesselation );\n    }\n\n    const Eigen::Matrix2Xd&\n    BezierCurve::get_control_points() const {\n        return _control_points_d0;\n    }\n\n\tvoid BezierCurve::set_params(const Eigen::VectorXd & params)\n\t{\n\t\tEigen::Matrix2Xd controlPoints(2, 4);\n\t\tcontrolPoints << params[0], params[2], params[4], params[6], params[1], params[3], params[5], params[7];\n\t\tset_control_points(controlPoints);\n\t}\n\n\tEigen::VectorXd BezierCurve::get_params() const\n\t{\n\t\tEigen::VectorXd params(n_params());\n\t\tparams << \n\t\t\t_control_points_d0.coeff(0, 0), _control_points_d0.coeff(1, 0),\n\t\t\t_control_points_d0.coeff(0, 1), _control_points_d0.coeff(1, 1),\n\t\t\t_control_points_d0.coeff(0, 2), _control_points_d0.coeff(1, 2),\n\t\t\t_control_points_d0.coeff(0, 3), _control_points_d0.coeff(1, 3);\n\t\treturn params;\n\t}\n\n\t//const Eigen::Matrix3Xd&\n    //BezierCurve::get_tesselation3() {\n    //    return _tesselation;\n    //}\n\n    Eigen::VectorXd\n    BezierCurve::get_tesselationt() const {\n        return _tesselation.row(0).transpose();\n    }\n\n    Eigen::Matrix2Xd\n    BezierCurve::get_tesselation2() const {\n        return _tesselation.bottomRows<2>();\n    }\n\n\n    double\n    BezierCurve::length() const {\n        const std::vector<double>& ww = _get_gauss_quad_weights();\n        const std::vector<double>& tt = _get_gauss_quad_locs();\n        double len = 0;\n\n        for ( unsigned i = 0; i < tt.size(); ++i ) {\n            len += ww[i] * dposdt ( tt[i] ).norm();\n        }\n\n        return len;\n    }\n\n\n    Eigen::VectorXd\n    BezierCurve::dlengthdparams() {\n        const int n_points = n_control_points();\n        const double tol = 1e-10;\n        const std::vector<double>& ww = _get_gauss_quad_weights();\n        const std::vector<double>& tt = _get_gauss_quad_locs();\n\n        Eigen::VectorXd dlendprams = Eigen::VectorXd ( n_points * 2 );\n        dlendprams.setZero();\n\n        for ( unsigned i = 0; i < tt.size(); ++i ) {\n            Eigen::Vector2d tang = dposdt ( tt[i] );\n            double tang_norm = std::max ( tang.norm(), tol );\n            dlendprams += ww[i] * 1. / tang_norm * dposdtdparams ( tt[i] ).transpose() * tang;\n        }\n\n        return dlendprams;\n    }    \n\n\tgeom::aabb BezierCurve::get_bounding_box() const\n\t{\n\t\tgeom::aabb b;\n\t\tfor (int i = 0; i < 4; ++i)\n\t\t\tb.add(_control_points_d0.col(i));\n\t\treturn b;\n\t}\n\n\tBezierCurve::BezierCurve(const Eigen::Matrix2Xd& C) {\n\t\tset_control_points(C);\n\t}\n\n\tstd::pair<GlobFitCurve*, GlobFitCurve*> BezierCurve::split(double t) const\n\t{\n\t\tEigen::Matrix2Xd cLeft(2, 4), cRight(2, 4);\n\t\t\n\t\tauto& p = _control_points_d0;\n\n\t\t// left curve\n\t\tcLeft.col(0) = p.col(0);\n\t\tcLeft.col(1) = _bezier_value_at(p.leftCols<2>(), t);\n\t\tcLeft.col(2) = _bezier_value_at(p.leftCols<3>(), t);\n\t\tcLeft.col(3) = _bezier_value_at(p.leftCols<4>(), t);\n\t\t\n\t\t// right curve\n\t\tcRight.col(0) = _bezier_value_at(p.rightCols<4>(), t);\n\t\tcRight.col(1) = _bezier_value_at(p.rightCols<3>(), t);\n\t\tcRight.col(2) = _bezier_value_at(p.rightCols<2>(), t);\n\t\tcRight.col(3) = p.col(3);\n\n\t\treturn std::make_pair(new BezierCurve(cLeft), new BezierCurve(cRight));\n\t}\n}\n", "meta": {"hexsha": "f2fce69a65e756f8f72e327601030c5382a0ad4c", "size": 13196, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/polyvec/curve-tracer/curve_bezier.cpp", "max_stars_repo_name": "ShnitzelKiller/polyfit", "max_stars_repo_head_hexsha": "51ddc6365a794db1678459140658211cb78f65b1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2020-08-17T17:25:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T05:49:12.000Z", "max_issues_repo_path": "source/polyvec/curve-tracer/curve_bezier.cpp", "max_issues_repo_name": "ShnitzelKiller/polyfit", "max_issues_repo_head_hexsha": "51ddc6365a794db1678459140658211cb78f65b1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-08-26T13:54:59.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-21T07:19:22.000Z", "max_forks_repo_path": "source/polyvec/curve-tracer/curve_bezier.cpp", "max_forks_repo_name": "ShnitzelKiller/polyfit", "max_forks_repo_head_hexsha": "51ddc6365a794db1678459140658211cb78f65b1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-08-26T23:26:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-04T09:06:07.000Z", "avg_line_length": 29.2594235033, "max_line_length": 106, "alphanum_fraction": 0.5979084571, "num_tokens": 4166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.91610961358942, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.7070932485568611}}
{"text": "// Copyright (C) 2000 Stephen Cleary\r\n//\r\n// Distributed under the Boost Software License, Version 1.0. (See\r\n// accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n//\r\n// See http://www.boost.org for updates, documentation, and revision history.\r\n\r\n#ifndef BOOST_POOL_CT_GCD_LCM_HPP\r\n#define BOOST_POOL_CT_GCD_LCM_HPP\r\n\r\n#include <boost/static_assert.hpp>\r\n#include <boost/type_traits/ice.hpp>\r\n\r\nnamespace boost {\r\n\r\nnamespace details {\r\nnamespace pool {\r\n\r\n// Compile-time calculation of greatest common divisor and least common multiple\r\n\r\n//\r\n// ct_gcd is a compile-time algorithm that calculates the greatest common\r\n//  divisor of two unsigned integers, using Euclid's algorithm.\r\n//\r\n// assumes: A != 0 && B != 0\r\n//\r\n\r\n#ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION\r\n\r\nnamespace details {\r\ntemplate <unsigned A, unsigned B, bool Bis0>\r\nstruct ct_gcd_helper;\r\ntemplate <unsigned A, unsigned B>\r\nstruct ct_gcd_helper<A, B, false>\r\n{\r\n  BOOST_STATIC_CONSTANT(unsigned, A_mod_B_ = A % B);\r\n  BOOST_STATIC_CONSTANT(unsigned, value =\r\n      (::boost::details::pool::details::ct_gcd_helper<\r\n        B, static_cast<unsigned>(A_mod_B_),\r\n        ::boost::type_traits::ice_eq<A_mod_B_, 0>::value\r\n        >::value) );\r\n};\r\ntemplate <unsigned A, unsigned B>\r\nstruct ct_gcd_helper<A, B, true>\r\n{\r\n  BOOST_STATIC_CONSTANT(unsigned, value = A);\r\n};\r\n} // namespace details\r\n\r\ntemplate <unsigned A, unsigned B>\r\nstruct ct_gcd\r\n{\r\n  BOOST_STATIC_ASSERT(A != 0 && B != 0);\r\n  BOOST_STATIC_CONSTANT(unsigned, value =\r\n      (::boost::details::pool::details::ct_gcd_helper<A, B, false>::value) );\r\n};\r\n\r\n#else\r\n\r\n// Thanks to Peter Dimov for providing this workaround!\r\nnamespace details {\r\ntemplate<unsigned A> struct ct_gcd2\r\n{\r\n  template<unsigned B>\r\n  struct helper\r\n  {\r\n    BOOST_STATIC_CONSTANT(unsigned, value = ct_gcd2<B>::helper<A % B>::value);\r\n  };\r\n  template<>\r\n  struct helper<0>\r\n  {\r\n    BOOST_STATIC_CONSTANT(unsigned, value = A);\r\n  };\r\n};\r\n} // namespace details\r\n\r\ntemplate<unsigned A, unsigned B> struct ct_gcd\r\n{\r\n  BOOST_STATIC_ASSERT(A != 0 && B != 0);\r\n  enum { value = details::ct_gcd2<A>::helper<B>::value };\r\n};\r\n\r\n#endif\r\n\r\n//\r\n// ct_lcm is a compile-time algorithm that calculates the least common\r\n//  multiple of two unsigned integers.\r\n//\r\n// assumes: A != 0 && B != 0\r\n//\r\ntemplate <unsigned A, unsigned B>\r\nstruct ct_lcm\r\n{\r\n  BOOST_STATIC_CONSTANT(unsigned, value =\r\n      (A / ::boost::details::pool::ct_gcd<A, B>::value * B) );\r\n};\r\n\r\n} // namespace pool\r\n} // namespace details\r\n\r\n} // namespace boost\r\n\r\n#endif\r\n", "meta": {"hexsha": "749d8ebbac765c6d30c6edd38fc6f0bc7eb718b9", "size": 2583, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/pool/detail/ct_gcd_lcm.hpp", "max_stars_repo_name": "dstrigl/mcotf", "max_stars_repo_head_hexsha": "92a9caf6173b1241a2f9ed45cd379469762b7178", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 460.0, "max_stars_repo_stars_event_min_datetime": "2016-01-13T12:49:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T04:10:40.000Z", "max_issues_repo_path": "include/boost/pool/detail/ct_gcd_lcm.hpp", "max_issues_repo_name": "dstrigl/mcotf", "max_issues_repo_head_hexsha": "92a9caf6173b1241a2f9ed45cd379469762b7178", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 206.0, "max_issues_repo_issues_event_min_datetime": "2015-11-09T00:27:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-04T19:05:18.000Z", "max_forks_repo_path": "include/boost/pool/detail/ct_gcd_lcm.hpp", "max_forks_repo_name": "dstrigl/mcotf", "max_forks_repo_head_hexsha": "92a9caf6173b1241a2f9ed45cd379469762b7178", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 148.0, "max_forks_repo_forks_event_min_datetime": "2016-01-17T03:16:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T12:20:36.000Z", "avg_line_length": 24.6, "max_line_length": 81, "alphanum_fraction": 0.674796748, "num_tokens": 638, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096158798117, "lm_q2_score": 0.7718434925908524, "lm_q1q2_score": 0.707093245516738}}
{"text": "#ifndef MLT_UTILS_ACTIVATION_FUNCTIONS_HPP\n#define MLT_UTILS_ACTIVATION_FUNCTIONS_HPP\n\n#include <Eigen/Core>\n\n#include \"../defs.hpp\"\n\nnamespace mlt {\nnamespace utils {\nnamespace activation_functions {\n\tclass SigmoidActivation {\n\tpublic:\n\t\tauto compute(MatrixXdRef x) const {\n\t\t\treturn x.unaryExpr([](double z) { double gz = 1.0 / (1.0 + std::exp(-z)); gz = gz < 1 ? gz : 0.9999999999; return gz; }).eval();\n\t\t}\n\n\t\tauto gradient(MatrixXdRef x) const {\n\t\t\treturn x.unaryExpr([](double z) { double gz = 1.0 / (1.0 + std::exp(-z)); gz = gz < 1 ? gz : 0.9999999999; return gz * (1 - gz); }).eval();\n\t\t}\n\t};\n}\n}\n}\n#endif", "meta": {"hexsha": "cd0d8faff34908e3141fee96487b0046576ae6b3", "size": 614, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/mlt/utils/activation_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/activation_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/activation_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": 25.5833333333, "max_line_length": 142, "alphanum_fraction": 0.654723127, "num_tokens": 191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.91610961358942, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.7070932437489142}}
{"text": "// Copyright University of Warwick 2014\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n// Authors:\n// John Back\n\n/*! \\file LpcConvexHull.cc\n    \\brief Class that calculates the \"convex hull\" extent of a cluster of hits\n*/\n\n#include \"LACE/LpcConvexHull.hh\"\n\n#include \"LACE/LpcCluster.hh\"\n\n#include <Eigen/Dense>\n\nLpcConvexHull::LpcConvexHull()\n{\n}\n\nLpcConvexHull::~LpcConvexHull()\n{\n}\n\nvoid LpcConvexHull::findLengths(LpcCluster* theCluster)\n{\n\n    // Find the convex hull lengths along the spatial dimensions of \n    // the cluster and store them in the cluster pointer. Originally,\n    // this method would require the calculation of the convex hull\n    // points with QHull. But, the extent of the hull is simply given\n    // by the size of the rectangular box that will enclose the\n    // cluster \"ellipsoid\", i.e. the lengths (max-min range) along \n    // each of the principal axes\n\n    if (!theCluster) {return;}\n\n    //Retrieve the matrix of cluster hit positions\n    Eigen::MatrixXd hitCoords = theCluster->getHitPositions();\n    \n    // We need to transform the point co-ordinates to lie along the principal axes.\n    // Find the eigenvectors of the covariance matrix of the hit co-ordinates\n    Eigen::MatrixXd covMatrix = functions_.getCovarianceMatrix(hitCoords);\n\n    std::pair<Eigen::VectorXd, Eigen::MatrixXd> pcaEigen = \n\tfunctions_.findNormEigenVectors(covMatrix);\n\n    Eigen::MatrixXd eVectors = pcaEigen.second;\n\n    Eigen::MatrixXd eV = eVectors.transpose();\n\n    // Transform the hit co-ordinates. Row = point, col = x,y,z,...\n    Eigen::MatrixXd transCoords = hitCoords*eV;\n\n    // Get the lengths along each axis\n    int nDim = hitCoords.cols();\n    Eigen::VectorXd lengths = Eigen::VectorXd::Zero(nDim);\n\n    for (int i = 0; i < nDim; i++) {\n\n\tEigen::VectorXd coordCol = transCoords.col(i);\n\tdouble maxVal = coordCol.maxCoeff();\n\tdouble minVal = coordCol.minCoeff();\n\tdouble range = fabs(maxVal - minVal);\n\n\tlengths(i) = range;\n\n    }\n\n    theCluster->storeConvexHull(lengths);\n\n}\n\n", "meta": {"hexsha": "bc7779df3b53aa087d93ea05cb31f82cea07100a", "size": 2113, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/LpcConvexHull.cc", "max_stars_repo_name": "petrmanek/LACE", "max_stars_repo_head_hexsha": "5e189bb871a47972490fe2888a60df876cb6b120", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-03-14T13:13:34.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-14T13:13:34.000Z", "max_issues_repo_path": "src/LpcConvexHull.cc", "max_issues_repo_name": "petrmanek/LACE", "max_issues_repo_head_hexsha": "5e189bb871a47972490fe2888a60df876cb6b120", "max_issues_repo_licenses": ["BSL-1.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": "src/LpcConvexHull.cc", "max_forks_repo_name": "petrmanek/LACE", "max_forks_repo_head_hexsha": "5e189bb871a47972490fe2888a60df876cb6b120", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-04-19T21:29:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-14T13:37:26.000Z", "avg_line_length": 28.1733333333, "max_line_length": 90, "alphanum_fraction": 0.7070515854, "num_tokens": 544, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473879530492, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.7070191609662755}}
{"text": "#include \"utils.hpp\"\n#include <cmath>\n#include <fstream>\n#include <boost/range/numeric.hpp>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/median.hpp>\n\nusing namespace std;\n\nnamespace delphi::utils {\n\n/**\n * Returns the square of a number.\n */\n// double sqr(double x) { return x * x; }\n\n/**\n * Returns the sum of a vector of doubles.\n */\ndouble sum(const std::vector<double> &v) { return boost::accumulate(v, 0.0); }\n\n/**\n * Returns the arithmetic mean of a vector of doubles.\n * Updated based on:\n * https://codereview.stackexchange.com/questions/185450/compute-mean-variance-and-standard-deviation-of-csv-number-file\n */\ndouble mean(const std::vector<double> &v) {\n    if (v.empty()) {\n        return std::numeric_limits<double>::quiet_NaN();\n    }\n\n    return sum(v) / v.size();\n}\n\n/**\n * Returns the sample standard deviation of a vector of doubles.\n * Based on:\n * https://codereview.stackexchange.com/questions/185450/compute-mean-variance-and-standard-deviation-of-csv-number-file\n */\ndouble standard_deviation(const double mean, const std::vector<double>& v)\n{\n    if (v.size() <= 1u)\n        return std::numeric_limits<double>::quiet_NaN();\n\n    auto const add_square = [mean](double sum, int i) {\n        auto d = i - mean;\n        return sum + d*d;\n    };\n    double total = std::accumulate(v.begin(), v.end(), 0.0, add_square);\n    return sqrt(total / (v.size() - 1));\n}\n\n/**\n * Returns the median of a vector of doubles.\n */\ndouble median(const std::vector<double> &xs) {\n  using namespace boost::accumulators;\n  accumulator_set<double, features<tag::median>> acc;\n  for (auto x : xs) {\n    acc(x);\n  }\n  return boost::accumulators::median(acc);\n}\n\ndouble log_normpdf(double x, double mean, double sd) {\n  double var = pow(sd, 2);\n  double log_denom = -0.5 * log(2 * M_PI) - log(sd);\n  double log_nume = pow(x - mean, 2) / (2 * var);\n\n  return log_denom - log_nume;\n}\n\nnlohmann::json load_json(string filename) {\n  ifstream i(filename);\n  nlohmann::json j = nlohmann::json::parse(i);\n  return j;\n}\n\n} // namespace delphi::utils\n", "meta": {"hexsha": "72cf747e13eb9971b48023a04705d9420a346b62", "size": 2081, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/utils.cpp", "max_stars_repo_name": "bkj/delphi", "max_stars_repo_head_hexsha": "14972e783551029ddf7db83961b73cf99c4c48e9", "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": "lib/utils.cpp", "max_issues_repo_name": "bkj/delphi", "max_issues_repo_head_hexsha": "14972e783551029ddf7db83961b73cf99c4c48e9", "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": "lib/utils.cpp", "max_forks_repo_name": "bkj/delphi", "max_forks_repo_head_hexsha": "14972e783551029ddf7db83961b73cf99c4c48e9", "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": 26.0125, "max_line_length": 120, "alphanum_fraction": 0.6684286401, "num_tokens": 550, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.872347368040789, "lm_q2_score": 0.8104789063814616, "lm_q1q2_score": 0.7070191408344451}}
{"text": "#include <armadillo>\n#include <math.h>\n#include <fruitpunch/Graphics/Matrices.h>\n#include <fruitpunch/Graphics/Vertex.h>\n#include <fruitpunch/Graphics/Renderer.h>\n#include <vector>\n\n#define PI180 0.0174532925\n\nusing namespace arma;\nusing namespace std;\n\nnamespace fp_core {\n\n/**\n * Returns\n */\nfmat33 rotation_matrix(float angle) {\n  float rad = angle * PI180;\n\n  fmat33 rot;\n  rot << cos(rad) << -sin(rad) << 0 << endr\n      << sin(rad) << cos(rad) << 0 << endr\n      << 0 << 0 << 1 << endr;\n  return rot;\n}\n\nfmat33 translation_matrix(point p) {\n  // generates the translation matrix\n  fmat33 trans;\n  trans.eye();\n  trans.at(0, 2) = p.x;\n  trans.at(1, 2) = p.y;\n\n  return trans;\n}\n\nfmat33 scale_matrix(point p) {\n  fmat33 trans;\n  trans.eye();\n  trans.at(0, 0) = p.x;\n  trans.at(1, 1) = p.y;\n\n  return trans;\n}\n\nfmat33 to_local_space_matrix(point center) {\n  center.x = -center.x;\n  center.y = -center.y;\n  return translation_matrix(center);\n}\n\nfmat33 to_global_space_matrix(point center) {\n  return translation_matrix(center);\n}\n\nvoid apply_matrix_transformation(point * points, int size,\n    Renderer& renderer, fmat33 transformation) {\n\n  // create point array\n  for (int i = 0; i < size; i++) {\n    // gets the point\n\n    point& p = points[i];\n    //printf(\"Added %d,%d\", m_vertices[i].position().x, m_vertices[i].position().y);\n    // transforms the point\n    points[i] = renderer.transform_point(p, transformation);\n    //printf(\"Transformed (%f,%f) \\n\", parr[i].x, parr[i].y);\n  }\n\n}\n\n}\n\n", "meta": {"hexsha": "a90e7976b90d1e6e9df8f672cbf078034b99286f", "size": 1497, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "fp_core/src/main/src/Graphics/Matrices.cpp", "max_stars_repo_name": "submain/fruitpunch", "max_stars_repo_head_hexsha": "31773128238830d3d335c1915877dc0db56836cd", "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": "fp_core/src/main/src/Graphics/Matrices.cpp", "max_issues_repo_name": "submain/fruitpunch", "max_issues_repo_head_hexsha": "31773128238830d3d335c1915877dc0db56836cd", "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": "fp_core/src/main/src/Graphics/Matrices.cpp", "max_forks_repo_name": "submain/fruitpunch", "max_forks_repo_head_hexsha": "31773128238830d3d335c1915877dc0db56836cd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-14T02:51:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-14T02:51:47.000Z", "avg_line_length": 19.96, "max_line_length": 84, "alphanum_fraction": 0.6492985972, "num_tokens": 443, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403959948494, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.7069794387951175}}
{"text": "/**\n * @file kruskal.cpp\n * @author prakash sellathurai\n * @brief minimum spanning tree using Kruskal algorithm\n * @version 0.1\n * @date 2021-07-16\n *\n * @copyright Copyright (c) 2021\n *\n */\n\n#include <algorithm>\n#include <boost/pending/disjoint_sets.hpp>\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\n/**\n * @brief Edge pairs are stored in a vector\n *\n */\nclass EdgePair {\npublic:\n  int x, y, weight;\n  EdgePair() {}\n  EdgePair(int x, int y, int weight) : x(x), y(y), weight(weight) {}\n};\n\n/**\n * @brief Weighted Graph\n * \n */\nclass Graph {\nprivate:\n  int V;                                // No. of vertices\n  int E;                                // No. of edges\n  vector<vector<pair<int, int>>> edges; // Graph represented as adjacency list\n\npublic:\n  Graph(int V) : V(V+1), E(0) { edges.resize(V+1); }\n  void addEdge(int v, int w, int weight) {\n    edges[v].push_back(make_pair(w, weight));\n    edges[w].push_back(make_pair(v, weight));\n    E++;\n  }\n\n  static bool sortbysec(const EdgePair &e1, const EdgePair &e2) {\n    return e1.weight < e2.weight;\n  }\n  vector<EdgePair> to_edgearray() {\n    vector<EdgePair> res;\n    for (int i = 0; i < V; i++) {\n      for (auto edge : edges[i]) {\n        res.push_back(EdgePair(i, edge.first, edge.second));\n      }\n    }\n    return res;\n  }\n\n  /**\n   * @brief kruskal  algorithm, for finding minimum spanning tree weight\n   *\n   * @return int\n   */\n  int kruskal() {\n    int weight = 0; /*cost of minimum spanning tree*/\n    vector<EdgePair> e = to_edgearray();\n    sort(e.begin(), e.end(), sortbysec);\n    int vectorlist[V + 1];\n    int parentlist[V + 1];\n    boost::disjoint_sets<int *, int *> ds(vectorlist, parentlist);\n    for (int i = 0; i < V; i++) {\n      ds.make_set(i);\n    }\n\n    std::cout << std::endl;\n    for (auto edge:e) {\n      auto u = ds.find_set(edge.x);\n      auto v = ds.find_set(edge.y);\n      if (u != v) {\n        std::cout << \"Edge : \" << edge.x << \" \" << edge.y << std::endl;\n        weight += edge.weight;\n        ds.link(edge.x, edge.y);\n      }\n    }\n    return weight;\n  }\n};\n\nint main(int argc, const char **argv) {\n  Graph g(5);\n  g.addEdge(0, 1, 1);\n  g.addEdge(1, 2, 2);\n  g.addEdge(2, 3, 3);\n  std::cout << \"Minimum spanning tree weight is : \" << g.kruskal() << std::endl;\n  return 0;\n}", "meta": {"hexsha": "94932a955432cb3b74d323288b41a7fc731e949e", "size": 2282, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/Graphs/minimum-spanning-tree/kruskal.cpp", "max_stars_repo_name": "fossabot/a-grim-loth", "max_stars_repo_head_hexsha": "a6c8d549289a39ec981c1e0d0c754bb2708dfff9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-06-26T17:18:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T15:02:27.000Z", "max_issues_repo_path": "cpp/Graphs/minimum-spanning-tree/kruskal.cpp", "max_issues_repo_name": "fossabot/a-grim-loth", "max_issues_repo_head_hexsha": "a6c8d549289a39ec981c1e0d0c754bb2708dfff9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2021-06-29T07:00:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-01T11:26:22.000Z", "max_forks_repo_path": "cpp/Graphs/minimum-spanning-tree/kruskal.cpp", "max_forks_repo_name": "fossabot/a-grim-loth", "max_forks_repo_head_hexsha": "a6c8d549289a39ec981c1e0d0c754bb2708dfff9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-07-14T14:42:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-07T19:36:53.000Z", "avg_line_length": 23.2857142857, "max_line_length": 80, "alphanum_fraction": 0.5670464505, "num_tokens": 681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105696, "lm_q2_score": 0.782662489091802, "lm_q1q2_score": 0.7069744962761441}}
{"text": "//\n// Created by Hamza El-Kebir on 4/17/21.\n//\n\n#ifndef LODESTAR_BILINEARTRANSFORMATION_HPP\n#define LODESTAR_BILINEARTRANSFORMATION_HPP\n\n#include <Eigen/Dense>\n#include \"Lodestar/systems/StateSpace.hpp\"\n#include \"Lodestar/aux/CompileTimeQualifiers.hpp\"\n\nnamespace ls {\n    namespace analysis {\n        /**\n         * @brief Routines for converting a state space system from continuous-\n         * to discrete-time and vice versa.\n         *\n         * @note\n         * Corresponds to SLICOT Routine <a href=\"http://slicot.org/objects/software/shared/doc/AB04MD.html\">AB04MD</a>\n         * (<em>Discrete-time <-> continuous-time conversion by bilinear transformation</em>).\n         */\n        class BilinearTransformation {\n        public:\n            template<typename TScalar = double, int TStateDim = Eigen::Dynamic, int TInputDim = Eigen::Dynamic, int TOutputDim = Eigen::Dynamic>\n            struct mallocStructC2D {\n                Eigen::ColPivHouseholderQR<Eigen::Matrix<TScalar, TStateDim, TStateDim>> HH;\n                Eigen::ColPivHouseholderQR<Eigen::Matrix<TScalar, TStateDim, TStateDim>> HH2;\n                Eigen::Matrix<TScalar, TStateDim, TStateDim> I;\n            };\n\n            template<typename TScalar = double, int TStateDim = Eigen::Dynamic, int TInputDim = Eigen::Dynamic, int TOutputDim = Eigen::Dynamic>\n            struct mallocStructD2C {\n                Eigen::ColPivHouseholderQR<Eigen::Matrix<TScalar, TStateDim, TStateDim>> HH;\n                Eigen::Matrix<TScalar, TStateDim, TStateDim> IMAC;\n                Eigen::Matrix<TScalar, TStateDim, TStateDim> I;\n            };\n\n            /**\n             * @brief Generates generalized bilinear transform of a\n             * continuous-time state space system.\n             *\n             * @param A TState matrix.\n             * @param B Input matrix.\n             * @param C Output matrix.\n             * @param D Feedforward matrix.\n             * @param dt Sampling period.\n             * @param alpha Generalized bilinear transformation parameter; default\n             * parameter corresponds to backward differencing transform.\n             *\n             * @return Transformed discrete-time state space system.\n             */\n            static systems::StateSpace<>\n            c2d(const Eigen::MatrixXd &A, const Eigen::MatrixXd &B,\n                const Eigen::MatrixXd &C, const Eigen::MatrixXd &D,\n                double dt,\n                double alpha = 1);\n\n            /**\n             * @brief Generates generalized bilinear transform of a\n             * continuous-time state space system.\n             *\n             * @param A Pointer to state matrix.\n             * @param B Pointer to input matrix.\n             * @param C Pointer to output matrix.\n             * @param D Pointer to feedforward matrix.\n             * @param dt Sampling period.\n             * @param alpha Generalized bilinear transformation parameter; default\n             * parameter corresponds to backward differencing transform.\n             *\n             * @return Transformed discrete-time state space system.\n             */\n            static systems::StateSpace<>\n            c2d(const Eigen::MatrixXd *A, const Eigen::MatrixXd *B, const Eigen::MatrixXd *C, const Eigen::MatrixXd *D,\n                double dt,\n                double alpha);\n\n            /**\n             * @brief Generates generalized bilinear transform of a\n             * continuous-time state space system.\n             *\n             * @param ss TState space system.\n             * @param dt Sampling period.\n             * @param alpha Generalized bilinear transformation parameter; default\n             * parameter corresponds to backward differencing transform.\n             *\n             * @return Transformed discrete-time state space system.\n             */\n            static systems::StateSpace<>\n            c2d(const systems::StateSpace<> &ss, double dt, double alpha = 1);\n\n            template<typename TScalar, int TStateDim, int TInputDim, int TOutputDim>\n            static void\n            c2d(const systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim> *ss, double dt, double alpha,\n                systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim> *out,\n                mallocStructC2D<TScalar, TStateDim, TInputDim, TOutputDim> *memStruct,\n                LS_IS_DYNAMIC_DEFAULT(TStateDim, TInputDim, TOutputDim));\n\n            template<typename TScalar, int TStateDim, int TInputDim, int TOutputDim>\n            static void\n            c2d(const systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim> *ss, double dt, double alpha,\n                systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim> *out,\n                mallocStructC2D<TScalar, TStateDim, TInputDim, TOutputDim> *memStruct,\n                LS_IS_STATIC_DEFAULT(TStateDim, TInputDim, TOutputDim));\n\n            /**\n             * @brief Generates generalized bilinear transform of a\n             * discrete-time state space system.\n             *\n             * @param ss TState space system.\n             * @param dt Sampling period.\n             * @param alpha Generalized bilinear transformation parameter; default\n             * parameter corresponds to backward differencing transform.\n             *\n             * @return Transformed continuous-time state space system.\n             */\n            static systems::StateSpace<>\n            d2c(const systems::StateSpace<> &ss, double dt,\n                double alpha = 1);\n\n            template<typename TScalar, int TStateDim, int TInputDim, int TOutputDim>\n            static void\n            d2c(const systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim> *ss, double dt, double alpha,\n                systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim> *out,\n                mallocStructD2C<TScalar, TStateDim, TInputDim, TOutputDim> *memStruct,\n                LS_IS_DYNAMIC_DEFAULT(TStateDim, TInputDim, TOutputDim));\n\n            template<typename TScalar, int TStateDim, int TInputDim, int TOutputDim>\n            static void\n            d2c(const systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim> *ss, double dt, double alpha,\n                systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim> *out,\n                mallocStructD2C<TScalar, TStateDim, TInputDim, TOutputDim> *memStruct,\n                LS_IS_STATIC_DEFAULT(TStateDim, TInputDim, TOutputDim));\n\n            /**\n             * @brief Generates generalized bilinear transform of a\n             * discrete-time state space system.\n             *\n             * This method retrieves the sampling period from the state space\n             * object.\n             *\n             * @param ss TState space system.\n             * @param alpha Generalized bilinear transformation parameter; default\n             * parameter corresponds to backward differencing transform.\n             *\n             * @return Transformed continuous-time state space system.\n             */\n            static systems::StateSpace<>\n            d2c(const systems::StateSpace<> &ss, double alpha = 1);\n\n            /**\n             * @brief Generates generalized bilinear transform of a\n             * discrete-time state space system.\n             *\n             * @param A TState matrix.\n             * @param B Input matrix.\n             * @param C Output matrix.\n             * @param D Feedforward matrix.\n             * @param dt Sampling period.\n             * @param alpha Generalized bilinear transformation parameter; default\n             * parameter corresponds to backward differencing transform.\n             *\n             * @return Transformed continuous-time state space system.\n             */\n            static systems::StateSpace<>\n            d2c(const Eigen::MatrixXd &A, const Eigen::MatrixXd &B,\n                const Eigen::MatrixXd &C, const Eigen::MatrixXd &D, double dt,\n                double alpha = 1);\n\n            /**\n             * @brief Generates generalized bilinear transform of a\n             * discrete-time state space system.\n             *\n             * @param A Pointer to state matrix.\n             * @param B Pointer to input matrix.\n             * @param C Pointer to output matrix.\n             * @param D Pointer to feedforward matrix.\n             * @param dt Sampling period.\n             * @param alpha Generalized bilinear transformation parameter; default\n             * parameter corresponds to backward differencing transform.\n             *\n             * @return Transformed continuous-time state space system.\n             */\n            static systems::StateSpace<>\n            d2c(const Eigen::MatrixXd *A, const Eigen::MatrixXd *B, const Eigen::MatrixXd *C, const Eigen::MatrixXd *D,\n                double dt,\n                double alpha);\n\n            /**\n             * @brief Generates Tustin transform of a continuous-time state\n             * space system.\n             *\n             * @param ss TState space system.\n             * @param dt Sampling period.\n             *\n             * @return Transformed discrete-time state space system.\n             */\n            static systems::StateSpace<>\n            c2dTustin(const systems::StateSpace<> &ss, double dt);\n\n            /**\n             * @brief Generates Tustin transform of a discrete-time state space\n             * system.\n             *\n             * @param ss TState space system.\n             * @param dt Sampling period.\n             *\n             * @return Transformed continuous-time state space system.\n             */\n            static systems::StateSpace<>\n            d2cTustin(const systems::StateSpace<> &ss, double dt);\n\n            /**\n             * @brief Generates Euler transform of a continuous-time state space\n             * system.\n             *\n             * @param ss TState space system.\n             * @param dt Sampling period.\n             *\n             * @return Transformed discrete-time state space system.\n             */\n            static systems::StateSpace<>\n            c2dEuler(const systems::StateSpace<> &ss, double dt);\n\n            /**\n             * @brief Generates Euler transform of a discrete-time state space\n             * system.\n             *\n             * @param ss TState space system.\n             * @param dt Sampling period.\n             *\n             * @return Transformed continuous-time state space system.\n             */\n            static systems::StateSpace<>\n            d2cEuler(const systems::StateSpace<> &ss, double dt);\n\n            /**\n             * @brief Generates backward differencing transform of a\n             * continuous-time state space system.\n             *\n             * @param ss TState space system.\n             * @param dt Sampling period.\n             *\n             * @return Transformed discrete-time state space system.\n             */\n            static systems::StateSpace<>\n            c2dBwdDiff(const systems::StateSpace<> &ss, double dt);\n\n            /**\n             * @brief Generates backward differencing transform of a\n             * discrete-time state space system.\n             *\n             * @param ss TState space system.\n             * @param dt Sampling period.\n             *\n             * @return Transformed continuous-time state space system.\n             */\n            static systems::StateSpace<>\n            d2cBwdDiff(const systems::StateSpace<> &ss, double dt);\n        };\n    }\n}\n\ntemplate<typename TScalar, int TStateDim, int TInputDim, int TOutputDim>\nvoid\nls::analysis::BilinearTransformation::c2d(const ls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim> *ss,\n                                          double dt, double alpha,\n                                          ls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim> *out,\n                                          mallocStructC2D<TScalar, TStateDim, TInputDim, TOutputDim> *memStruct,\n                                          LS_IS_DYNAMIC(TStateDim, TInputDim, TOutputDim))\n{\n    if (alpha < 0 || alpha > 1) alpha = 0;\n    dt = abs(dt);\n\n    memStruct->I.setIdentity(ss->stateDim(), ss->stateDim());\n    memStruct->HH = Eigen::ColPivHouseholderQR<Eigen::Matrix<TScalar, TStateDim, TStateDim>>(\n            memStruct->I - alpha * dt * (ss->getA()));\n    memStruct->HH2 = Eigen::ColPivHouseholderQR<Eigen::Matrix<TScalar, TStateDim, TStateDim>>(\n            (memStruct->I - alpha * dt * (ss->getA())).transpose());\n\n    out->setA(memStruct->HH.template solve(memStruct->I - (1 - alpha) * dt * (ss->getA())));\n    out->setB(memStruct->HH.template solve(dt * (ss->getB())));\n    out->setC(memStruct->HH2.template solve((ss->getC()).transpose()).transpose());\n    out->setD((ss->getD()) + alpha * (ss->getC()) * (out->getB()));\n    out->setDiscreteParams(dt, true);\n}\n\ntemplate<typename TScalar, int TStateDim, int TInputDim, int TOutputDim>\nvoid\nls::analysis::BilinearTransformation::c2d(const ls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim> *ss,\n                                          double dt, double alpha,\n                                          ls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim> *out,\n                                          mallocStructC2D<TScalar, TStateDim, TInputDim, TOutputDim> *memStruct,\n                                          LS_IS_STATIC(TStateDim, TInputDim, TOutputDim))\n{\n    if (alpha < 0 || alpha > 1) alpha = 0;\n    dt = abs(dt);\n\n    memStruct->I.setIdentity();\n    memStruct->HH = Eigen::ColPivHouseholderQR<Eigen::Matrix<TScalar, TStateDim, TStateDim>>(\n            memStruct->I - alpha * dt * (ss->getA()));\n    memStruct->HH2 = Eigen::ColPivHouseholderQR<Eigen::Matrix<TScalar, TStateDim, TStateDim>>(\n            (memStruct->I - alpha * dt * (ss->getA())).transpose());\n\n    out->setA(memStruct->HH.template solve(memStruct->I - (1 - alpha) * dt * (ss->getA())));\n    out->setB(memStruct->HH.template solve(dt * (ss->getB())));\n    out->setC(memStruct->HH2.template solve((ss->getC()).transpose()).transpose());\n    out->setD((ss->getD()) + alpha * (ss->getC()) * (*out->getB()));\n    out->setDiscreteParams(dt, true);\n}\n\ntemplate<typename TScalar, int TStateDim, int TInputDim, int TOutputDim>\nvoid\nls::analysis::BilinearTransformation::d2c(const ls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim> *ss,\n                                          double dt, double alpha,\n                                          ls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim> *out,\n                                          mallocStructD2C<TScalar, TStateDim, TInputDim, TOutputDim> *memStruct,\n                                          LS_IS_DYNAMIC(TStateDim, TInputDim, TOutputDim))\n{\n    if (alpha < 0 || alpha > 1) alpha = 0;\n    dt = abs(dt);\n\n    memStruct->I.setIdentity(ss->stateDim(), ss->stateDim());\n    memStruct->HH = Eigen::ColPivHouseholderQR<Eigen::Matrix<TScalar, TStateDim, TStateDim>>(\n            alpha * dt * (ss->getA()).transpose() + (1 - alpha) * dt * memStruct->I);\n    out->setA(memStruct->HH.template solve((ss->getA()).transpose() - memStruct->I));\n    memStruct->IMAC = memStruct->I - alpha * dt * (out->getA());\n\n    out->setB(memStruct->IMAC * (ss->getB()) / dt);\n    out->setC((ss->getC()) * memStruct->IMAC);\n    out->setD((ss->getD()) - alpha * (out->getC()) * (ss->getB()));\n    out->setDiscreteParams(-1, false);\n}\n\ntemplate<typename TScalar, int TStateDim, int TInputDim, int TOutputDim>\nvoid\nls::analysis::BilinearTransformation::d2c(const ls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim> *ss,\n                                          double dt, double alpha,\n                                          ls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim> *out,\n                                          mallocStructD2C<TScalar, TStateDim, TInputDim, TOutputDim> *memStruct,\n                                          LS_IS_STATIC(TStateDim, TInputDim, TOutputDim))\n{\n    if (alpha < 0 || alpha > 1) alpha = 0;\n    dt = abs(dt);\n\n    memStruct->I.setIdentity();\n    memStruct->HH = Eigen::ColPivHouseholderQR<Eigen::Matrix<TScalar, TStateDim, TStateDim>>(\n            alpha * dt * (ss->getA()).transpose() + (1 - alpha) * dt * memStruct->I);\n    out->setA(memStruct->HH.template solve((ss->getA()).transpose() - memStruct->I));\n    memStruct->IMAC = memStruct->I - alpha * dt * (out->getA());\n\n    out->setB(memStruct->IMAC * (ss->getB()) / dt);\n    out->setC((ss->getC()) * memStruct->IMAC);\n    out->setD((ss->getD()) - alpha * (out->getC()) * (ss->getB()));\n    out->setDiscreteParams(-1, false);\n}\n\n#endif //LODESTAR_BILINEARTRANSFORMATION_HPP\n", "meta": {"hexsha": "5ba667473f2d5461208a966b67a2342ad11427ba", "size": 16718, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Lodestar/analysis/BilinearTransformation.hpp", "max_stars_repo_name": "helkebir/Lodestar", "max_stars_repo_head_hexsha": "6b325d3e7a388676ed31d44eac1146630ee4bb2c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-06-05T14:08:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-26T22:15:31.000Z", "max_issues_repo_path": "Lodestar/analysis/BilinearTransformation.hpp", "max_issues_repo_name": "helkebir/Lodestar", "max_issues_repo_head_hexsha": "6b325d3e7a388676ed31d44eac1146630ee4bb2c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-06-25T15:14:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-01T17:43:20.000Z", "max_forks_repo_path": "Lodestar/analysis/BilinearTransformation.hpp", "max_forks_repo_name": "helkebir/Lodestar", "max_forks_repo_head_hexsha": "6b325d3e7a388676ed31d44eac1146630ee4bb2c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-16T03:15:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-16T03:15:23.000Z", "avg_line_length": 46.6983240223, "max_line_length": 144, "alphanum_fraction": 0.5746500778, "num_tokens": 3813, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105695, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.7069744916969553}}
{"text": "#include <iostream>\n#include <Eigen/Core>\n#include <Eigen/Eigen>\n#include <fstream>\n#include <vector>\n#include <iomanip>\n#include <math.h>\n\n\nvoid load_csv(std::string filename, Eigen::ArrayXXd &output);\n\nvoid writeToCSVfile(std::string name,Eigen::MatrixXd matrix)\n{\n  std::ofstream file(name.c_str());\n\n  for(int  i = 0; i < matrix.rows(); i++){\n      for(int j = 0; j < matrix.cols(); j++){\n         std::string str = std::to_string(matrix(i,j));\n         if(j+1 == matrix.cols()){\n             file<<str;\n         }else{\n             file<<str<<',';\n         }\n      }\n      file<<'\\n';\n  }\n}\n\nint main(int argc, char const *argv[])\n{\n\tEigen::ArrayXXd Input;\n\tEigen::ArrayXXd Feature;\n\n\t// Choose how many samples to skip at each iteration\n\tint samplingTime = 3;\n\n\t// Load Data\n\t// Input has dimension Time X 1\n\t// Feature has dimension Time X N_Feature\n\tload_csv(\"Feature.csv\", Feature);\n\tload_csv(\"TrainData.csv\", Input);\n\n\t// Calculate effective dimension\n\tint dimension = ceil(Input.rows()/(double) samplingTime);\n\n\t// Create structures\n\tEigen::ArrayXXd distances_feature(dimension, dimension);\n\tEigen::ArrayXXd distances_input_corr(dimension,dimension);\n\n\tEigen::ArrayXXd distances_input(dimension, dimension);\n\tEigen::ArrayXXd distances_mixed(dimension, dimension);\n\n\t//Compute Kernels for 1D and 2D data\n\tdouble h_1D = 0.9 * pow((double)dimension, -1.0/5.0);\n\th_1D = pow(h_1D,2);\n\n\tdouble h_2D =  pow((double)dimension, -1.0/6.0);\n\th_2D = pow(h_2D,2);\n\n\t// Structures for variance\n    double var_correction = dimension/(double)(dimension-1);\n\tdouble var_input;\n\tdouble var_feature;\n\tdouble extra_diagonal;\n\tEigen::MatrixXd CovMatrix(2,2);\n\n    var_input= var_correction * (Input.pow(2).mean()-pow(Input.mean(),2));\n\n    // Compute distance matrix for input\n\tint i_aux = 0, j_aux;\n\tfor (int i = 0; i < Input.rows(); i = i+samplingTime)\n\t{\n\t\tj_aux = i_aux;\n\t\tfor (int j = i; j < Input.rows(); j = j+samplingTime)\n\t\t{\t\n\t\t\tdistances_input(i_aux,j_aux) = Input(i) - Input(j);\n\t\t\tdistances_input(j_aux,i_aux) = distances_input(i_aux,j_aux);\n\t\t\tj_aux++;\n\t\t}\n\t\ti_aux++;\n\t}\n\n\t// Compute Kernel Distances\n\tdistances_input_corr = -1.0 * distances_input.pow(2) / (2*var_input * h_1D);\n\tdistances_input_corr = distances_input_corr.exp() / std::sqrt(2*M_PI*var_input * h_1D);\n\t// Compute input pdf \n\tEigen::ArrayXd C_Input = distances_input_corr.rowwise().mean();\n\n\t// Analyze Feature Matrix\n\tfor (int z = 0; z < Feature.cols(); ++z)\n\t{\n\t\t// Isolate signal from one feature\n\t\tEigen::ArrayXd signal = Feature.col(z);\n\n\t\t// Compute variance\n\t\tvar_feature = var_correction * (signal.pow(2).mean()-pow(signal.mean(),2));\n\t\t//var_feature = var_feature;\n\t\t\n\t\t// extra_diagonal =( ( signal - signal.mean()) * (Input - Input.mean()) ).mean() / (double) (dimension-1);\n\t\t// Compute Covariance Matrix. Kernel width is 0 for extra-diagonal term\n\t\tCovMatrix(0,0) = var_input * h_2D;\n\t\tCovMatrix(0,1) = 0;\n\t\tCovMatrix(1,0) = 0;\n\t\tCovMatrix(1,1) = var_feature * h_2D;\n\n\t\tdouble determinant = std::sqrt(CovMatrix.determinant());\n\n\t\t// Compute inverse of diagonal matrix\n\t\tCovMatrix(0,0) = 1/(var_input * h_2D);\n\t\tCovMatrix(1,1) = 1/(var_feature * h_2D);\n\n\t\tEigen::MatrixXd Support(2,1);\n\n\t\tint i_aux = 0, j_aux;\n\t\tfor (int i = 0; i < Input.rows(); i = i+samplingTime)\n\t\t{\n\t\t\tj_aux = i_aux;\n\t\t\tfor (int j = i; j < Input.rows(); j = j+samplingTime)\n\t\t\t{\n\t\t\t\t// Compute distance feature\n\t\t\t\tdistances_feature(i_aux,j_aux) = signal(i) - signal(j);\n\t\t\t\tdistances_feature(j_aux, i_aux) = distances_feature(i_aux,j_aux);\n\n\t\t\t\tSupport(0,0) = distances_input(i_aux,j_aux);\n\t\t\t\tSupport(1,0) = distances_feature(i_aux, j_aux);\n\t\t\t\tdouble result = (- ( (Support.transpose() * CovMatrix) * Support))(0,0);\n\t\t\t\tdistances_mixed(i_aux,j_aux) = exp( result/(2) );\n\t\t\t\tdistances_mixed(j_aux, i_aux) = distances_mixed(i_aux, j_aux);\n\n\t\t\t\tj_aux++;\n\t\t\t}\n\t\ti_aux++;\n\t\t}\n\t// Compute Kernel Feature Matrix and Kernel Joint Distance Matrix\n\tdistances_mixed = distances_mixed / (2 * M_PI * determinant);\n\tdistances_feature = -1.0 * distances_feature.pow(2) / (2*var_feature* h_1D);\n\tdistances_feature = distances_feature.exp()/std::sqrt(2*M_PI * var_feature * h_1D);\n\t\n\t// Compute Feature pdf\n\tEigen::ArrayXd C_Feature = distances_feature.rowwise().mean();\n\n\t// Compute Mutual Information\n\tEigen::ArrayXd num =  distances_mixed.rowwise().mean();\n\tEigen::ArrayXd den = C_Feature * C_Input;\n\tnum = num.cwiseQuotient(den);\n\tnum = num.log() / log(2);\n\tstd::cout << \"Feature: \" << z << std::endl;\n\tstd::cout <<\"MI: \" << num.mean() << std::endl;\n\n\t// Single Entropies\n\tauto feature_pdf = distances_feature.rowwise().mean().log() / log(2);\n\tauto input_pdf = distances_input_corr.rowwise().mean().log()/log(2);\n\tauto joint_pdf = distances_mixed.rowwise().mean().log()/log(2);\n\n\n\tstd::cout << \"Entropy Feature H(Y): \" << -feature_pdf.mean() << std::endl;\n\tstd::cout << \"Entropy Input H(X): \" << -input_pdf.mean() << std::endl;\n\tstd::cout << \"Entropy Joint H(X|Y): \" << -joint_pdf.mean() << std::endl;\n\n\n\n\n\t}\n\treturn 0;\n}\n\nvoid load_csv(std::string filename, Eigen::ArrayXXd &output)\n{\n    std::vector<double> vec;\n    std::string buffer;\n    char *tokens;\n    int i, j;\n    int cols = 0, line = 0;\n\n    std::ifstream input_stream(filename.c_str());\n\n    if (input_stream.is_open())\n    {\n        // // Read header\n        // if (!input_stream.eof())\n        // {\n        //     getline(input_stream, buffer, '\\n');\n        //     cols = std::count(buffer.begin(), buffer.end(), ',') + 1;\n        // }\n\n        // Read data\n        while (!input_stream.eof())\n        {\n\n            getline(input_stream, buffer, '\\n');\n            if(line == 0)\n\t        \tcols = std::count(buffer.begin(), buffer.end(), ',') + 1;\n\n            tokens = strtok(strdup(buffer.c_str()), \",\");\n            for (i = 0; (i < cols) && (tokens != NULL); i++)\n            {\n                vec.push_back(atof(tokens));\n                tokens = strtok(NULL, \",\");\n            }\n            line++;\n        }\n        // Close file\n        input_stream.close();\n\n        // Place data in matrix\n        if (line > 1)\n        {\n            output.conservativeResize(line - 1, cols);\n            for (i = 0; i < line - 1; i++)\n            {\n                for (j = 0; j < cols; j++)\n                {\n                    output(i, j) = vec[i * cols + j];\n                }\n            }\n        }\n    }\n    else\n    {\n        std::cerr << \"File \" << filename << \" not found\" << std::endl;\n        throw;\n    }\n}", "meta": {"hexsha": "b2d8784b639a3c14f965700be3f11726c5e3506f", "size": 6426, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "Giuseppe5/Mutual-Information-C-", "max_stars_repo_head_hexsha": "e444899acfb277dab015664e7a562dcbadbafd98", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-10-26T15:53:54.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-26T15:53:54.000Z", "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "Giuseppe5/Mutual-Information-KDE", "max_issues_repo_head_hexsha": "e444899acfb277dab015664e7a562dcbadbafd98", "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": "Giuseppe5/Mutual-Information-KDE", "max_forks_repo_head_hexsha": "e444899acfb277dab015664e7a562dcbadbafd98", "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.8161434978, "max_line_length": 108, "alphanum_fraction": 0.604886399, "num_tokens": 1851, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810496235896, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.7068779370345717}}
{"text": "#include <Eigen/Dense>\n#include <algorithm>\n#include <cfloat>\n#include <random>\n#include <iostream>\n#include <simpleClusterization_common.hpp>\n#include <simpleClusterization.hpp>\n\nusing namespace Eigen;\n\nfloat euclideanNorm(\n        const VectorXf &v1, \n        const VectorXf &v2\n    ){\n    return (v1 - v2).squaredNorm();\n}\n\nvoid calculateFuzzyWeights(\n        const Ref<const MatrixXf>   &entities,\n        const Ref<const MatrixXf>   &centroids,\n        Ref<MatrixXfR>              weights,\n        squaredNorm_t               *norm\n        ){\n    const int entitiesNumber  = entities.rows();\n    const int centroidsNumber = centroids.rows();\n    for(int i=0;i<centroidsNumber;++i){\n        for(int j=0;j<entitiesNumber;++j){\n            weights(i, j) = (*norm)(centroids.row(i), entities.row(j));\n            assert(weights(i, j)> FCM_THRESHOLD && \"A centroid and an entity coincide, this leads to infinite weights, correct\\n\");\n        }\n    }\n    weights.array() = 1.0 / weights.array();\n}\n\n\nvoid FCMGenerator(\n        const Ref<const MatrixXf>   &entities, \n        Ref<MatrixXf>               centroids, \n        Ref<MatrixXfR>              weights, \n        squaredNorm_t               *norm\n    ){\n    //The loop is as following:\n    //1 - We initialize weights to random values from 0 to 1 (to check if they need to sum up to 1)\n    //2 - We calculate the Centroids of each cluster (what is gonna end up in entities as a Statistical Entity according to the following formula: c_j = (Sum_i w_ij^m * x_i)/(Sum_i w_ij^m)\n    //3 - We update weights according to this formula:  w_ij = 1 / (Sum_k (distance(x_i, c_j)/distance(x_i, c_k)) ^ (2 / m-1)) where m is a fuzziness parameter that's usually put equal to 2\n    // Loop until Norm(W_i+1 - W_i) < Epsilon where Epsilon is a threshold decided by the coder\n    assert(weights.cols()==entities.rows() && centroids.rows()==weights.rows() && centroids.cols()==entities.cols() && \"Matrix sizes for FCMGenerator not compatibles\\n\");\n    const int centroidsNumber = centroids.rows();\n    MatrixXfR weightsOld(weights.rows(), weights.cols());\n    MatrixXfR weights2(weights.rows(), weights.cols());\n    MatrixXfR weightsOld2(weights.rows(), weights.cols());\n    //Initialization of the weights at random values, might be improved if we could get a reasonable initial guess\n    weightsOld = MatrixXf::Zero(weights.rows(), weights.cols());\n    weights = MatrixXf::Random(weights.rows(), weights.cols());\n    for(int loopIndex=0;loopIndex<FCM_MAX_ITERATIONS && (weights - weightsOld).squaredNorm() > FCM_THRESHOLD;++loopIndex){\n        weightsOld = weights;\n        weights2 = weights.array().square();\n        //Calculation of the Centroids\n        centroids = weights2 * entities;\n        for(int i=0;i<centroidsNumber;++i){\n            float multiplier  = 1.0 / weights2.row(i).sum();\n            centroids.row(i) *= multiplier; \n        }\n        //Update of the weights with the new Centroids\n        calculateFuzzyWeights(entities, centroids, weights, norm);\n        weights.rowwise().normalize();\n    }\n}\n\nfloat daviesBouldinIndex(\n        const Ref<const MatrixXf>    &entities,\n        const Ref<const MatrixXf>    &centroids,\n        const Ref<const MatrixXb>    &weights,\n        squaredNorm_t                *norm\n    ){\n    const int clustersNumber = centroids.rows();\n    const int startingEntitiesNumber = entities.rows();\n    VectorXf scatterVector = VectorXf::Zero(clustersNumber);\n    for(int i=0;i<clustersNumber;++i){\n        for(int j=0;j<startingEntitiesNumber;++j){\n            if(weights(i, j)){\n                scatterVector(i)+=(*norm)(centroids.row(i), entities.row(j));\n            }\n        }\n        float multiplier  = 1.0 / (float) weights.row(i).count();\n        scatterVector(i) *= multiplier;\n    }\n    scatterVector = scatterVector.cwiseSqrt();\n    MatrixXf clusterSeparationMatrix(clustersNumber, clustersNumber);\n    for(int i=0;i<clustersNumber;++i){\n        for(int j=0;j<clustersNumber;++j){\n            clusterSeparationMatrix(i, j) = (*norm)(centroids.row(i), centroids.row(j));\n        }\n    }\n    clusterSeparationMatrix = clusterSeparationMatrix.cwiseSqrt();\n    float dbIndex = 0;\n    for(int i=0;i<clustersNumber;++i){\n        float dbIndexCluster = 0;\n        for(int j=0;j<clustersNumber;++j){\n            if(i!=j){\n                dbIndexCluster = std::max((scatterVector(i) + scatterVector(j))/clusterSeparationMatrix(i, j), dbIndexCluster);\n            }\n        }\n        dbIndex+=dbIndexCluster;\n    }\n    return dbIndex/float(clustersNumber);\n}\n\nfloat silhouetteTest(\n        const Ref<const MatrixXf>   &entities, \n        const Ref<const MatrixXf>   &clusters,\n        const Ref<const MatrixXfR>  &weights\n        ){\n    //TODO\n    return 1.;\n}\n\n\n/*!\n * @brief      Takes data points and a k-long cluster matrix, generates initial values for k centroids.\n * @note       entities is copied and not referenced, as it needs to be altered for simplicity's sake\n * @param[in]  entities    The datapoints\n * @param[in-out] centroids   The centroids of the clusters generated by this function\n * @param[in]  norm        A pointer to the norm function you want to use\n*/\nvoid kmeansInitializer(\n        const Ref<const MatrixXf>    &entities,\n        Ref<MatrixXf>                centroids,\n        squaredNorm_t                *norm\n    ){\n    const int statsNumber = entities.cols();\n    const int startingEntitiesNumber = entities.rows();\n    const int clustersNumber = centroids.rows();\n    int currentClustersNumber = 0;\n    MatrixXfR mEntities = entities;\n    VectorXf squaredDistances(startingEntitiesNumber);\n    std::random_device rd;\n    std::mt19937 gen(rd());\n    std::uniform_int_distribution<> intDistribution(0, startingEntitiesNumber - 1);\n//   1. Choose one center uniformly at random among the data points.\n    int randomIndex = intDistribution(gen);\n    while(true){\n        centroids.row(currentClustersNumber) = mEntities.row(randomIndex);\n        mEntities.row(randomIndex) = mEntities.row(startingEntitiesNumber - currentClustersNumber - 1);\n        mEntities.row(startingEntitiesNumber - currentClustersNumber - 1) = VectorXf::Zero(statsNumber);\n        ++currentClustersNumber;\n        if(currentClustersNumber==clustersNumber){\n            break;\n        }\n        //   2. For each data point x not chosen yet, compute D(x), the distance between x and the nearest center that has already been chosen.\n        for(int j=0;j<startingEntitiesNumber - currentClustersNumber;++j){\n            squaredDistances(j) = (*norm)(centroids.row(0), mEntities.row(j));\n            for(int i=1;i<currentClustersNumber;++i){\n                squaredDistances(j) = std::min((*norm)(centroids.row(i), mEntities.row(j)), squaredDistances(j));\n            }\n        }\n        //   3. Choose one new data point at random as a new center, using a weighted probability distribution where a point x is chosen with probability proportional to D(x)2.\n        std::partial_sum(squaredDistances.data(), squaredDistances.data() + startingEntitiesNumber - currentClustersNumber - 1, squaredDistances.data());\n        std::uniform_real_distribution<> floatDistribution(squaredDistances(0), squaredDistances(startingEntitiesNumber - currentClustersNumber - 1));\n        float randomFloat = floatDistribution(gen);\n        randomIndex = std::upper_bound(squaredDistances.data(), squaredDistances.data() + startingEntitiesNumber - currentClustersNumber - 1, randomFloat) - squaredDistances.data();\n        //   4. Repeat Steps 2 and 3 until k centers have been chosen.\n    }\n//   5. Now that the initial centers have been chosen, proceed using standard k-means clustering.\n}\n\n\nvoid calculateBooleanWeights(\n        const Ref<const MatrixXf>   &entities,\n        const Ref<const MatrixXf>   &centroids,\n        Ref<MatrixXbR>              weights,\n        squaredNorm_t               *norm\n    ){\n    const int entitiesNumber = entities.rows();\n    const int clustersNumber = centroids.rows();\n    weights.setConstant(false);\n    for(int j=0;j<entitiesNumber;j++){\n        float minDistance = (*norm)(centroids.row(0), entities.row(j));\n        int minIndex = 0;\n        for(int i=1;i<clustersNumber;i++){\n            float currentDistance = (*norm)(centroids.row(i), entities.row(j));\n            if(currentDistance < minDistance){\n                minDistance = currentDistance;\n                minIndex = i;\n            }\n        }\n        weights(minIndex, j) = true;\n    }\n}\n\n\nvoid kmeansGenerator(\n        const Ref<const MatrixXf>   &entities,\n        Ref<MatrixXf>               centroids,\n        Ref<MatrixXbR>              weights,\n        squaredNorm_t               *norm\n    ){\n    assert(entities.cols()==centroids.cols() && \"Called cmeansGenerator with entities and centroids having different dimensions\\n\");\n    const int entitiesNumber = entities.rows();\n    const int clustersNumber = centroids.rows();\n    //We initialize the centroids with some datapoints that are spread out across the dataset, according to the kmeans++ algorithm\n    kmeansInitializer(entities, centroids, norm);\n    calculateBooleanWeights(entities, centroids, weights, norm);\n    MatrixXb oldWeights(clustersNumber, entitiesNumber);\n    oldWeights.setConstant(false);\n    while(oldWeights!=weights){\n        oldWeights = weights;\n        centroids = (weights.cast<float>()) * entities;\n        for(int i=0;i<clustersNumber;++i){\n            float multiplier  = 1.0 / (float) weights.row(i).count();\n            centroids.row(i) *= multiplier; \n        }\n        calculateBooleanWeights(entities, centroids, weights, norm);\n    }\n}\n    \nint clusterGeneratorApproximate(\n        const Ref<const MatrixXf>   &entities,\n        Ref<MatrixXf>               centroids,\n        Ref<MatrixXfR>              weights,\n        Ref<MatrixXbR>              boolWeights,\n        squaredNorm_t               *norm\n    ){\n    assert(centroids.cols()==entities.cols() && \"clusterGeneratorApproximate: called with entities and centroids having different sizes\");\n    const int statsNumber = entities.cols();\n    const int entitiesNumber = entities.rows();\n    const int maxClustersNumber = centroids.rows(); \n    float fitnessCandidate = 50.;\n    float newFitness = 50.;\n    MatrixXf currentClustersCandidate(maxClustersNumber, statsNumber); \n    MatrixXbR currentBoolWeightsCandidate(maxClustersNumber, entitiesNumber);\n    int clustersNumber = 2;\n    //The minimum amount of clusters is 2 because otherwise the Davies-Bouldin index fails\n    for(int currentClustersNumber = 2; currentClustersNumber<=maxClustersNumber; ++currentClustersNumber){\n        for(int i=0;i<attemptsPerClustersNumber;++i){\n            int iterations = 0;\n            do{\n                currentClustersCandidate.topLeftCorner(currentClustersNumber, statsNumber).setZero();\n                currentBoolWeightsCandidate.topLeftCorner(currentClustersNumber, entitiesNumber).setZero();\n                kmeansGenerator(entities, currentClustersCandidate.topLeftCorner(currentClustersNumber, statsNumber), currentBoolWeightsCandidate.topLeftCorner(currentClustersNumber, entitiesNumber), norm);\n                newFitness = daviesBouldinIndex(entities, currentClustersCandidate.topLeftCorner(currentClustersNumber, statsNumber), currentBoolWeightsCandidate.topLeftCorner(currentClustersNumber, entitiesNumber),  norm);\n                ++iterations;\n            }while(std::isnan(newFitness) && iterations < maxIterationPerClustersNumber);\n            if (newFitness < fitnessCandidate){\n                centroids.topLeftCorner(currentClustersNumber, statsNumber)            = currentClustersCandidate.topLeftCorner(currentClustersNumber, statsNumber);\n                boolWeights.topLeftCorner(currentClustersNumber, entitiesNumber)       = currentBoolWeightsCandidate.topLeftCorner(currentClustersNumber, entitiesNumber);\n                fitnessCandidate                                                = newFitness;\n                clustersNumber                                                 = currentClustersNumber;\n            }\n        }\n    }\n    //Single-datapoint clusters lead to infinite fuzzy weights, so we offset them by a small vector.\n    //The risk in doing this is that we might end up moving the centroid too much, so that its datapoint ends up in another cluster.\n    //So to avoid this, we scale our offsetConstant by the dataset's dimensionality.\n    //Additionally, we choose as a direction the one defined by the current vector and the average one the result is that we're pushing the centroid towards the center of the whole dataset, \n    //which makes it slightly harder for the worst case scenario to happen.\n    const float shiftMultiplier = offsetConstant / float(statsNumber);\n    const RowVectorXf averageEntity = entities.colwise().mean();\n    for(int i=0;i<clustersNumber;++i){\n        if(boolWeights.row(i).count()==1){\n            centroids.row(i) += shiftMultiplier * (centroids.row(i) - averageEntity);\n        }\n    }\n    calculateFuzzyWeights(entities, centroids.topRightCorner(clustersNumber, statsNumber), weights.topLeftCorner(clustersNumber, entitiesNumber), norm);\n    return clustersNumber;\n}\n\nint clusterGeneratorExact(\n        const Ref<const MatrixXf>   &entities,\n        Ref<MatrixXf>               centroids,\n        MatrixXfR                   &weights, \n        squaredNorm_t               *norm\n    ){\n    assert(weights.rows()==weights.cols() && \"Called clusterGenerator with a non-square weights matrix\\n\");\n    const int statsNumber = entities.cols();\n    const int entitiesNumber = entities.rows();\n    const int maxClustersNumber = centroids.rows();\n    float fitnessCandidate = 0;\n    float newFitness = 0;\n    int centroidsNumber = 2;\n    MatrixXf currentClustersCandidate(maxClustersNumber, statsNumber);\n    //Initialized to catch the improbable case of silhouetteTest() always returning 0\n    MatrixXfR currentWeightsCandidate, weightsCandidate;\n    //Initialized to catch the improbable case of silhouetteTest() always returning 0\n    for(int clustersNumber = 2; clustersNumber<=maxClustersNumber; ++clustersNumber){\n        currentClustersCandidate.topLeftCorner(clustersNumber, statsNumber).setZero();\n        currentWeightsCandidate.topLeftCorner(clustersNumber, entitiesNumber).setZero();\n        FCMGenerator(entities, currentClustersCandidate, currentWeightsCandidate, norm);\n        newFitness = silhouetteTest(entities, currentClustersCandidate, currentWeightsCandidate);\n        if (newFitness > fitnessCandidate){\n            centroids.topLeftCorner(clustersNumber, statsNumber) = currentClustersCandidate.topLeftCorner(clustersNumber, statsNumber);\n            weights.topLeftCorner(clustersNumber, entitiesNumber) = currentWeightsCandidate.topLeftCorner(clustersNumber, entitiesNumber);\n            fitnessCandidate = newFitness;\n            centroidsNumber = clustersNumber;\n        }\n    }\n    return centroidsNumber;\n}\n", "meta": {"hexsha": "54c5d90314cbdaf068909eab9918d6085d02a70f", "size": 14933, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/simpleClusterization.cpp", "max_stars_repo_name": "tesseract241/simpleClusterization", "max_stars_repo_head_hexsha": "d5125e5b99b67ac92847cccb28b8bf058ac35efd", "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": "source/simpleClusterization.cpp", "max_issues_repo_name": "tesseract241/simpleClusterization", "max_issues_repo_head_hexsha": "d5125e5b99b67ac92847cccb28b8bf058ac35efd", "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": "source/simpleClusterization.cpp", "max_forks_repo_name": "tesseract241/simpleClusterization", "max_forks_repo_head_hexsha": "d5125e5b99b67ac92847cccb28b8bf058ac35efd", "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": 49.9431438127, "max_line_length": 223, "alphanum_fraction": 0.6666443447, "num_tokens": 3297, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850110816423, "lm_q2_score": 0.7549149758396752, "lm_q1q2_score": 0.706815576519748}}
{"text": "/*\n * Copyright 2010 Savarese Software Research Corporation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.savarese.com/software/ApacheLicense-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n#include <iostream>\n#include <ssrc/spatial/distance.h>\n\n#include <array>\n\n#define BOOST_TEST_MODULE DistanceTest\n#include <boost/test/unit_test.hpp>\n#include <boost/mpl/list.hpp>\n\nusing namespace ssrc::spatial;\n\ntypedef boost::mpl::list<unsigned int, int, double> coordinate_types;\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_d2_0, coordinate_type, coordinate_types) {\n  typedef NS_TR1::array<coordinate_type, 1> Point;\n\n  BOOST_REQUIRE_EQUAL(euclidean_distance<Point>::d2(Point{{1}}, Point{{1}}), 0);\n  BOOST_REQUIRE_EQUAL(euclidean_distance<Point>::d2(Point{{1}}, Point{{2}}), 1);\n  BOOST_REQUIRE_EQUAL(euclidean_distance<Point>::d2(Point{{48}},\n                                                    Point{{52}}), 16);\n  BOOST_REQUIRE_EQUAL(euclidean_distance<Point>::d2(Point{{4}},\n                                                    Point{{1}}), 9);\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_d2_1, coordinate_type, coordinate_types) {\n  typedef NS_TR1::array<coordinate_type, 2> Point;\n\n  BOOST_REQUIRE_EQUAL(euclidean_distance<Point>::d2(Point{{1,1}},\n                                                    Point{{1,1}}), 0);\n  BOOST_REQUIRE_EQUAL(euclidean_distance<Point>::d2(Point{{1,1}},\n                                                    Point{{2,2}}), 2);\n  BOOST_REQUIRE_EQUAL(euclidean_distance<Point>::d2(Point{{83,9451}},\n                                                    Point{{4382,2383}}),\n                      68438025);\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_d2_2, coordinate_type, coordinate_types) {\n  typedef NS_TR1::array<coordinate_type, 3> Point;\n\n  BOOST_REQUIRE_EQUAL(euclidean_distance<Point>::d2(Point{{1,1,1}},\n                                                    Point{{1,1,1}}), 0);\n  BOOST_REQUIRE_EQUAL(euclidean_distance<Point>::d2(Point{{1,1,1}},\n                                                    Point{{2,2,2}}), 3);\n  BOOST_REQUIRE_EQUAL(euclidean_distance<Point>::d2(Point{{9,0,4}},\n                                                    Point{{100,32,0}}), 9321);\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_d2_4, coordinate_type, coordinate_types) {\n  typedef NS_TR1::array<coordinate_type, 4> Point;\n\n  BOOST_REQUIRE_EQUAL(euclidean_distance<Point>::d2(Point{{1,1,1,1}},\n                                                    Point{{1,1,1,1}}), 0);\n  BOOST_REQUIRE_EQUAL(euclidean_distance<Point>::d2(Point{{1,1,1,1}},\n                                                    Point{{2,2,2,2}}), 4);\n}\n", "meta": {"hexsha": "120f968536e99e37c13bf6880895bcf7ff211331", "size": 3044, "ext": "cc", "lang": "C++", "max_stars_repo_path": "external/libssrckdtree-1.0.7/tests/spatial/distance_test.cc", "max_stars_repo_name": "zigaosolin/Raytracer", "max_stars_repo_head_hexsha": "df17f77e814b2e4b90c4a194e18cc81fa84dcb27", "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": "external/libssrckdtree-1.0.7/tests/spatial/distance_test.cc", "max_issues_repo_name": "zigaosolin/Raytracer", "max_issues_repo_head_hexsha": "df17f77e814b2e4b90c4a194e18cc81fa84dcb27", "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": "external/libssrckdtree-1.0.7/tests/spatial/distance_test.cc", "max_forks_repo_name": "zigaosolin/Raytracer", "max_forks_repo_head_hexsha": "df17f77e814b2e4b90c4a194e18cc81fa84dcb27", "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.8732394366, "max_line_length": 80, "alphanum_fraction": 0.6120236531, "num_tokens": 709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.8221891392358015, "lm_q1q2_score": 0.7068062049761856}}
{"text": "///////////////////////////////////////////////////////////////////\n//  Copyright Eduardo Quintana 2021\n//  Copyright Janek Kozicki 2021\n//  Copyright Christopher Kormanyos 2021\n//  Distributed under the Boost Software License,\n//  Version 1.0. (See accompanying file LICENSE_1_0.txt\n//  or copy at http://www.boost.org/LICENSE_1_0.txt)\n/*\n    boost::math::fft example 06\n    \n    Fast Polynomial Multiplication\n*/\n\n#include <boost/math/fft/bsl_backend.hpp>\n#include <iostream>\n#include <vector>\n#include <exception>\n#include <boost/core/demangle.hpp>\n\ntemplate<class T>\nvoid print(const std::vector<T>& V)\n{\n  std::cout << \"size(V) = \" << V.size() << \"\\n\";\n  std::cout << \"[\";\n  for(auto x: V)\n  {\n    std::cout << x << \", \";\n  }\n  std::cout << \"]\\n\";\n}\n\ntemplate<class T>\nstd::vector<T> multiply_halfcomplex(const std::vector<T>& A, const std::vector<T>& B)\n// I strongly discourage to use this function that depends on the halfcomplex representation\n// TODO: create a class to \"view\" the contents of a halfcomplex array\n{\n  std::cout << \"Polynomial multiplication using halfcomplex with: \"<< boost::core::demangle(typeid(T).name()) <<\"\\n\";\n  const std::size_t N = A.size();\n  std::vector<T> TA(N),TB(N);\n  boost::math::fft::bsl_rdft<T> P(N); \n  P.real_to_halfcomplex(A.begin(),A.end(),TA.begin());\n  P.real_to_halfcomplex(B.begin(),B.end(),TB.begin());\n  \n  std::vector<T> C(N);\n  \n  C[0]=TA[0]*TB[0];\n  for(unsigned int i=1;i+1<N;i+=2)\n  {\n    C[i] = TA[i]*TB[i]-TA[i+1]*TB[i+1];\n    C[i+1] = TA[i]*TB[i+1] + TA[i+1]*TB[i];\n  }\n  if(N%2==0)\n  {\n    C.back() = TA.back()*TB.back();\n  }\n  \n  P.halfcomplex_to_real(C.begin(),C.end(),C.begin());\n  std::transform(C.begin(), C.end(), C.begin(),\n                 [N](T x) { return x / N; });\n  \n  print(C);\n  return C;\n}\ntemplate<class T>\nstd::vector<T> multiply_complex(const std::vector<T>& A, const std::vector<T>& B)\n{\n  std::cout << \"Polynomial multiplication using complex: \"<< boost::core::demangle(typeid(T).name()) <<\"\\n\";\n  const std::size_t N = A.size();\n  std::vector< boost::multiprecision::complex<T> > TA(N),TB(N);\n  boost::math::fft::bsl_rdft<T> P(N); \n  P.real_to_complex(A.begin(),A.end(),TA.begin());\n  P.real_to_complex(B.begin(),B.end(),TB.begin());\n  \n  std::vector<T> C(N);\n  \n  for(unsigned int i=0;i<N;++i)\n  {\n    TA[i]*=TB[i];\n  }\n  \n  P.complex_to_real(TA.begin(),TA.end(),C.begin());\n  std::transform(C.begin(), C.end(), C.begin(),\n                 [N](T x) { return x / N; });\n  \n  print(C);\n  return C;\n}\n\ntemplate<class T>\nT difference(const std::vector<T>& A, const std::vector<T>& B)\n{\n  using std::abs;\n  T diff{};\n  if(A.size()!=B.size()) return -1;\n  for(unsigned int i=0;i<A.size();++i)\n  {\n    diff += abs(A[i]-B[i]);\n  }\n  return diff;\n}\n\ntemplate<typename Real>\nvoid multiply() {\n  using std::abs;\n  std::vector<Real> A{1.,4.,-5.,1.,0.,0.,0.,0.};\n  std::vector<Real> B{-1.,1.,2.,3.,0.,0.,0.,0.};\n  std::vector<Real> C{-1,-3,11,5,3,-13,3,0};\n  \n  std::vector<Real> result;\n  Real diff;\n  \n  // result = multiply_halfcomplex(A,B);\n  // diff = difference(result,C);\n  // if(abs(diff)>1e-6) \n  //   throw std::runtime_error(\"wrong result\");\n  result = multiply_complex(A,B);\n  diff = difference(result,C);\n  if(abs(diff)>1e-3) \n    throw std::runtime_error(\"wrong result\");\n}\n\nint main()\n{\n  multiply<float>();\n  multiply<double>();\n  multiply<long double>();\n  return 0;\n}\n\n\n", "meta": {"hexsha": "1818b4e1e1d06818c56f7c572a8ee8bc5bb8aa47", "size": 3361, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/fft_ex06.cpp", "max_stars_repo_name": "BoostGSoC21/math", "max_stars_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_stars_repo_licenses": ["BSL-1.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": "example/fft_ex06.cpp", "max_issues_repo_name": "BoostGSoC21/math", "max_issues_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 30.0, "max_issues_repo_issues_event_min_datetime": "2021-06-22T12:59:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-02T09:27:49.000Z", "max_forks_repo_path": "example/fft_ex06.cpp", "max_forks_repo_name": "BoostGSoC21/math", "max_forks_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-07T21:15:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-07T21:15:02.000Z", "avg_line_length": 25.6564885496, "max_line_length": 117, "alphanum_fraction": 0.5894079143, "num_tokens": 1037, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361676202372, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.7067578992977126}}
{"text": "#ifndef EXPSUM_KERNEL_FUNCTIONS_POW_KERNEL_HPP\n#define EXPSUM_KERNEL_FUNCTIONS_POW_KERNEL_HPP\n\n#include <cassert>\n#include <sstream>\n#include <stdexcept>\n#include <tuple>\n\n#include <armadillo>\n\n#include \"expsum/constants.hpp\"\n#include \"expsum/exponential_sum.hpp\"\n#include \"expsum/kernel_functions/gamma.hpp\"\n#include \"expsum/kernel_functions/gauss_quadrature.hpp\"\n\nnamespace expsum\n{\n\n//\n// Approximate power function by an exponential sum.\n//\n// For given accuracy ``$\\epsilon > 0$`` and distance to the singularity\n// ``$\\delta > 0$``, this find the approximation of power function\n// ``$f(r)=r^{-\\beta}$`` with a linear combination of exponential functions\n// such that\n//\n// ``` math\n// \\left| r^{-\\beta}-\\sum_{m=1}^{M}w_{m}e^{-a_{m}r} \\right|\n//    \\leq r^{-\\beta}\\epsilon\n// ```\n//\n// for ``$r\\in [\\delta,1]$.\n//\n// @beta   power factor ``$beta > 0$``\n// @delta  distance to the singularity ``$0 < \\delta < 1$``\n// @eps    required accuracy ``$0 < \\epsilon < e^{-1}$``\n// @return pair of vectors holding expnents ``$a_{m}$`` and weights ``$w_{m}$``\n//\n\ntemplate <typename T>\nstruct pow_kernel\n{\npublic:\n    using size_type   = arma::uword;\n    using real_type   = T;\n    using vector_type = arma::Col<T>;\n    using matrix_type = arma::Mat<T>;\n\nprivate:\n    vector_type exponent_;\n    vector_type weight_;\n    real_type beta_;\n    real_type delta_;\n    real_type eps_;\n\npublic:\n    void compute(real_type beta__, real_type delta__, real_type eps__);\n\n    size_type size() const\n    {\n        return exponent_.size();\n    }\n\n    const vector_type& exponents() const\n    {\n        return exponent_;\n    }\n\n    const vector_type& weights() const\n    {\n        return weight_;\n    }\n\n    real_type beta() const\n    {\n        return beta_;\n    }\n\n    real_type delta() const\n    {\n        return delta_;\n    }\n\n    real_type eps() const\n    {\n        return eps_;\n    }\n\nprivate:\n    static void check_params(real_type beta__, real_type delta__,\n                             real_type eps__);\n    static size_type get_num_intervals(real_type beta__, real_type delta__,\n                                       real_type eps__);\n    static std::tuple<size_type, real_type>\n    get_num_gauss_jacobi(real_type beta__, real_type eps__);\n    static std::tuple<size_type, real_type>\n    get_num_gauss_legendre(real_type beta__, real_type eps__);\n};\n\ntemplate <typename T>\nvoid pow_kernel<T>::compute(real_type beta__, real_type delta__,\n                            real_type eps__)\n{\n    check_params(beta__, delta__, eps__);\n\n    beta_  = beta__;\n    delta_ = delta__;\n    eps_   = eps__;\n\n    //\n    // Find the sub-optimal sum-of-exponential approximation by discretizing the\n    // integral representation of power function\n    //\n    // ``` math\n    //  r^{-\\beta} = \\frac{1}{\\Gamma(\\beta)}\n    //               \\int_{0}^{\\infty} e^{-rx} x^{\\beta-1} dx \\quad (t > 0).\n    // ```\n    //\n    // Split the integral into $J+1$ sub-intervals as\n    //\n    // ``` math\n    //  r^{-\\beta}\n    //     = \\frac{1}{\\Gamma(\\beta)}\n    //       \\left( \\int_{0}^{2} + \\int_{4}^{2} + \\int_{8}^{4} + \\cdots\n    //             + \\int_{2^{J-1}}^{2^J} + \\int_{2^J}^{\\infty} \\right)\n    //       e^{-ry} x^{\\beta-1} dy.\n    // ```\n    //\n    // The integral over the first interval $[0,2]$ is approximated by the $N_1$\n    // point Gauss-Jacobi rule, while the integral over the inteval\n    // $[2^{j-1},2^j]$ is approximated by the $N_2$ point Gauss-Legendre rule.\n    //\n    // The number of intervals $J$ and quadrature points $N_1,N_2$ are\n    // determined so as to the relative error of the truncation becomes smaller\n    // than $\\epsilon$.\n    //\n    size_type J, N1, N2;\n    T b1, b2;\n    J = get_num_intervals(beta__, delta__ / 2, eps__);\n    std::tie(N1, b1) = get_num_gauss_jacobi(beta__, eps__ / (J + 1));\n    std::tie(N2, b2) = get_num_gauss_legendre(beta__, eps__ / (J + 1));\n    //\n    // Discritization of the integral representation by applying the quadrature\n    // rule to each interval\n    //\n    const size_type N = N1 + (J - 1) * N2;\n    gauss_jacobi_rule<T> gaujac(N1, T(), beta__ - 1);\n    gauss_legendre_rule<T> gauleg(N2);\n\n    assert(gaujac.size() == N1);\n    assert(gauleg.size() == N2);\n\n    vector_type a(N);\n    vector_type w(N);\n\n    auto ait = std::begin(a);\n    auto wit = std::begin(w);\n\n    const auto scale = T(1) / std::tgamma(beta__);\n\n    for (size_type i = 0; i < gaujac.size(); ++i)\n    {\n        *ait = gaujac.x(i) + T(1);\n        *wit = scale * gaujac.w(i);\n        ++ait;\n        ++wit;\n    }\n\n    // The upper/lower bound of interval\n    auto lower = T(1);\n    auto upper = T(2);\n    for (size_type k = 1; k < J; ++k)\n    {\n        lower *= 2; // lower = 2^(k-1)\n        upper *= 2; // upper = 2^k\n        const auto a1 = (upper - lower) / 2;\n        const auto b1 = (upper + lower) / 2;\n        for (size_type i = 0; i < gauleg.size(); ++i)\n        {\n            const auto y = a1 * gauleg.x(i) + b1;\n            *ait         = y;\n            *wit         = a1 * scale * std::pow(y, beta__ - 1) * gauleg.w(i);\n            ++ait;\n            ++wit;\n        }\n    }\n\n    std::swap(exponent_, a);\n    std::swap(weight_, w);\n    return;\n}\n\n//------------------------------------------------------------------------------\n// Private member functions\n//------------------------------------------------------------------------------\ntemplate <typename T>\nvoid pow_kernel<T>::check_params(real_type beta__, real_type delta__,\n                                 real_type eps__)\n{\n    if (!(beta__ > real_type()))\n    {\n        std::ostringstream msg;\n        msg << \"Invalid value for the argument `beta': \"\n               \"beta > 0 expected, but beta = \"\n            << beta__ << \" is given\";\n        throw std::invalid_argument(msg.str());\n    }\n\n    if (!(real_type() < delta__ && delta__ < real_type(1)))\n    {\n        std::ostringstream msg;\n        msg << \"Invalid value for the argument `delta': \"\n               \"0 < delta < 1 expected, but delta = \"\n            << delta__ << \" is given\";\n        throw std::invalid_argument(msg.str());\n    }\n\n    if (!(real_type() < eps__ &&\n          eps__ < real_type(1) / arma::Datum<real_type>::e))\n    {\n        std::ostringstream msg;\n        msg << \"Invalid value for the argument `eps': \"\n               \"0 < eps < 1/e expected, but \"\n            << eps__ << \" is given\";\n        throw std::invalid_argument(msg.str());\n    }\n}\n\ntemplate <typename T>\ntypename pow_kernel<T>::size_type\npow_kernel<T>::get_num_intervals(real_type beta__, real_type delta__,\n                                 real_type eps__)\n{\n    //\n    // Find minimal integer J, such that\n    //\n    //  Gamma(beta, delta * 2^J) / Gamma(beta) <= eps / (J + 1)\n    //\n    size_type J1 = 0;\n    size_type J2 = 20;\n\n    while (true)\n    {\n        auto x  = delta__ * std::pow(T(2), J2);\n        auto fj = gamma_q(beta__, x);\n\n        if (fj * (J2 + 1) <= eps__)\n        {\n            if (J2 - J1 <= 1)\n            {\n                break;\n            }\n\n            J2 = (J1 + J2) / 2;\n        }\n        else\n        {\n            J1 = J2;\n            J2 = J2 + 5;\n        }\n    }\n\n    return J2;\n}\n\ntemplate <typename T>\nstd::tuple<typename pow_kernel<T>::size_type, T>\npow_kernel<T>::get_num_gauss_jacobi(real_type beta__, real_type eps__)\n{\n    //\n    // Find N such that R(N, b) <= eps with\n    //\n    // R(N, x) = 2^(beta + 2) / Gamma(beta + 1) * exp(cosh(x)-1)\n    //         * exp(-2*N*x) / (1 - exp(-2*x)).\n    //\n    // Here, the parameter b is chosen to minimize R(N, x) for each N.\n    //\n\n    // Logarithm of pre-factor of R(N, x),\n    const auto ln_pre = (beta__ + 2) * std::log(T(2)) - std::lgamma(beta__ + 1);\n\n    const size_type max_iter = 100;\n    const auto ln_eps        = std::log(eps__);\n\n    // Initial guesses of parameters\n    size_type n1 = 0;\n    size_type n2 = 4;\n    auto x       = T(4);\n\n    while (true)\n    {\n        // For given N = n2, minimize R(N, x) w.r.t. x\n        for (size_type i = 0; i < max_iter; ++i)\n        {\n            // R'(N, x) without pre-factor\n            auto df = std::sinh(x) + 2 / std::expm1(2 * x) - 2 * n2;\n            // R''(N, x) without pre-factor\n            auto t   = std::expm1(2 * x);\n            auto ddf = std::cosh(x) - 4 * std::exp(2 * x) / (t * t);\n            auto dx  = -df / ddf;\n\n            if (x + dx < T()) // ensure x > 0\n            {\n                x *= T(0.5);\n            }\n            else\n            {\n                x += dx;\n            }\n\n            if (std::abs(dx) <= x * eps__)\n            {\n                break;\n            }\n        }\n\n        // ln(R(N, b))\n        auto ln_resid = (std::expm1(x) + std::expm1(-x)) / 2 // cosh(x) - 1\n                        - 2 * n2 * x                         // ln(exp(-2*n*x))\n                        - std::log(-std::expm1(-2 * x)); // log(1 - exp(-2*x))\n\n        if (ln_pre + ln_resid <= ln_eps) // equiv to R(N, b) <= eps\n        {\n            if (n2 - n1 <= 1)\n            {\n                break;\n            }\n\n            n2 = (n1 + n2) / 2;\n        }\n        else\n        {\n            n1 = n2;\n            n2 = n2 + 2;\n        }\n    }\n\n    return {n2, x};\n}\n\ntemplate <typename T>\nstd::tuple<typename pow_kernel<T>::size_type, T>\npow_kernel<T>::get_num_gauss_legendre(real_type beta__, real_type eps__)\n{\n    //\n    // Find N such that R(N, b) <= eps with\n    //\n    // R(N, x) = 8 / Gamma(beta) * (beta / (e*x))^(beta)\n    //         * rho^(-2*N) / (1 - rho^(-2)) * g(x),\n    //\n    // for 0 < x < 2, where rho(x) = 3 - x + sqrt((2 - x) * (4 - x)), and\n    //\n    //  g(x) = x^(beta-1)        if 0 < beta <= 1,\n    //  g(x) = (6 - x)^(beta-1)  if beta > 1\n    //\n\n    // Logarithm of pre-factor of R(N, x),\n    const auto ln_pre = std::log(T(8)) - std::lgamma(beta__) +\n                        beta__ * std::log(beta__ / constant<T>::e);\n\n    const size_type max_iter = 100;\n    const auto ln_eps        = std::log(eps__);\n\n    // Initial guesses of parameters\n\n    size_type n1 = 0;\n    size_type n2 = 4;\n    auto x       = T(1);\n\n    // function log(g(x))\n    auto fn_g = [=](T z) {\n        return beta__ <= T(1)\n                   ? -std::log(z)\n                   : (beta__ - 1) * std::log(6 - z) - beta__ * std::log(z);\n    };\n\n    // first derivative of log(g(x))\n    auto fn_dg = [=](T z) {\n        return beta__ <= T(1) ? -1 / z : (1 - beta__) / (6 - z) - beta__ / z;\n    };\n\n    // second derivative of log(g(x))\n    auto fn_d2g = [=](T z) {\n        return beta__ <= T(1)\n                   ? 1 / (z * z)\n                   : (1 - beta__) / ((6 - z) * (6 - z)) + beta__ / (z * z);\n    };\n\n    while (true)\n    {\n        // For given N = n2, minimize R(N, x) w.r.t. x\n        for (size_type i = 0; i < max_iter; ++i)\n        {\n            auto p    = std::sqrt((2 - x) * (4 - x));\n            auto pinv = 1 / p;\n            // rho(x) = 3 - x + sqrt((2 - x) * (4 - x))\n            auto rho = 3 - x + p;\n            // d rho(x) / d x = -1 - (3 - x) / sqrt((2 - x) * (4 - x))\n            //                = - rho / p\n            // auto drho = -rho * pinv;\n            // d^2 rho(x) / d x^2\n            // auto d2rho = rho * pinv * pinv * (1 - (3 - x) * pinv);\n\n            //\n            // Let f(x) = log(rho^{-2N}(x) / (1 -rho^{2}(x))) and compute its\n            // first and second derivatives\n            //\n            auto t   = 1 / (rho + 1) * (rho - 1);\n            auto df  = 2 * (n2 - t) * pinv;\n            auto d2f = (df * (3 - x) - 2 * rho * rho * t * t) * pinv * pinv;\n\n            //\n            // Compute first and second derivatives of log(g(x))\n            //\n            auto dg  = fn_dg(x);\n            auto d2g = fn_d2g(x);\n\n            // d log(R(N, x)) / d x without pre-factor\n            auto dr = df + dg;\n            // d^2 log(R(N, x)) / d x^2  without pre-factor\n            auto d2r = d2f + d2g;\n\n            // Update x\n            auto dx = -dr / d2r;\n\n            if (x + dx < T()) // ensure x > 0\n            {\n                x *= T(0.5);\n            }\n            else if (x + dx > T(2)) // ensure x < 2\n            {\n                x += (2 - x) / T(2);\n            }\n            else\n            {\n                x += dx;\n            }\n\n            if (std::abs(dx) <= x * eps__)\n            {\n                break;\n            }\n        }\n\n        // ln(R(N, b))\n        const auto rho = 3 - x + std::sqrt((2 - x) * (4 - x));\n        const auto fx =\n            -T(2 * n2) * std::log(rho) - std::log1p(-T(1) / rho / rho);\n        const auto ln_resid = fx + fn_g(x);\n\n        if (ln_pre + ln_resid <= ln_eps) // equiv to R(N, b) <= eps\n        {\n            if (n2 - n1 <= 1)\n            {\n                break;\n            }\n\n            n2 = (n1 + n2) / 2;\n        }\n        else\n        {\n            n1 = n2;\n            n2 = n2 + 2;\n        }\n    }\n\n    return {n2, std::acosh(3 - x)};\n}\n} // namespace: expsum\n\n#endif /* EXPSUM_KERNEL_FUNCTIONS_POW_KERNEL_HPP */\n", "meta": {"hexsha": "8433eb0d9d84883f61ca33e46a7327b75fbf4f5a", "size": 12898, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/expsum/kernel_functions/pow_kernel.hpp", "max_stars_repo_name": "hide-ikeno/expsum", "max_stars_repo_head_hexsha": "7b1be33b7c342f875d6d5e5c0cd8df9ec62abbda", "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/expsum/kernel_functions/pow_kernel.hpp", "max_issues_repo_name": "hide-ikeno/expsum", "max_issues_repo_head_hexsha": "7b1be33b7c342f875d6d5e5c0cd8df9ec62abbda", "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": "include/expsum/kernel_functions/pow_kernel.hpp", "max_forks_repo_name": "hide-ikeno/expsum", "max_forks_repo_head_hexsha": "7b1be33b7c342f875d6d5e5c0cd8df9ec62abbda", "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.3262711864, "max_line_length": 80, "alphanum_fraction": 0.4655760583, "num_tokens": 3842, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898279984214, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.7066656381746186}}
{"text": "/* \n * genstudenttab.cpp:\n *\n */\n#include <iostream>\n#include <iomanip>\n#include <boost/math/distributions/students_t.hpp>\n\nusing namespace std;\nusing namespace boost::math;\n\nconst int samplesize_max = 100;\n\nint main()\n{\n    double alpha[] = { 0.1, 0.05, 0.01 }; /* 90%, 95%, 99% */\n\n    cout << \"int tstud_tab_size = \" << samplesize_max << \";\\n\";\n\n    for(int i = 0; i < sizeof(alpha) / sizeof(alpha[0]); ++i) {\n        \n        students_t d(99999);\n        double t = quantile(complement(d, alpha[i] / 2));\n        cout << \"double tstud_p\" << fixed << setprecision(0) << 100 * (1 - alpha[i])\n             << \"_ninf = \" << fixed << setprecision(3) << t << \";\\n\";\n             \n        cout << \"double tstud_tab_p\" << setprecision(0) << 100 * (1 - alpha[i])\n             << \"[] = {\\n\";\n        cout << \"    \";\n        for (int n = 2; n <= samplesize_max; ++n) {\n            students_t dist(n - 1);\n            double t = quantile(complement(dist, alpha[i] / 2));\n            cout << fixed << setprecision(3) << left << t << \", \";\n            if (n % 8 == 0) {\n                cout << endl << \"    \";\n            }\n        }\n        cout << \"\\n};\\n\";\n    }\n    return 0;\n}\n", "meta": {"hexsha": "e8558f2e6fe2a56d6c284c22774a75855faa05a7", "size": 1172, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "maint/stats_tstud/genstudenttab.cpp", "max_stars_repo_name": "mkurnosov/mpiperf", "max_stars_repo_head_hexsha": "5a92abcfdc92434f15fae76409c4c919ef00deb3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2015-06-03T09:38:16.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-25T14:57:46.000Z", "max_issues_repo_path": "maint/stats_tstud/genstudenttab.cpp", "max_issues_repo_name": "mkurnosov/mpiperf", "max_issues_repo_head_hexsha": "5a92abcfdc92434f15fae76409c4c919ef00deb3", "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": "maint/stats_tstud/genstudenttab.cpp", "max_forks_repo_name": "mkurnosov/mpiperf", "max_forks_repo_head_hexsha": "5a92abcfdc92434f15fae76409c4c919ef00deb3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-25T14:58:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-25T14:58:04.000Z", "avg_line_length": 27.9047619048, "max_line_length": 84, "alphanum_fraction": 0.4692832765, "num_tokens": 346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898279984214, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.7066656381746186}}
{"text": "/*\n   Copyright (C) 2015-2021 by Synge Todo <wistaria@phys.s.u-tokyo.ac.jp>\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n     http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*/\n\n// Free energy, energy, and specific heat of square lattice Ising model\n\n#include <iomanip>\n#include <iostream>\n#include <boost/math/differentiation/autodiff.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include \"ising/mp_wrapper.hpp\"\n#include \"ising/tc/square.hpp\"\n#include \"options.hpp\"\n#include \"square.hpp\"\n\ntemplate<typename T>\nvoid calc0(const options2& opt) {\n  using namespace ising::free_energy;\n  typedef T real_t;\n  real_t Jx = convert<real_t>(opt.Jx);\n  real_t Jy = convert<real_t>(opt.Jy);\n  real_t Tmin, Tmax, dT;\n  if (opt.Tmin == \"tc\" || opt.Tmin == \"Tc\") {\n    Tmin = Tmax = dT = ising::tc::square(Jx, Jy);\n  } else {\n    Tmin = convert<real_t>(opt.Tmin);\n    Tmax = convert<real_t>(opt.Tmax);\n    dT = convert<real_t>(opt.dT);\n  }\n  if (Tmin < 0 || Tmax < 0) throw(std::invalid_argument(\"Temperature should be positive\"));\n  if (Tmin > Tmax) throw(std::invalid_argument(\"Tmax should be larger than Tmin\"));\n  if (dT <= 0) throw(std::invalid_argument(\"dT should be positive\"));\n  std::cout << std::scientific << std::setprecision(std::numeric_limits<real_t>::digits10)\n            << \"# lattice: square\\n\"\n            << \"# precision: \" << std::numeric_limits<real_t>::digits10 << std::endl\n            << \"# Lx Ly Jx Jy T 1/T F/N E/N C/N\\n\";\n  for (auto t = Tmin; t < Tmax + 1e-4 * dT; t += dT) {\n    real_t beta = 1 / t;\n    auto f = square::infinite(Jx, Jy, beta);\n    std::cout << \"inf inf \" << Jx << ' ' << Jy << ' ' << t << ' ' << beta << ' '\n              << f << \" N/A N/A\" << std::endl;\n  }\n}\n\ntemplate<typename T>\nvoid calc(const options2& opt) {\n  using namespace ising::free_energy;\n  typedef T real_t;\n  real_t Jx = convert<real_t>(opt.Jx);\n  real_t Jy = convert<real_t>(opt.Jy);\n  real_t Tmin, Tmax, dT;\n  if (opt.Tmin == \"tc\" || opt.Tmin == \"Tc\") {\n    Tmin = Tmax = dT = ising::tc::square(Jx, Jy);\n  } else {\n    Tmin = convert<real_t>(opt.Tmin);\n    Tmax = convert<real_t>(opt.Tmax);\n    dT = convert<real_t>(opt.dT);\n  }\n  if (Tmin < 0 || Tmax < 0) throw(std::invalid_argument(\"Temperature should be positive\"));\n  if (Tmin > Tmax) throw(std::invalid_argument(\"Tmax should be larger than Tmin\"));\n  if (dT <= 0) throw(std::invalid_argument(\"dT should be positive\"));\n  std::cout << std::scientific << std::setprecision(std::numeric_limits<real_t>::digits10)\n            << \"# lattice: square\\n\"\n            << \"# precision: \" << std::numeric_limits<real_t>::digits10 << std::endl\n            << \"# Lx Ly Jx Jy T 1/T F/N E/N C/N\\n\";\n  for (auto t = Tmin; t < Tmax + 1e-4 * dT; t += dT) {\n    auto beta = boost::math::differentiation::make_fvar<real_t, 2>(1 / t);\n    auto f = square::infinite(Jx, Jy, beta);\n    std::cout << \"inf inf \" << Jx << ' ' << Jy << ' ' << t << ' ' << (1 / t) << ' '\n              << free_energy(f, beta) << ' ' << energy(f, beta) << ' '\n              << specific_heat(f, beta) << std::endl;\n  }\n}\n\nint main(int argc, char **argv) {\n  using namespace boost::multiprecision;\n  options2 opt(argc, argv);\n  if (!opt.valid) return 127;\n  if (opt.prec <= std::numeric_limits<float>::digits10) {\n    calc<float>(opt);\n  } else if (opt.prec <= std::numeric_limits<double>::digits10) {\n    calc<double>(opt);\n  } else if (opt.prec <= std::numeric_limits<mp_wrapper<cpp_dec_float_50>>::digits10) {\n    calc0<mp_wrapper<cpp_dec_float_50>>(opt);\n    // calc<mp_wrapper<cpp_dec_float_50>>(opt);\n  } else if (opt.prec <= std::numeric_limits<mp_wrapper<cpp_dec_float_100>>::digits10) {\n    calc0<mp_wrapper<cpp_dec_float_100>>(opt);\n    // calc<mp_wrapper<cpp_dec_float_100>>(opt);\n  } else {\n    std::cerr << \"Error: Required precision is too high\\n\"; return 127;\n  }\n}\n", "meta": {"hexsha": "e1ecdd6400af8cd0ba973ef4fee3c93051acbaf9", "size": 4256, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ising/free_energy/square.cpp", "max_stars_repo_name": "todo-group/exact", "max_stars_repo_head_hexsha": "ee76421fab9b2b1eaf77d6b01830a18e66f7180a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-27T14:45:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-27T14:45:49.000Z", "max_issues_repo_path": "ising/free_energy/square.cpp", "max_issues_repo_name": "todo-group/exact", "max_issues_repo_head_hexsha": "ee76421fab9b2b1eaf77d6b01830a18e66f7180a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-11-30T14:48:41.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-30T14:48:41.000Z", "max_forks_repo_path": "ising/free_energy/square.cpp", "max_forks_repo_name": "todo-group/exact", "max_forks_repo_head_hexsha": "ee76421fab9b2b1eaf77d6b01830a18e66f7180a", "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": 40.5333333333, "max_line_length": 91, "alphanum_fraction": 0.6304041353, "num_tokens": 1273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600902, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.7066656269279173}}
{"text": "// Example: exercise2-advanced\n//\n// Goal: implement a simple adaptive strategy based on exact solution\n//\n// Reference: see https://fusionforge.zih.tu-dresden.de/plugins/mediawiki/wiki/amdis/index.php/AMDiS::Expressions\n//            for a detailed description of possible expression terms.\n//\n// Compile-and-run: \n// > cd build\n// > make exercise2b\n// > cd ..\n// > build/exercise2b init/exercise2.dat.2d\n//\n\n#include \"AMDiS.h\"\n\n#include <array>\n#include <boost/numeric/mtl/mtl.hpp>\n\nusing namespace AMDiS;\n\n\nvoid convergence_factor(std::vector<std::array<double,2>> const& error)\n{\n  mtl::dense_vector<double> rhs_res(error.size());\n  mtl::dense2D<double> A_res(error.size(), 2);\n  for (size_t i = 0; i < error.size(); ++i) {\n    rhs_res(i) = std::log(error[i][1]);\n    A_res(i, 0) = 1;\n    A_res(i, 1) = std::log(error[i][0]);\n  }\n  \n  mtl::dense_vector<double> convergence(2);\n  \n  mtl::dense2D<double> Q(num_rows(A_res), num_rows(A_res)), R(num_rows(A_res), num_cols(A_res));\n  boost::tie(Q, R)= mtl::matrix::qr(A_res);\n  \n  mtl::dense_vector<double> b(trans(Q)*rhs_res);\n  mtl::irange rows(0,num_cols(A_res));\n  \n  mtl::dense2D<double> R_ = R[rows][rows];\n  convergence = mtl::matrix::upper_trisolve(R_, b[rows]);\n  \n  std::cout << \"\\n|u - u_h| = C * h^k\\n   C = \" << std::exp(convergence(0)) << \"\\n   k = \" << convergence(1) << \"\\n\\n\";\n}\n\ninline double calcMeshSizes(Mesh* mesh) \n{\n  TraverseStack stack;\n  ElInfo *elInfo = stack.traverseFirst(mesh, -1, Mesh::CALL_LEAF_EL | Mesh::FILL_COORDS);\n  double maxH = 0.0;\n  while (elInfo) {\n    auto coords = elInfo->getCoords();\n    for (int i = 0; i < coords.getSize(); i++)\n      for (int j = i+1; j < coords.getSize(); j++)\n\t  maxH = std::max(maxH, norm(coords[i] - coords[j]));\n    elInfo = stack.traverseNext(elInfo);\n  }\n  return maxH;\n}\n\nstruct G : AbstractFunction<double, WorldVector<double> >\n{\n  double operator()(WorldVector<double> const& x) const \n  {\n    return std::exp(-10.0*(x*x));\n  }\n};\n\n// solve: -laplace(u) = f(x) in Omega,    u = g on Gamma\nint main(int argc, char* argv[])\n{ FUNCNAME(\"Main\");\n\n  AMDiS::init(argc, argv);\n\n  // ===== create and init the scalar problem ===== \n  ProblemStat prob(\"poisson\");\n  prob.initialize(INIT_ALL);\n\n  // ===== define operators =====\n  Operator opLaplace(prob.getFeSpace(), prob.getFeSpace());\n  addSOT(opLaplace, 1.0);\n  \n  Operator opF(prob.getFeSpace());\n  auto f = -(400.0*(X()*X()) - 40.0)*exp(-10.0*(X()*X()));\n  addZOT(opF, f); // f(x)\n  \n  // ===== add operators to problem =====\n  prob.addMatrixOperator(opLaplace, 0, 0);   // -laplace(u)\n  prob.addVectorOperator(opF, 0);            // f(x)\n\n  // ===== add boundary conditions =====\n  BoundaryType nr = 1;\n  prob.addDirichletBC(nr, 0, 0, new G); // g(x)\n\n  // ===== create info-object, that holds parameters ===\n  AdaptInfo adaptInfo(\"adapt\");\n  \n  DOFVector<double>& U = *prob.getSolution(0);\n  DOFVector<double> ErrVec(U), UExact(U);\n  \n  auto u_exact = exp(-10.0*(X()*X()));\n  \n  std::vector<std::array<double, 2>> error_vec_L2;\n  std::vector<std::array<double, 2>> error_vec_H1;\n  std::vector<std::array<double, 2>> error_vec_P;\n  \n  double error = 1.e10;  \n  for (int i = 0; i < adaptInfo.getMaxSpaceIteration(); ++i)\n  {\n    // ===== assemble and solve linear system =====\n    prob.assemble(&adaptInfo);\n    prob.solve(&adaptInfo);\n  \n    ErrVec << absolute(valueOf(U) - u_exact);\n    io::writeFile(ErrVec, \"error_\" + std::to_string(i) + \".vtu\");\n    \n    UExact << u_exact;\n    double errorL2 = std::sqrt( integrate( pow<2>(valueOf(U) - valueOf(UExact)) ) );\n    double errorH1 = std::sqrt( integrate( pow<2>(valueOf(U) - valueOf(UExact)) + unary_dot(gradientOf(U) - gradientOf(UExact)) ) );\n    \n    double h_max = calcMeshSizes(prob.getMesh());\n    \n    WorldVector<double> p; p[0] = 0.5; p[1] = 0.5;    \n    double errorP = std::abs(U(p) - exp(-10.0*(p*p)));\n    MSG(\"h(%d) = %f\\n\", i, h_max);\n    MSG(\"errorL2(%d) = %e\\n\", i, errorL2);\n    MSG(\"errorH1(%d) = %e\\n\", i, errorH1);\n    MSG(\"errorP(%d) = %e\\n\", i, errorP);\n        \n    error_vec_L2.push_back({h_max, errorL2});\n    error_vec_H1.push_back({h_max, errorH1});\n    error_vec_P.push_back({h_max, errorP});\n    \n    error = errorL2;\n    if (error < adaptInfo.getSpaceTolerance(0))\n      break;\n    \n    // refine mesh\n    RefinementManager* refManager = prob.getRefinementManager();\n    Flag f = refManager->globalRefine(prob.getMesh(), 1);\n  }\n  \n  std::cout << \"L2-norm:\\n\";\n  convergence_factor(error_vec_L2);\n  \n  std::cout << \"H1-norm:\\n\";\n  convergence_factor(error_vec_H1);\n  \n  std::cout << \"pointwise-norm:\\n\";\n  convergence_factor(error_vec_P);\n  \n  AMDiS::finalize();\n}\n", "meta": {"hexsha": "c12ddc156206d1356fbb67171940d6f3167029f2", "size": 4623, "ext": "cc", "lang": "C++", "max_stars_repo_path": "solution/src/exercise2b.cc", "max_stars_repo_name": "spraetor/amdis_workshop", "max_stars_repo_head_hexsha": "9e9d3d91cff63155d18eec2450725e176d939ebd", "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": "solution/src/exercise2b.cc", "max_issues_repo_name": "spraetor/amdis_workshop", "max_issues_repo_head_hexsha": "9e9d3d91cff63155d18eec2450725e176d939ebd", "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": "solution/src/exercise2b.cc", "max_forks_repo_name": "spraetor/amdis_workshop", "max_forks_repo_head_hexsha": "9e9d3d91cff63155d18eec2450725e176d939ebd", "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.8258064516, "max_line_length": 132, "alphanum_fraction": 0.6162664936, "num_tokens": 1476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898178450965, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.7066656209882762}}
{"text": "/*\nCopyright 2009-2021 Nicolas Colombe\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*/\n\n#include <math/principalaxis.hpp>\n\n#include <armadillo>\n\nnamespace eXl\n{\n  \n  bool ComputePrincipalAxis::operator()(Polygoni const& iPoly)\n  {\n    return Compute(iPoly);\n  }\n\n  bool ComputePrincipalAxis::operator()(Polygonf const& iPoly)\n  {\n    return Compute(iPoly);\n  }\n\n  bool ComputePrincipalAxis::operator()(Polygond const& iPoly)\n  {\n    return Compute(iPoly);\n  }\n\n  bool ComputePrincipalAxis::operator()(Vector<Vector2f> const& iPoints)\n  {\n    return Compute(iPoints.data(), iPoints.size());\n  }\n\n  bool ComputePrincipalAxis::operator()(Vector<Vector2d> const& iPoints)\n  {\n    return Compute(iPoints.data(), iPoints.size());\n  }\n\n  template <typename Real>\n  bool ComputePrincipalAxis::Compute(Polygon<Real> const& iPoly)\n  {\n    if (iPoly.Border().size() == 0)\n    {\n      return false;\n    }\n    uint32_t numPt = iPoly.Border().size();\n    Vector2<Real> const* points = iPoly.Border().data();\n    if (numPt > 1 && points[0] == points[numPt - 1])\n    {\n      --numPt;\n    }\n    \n    return Compute(points, numPt);\n  }\n\n  template <typename Real>\n  bool ComputePrincipalAxis::Compute(Vector2<Real> const* iPoints, uint32_t iNumPt)\n  {\n    if (iNumPt == 0)\n    {\n      return false;\n    }\n    arma::mat covarianceMatrix(2, 2, arma::fill::zeros);\n    m_Center = Vector2d::ZERO;\n\n    for (unsigned int i = 0; i < iNumPt; ++i)\n    {\n      Vector2<Real> const& curValue = iPoints[i];\n      m_Center.X() += curValue.X();\n      m_Center.Y() += curValue.Y();\n    }\n\n    m_Center.X() /= iNumPt;\n    m_Center.Y() /= iNumPt;\n\n    for (unsigned int i = 0; i < iNumPt; ++i)\n    {\n      Vector2<Real> const& curValue = iPoints[i];\n      double centeredX = curValue.X() - m_Center.X();\n      double centeredY = curValue.Y() - m_Center.Y();\n      covarianceMatrix.at(0,0) += centeredX * centeredX;\n      covarianceMatrix.at(1,1) += centeredY * centeredY;\n      covarianceMatrix.at(0,1) += centeredX * centeredY;\n    }\n\n    covarianceMatrix.at(0,0) /= iNumPt;\n    covarianceMatrix.at(1,1) /= iNumPt;\n    covarianceMatrix.at(0,1) /= iNumPt;\n    covarianceMatrix.at(1,0) = covarianceMatrix.at(0,1);\n\n    arma::colvec eigval;\n    arma::mat eigvect;\n      \n    bool res = arma::eig_sym(eigval, eigvect, covarianceMatrix);\n\n    eXl_ASSERT_REPAIR_RET(res, false);\n\n    unsigned int maxIdx = 0;\n    double maxVal = eigval.at(0);\n    if (eigval.at(1) > maxVal)\n    {\n      maxIdx = 1;\n      maxVal = eigval.at(1);\n    }\n\n    m_PrimaryAxis.X() = eigvect.at(maxIdx, 0);\n    m_PrimaryAxis.Y() = eigvect.at(maxIdx, 1);\n\n    return true;\n  }\n}", "meta": {"hexsha": "b70f3e6bc30320c2300f3709282fd3abe4dfa76d", "size": 3591, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/math/principalaxis.cpp", "max_stars_repo_name": "eXl-Nic/eXl", "max_stars_repo_head_hexsha": "a5a0f77f47db3179365c107a184bb38b80280279", "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/principalaxis.cpp", "max_issues_repo_name": "eXl-Nic/eXl", "max_issues_repo_head_hexsha": "a5a0f77f47db3179365c107a184bb38b80280279", "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/principalaxis.cpp", "max_forks_repo_name": "eXl-Nic/eXl", "max_forks_repo_head_hexsha": "a5a0f77f47db3179365c107a184bb38b80280279", "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.2260869565, "max_line_length": 460, "alphanum_fraction": 0.6739069897, "num_tokens": 960, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898102301019, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.7066656196820451}}
{"text": "/*\n   ____    _ __           ____               __    ____\n  / __/___(_) /  ___ ____/ __ \\__ _____ ___ / /_  /  _/__  ____\n _\\ \\/ __/ / _ \\/ -_) __/ /_/ / // / -_|_-</ __/ _/ // _ \\/ __/\n/___/\\__/_/_.__/\\__/_/  \\___\\_\\_,_/\\__/___/\\__/ /___/_//_/\\__(_)\n\nCopyright 2012 SciberQuest Inc.\n*/\n#ifndef Numerics_hxx\n#define Numerics_hxx\n\n#include<iostream>\n\n#include <cstdlib>\n#include <cmath>\n#include <complex>\n\n#include \"SQPOSIXOnWindowsWarningSupression.h\"\n#include \"SQPosixOnWindows.h\"\n#include \"SQEigenWarningSupression.h\"\n#include <Eigen/Eigenvalues>\nusing namespace Eigen;\n\n#include \"Tuple.hxx\"\n#include \"FlatIndex.h\"\n#include \"SQMacros.h\"\n\n//*****************************************************************************\ntemplate<typename T>\nbool IsReal(std::complex<T> &c, T eps=T(1.0e-6))\n{\n  return (fabs(imag(c)) < eps);\n}\n\n//*****************************************************************************\ntemplate<typename T>\nbool IsComplex(std::complex<T> &c, T eps=T(1.0e-6))\n{\n  return (fabs(imag(c)) >= eps);\n}\n\n//*****************************************************************************\ntemplate<typename T>\nint fequal(T a, T b, T tol)\n{\n  T pda=fabs(a);\n  T pdb=fabs(b);\n  pda=pda<tol?tol:pda;\n  pdb=pdb<tol?tol:pdb;\n  T smaller=pda<pdb?pda:pdb;\n  T norm=fabs(b-a)/smaller;\n  if (norm<=tol)\n    {\n    return 1;\n    }\n  return 0;\n}\n\n//*****************************************************************************\ntemplate <typename T>\nT LaplacianOfGaussian(T X[3], T a, T B[3], T c)\n{\n  // X - evaluate at this location\n  // a - peak height\n  // B - center\n  // c - width\n\n  T x,y,z;\n  x=X[0]-B[0];\n  y=X[1]-B[1];\n  z=X[2]-B[2];\n\n  T r2 = x*x+y*y+z*z;\n  T c2 = c*c;\n\n  return -a/c2 * (((T)1)-r2/c2) * ((T)exp(-r2/(((T)2)*c2)));\n}\n\n\n//*****************************************************************************\ntemplate <typename T>\nT Gaussian(T X[3], T a, T B[3], T c)\n{\n  // X - evaluate at this location\n  // a - peak height\n  // B - center\n  // c - width\n\n  T x,y,z;\n  x=X[0]-B[0];\n  y=X[1]-B[1];\n  z=X[2]-B[2];\n\n  T r2 = x*x+y*y+z*z;\n\n  return a*((T)exp(-r2/(((T)2)*c*c)));\n}\n\n//*****************************************************************************\ninline\nvoid indexToIJ(int idx, int nx, int &i, int &j)\n{\n  // convert a flat array index into a i,j,k three space tuple.\n  j=idx/nx;\n  i=idx-j*nx;\n}\n\n//*****************************************************************************\ninline\nvoid indexToIJK(int idx, int nx, int nxy, int &i, int &j, int &k)\n{\n  // convert a flat array index into a i,j,k three tuple.\n  k=idx/nxy;\n  j=(idx-k*nxy)/nx;\n  i=idx-k*nxy-j*nx;\n}\n\n//*****************************************************************************\ntemplate <typename T>\nvoid linspace(T lo, T hi, int n, T *data)\n{\n  // generate n equally spaced points on the segment [lo hi] on real line\n  // R^1.\n\n  if (n==1)\n    {\n    data[0]=(hi+lo)/((T)2);\n    return;\n    }\n\n  T delta=(hi-lo)/((T)(n-1));\n\n  for (int i=0; i<n; ++i)\n    {\n    data[i]=lo+((T)i)*delta;\n    }\n}\n\n//*****************************************************************************\ntemplate <typename Ti, typename To>\nvoid linspace(Ti X0[3], Ti X1[3], int n, To *X)\n{\n  // generate n equally spaced points on the line segment [X0 X1] in R^3.\n\n  if (n==1)\n    {\n    X[0]=(To)((X1[0]+X0[0])/Ti(2));\n    X[1]=(To)((X1[1]+X0[1])/Ti(2));\n    X[2]=(To)((X1[2]+X0[2])/Ti(2));\n    return;\n    }\n\n  Ti dX[3]={\n    (X1[0]-X0[0])/((Ti)(n-1)),\n    (X1[1]-X0[1])/((Ti)(n-1)),\n    (X1[2]-X0[2])/((Ti)(n-1))};\n\n  for (int i=0; i<n; ++i)\n    {\n    X[0]=(To)(X0[0]+((Ti)i)*dX[0]);\n    X[1]=(To)(X0[1]+((Ti)i)*dX[1]);\n    X[2]=(To)(X0[2]+((Ti)i)*dX[2]);\n    X+=3;\n    }\n}\n\n//*****************************************************************************\ntemplate <typename T>\nvoid logspace(T lo, T hi, int n, T p, T *data)\n{\n  // generate n log spaced points inbetween lo and hi on\n  // the real line (R^1). The variation in the spacing is\n  // symetric about the mid point of the [lo hi] range.\n\n  int mid=n/2;\n  int nlo=mid;\n  int nhi=n-mid;\n  T s=hi-lo;\n\n  T rhi=(T)pow(((T)10),p);\n\n  linspace<T>(((T)1),T(0.99)*rhi,nlo,data);\n  linspace<T>(((T)1),rhi,nhi,data+nlo);\n\n  int i=0;\n  for (; i<nlo; ++i)\n    {\n    data[i]=lo+s*(T(0.5)*((T)log10(data[i]))/p);\n    }\n  for (; i<n; ++i)\n    {\n    data[i]=lo+s*(((T)1)-((T)log10(data[i]))/(((T)2)*p));\n    }\n}\n\n//*****************************************************************************\ntemplate <typename T>\nT Interpolate(double t, T v0, T v1)\n{\n  T w=(((T)1)-T(t))*v0 + T(t)*v1;\n  return w;\n}\n\n//*****************************************************************************\ntemplate <typename T>\nT Interpolate(double t0, double t1, T v0, T v1, T v2, T v3)\n{\n  T w0=Interpolate(t0,v0,v1);\n  T w1=Interpolate(t0,v2,v3);\n  T w2=Interpolate(t1,w0,w1);\n  return w2;\n}\n\n//*****************************************************************************\ntemplate <typename T>\nT Interpolate(\n      double t0,\n      double t1,\n      double t2,\n      T v0,\n      T v1,\n      T v2,\n      T v3,\n      T v4,\n      T v5,\n      T v6,\n      T v7)\n{\n  T w0=Interpolate(t0,t1,v0,v1,v2,v3);\n  T w1=Interpolate(t0,t1,v4,v5,v6,v7);\n  T w2=Interpolate(t2,w0,w1);\n  return w2;\n}\n\n//=============================================================================\ntemplate <typename T>\nclass CentralStencil\n{\npublic:\n  CentralStencil(int ni, int nj, int nk, int nComps, T *v)\n       :\n      Ni(ni),Nj(nj),Nk(nk),NiNj(ni*nj),\n      NComps(nComps),\n      Vilo(0),Vihi(0),Vjlo(0),Vjhi(0),Vklo(0),Vkhi(0),\n      V(v)\n       {}\n\n  void SetCenter(int i, int j, int k)\n    {\n    this->Vilo=this->NComps*(k*this->NiNj+j*this->Ni+(i-1));\n    this->Vihi=this->NComps*(k*this->NiNj+j*this->Ni+(i+1));\n    this->Vjlo=this->NComps*(k*this->NiNj+(j-1)*this->Ni+i);\n    this->Vjhi=this->NComps*(k*this->NiNj+(j+1)*this->Ni+i);\n    this->Vklo=this->NComps*((k-1)*this->NiNj+j*this->Ni+i);\n    this->Vkhi=this->NComps*((k+1)*this->NiNj+j*this->Ni+i);\n    }\n\n  // center\n  // T *Operator()()\n  //   {\n  //   return this->V+this->Vilo+this->NComps;\n  //   }\n\n  // i direction\n  T ilo(int comp)\n    {\n    return this->V[this->Vilo+comp];\n    }\n  T ihi(int comp)\n    {\n    return this->V[this->Vihi+comp];\n    }\n  // j direction\n  T jlo(int comp)\n    {\n    return this->V[this->Vjlo+comp];\n    }\n  T jhi(int comp)\n    {\n    return this->V[this->Vjhi+comp];\n    }\n  // k-direction\n  T klo(int comp)\n    {\n    return this->V[this->Vklo+comp];\n    }\n  T khi(int comp)\n    {\n    return this->V[this->Vkhi+comp];\n    }\n\n\nprivate:\n  CentralStencil();\nprivate:\n  int Ni,Nj,Nk,NiNj;\n  int NComps;\n  int Vilo,Vihi,Vjlo,Vjhi,Vklo,Vkhi;\n  T *V;\n};\n\n//*****************************************************************************\ntemplate<typename T>\nvoid slowSort(T *a, int l, int r)\n{\n  for (int i=l; i<r; ++i)\n    {\n    for (int j=i; j>l; --j)\n      {\n      if (a[j]>a[j-1])\n        {\n        T tmp=a[j-1];\n        a[j-1]=a[j];\n        a[j]=tmp;\n        }\n      }\n    }\n}\n\n//*****************************************************************************\ntemplate<typename T, int nComp>\nbool IsNan(T *V)\n{\n  bool nan=false;\n  for (int i=0; i<nComp; ++i)\n    {\n    if (isnan(V[i]))\n      {\n      nan=true;\n      break;\n      }\n    }\n  return nan;\n}\n\n//*****************************************************************************\ntemplate<typename T, int nComp>\nvoid Init(T *V, T *V_0, int n)\n{\n  for (int i=0; i<n; ++i, V+=nComp)\n    {\n    for (int j=0; j<nComp; ++j)\n      {\n      V[j]=V_0[j];\n      }\n    }\n}\n\n//*****************************************************************************\ntemplate<typename T, int nComp>\nbool Find(int *I, T *V, T *val)\n{\n  bool has=false;\n\n  int ni=I[0];\n  int nj=I[1];\n  int ninj=ni*nj;\n\n  for (int k=0; k<I[2]; ++k)\n    {\n    for (int j=0; j<I[1]; ++j)\n      {\n      for (int i=0; i<I[0]; ++i)\n        {\n        int q=k*ninj+j*ni+i;\n        int hit=0;\n\n        for (int p=0; p<nComp; ++p)\n          {\n          if (V[q+p]==val[p])\n            {\n            ++hit;\n            }\n          }\n\n         // match only if all comps match.\n         if (hit==nComp)\n          {\n          has=true;\n          std::cerr\n            << __LINE__ << \" FOUND val=\" << val\n            << \" at \" << Tuple<int>(i,j,k) << std::endl;\n          }\n        }\n      }\n    }\n  return has;\n}\n\n//*****************************************************************************\ntemplate<typename T, int nComp>\nbool HasNans(int *I, T *V, T *val)\n{\n  (void)val;\n\n  bool has=false;\n\n  int ni=I[0];\n  int nj=I[1];\n  int ninj=ni*nj;\n\n  for (int k=0; k<I[2]; ++k)\n    {\n    for (int j=0; j<I[1]; ++j)\n      {\n      for (int i=0; i<I[0]; ++i)\n        {\n        int q=k*ninj+j*ni+i;\n        for (int p=0; p<nComp; ++p)\n          {\n          if (isnan(V[q+p]))\n            {\n            has=true;\n            std::cerr\n              << __LINE__ << \" ERROR NAN. \"\n              << \"I+\" << q+p <<\"=\" << Tuple<int>(i,j,k)\n              << std::endl;\n            }\n          }\n        }\n      }\n    }\n  return has;\n}\n\n// I  -> number of points\n// V  -> vector field\n// mV -> Magnitude\n//*****************************************************************************\ntemplate <typename T>\nvoid Magnitude(int *I, T *  V, T *  mV)\n{\n  for (int k=0; k<I[2]; ++k)\n    {\n    for (int j=0; j<I[1]; ++j)\n      {\n      for (int i=0; i<I[0]; ++i)\n        {\n        const int p  = k*I[0]*I[1]+j*I[0]+i;\n        const int vi = 3*p;\n        const int vj = vi + 1;\n        const int vk = vi + 2;\n        mV[p]=sqrt(V[vi]*V[vi]+V[vj]*V[vj]+V[vk]*V[vk]);\n        }\n      }\n    }\n}\n\n// Magnitude of a vector\n//*****************************************************************************\ntemplate <typename T>\nvoid Magnitude(\n      size_t n,\n      T * __restrict__ V,\n      T * __restrict__ mV)\n{\n  for (size_t q=0; q<n; ++q)\n    {\n    size_t qq=3*q;\n    mV[q] = ((T)sqrt(V[qq]*V[qq]+V[qq+1]+V[qq+1]+V[qq+2]*V[qq+2]));\n    }\n}\n\n// Magnitude of a vector\n//*****************************************************************************\ntemplate <typename T>\nvoid Magnitude(\n      size_t nt, // number of tuples\n      size_t nc, // number of components\n      T * __restrict__ V,\n      T * __restrict__ mV)\n{\n  for (size_t q=0; q<nt; ++q)\n    {\n    size_t qq=nc*q;\n    T vv=((T)0);\n    for (size_t c=0; c<nc; ++c)\n      {\n      size_t r=qq+c;\n      vv+=V[r]*V[r];\n      }\n    mV[q] = ((T)sqrt(vv));\n    }\n}\n\n// Difference of two arrays D=A-B\n//*****************************************************************************\ntemplate <typename T>\nvoid Difference(\n      size_t nt, // number of tuples\n      size_t nc, // number of components\n      T * __restrict__ A,\n      T * __restrict__ B,\n      T * __restrict__ D)\n{\n  for (size_t q=0; q<nt; ++q)\n    {\n    size_t qq=nc*q;\n    for (size_t c=0; c<nc; ++c)\n      {\n      size_t r=qq+c;\n      D[r]=A[r]-B[r];\n      }\n    }\n}\n\n//*****************************************************************************\ntemplate<typename T>\nvoid Split(\n      int c,\n      size_t n,\n      int nComp,\n      T * __restrict__  V,\n      T * __restrict__  Vc)\n{\n  // take vector array and split a component into a scalar array.\n  for (size_t i=0; i<n; ++i)\n    {\n    size_t ii=nComp*i;\n    Vc[i]=V[ii+c];\n    }\n}\n\n//*****************************************************************************\ntemplate<typename T>\nvoid Split(\n      size_t n,\n      T * __restrict__  V,\n      T * __restrict__  Vx,\n      T * __restrict__  Vy,\n      T * __restrict__  Vz)\n{\n  // take vector array and split into 3 scalar arrays.\n  for (size_t i=0; i<n; ++i)\n    {\n    size_t ii=3*i;\n    Vx[i]=V[ii  ];\n    Vy[i]=V[ii+1];\n    Vz[i]=V[ii+2];\n    }\n}\n\n//*****************************************************************************\ntemplate<typename T>\nvoid Split(\n      int n,\n      T * __restrict__  V,\n      T * __restrict__  Vxx,\n      T * __restrict__  Vxy,\n      T * __restrict__  Vxz,\n      T * __restrict__  Vyx,\n      T * __restrict__  Vyy,\n      T * __restrict__  Vyz,\n      T * __restrict__  Vzx,\n      T * __restrict__  Vzy,\n      T * __restrict__  Vzz)\n{\n  // take scalar components and interleve into a vector array.\n  for (int i=0; i<n; ++i)\n    {\n    int ii=9*i;\n    Vxx[i]=V[ii  ];\n    Vxy[i]=V[ii+1];\n    Vxz[i]=V[ii+2];\n    Vyx[i]=V[ii+3];\n    Vyy[i]=V[ii+4];\n    Vyz[i]=V[ii+5];\n    Vzx[i]=V[ii+6];\n    Vzy[i]=V[ii+7];\n    Vzz[i]=V[ii+8];\n    }\n}\n\n//*****************************************************************************\ntemplate<typename T>\nvoid Interleave(\n      size_t n,\n      T * __restrict__  Vx,\n      T * __restrict__  Vy,\n      T * __restrict__  Vz,\n      T * __restrict__  V)\n{\n  // take scalar components and interleve into a vector array.\n  for (size_t i=0; i<n; ++i)\n    {\n    size_t ii=3*i;\n    V[ii  ]=Vx[i];\n    V[ii+1]=Vy[i];\n    V[ii+2]=Vz[i];\n    }\n}\n\n//*****************************************************************************\ntemplate<typename T>\nvoid Interleave(\n      int n,\n      T * __restrict__  Vxx,\n      T * __restrict__  Vxy,\n      T * __restrict__  Vxz,\n      T * __restrict__  Vyx,\n      T * __restrict__  Vyy,\n      T * __restrict__  Vyz,\n      T * __restrict__  Vzx,\n      T * __restrict__  Vzy,\n      T * __restrict__  Vzz,\n      T * __restrict__  V)\n{\n  // take scalar components and interleve into a vector array.\n  for (int i=0; i<n; ++i)\n    {\n    int ii=9*i;\n    V[ii  ]=Vxx[i];\n    V[ii+1]=Vxy[i];\n    V[ii+2]=Vxz[i];\n    V[ii+3]=Vyx[i];\n    V[ii+4]=Vyy[i];\n    V[ii+5]=Vyz[i];\n    V[ii+6]=Vzx[i];\n    V[ii+7]=Vzy[i];\n    V[ii+8]=Vzz[i];\n    }\n}\n\n// input  -> input(src) patch bounds\n// output -> output(dest) patch bounds\n// V      -> input(src) data\n// W      -> output(dest) data\n// nComp  -> number of sclar components\n//*****************************************************************************\n#define USE_INPUT_BOUNDS true\n#define USE_OUTPUT_BOUNDS false\ntemplate <typename T>\nvoid Copy(\n      int *input,\n      int *output,\n      T*  V,\n      T*  W,\n      int nComp,\n      int mode,\n      bool inputBounds=true)\n{\n  // input array bounds.\n  const int ni=input[1]-input[0]+1;\n  const int nj=input[3]-input[2]+1;\n  const int nk=input[5]-input[4]+1;\n  FlatIndex idx(ni,nj,nk,mode);\n\n  // output array bounds\n  const int _ni=output[1]-output[0]+1;\n  const int _nj=output[3]-output[2]+1;\n  const int _nk=output[5]-output[4]+1;\n  FlatIndex _idx(_ni,_nj,_nk,mode);\n\n  // use the smaller of the input and output for\n  // loop bounds.\n  int bounds[6];\n  if (inputBounds)\n    {\n    memcpy(bounds,input,6*sizeof(int));\n    }\n  else\n    {\n    memcpy(bounds,output,6*sizeof(int));\n    }\n\n  // loop over input in patch coordinates (both patches are in the same space)\n  for (int r=bounds[4]; r<=bounds[5]; ++r)\n    {\n    const int _k=r-output[4];\n    const int  k=r-input[4];\n    for (int q=bounds[2]; q<=bounds[3]; ++q)\n      {\n      const int _j=q-output[2];\n      const int  j=q-input[2];\n      for (int p=bounds[0]; p<=bounds[1]; ++p)\n        {\n        const int _i=p-output[0];\n        const int  i=p-input[0];\n\n        size_t _vi=nComp*_idx.Index(_i,_j,_k);\n        size_t  vi=nComp*idx.Index(i,j,k);\n\n        // copy components\n        for (int c=0; c<nComp; ++c)\n          {\n          W[_vi+c] = V[vi+c];\n          }\n        }\n      }\n    }\n}\n\n// input  -> patch input array is defined on\n// output -> patch outpu array is defined on\n// nComp  -> number of components in V\n// V      -> input patch scalar or vector field\n// W      -> output patch scalar or vector field\n// D      -> output patch scalar or vector field\n//*****************************************************************************\ntemplate <typename T>\nvoid Difference(\n      int *input,\n      int *output,\n      int nComp,\n      int mode,\n      T* __restrict__  V,\n      T* __restrict__  W,\n      T* __restrict__  D)\n{\n  // input array bounds.\n  const int ni=input[1]-input[0]+1;\n  const int nj=input[3]-input[2]+1;\n  const int nk=input[5]-input[4]+1;\n  FlatIndex idx(ni,nj,nk,mode);\n\n  // output array bounds\n  const int _ni=output[1]-output[0]+1;\n  const int _nj=output[3]-output[2]+1;\n  const int _nk=output[5]-output[4]+1;\n  FlatIndex _idx(_ni,_nj,_nk,mode);\n\n  // loop over output in patch coordinates (both patches are in the same space)\n  for (int r=output[4]; r<=output[5]; ++r)\n    {\n    const int _k=r-output[4];\n    const int  k=r-input[4];\n\n    for (int q=output[2]; q<=output[3]; ++q)\n      {\n      const int _j=q-output[2];\n      const int  j=q-input[2];\n\n      for (int p=output[0]; p<=output[1]; ++p)\n        {\n        const int _i=p-output[0];\n        const int  i=p-input[0];\n\n        const size_t _pi=nComp*_idx.Index(_i,_j,_k);\n\n        size_t vi = nComp*idx.Index(i,j,k);\n\n        for (int c=0; c<nComp; ++c)\n          {\n          D[_pi+c] = V[vi+c] - W[_pi+c];\n          }\n        }\n      }\n    }\n}\n\n// input  -> patch input array is defined on\n// output -> patch outpu array is defined on\n// K      -> kernel (square matrix whose sum is 1)\n// nk     -> number of rows in K\n// V      -> scalar or vector field\n// nComp  -> number of components in V\n// W      -> convolution of V and K\n// dim    -> dim, 2d or 3d\n//*****************************************************************************\ntemplate <typename T>\nvoid Convolution(\n      int *input,\n      int *output,\n      int *kernel,\n      int nComp,\n      int mode,\n      T* __restrict__  V,\n      T* __restrict__  W,\n      float * __restrict__ K)\n{\n  // input array bounds.\n  const int ni=input[1]-input[0]+1;\n  const int nj=input[3]-input[2]+1;\n  const int nk=input[5]-input[4]+1;\n  FlatIndex idx(ni,nj,nk,mode);\n\n  // output array bounds\n  const int _ni=output[1]-output[0]+1;\n  const int _nj=output[3]-output[2]+1;\n  const int _nk=output[5]-output[4]+1;\n  FlatIndex _idx(_ni,_nj,_nk,mode);\n\n  // kernel dimensions\n  const int kni=kernel[1]-kernel[0]+1;\n  const int knj=kernel[3]-kernel[2]+1;\n  const int knk=kernel[5]-kernel[4]+1;\n  FlatIndex kidx(kni,knj,knk,mode);\n\n  // loop over output in patch coordinates (both patches are in the same space)\n  for (int r=output[4]; r<=output[5]; ++r)\n    {\n    const int _k=r-output[4];\n    const int  k=r-input[4];\n\n    for (int q=output[2]; q<=output[3]; ++q)\n      {\n      const int _j=q-output[2];\n      const int  j=q-input[2];\n\n      for (int p=output[0]; p<=output[1]; ++p)\n        {\n        const int _i=p-output[0];\n        const int  i=p-input[0];\n\n        const size_t _pi=nComp*_idx.Index(_i,_j,_k);\n\n        // intialize the output\n        for (int c=0; c<nComp; ++c)\n          {\n          W[_pi+c] = ((T)0);\n          }\n\n        for (int h=kernel[4]; h<=kernel[5]; ++h)\n          {\n          const int kk=h-kernel[4];\n\n          for (int g=kernel[2]; g<=kernel[3]; ++g)\n            {\n            const int kj=g-kernel[2];\n\n            for (int f=kernel[0]; f<=kernel[1]; ++f)\n              {\n              const int ki=f-kernel[0];\n              size_t kii = kidx.Index(ki,kj,kk);\n\n              size_t vi = nComp*idx.Index(i+f,j+g,k+h);\n\n              for (int c=0; c<nComp; ++c)\n                {\n                W[_pi+c] += V[vi+c]*((T)K[kii]);\n                }\n              }\n            }\n          }\n        }\n      }\n    }\n}\n\n/**\nThis implementation is written so that adjacent threads access adjacent\nmemory locations. This requires that vtk vectors/tensors etc be split.\n*/\n//*****************************************************************************\ntemplate<typename T>\nvoid ScalarConvolution2D(\n      //int worldRank,\n      size_t vni,\n      size_t wni,\n      size_t wnij,\n      size_t kni,\n      size_t knij,\n      size_t nGhost,\n      T * __restrict__ V,\n      T * __restrict__ W,\n      float * __restrict__ K)\n{\n  (void)knij;\n  (void)nGhost;\n\n  // get a tuple from the current flat index in the output\n  // index space\n  for (size_t wi=0; wi<wnij; ++wi)\n    {\n    size_t i,j;\n    j=wi/wni;\n    i=wi-j*wni;\n\n    // compute using the aligned buffers\n    T w=(0);\n    for (size_t g=0; g<kni; ++g)\n      {\n      size_t b=kni*g;\n      size_t q=vni*(j+g)+i;\n      for (size_t f=0; f<kni; ++f)\n        {\n        size_t vi=q+f;\n        size_t ki=b+f;\n        w+=V[vi]*((T)K[ki]);\n        }\n      }\n    W[wi]=w;\n    }\n}\n\n//*****************************************************************************\ntemplate<typename T>\nvoid ScalarConvolution3D(\n      size_t vni,\n      size_t vnij,\n      size_t wni,\n      size_t wnij,\n      size_t wnijk,\n      size_t kni,\n      size_t knij,\n      size_t knijk,\n      size_t nGhost,\n      T * __restrict__ V,\n      T * __restrict__ W,\n      float * __restrict__ K)\n{\n  (void)knijk;\n  (void)nGhost;\n\n  // visit each output element\n  for (size_t wi=0; wi<wnijk; ++wi)\n    {\n    size_t i,j,k;\n    k=wi/wnij;\n    j=(wi-k*wnij)/wni;\n    i=wi-k*wnij-j*wni;\n\n    // compute convolution\n    T w=((T)0);\n    for (size_t h=0; h<kni; ++h)\n      {\n      size_t c=knij*h;\n      size_t r=vnij*(k+h);\n      for (size_t g=0; g<kni; ++g)\n        {\n        size_t b=c+kni*g;\n        size_t q=r+vni*(j+g)+i;\n        for (size_t f=0; f<kni; ++f)\n          {\n          size_t ki=b+f;\n          size_t vi=q+f;\n\n          w+=V[vi]*((T)K[ki]);\n          }\n        }\n      }\n\n    W[wi]=w;\n    }\n}\n\n/*\nthis vectorized version is slightly SLOWER than then unoptimized version\n\n// ****************************************************************************\ntemplate<typename T>\nvoid ScalarConvolution2D(\n      //int worldRank,\n      size_t vni,\n      size_t wni,\n      size_t wnij,\n      size_t kni,\n      size_t knij,\n      size_t nGhost,\n      T * __restrict__ V,\n      T * __restrict__ W,\n      float * __restrict__ K)\n{\n  // buffers for vectorized inner loop\n  size_t knij4=knij+4-knij%4;\n  size_t knij4b=knij4*sizeof(float);\n  float * __restrict__ aK=0;\n  posix_memalign((void**)&aK,16,knij4b);\n  memset(aK,0,knij4b);\n  for (size_t ki=0; ki<knij; ++ki)\n    {\n    aK[ki]=K[ki];\n    }\n\n  float * __restrict__ aV=0;\n  posix_memalign((void**)&aV,16,knij4b);\n  memset(aV,0,knij4b);\n\n  // get a tuple from the current flat index in the output\n  // index space\n  for (size_t wi=0; wi<wnij; ++wi)\n    {\n    size_t i,j;\n    j=wi/wni;\n    i=wi-j*wni;\n\n    // move input elements to the aligned buffer\n    size_t avi=0;\n    for (size_t g=0; g<kni; ++g)\n      {\n      size_t q=vni*(j+g)+i;\n      for (size_t f=0; f<kni; ++f)\n        {\n        size_t vi=q+f;\n        aV[avi]=V[vi];\n        ++avi;\n        }\n      }\n\n    // compute using the aligned buffers\n    float w=((T)0);\n    for (size_t ki=0; ki<knij4; ++ki)\n      {\n      w=w+aV[ki]*aK[ki];\n      }\n\n    W[wi]=w;\n    }\n\n  free(aV);\n  free(aK);\n}\n\n// ****************************************************************************\ntemplate<typename T>\nvoid ScalarConvolution3D(\n      size_t vni,\n      size_t vnij,\n      size_t wni,\n      size_t wnij,\n      size_t wnijk,\n      size_t kni,\n      size_t knij,\n      size_t knijk,\n      size_t nGhost,\n      T * __restrict__ V,\n      T * __restrict__ W,\n      float * __restrict__ K)\n{\n  // buffers for vectorized inner loop\n  size_t knijk4=knijk+4-knijk%4;\n  size_t knijk4b=knijk4*sizeof(float);\n  float * __restrict__ aK=0;\n  posix_memalign((void**)&aK,16,knijk4b);\n  memset(aK,0,knijk4b);\n  for (size_t ki=0; ki<knijk; ++ki)\n    {\n    aK[ki]=K[ki];\n    }\n\n  float * __restrict__ aV=0;\n  posix_memalign((void**)&aV,16,knijk4b);\n  memset(aV,0,knijk4b);\n\n  // visit each output element\n  for (size_t wi=0; wi<wnijk; ++wi)\n    {\n    size_t i,j,k;\n    k=wi/wnij;\n    j=(wi-k*wnij)/wni;\n    i=wi-k*wnij-j*wni;\n\n    // move input data into aligned buffer\n    size_t avi=0;\n    for (size_t h=0; h<kni; ++h)\n      {\n      size_t r=vnij*(k+h);\n      for (size_t g=0; g<kni; ++g)\n        {\n        size_t q=r+vni*(j+g)+i;\n        for (size_t f=0; f<kni; ++f)\n          {\n          size_t vi=q+f;\n\n          aV[avi]=V[vi];\n          ++avi;\n          }\n        }\n      }\n\n    // compute convolution\n    float w=((T)0);\n    for (size_t ki=0; ki<knijk4; ++ki)\n      {\n      w=w+aV[ki]*aK[ki];\n      }\n\n    W[wi]=w;\n    }\n\n  free(aV);\n  free(aK);\n}\n*/\n\n\n/**\nFunctor for comapring array values by index\n*/\ntemplate<typename T>\nclass IndirectCompare\n{\npublic:\n  //\n  IndirectCompare() : Data(0) {}\n  IndirectCompare(T *data) : Data(data) {}\n\n  // compare data at the given indices\n  bool operator()(size_t l, size_t r)\n  { return this->Data[l]<this->Data[r]; }\n\nprivate:\n  T *Data;\n};\n\n/**\nThis implementation is written so that adjacent threads access adjacent\nmemory locations. This requires that vtk vectors/tensors etc be split.\n*/\n//*****************************************************************************\ntemplate<typename T>\nvoid ScalarMedianFilter2D(\n      //int worldRank,\n      size_t vni,\n      size_t wni,\n      size_t wnij,\n      size_t kni,\n      size_t knij,\n      size_t nGhost,\n      T * __restrict__ V,\n      T * __restrict__ W)\n{\n  (void)nGhost;\n\n  size_t *ids=0;\n  posix_memalign((void**)&ids,16,knij*sizeof(size_t));\n\n  IndirectCompare<T> comp(V);\n\n  // get a tuple from the current flat index in the output\n  // index space\n  for (size_t wi=0; wi<wnij; ++wi)\n    {\n    size_t i,j;\n    j=wi/wni;\n    i=wi-j*wni;\n\n    // setup search space\n    size_t ki=0;\n    for (size_t g=0; g<kni; ++g)\n      {\n      size_t q=vni*(j+g)+i;\n      for (size_t f=0; f<kni; ++f)\n        {\n        size_t vi=q+f;\n        ids[ki]=vi;\n        ++ki;\n        }\n      }\n\n    // sort\n    //std::sort(ids,ids+knij,comp);\n    std::partial_sort(ids,ids+knij/2+1,ids+knij,comp);\n\n    // std::cerr << wi << \" \" << V[ids[0]] << \" \" << V[ids[knij/2]] << \" \" << V[ids[knij-1]] << std::endl;\n\n    // median\n    W[wi]=V[ids[knij/2]];\n    }\n\n  free(ids);\n}\n\n//*****************************************************************************\ntemplate<typename T>\nvoid ScalarMedianFilter3D(\n      size_t vni,\n      size_t vnij,\n      size_t wni,\n      size_t wnij,\n      size_t wnijk,\n      size_t kni,\n      size_t knij,\n      size_t knijk,\n      size_t nGhost,\n      T * __restrict__ V,\n      T * __restrict__ W)\n{\n  (void)knij;\n  (void)nGhost;\n\n  size_t *ids=0;\n  posix_memalign((void**)&ids,16,knijk*sizeof(size_t));\n\n  IndirectCompare<T> comp(V);\n\n  // visit each output element\n  for (size_t wi=0; wi<wnijk; ++wi)\n    {\n    size_t i,j,k;\n    k=wi/wnij;\n    j=(wi-k*wnij)/wni;\n    i=wi-k*wnij-j*wni;\n\n    // set up search space\n    size_t ki=0;\n    for (size_t h=0; h<kni; ++h)\n      {\n      size_t r=vnij*(k+h);\n      for (size_t g=0; g<kni; ++g)\n        {\n        size_t q=r+vni*(j+g)+i;\n        for (size_t f=0; f<kni; ++f)\n          {\n          size_t vi=q+f;\n          ids[ki]=vi;\n          ++ki;\n          }\n        }\n      }\n\n    // sort\n    //std::sort(ids,ids+knijk,comp);\n    std::partial_sort(ids,ids+knijk/2+1,ids+knijk,comp);\n\n    // median\n    W[wi]=V[ids[knijk/2]];\n    }\n\n  free(ids);\n}\n\n\n//*****************************************************************************\ntemplate <typename T>\nvoid DivergenceFace(int *I, double *dX, T *V, T *mV, T *div)\n{\n  // *hi variables are number of cells in the out cell centered\n  // array. The in array is a point centered array of face data\n  // with the last face left off.\n  const int pihi=I[0]+1;\n  const int pjhi=I[1]+1;\n  // const int pkhi=I[2]+1;\n\n  for (int k=0; k<I[2]; ++k)\n    {\n    for (int j=0; j<I[1]; ++j)\n      {\n      for (int i=0; i<I[0]; ++i)\n        {\n        const int c=k*I[0]*I[1]+j*I[0]+i;\n        const int p=k*pihi*pjhi+j*pihi+i;\n\n        const int vilo = 3 * (k*pihi*pjhi+j*pihi+ i   );\n        const int vihi = 3 * (k*pihi*pjhi+j*pihi+(i+1));\n        const int vjlo = 3 * (k*pihi*pjhi+   j *pihi+i) + 1;\n        const int vjhi = 3 * (k*pihi*pjhi+(j+1)*pihi+i) + 1;\n        const int vklo = 3 * (   k *pihi*pjhi+j*pihi+i) + 2;\n        const int vkhi = 3 * ((k+1)*pihi*pjhi+j*pihi+i) + 2;\n\n        //std::cerr << \"(\" << vilo << \", \" << vihi << \", \" << vjlo << \", \" << vjhi << \", \" << vklo << \", \" << vkhi << \")\" << std::endl;\n\n        // const double modV=mV[cId];\n        // (sqrt(V[vilo]*V[vilo] + V[vjlo]*V[vjlo] + V[vklo]*V[vklo])\n        // + sqrt(V[vihi]*V[vihi] + V[vjhi]*V[vjhi] + V[vkhi]*V[vkhi]))/((T)2);\n\n        div[c] =(V[vihi]-V[vilo])/dX[0]/mV[p];\n        div[c]+=(V[vjhi]-V[vjlo])/dX[1]/mV[p];\n        div[c]+=(V[vkhi]-V[vklo])/dX[2]/mV[p];\n        }\n      }\n    }\n}\n\n// input  -> patch input array is defined on\n// output -> patch outpu array is defined on\n// dX     -> grid spacing triple\n// V      -> vector field\n// W      -> vector curl\n//*****************************************************************************\ntemplate <typename T>\nvoid Rotation(\n      int *input,\n      int *output,\n      int mode,\n      double *dX,\n      T *V,\n      T *Wx,\n      T *Wy,\n      T *Wz)\n{\n  // input array bounds.\n  const int ni=input[1]-input[0]+1;\n  const int nj=input[3]-input[2]+1;\n  const int nk=input[5]-input[4]+1;\n  FlatIndex idx(ni,nj,nk,mode);\n\n  const int iok=(ni<3?0:1);\n  const int jok=(nj<3?0:1);\n  const int kok=(nk<3?0:1);\n\n  // output array bounds\n  const int _ni=output[1]-output[0]+1;\n  const int _nj=output[3]-output[2]+1;\n  const int _nk=output[5]-output[4]+1;\n  FlatIndex _idx(_ni,_nj,_nk,mode);\n\n  // stencil deltas\n  const T dx[3]={\n      ((T)dX[0])*((T)2),\n      ((T)dX[1])*((T)2),\n      ((T)dX[2])*((T)2)};\n\n  // loop over output in patch coordinates (both patches are in the same space)\n  for (int r=output[4]; r<=output[5]; ++r)\n    {\n    const int  k=r-input[4];\n    const int _k=r-output[4];\n\n    for (int q=output[2]; q<=output[3]; ++q)\n      {\n      const int  j=q-input[2];\n      const int _j=q-output[2];\n\n      for (int p=output[0]; p<=output[1]; ++p)\n        {\n        const int  i=p-input[0];\n        const int _i=p-output[0];\n\n        const size_t _pi=_idx.Index(_i,_j,_k);\n\n        //      __   ->\n        //  w = \\/ x V\n        Wx[_pi]=((T)0);\n        Wy[_pi]=((T)0);\n        Wz[_pi]=((T)0);\n        if (iok)\n          {\n          size_t vilo_y=3*idx.Index(i-1,j,k)+1;\n          size_t vilo_z=vilo_y+1;\n\n          size_t vihi_y=3*idx.Index(i+1,j,k)+1;\n          size_t vihi_z=vihi_y+1;\n\n          Wy[_pi] -= (V[vihi_z]-V[vilo_z])/dx[0];\n          Wz[_pi] += (V[vihi_y]-V[vilo_y])/dx[0];\n          }\n\n        if (jok)\n          {\n          size_t vjlo_x=3*idx.Index(i,j-1,k);\n          size_t vjlo_z=vjlo_x+2;\n\n          size_t vjhi_x=3*idx.Index(i,j+1,k);\n          size_t vjhi_z=vjhi_x+2;\n\n          Wx[_pi] += (V[vjhi_z]-V[vjlo_z])/dx[1];\n          Wz[_pi] -= (V[vjhi_x]-V[vjlo_x])/dx[1];\n          }\n\n        if (kok)\n          {\n          size_t vklo_x=3*idx.Index(i,j,k-1);\n          size_t vklo_y=vklo_x+1;\n\n          size_t vkhi_x=3*idx.Index(i,j,k+1);\n          size_t vkhi_y=vkhi_x+1;\n\n          Wx[_pi] -= (V[vkhi_y]-V[vklo_y])/dx[2];\n          Wy[_pi] += (V[vkhi_x]-V[vklo_x])/dx[2];\n          }\n        }\n      }\n    }\n}\n\n// input  -> patch input array is defined on\n// output -> patch outpu array is defined on\n// dX     -> grid spacing triple\n// V      -> vector field\n// W      -> vector curl\n//*****************************************************************************\ntemplate <typename TP, typename TD>\nvoid Rotation(\n      int *input,\n      int *output,\n      TP *x,\n      TP *y,\n      TP *z,\n      TD *V,\n      TD *Wx,\n      TD *Wy,\n      TD *Wz)\n{\n  // input array bounds.\n  const int ni=input[1]-input[0]+1;\n  const int nj=input[3]-input[2]+1;\n  const int ninj=ni*nj;\n\n  // output array bounds\n  const int _ni=output[1]-output[0]+1;\n  const int _nj=output[3]-output[2]+1;\n  const int _ninj=_ni*_nj;\n\n  // loop over output in patch coordinates (both patches are in the same space)\n  for (int r=output[4]; r<=output[5]; ++r)\n    {\n    for (int q=output[2]; q<=output[3]; ++q)\n      {\n      for (int p=output[0]; p<=output[1]; ++p)\n        {\n        // stencil deltas\n        const TP dx[3]\n          = {x[p+1]-x[p-1],y[q+1]-y[q-1],z[r+1]-z[r-1]};\n\n        // output array indices\n        const int _i=p-output[0];\n        const int _j=q-output[2];\n        const int _k=r-output[4];\n        // index into output array;\n        const int pi=_k*_ninj+_j*_ni+_i;\n\n        // input array indices\n        const int i=p-input[0];\n        const int j=q-input[2];\n        const int k=r-input[4];\n        // stencil into the input array\n        const int vilo=3*(k*ninj+j*ni+(i-1));\n        const int vihi=3*(k*ninj+j*ni+(i+1));\n        const int vjlo=3*(k*ninj+(j-1)*ni+i);\n        const int vjhi=3*(k*ninj+(j+1)*ni+i);\n        const int vklo=3*((k-1)*ninj+j*ni+i);\n        const int vkhi=3*((k+1)*ninj+j*ni+i);\n\n        //      __   ->\n        //  w = \\/ x V\n        Wx[pi]=T((V[vjhi+2]-V[vjlo+2])/dx[1]-(V[vkhi+1]-V[vklo+1])/dx[2]);\n        Wy[pi]=T((V[vkhi  ]-V[vklo  ])/dx[2]-(V[vihi+2]-V[vilo+2])/dx[0]);\n        Wz[pi]=T((V[vihi+1]-V[vilo+1])/dx[0]-(V[vjhi  ]-V[vjlo  ])/dx[1]);\n        }\n      }\n    }\n}\n\n// input  -> patch input array is defined on\n// output -> patch outpu array is defined on\n// dX     -> grid spacing triple\n// V      -> vector field\n// H      -> helicity\n//*****************************************************************************\ntemplate <typename T>\nvoid Helicity(\n      int *input,\n      int *output,\n      int mode,\n      double *dX,\n      T *V,\n      T *H)\n{\n  // input array bounds.\n  const int ni=input[1]-input[0]+1;\n  const int nj=input[3]-input[2]+1;\n  const int nk=input[5]-input[4]+1;\n  FlatIndex idx(ni,nj,nk,mode);\n\n  const int iok=(ni<3?0:1);\n  const int jok=(nj<3?0:1);\n  const int kok=(nk<3?0:1);\n\n  // output array bounds\n  const int _ni=output[1]-output[0]+1;\n  const int _nj=output[3]-output[2]+1;\n  const int _nk=output[5]-output[4]+1;\n  FlatIndex _idx(_ni,_nj,_nk,mode);\n\n  // stencil deltas\n  const T dx[3]={\n      ((T)dX[0])*((T)2),\n      ((T)dX[1])*((T)2),\n      ((T)dX[2])*((T)2)};\n\n  // loop over output in patch coordinates (both patches are in the same space)\n  for (int r=output[4]; r<=output[5]; ++r)\n    {\n    const int _k=r-output[4];\n    const int  k=r-input[4];\n    for (int q=output[2]; q<=output[3]; ++q)\n      {\n      const int _j=q-output[2];\n      const int  j=q-input[2];\n      for (int p=output[0]; p<=output[1]; ++p)\n        {\n        const int _i=p-output[0];\n        const int  i=p-input[0];\n\n        //      __   ->\n        //  w = \\/ x V\n        T wx=((T)0);\n        T wy=((T)0);\n        T wz=((T)0);\n        if (iok)\n          {\n          size_t vilo_y=3*idx.Index(i-1,j,k)+1;\n          size_t vilo_z=vilo_y+1;\n\n          size_t vihi_y=3*idx.Index(i+1,j,k)+1;\n          size_t vihi_z=vihi_y+1;\n\n          wy -= (V[vihi_z]-V[vilo_z])/dx[0];\n          wz += (V[vihi_y]-V[vilo_y])/dx[0];\n          }\n\n        if (jok)\n          {\n          size_t vjlo_x=3*idx.Index(i,j-1,k);\n          size_t vjlo_z=vjlo_x+2;\n\n          size_t vjhi_x=3*idx.Index(i,j+1,k);\n          size_t vjhi_z=vjhi_x+2;\n\n          wx += (V[vjhi_z]-V[vjlo_z])/dx[1];\n          wz -= (V[vjhi_x]-V[vjlo_x])/dx[1];\n          }\n\n        if (kok)\n          {\n          size_t vklo_x=3*idx.Index(i,j,k-1);\n          size_t vklo_y=vklo_x+1;\n\n          size_t vkhi_x=3*idx.Index(i,j,k+1);\n          size_t vkhi_y=vkhi_x+1;\n\n          wx -= (V[vkhi_y]-V[vklo_y])/dx[2];\n          wy += (V[vkhi_x]-V[vklo_x])/dx[2];\n          }\n\n        const size_t pi=_idx.Index(_i,_j,_k);\n\n        const size_t vi=3*idx.Index(i,j,k);;\n        const size_t vj=vi+1;\n        const size_t vk=vj+1;\n\n        //        ->  ->\n        // H =  V . w\n        H[pi]=(V[vi]*wx+V[vj]*wy+V[vk]*wz);\n        }\n      }\n    }\n}\n\n// input  -> patch input array is defined on\n// output -> patch outpu array is defined on\n// dX     -> grid spacing triple\n// V      -> vector field\n// H      -> helicity\n//*****************************************************************************\ntemplate <typename TP, typename TD>\nvoid Helicity(int *input, int *output, TP *x, TP *y, TP *z, TD *V, TD *H)\n{\n  // input array bounds.\n  const int ni=input[1]-input[0]+1;\n  const int nj=input[3]-input[2]+1;\n  const int ninj=ni*nj;\n\n  // output array bounds\n  const int _ni=output[1]-output[0]+1;\n  const int _nj=output[3]-output[2]+1;\n  const int _ninj=_ni*_nj;\n\n  // loop over output in patch coordinates (both patches are in the same space)\n  for (int r=output[4]; r<=output[5]; ++r)\n    {\n    for (int q=output[2]; q<=output[3]; ++q)\n      {\n      for (int p=output[0]; p<=output[1]; ++p)\n        {\n        // stencil deltas\n        const TD dx[3] = {\n            (TD)(x[p+1]-x[p-1]),\n            (TD)(y[q+1]-y[q-1]),\n            (TD)(z[r+1]-z[r-1])};\n\n        // output array indices\n        const int _i=p-output[0];\n        const int _j=q-output[2];\n        const int _k=r-output[4];\n        // index into output array;\n        const int pi=_k*_ninj+_j*_ni+_i;\n        const int vi=3*pi;\n        const int vj=vi+1;\n        const int vk=vi+2;\n\n        // input array indices\n        const int i=p-input[0];\n        const int j=q-input[2];\n        const int k=r-input[4];\n        // stencil\n        const int vilo=3*(k*ninj+j*ni+(i-1));\n        const int vihi=3*(k*ninj+j*ni+(i+1));\n        const int vjlo=3*(k*ninj+(j-1)*ni+i);\n        const int vjhi=3*(k*ninj+(j+1)*ni+i);\n        const int vklo=3*((k-1)*ninj+j*ni+i);\n        const int vkhi=3*((k+1)*ninj+j*ni+i);\n\n        //      __   ->\n        //  w = \\/ x V\n        const TD w[3]={\n              (V[vjhi+2]-V[vjlo+2])/dx[1]-(V[vkhi+1]-V[vklo+1])/dx[2],\n              (V[vkhi  ]-V[vklo  ])/dx[2]-(V[vihi+2]-V[vilo+2])/dx[0],\n              (V[vihi+1]-V[vilo+1])/dx[0]-(V[vjhi  ]-V[vjlo  ])/dx[1]\n              };\n        //        ->  ->\n        // H =  V . w\n        H[pi]=(V[vi]*w[0]+V[vj]*w[1]+V[vk]*w[2]);\n        }\n      }\n    }\n}\n\n// input  -> patch input array is defined on\n// output -> patch outpu array is defined on\n// dX     -> grid spacing triple\n// V      -> vector field\n// H      -> normalized helicity(out)\n//*****************************************************************************\ntemplate <typename T>\nvoid NormalizedHelicity(\n    int *input,\n    int *output,\n    int mode,\n    double *dX,\n    T *V,\n    T *H)\n{\n  // input array bounds.\n  const int ni=input[1]-input[0]+1;\n  const int nj=input[3]-input[2]+1;\n  const int nk=input[5]-input[4]+1;\n  FlatIndex idx(ni,nj,nk,mode);\n\n  const int iok=(ni<3?0:1);\n  const int jok=(nj<3?0:1);\n  const int kok=(nk<3?0:1);\n\n  // output array bounds\n  const int _ni=output[1]-output[0]+1;\n  const int _nj=output[3]-output[2]+1;\n  const int _nk=output[5]-output[4]+1;\n  FlatIndex _idx(_ni,_nj,_nk,mode);\n\n  // stencil deltas\n  const T dx[3]={\n      ((T)dX[0])*((T)2),\n      ((T)dX[1])*((T)2),\n      ((T)dX[2])*((T)2)};\n\n  // loop over output in patch coordinates (both patches are in the same space)\n  for (int r=output[4]; r<=output[5]; ++r)\n    {\n    const int _k=r-output[4];\n    const int  k=r-input[4];\n    for (int q=output[2]; q<=output[3]; ++q)\n      {\n      const int _j=q-output[2];\n      const int  j=q-input[2];\n      for (int p=output[0]; p<=output[1]; ++p)\n        {\n        const int _i=p-output[0];\n        const int  i=p-input[0];\n\n        //      __   ->\n        //  w = \\/ x V\n        T wx=((T)0);\n        T wy=((T)0);\n        T wz=((T)0);\n        if (iok)\n          {\n          size_t vilo_y=3*idx.Index(i-1,j,k)+1;\n          size_t vilo_z=vilo_y+1;\n\n          size_t vihi_y=3*idx.Index(i+1,j,k)+1;\n          size_t vihi_z=vihi_y+1;\n\n          wy -= (V[vihi_z]-V[vilo_z])/dx[0];\n          wz += (V[vihi_y]-V[vilo_y])/dx[0];\n          }\n\n        if (jok)\n          {\n          size_t vjlo_x=3*idx.Index(i,j-1,k);\n          size_t vjlo_z=vjlo_x+2;\n\n          size_t vjhi_x=3*idx.Index(i,j+1,k);\n          size_t vjhi_z=vjhi_x+2;\n\n          wx += (V[vjhi_z]-V[vjlo_z])/dx[1];\n          wz -= (V[vjhi_x]-V[vjlo_x])/dx[1];\n          }\n\n        if (kok)\n          {\n          size_t vklo_x=3*idx.Index(i,j,k-1);\n          size_t vklo_y=vklo_x+1;\n\n          size_t vkhi_x=3*idx.Index(i,j,k+1);\n          size_t vkhi_y=vkhi_x+1;\n\n          wx -= (V[vkhi_y]-V[vklo_y])/dx[2];\n          wy += (V[vkhi_x]-V[vklo_x])/dx[2];\n          }\n\n        //  ->\n        // |w|\n        const T modW=((T)sqrt(wx*wx+wy*wy+wz*wz));\n\n        const size_t vi=3*idx.Index(i,j,k);\n        const size_t vj=vi+1;\n        const size_t vk=vj+1;\n\n        //  ->\n        // |V|\n        const T modV\n          = ((T)sqrt(V[vi]*V[vi]+V[vj]*V[vj]+V[vk]*V[vk]));\n\n        const size_t pi=_idx.Index(_i,_j,_k);\n\n        //         ->  ->     -> ->\n        // H_n = ( V . w ) / |V||w|\n        H[pi]=(V[vi]*wx+V[vj]*wy+V[vk]*wz)/(modV*modW);\n        // Cosine of the angle between v and w. Angle between v and w is small\n        // near vortex, H_n = +-1.\n        }\n      }\n    }\n}\n\n// input  -> patch input array is defined on\n// output -> patch outpu array is defined on\n// dX     -> grid spacing triple\n// V      -> vector field\n// H      -> normalized helicity(out)\n//*****************************************************************************\ntemplate <typename TP, typename TD>\nvoid NormalizedHelicity(\n      int *input,\n      int *output,\n      TP *x,\n      TP *y,\n      TP *z,\n      TD *V,\n      TD *H)\n{\n  // input array bounds.\n  const int ni=input[1]-input[0]+1;\n  const int nj=input[3]-input[2]+1;\n  const int ninj=ni*nj;\n\n  // output array bounds\n  const int _ni=output[1]-output[0]+1;\n  const int _nj=output[3]-output[2]+1;\n  const int _ninj=_ni*_nj;\n\n  // loop over output in patch coordinates (both patches are in the same space)\n  for (int r=output[4]; r<=output[5]; ++r)\n    {\n    for (int q=output[2]; q<=output[3]; ++q)\n      {\n      for (int p=output[0]; p<=output[1]; ++p)\n        {\n        // stencil deltas\n        const TD dx[3] = {\n            ((TD)(x[p+1]-x[p-1]))\n            ((TD)(y[q+1]-y[q-1]))\n            ((TD)(z[r+1]-z[r-1]))};\n\n        // output array indices\n        const int _i=p-output[0];\n        const int _j=q-output[2];\n        const int _k=r-output[4];\n        // index into output array;\n        const int pi=_k*_ninj+_j*_ni+_i;\n\n        // TODO vi is input pi is output\n        const int vi=3*pi;\n        const int vj=vi+1;\n        const int vk=vi+2;\n\n        // input array indices\n        const int i=p-input[0];\n        const int j=q-input[2];\n        const int k=r-input[4];\n        // stencil\n        const int vilo=3*(k*ninj+j*ni+(i-1));\n        const int vihi=3*(k*ninj+j*ni+(i+1));\n        const int vjlo=3*(k*ninj+(j-1)*ni+i);\n        const int vjhi=3*(k*ninj+(j+1)*ni+i);\n        const int vklo=3*((k-1)*ninj+j*ni+i);\n        const int vkhi=3*((k+1)*ninj+j*ni+i);\n\n        //  ->\n        // |V|\n        const TD modV\n          = sqrt(V[vi]*V[vi]+V[vj]*V[vj]+V[vk]*V[vk]);\n\n        //      __   ->\n        //  w = \\/ x V\n        const TD w[3]={\n              (V[vjhi+2]-V[vjlo+2])/dx[1]-(V[vkhi+1]-V[vklo+1])/dx[2],\n              (V[vkhi  ]-V[vklo  ])/dx[2]-(V[vihi+2]-V[vilo+2])/dx[0],\n              (V[vihi+1]-V[vilo+1])/dx[0]-(V[vjhi  ]-V[vjlo  ])/dx[1]};\n\n        const TD modW=sqrt(w[0]*w[0]+w[1]*w[1]+w[2]*w[2]);\n\n        //         ->  ->     -> ->\n        // H_n = ( V . w ) / |V||w|\n        H[pi]=(V[vi]*w[0]+V[vj]*w[1]+V[vk]*w[2])/(modV*modW);\n        // Cosine of the angle between v and w. Angle between v and w is small\n        // near vortex, H_n = +-1.\n\n        // std::cerr\n        //   << \"H=\" << H[pi] << \" \"\n        //   << \"modV= \" << modV << \" \"\n        //   << \"modW=\" << modW << \" \"\n        //   << \"w=\" << Tuple<double>((double *)w,3) << \" \"\n        //   << \"V=\" << Tuple<T>(&V[vi],3)\n        //   << std::endl;\n        }\n      }\n    }\n}\n\n// input  -> patch input array is defined on\n// output -> patch outpu array is defined on\n// dX     -> grid spacing triple\n// V      -> vector field\n// L      -> eigenvalues (lambda) of the corrected pressure hessian\n//*****************************************************************************\ntemplate <typename T>\nvoid Lambda(\n      int *input,\n      int *output,\n      int mode,\n      double *dX,\n      T *V,\n      T *L)\n{\n  // input array bounds.\n  const int ni=input[1]-input[0]+1;\n  const int nj=input[3]-input[2]+1;\n  const int nk=input[5]-input[4]+1;\n  FlatIndex idx(ni,nj,nk,mode);\n\n  const int iok=(ni<3?0:1);\n  const int jok=(nj<3?0:1);\n  const int kok=(nk<3?0:1);\n\n  // output array bounds\n  const int _ni=output[1]-output[0]+1;\n  const int _nj=output[3]-output[2]+1;\n  const int _nk=output[5]-output[4]+1;\n  FlatIndex _idx(_ni,_nj,_nk,mode);\n\n  // stencil deltas\n  const T dx[3]={\n      ((T)dX[0])*((T)2),\n      ((T)dX[1])*((T)2),\n      ((T)dX[2])*((T)2)};\n\n  // loop over output in patch coordinates (both patches are in the same space)\n  for (int r=output[4]; r<=output[5]; ++r)\n    {\n    const int _k=r-output[4];\n    const int  k=r-input[4];\n    for (int q=output[2]; q<=output[3]; ++q)\n      {\n      const int _j=q-output[2];\n      const int  j=q-input[2];\n      for (int p=output[0]; p<=output[1]; ++p)\n        {\n        const int _i=p-output[0];\n        const int  i=p-input[0];\n\n        // J: gradient velocity tensor, (jacobian)\n        T j11=((T)0), j12=((T)0), j13=((T)0);\n        if (iok)\n          {\n          size_t vilo_x=3*idx.Index(i-1,j,k);\n          size_t vilo_y=vilo_x+1;\n          size_t vilo_z=vilo_y+1;\n\n          size_t vihi_x=3*idx.Index(i+1,j,k);\n          size_t vihi_y=vihi_x+1;\n          size_t vihi_z=vihi_y+1;\n\n          j11=(V[vihi_x]-V[vilo_x])/dx[0];\n          j12=(V[vihi_y]-V[vilo_y])/dx[0];\n          j13=(V[vihi_z]-V[vilo_z])/dx[0];\n          }\n\n        T j21=((T)0), j22=((T)0), j23=((T)0);\n        if (jok)\n          {\n          size_t vjlo_x=3*idx.Index(i,j-1,k);\n          size_t vjlo_y=vjlo_x+1;\n          size_t vjlo_z=vjlo_y+1;\n\n          size_t vjhi_x=3*idx.Index(i,j+1,k);\n          size_t vjhi_y=vjhi_x+1;\n          size_t vjhi_z=vjhi_y+1;\n\n          j21=(V[vjhi_x]-V[vjlo_x])/dx[1];\n          j22=(V[vjhi_y]-V[vjlo_y])/dx[1];\n          j23=(V[vjhi_z]-V[vjlo_z])/dx[1];\n          }\n\n        T j31=((T)0), j32=((T)0), j33=((T)0);\n        if (kok)\n          {\n          size_t vklo_x=3*idx.Index(i,j,k-1);\n          size_t vklo_y=vklo_x+1;\n          size_t vklo_z=vklo_y+1;\n\n          size_t vkhi_x=3*idx.Index(i,j,k+1);\n          size_t vkhi_y=vkhi_x+1;\n          size_t vkhi_z=vkhi_y+1;\n\n          j31=(V[vkhi_x]-V[vklo_x])/dx[2];\n          j32=(V[vkhi_y]-V[vklo_y])/dx[2];\n          j33=(V[vkhi_z]-V[vklo_z])/dx[2];\n          }\n\n        Matrix<T,3,3> J;\n        J <<\n          j11, j12, j13,\n          j21, j22, j23,\n          j31, j32, j33;\n\n        // construct pressure corrected hessian\n        Matrix<T,3,3> S=0.5*(J+J.transpose());\n        Matrix<T,3,3> W=0.5*(J-J.transpose());\n        Matrix<T,3,3> HP=S*S+W*W;\n\n        // compute eigen values, lambda\n        Matrix<T,3,1> e;\n        SelfAdjointEigenSolver<Matrix<T,3,3> >solver(HP,false);\n        e=solver.eigenvalues();\n\n        const size_t pi=_idx.Index(_i,_j,_k);\n        const size_t vi=3*pi;\n        const size_t vj=vi+1;\n        const size_t vk=vj+1;\n\n        L[vi]=e(0,0);\n        L[vj]=e(1,0);\n        L[vk]=e(2,0);\n\n        slowSort(&L[vi],0,3);\n        }\n      }\n    }\n}\n\n// input  -> patch input array is defined on\n// output -> patch outpu array is defined on\n// dX     -> grid spacing triple\n// V      -> vector field\n// L      -> eigenvalues (lambda) of the corrected pressure hessian\n//*****************************************************************************\ntemplate <typename TP, typename TD>\nvoid Lambda(int *input, int *output, TP *x, TP *y, TP *z, TD *V, TD *L)\n{\n  // input array bounds.\n  const int ni=input[1]-input[0]+1;\n  const int nj=input[3]-input[2]+1;\n  const int ninj=ni*nj;\n\n  // output array bounds\n  const int _ni=output[1]-output[0]+1;\n  const int _nj=output[3]-output[2]+1;\n  const int _ninj=_ni*_nj;\n\n  // loop over output in patch coordinates (both patches are in the same space)\n  for (int r=output[4]; r<=output[5]; ++r)\n    {\n    for (int q=output[2]; q<=output[3]; ++q)\n      {\n      for (int p=output[0]; p<=output[1]; ++p)\n        {\n        // stencil deltas\n        const TD dx[3] = {\n            ((TD)(x[p+1]-x[p-1])),\n            ((TD)(y[q+1]-y[q-1])),\n            ((TD)(z[r+1]-z[r-1]))};\n\n        // output array indices\n        const int _i=p-output[0];\n        const int _j=q-output[2];\n        const int _k=r-output[4];\n        // index into output array;\n        const int pi=_k*_ninj+_j*_ni+_i;\n        const int vi=3*pi;\n        const int vj=vi+1;\n        const int vk=vi+2;\n\n        // input array indices\n        const int i=p-input[0];\n        const int j=q-input[2];\n        const int k=r-input[4];\n        // stencil\n        const int vilo=3*(k*ninj+j*ni+(i-1));\n        const int vihi=3*(k*ninj+j*ni+(i+1));\n        const int vjlo=3*(k*ninj+(j-1)*ni+i);\n        const int vjhi=3*(k*ninj+(j+1)*ni+i);\n        const int vklo=3*((k-1)*ninj+j*ni+i);\n        const int vkhi=3*((k+1)*ninj+j*ni+i);\n\n        // J: gradient velocity tensor, (jacobian)\n        Matrix<TD,3,3> J;\n        J <<\n          (V[vihi]-V[vilo])/dx[0], (V[vihi+1]-V[vilo+1])/dx[0], V[vihi+2]-V[vilo+2]/dx[0],\n          (V[vjhi]-V[vjlo])/dx[1], (V[vjhi+1]-V[vjlo+1])/dx[1], V[vjhi+2]-V[vjlo+2]/dx[1],\n          (V[vkhi]-V[vklo])/dx[2], (V[vkhi+1]-V[vklo+1])/dx[2], V[vkhi+2]-V[vklo+2]/dx[2];\n\n        // construct pressure corrected hessian\n        Matrix<TD,3,3> S=((TD)0.5)*(J+J.transpose());\n        Matrix<TD,3,3> W=((TD)0.5)*(J-J.transpose());\n        Matrix<TD,3,3> HP=S*S+W*W;\n\n        // compute eigen values, lambda\n        Matrix<TD,3,1> e;\n        SelfAdjointEigenSolver<Matrix<TD,3,3> >solver(HP,false);\n        e=solver.eigenvalues();\n\n        L[vi]=e(0,0);\n        L[vj]=e(1,0);\n        L[vk]=e(2,0);\n\n        L[vi]=(((L[vi]>=((TD)-1E-5))&&(L[vi]<=((TD)1E-5)))?TD(0):L[vi]);\n        L[vj]=(((L[vj]>=((TD)-1E-5))&&(L[vj]<=((TD)1E-5)))?TD(0):L[vj]);\n        L[vk]=(((L[vk]>=((TD)-1E-5))&&(L[vk]<=((TD)1E-5)))?TD(0):L[vk]);\n\n        slowSort(&L[vi],0,3);\n        // std::cerr << L[vi] << \", \"  << L[vj] << \", \" << L[vk] << std::endl;\n        }\n      }\n    }\n}\n\n// input  -> patch input array is defined on\n// output -> patch outpu array is defined on\n// dX     -> grid spacing triple\n// V      -> vector field\n// L      -> second eigenvalues (lambda-2) of the corrected pressure hessian\n//*****************************************************************************\ntemplate <typename T>\nvoid Lambda2(\n      int *input,\n      int *output,\n      int mode,\n      double *dX,\n      T *V,\n      T *L2)\n{\n  // input array bounds.\n  const int ni=input[1]-input[0]+1;\n  const int nj=input[3]-input[2]+1;\n  const int nk=input[5]-input[4]+1;\n  FlatIndex idx(ni,nj,nk,mode);\n\n  const int iok=(ni<3?0:1);\n  const int jok=(nj<3?0:1);\n  const int kok=(nk<3?0:1);\n\n  // output array bounds\n  const int _ni=output[1]-output[0]+1;\n  const int _nj=output[3]-output[2]+1;\n  const int _nk=output[5]-output[4]+1;\n  FlatIndex _idx(_ni,_nj,_nk,mode);\n\n  // stencil deltas\n  const T dx[3]={\n      ((T)dX[0])*((T)2),\n      ((T)dX[1])*((T)2),\n      ((T)dX[2])*((T)2)};\n\n  // loop over output in patch coordinates (both patches are in the same space)\n  for (int r=output[4]; r<=output[5]; ++r)\n    {\n    const int _k=r-output[4];\n    const int  k=r-input[4];\n    for (int q=output[2]; q<=output[3]; ++q)\n      {\n      const int _j=q-output[2];\n      const int  j=q-input[2];\n      for (int p=output[0]; p<=output[1]; ++p)\n        {\n        const int _i=p-output[0];\n        const int  i=p-input[0];\n\n        // J: gradient velocity tensor, (jacobian)\n        T j11=((T)0), j12=((T)0), j13=((T)0);\n        if (iok)\n          {\n          size_t vilo_x=3*idx.Index(i-1,j,k);\n          size_t vilo_y=vilo_x+1;\n          size_t vilo_z=vilo_y+1;\n\n          size_t vihi_x=3*idx.Index(i+1,j,k);\n          size_t vihi_y=vihi_x+1;\n          size_t vihi_z=vihi_y+1;\n\n          j11=(V[vihi_x]-V[vilo_x])/dx[0];\n          j12=(V[vihi_y]-V[vilo_y])/dx[0];\n          j13=(V[vihi_z]-V[vilo_z])/dx[0];\n          }\n\n        T j21=((T)0), j22=((T)0), j23=((T)0);\n        if (jok)\n          {\n          size_t vjlo_x=3*idx.Index(i,j-1,k);\n          size_t vjlo_y=vjlo_x+1;\n          size_t vjlo_z=vjlo_y+1;\n\n          size_t vjhi_x=3*idx.Index(i,j+1,k);\n          size_t vjhi_y=vjhi_x+1;\n          size_t vjhi_z=vjhi_y+1;\n\n          j21=(V[vjhi_x]-V[vjlo_x])/dx[1];\n          j22=(V[vjhi_y]-V[vjlo_y])/dx[1];\n          j23=(V[vjhi_z]-V[vjlo_z])/dx[1];\n          }\n\n        T j31=((T)0), j32=((T)0), j33=((T)0);\n        if (kok)\n          {\n          size_t vklo_x=3*idx.Index(i,j,k-1);\n          size_t vklo_y=vklo_x+1;\n          size_t vklo_z=vklo_y+1;\n\n          size_t vkhi_x=3*idx.Index(i,j,k+1);\n          size_t vkhi_y=vkhi_x+1;\n          size_t vkhi_z=vkhi_y+1;\n\n          j31=(V[vkhi_x]-V[vklo_x])/dx[2];\n          j32=(V[vkhi_y]-V[vklo_y])/dx[2];\n          j33=(V[vkhi_z]-V[vklo_z])/dx[2];\n          }\n\n        Matrix<T,3,3> J;\n        J <<\n          j11, j12, j13,\n          j21, j22, j23,\n          j31, j32, j33;\n\n        // construct pressure corrected hessian\n        Matrix<T,3,3> S=0.5*(J+J.transpose());\n        Matrix<T,3,3> W=0.5*(J-J.transpose());\n        Matrix<T,3,3> HP=S*S+W*W;\n\n        // compute eigen values, lambda\n        Matrix<T,3,1> e;\n        SelfAdjointEigenSolver<Matrix<T,3,3> >solver(HP,false);\n        e=solver.eigenvalues();  // input array bounds.\n\n        const size_t pi=_idx.Index(_i,_j,_k);\n        /*\n        const size_t vi=3*pi;\n        const size_t vj=vi+1;\n        const size_t vk=vi+2;\n        */\n\n        // extract lambda-2\n        slowSort(e.data(),0,3);\n        L2[pi]=e(1,0);\n        }\n      }\n    }\n}\n\n// input  -> patch input array is defined on\n// output -> patch outpu array is defined on\n// dX     -> grid spacing triple\n// V      -> vector field\n// L      -> second eigenvalues (lambda-2) of the corrected pressure hessian\n//*****************************************************************************\ntemplate <typename TP, typename TD>\nvoid Lambda2(int *input, int *output, TP *x, TP *y, TP *z, TD *V, TD *L2)\n{\n  // input array bounds.\n  const int ni=input[1]-input[0]+1;\n  const int nj=input[3]-input[2]+1;\n  const int ninj=ni*nj;\n\n  // output array bounds\n  const int _ni=output[1]-output[0]+1;\n  const int _nj=output[3]-output[2]+1;\n  const int _ninj=_ni*_nj;\n\n  // loop over output in patch coordinates (both patches are in the same space)\n  for (int r=output[4]; r<=output[5]; ++r)\n    {\n    for (int q=output[2]; q<=output[3]; ++q)\n      {\n      for (int p=output[0]; p<=output[1]; ++p)\n        {\n        const TD dx[3] = {\n            ((TD)(x[p+1]-x[p-1])),\n            ((TD)(y[q+1]-y[q-1])),\n            ((TD)(z[r+1]-z[r-1]))};\n\n        // output array indices\n        const int _i=p-output[0];\n        const int _j=q-output[2];\n        const int _k=r-output[4];\n        // index into output array;\n        const int pi=_k*_ninj+_j*_ni+_i;\n\n        // input array indices\n        const int i=p-input[0];\n        const int j=q-input[2];\n        const int k=r-input[4];\n        // stencil\n        const int vilo=3*(k*ninj+j*ni+(i-1));\n        const int vihi=3*(k*ninj+j*ni+(i+1));\n        const int vjlo=3*(k*ninj+(j-1)*ni+i);\n        const int vjhi=3*(k*ninj+(j+1)*ni+i);\n        const int vklo=3*((k-1)*ninj+j*ni+i);\n        const int vkhi=3*((k+1)*ninj+j*ni+i);\n\n        // J: gradient velocity tensor, (jacobian)\n        Matrix<TD,3,3> J;\n        J <<\n          (V[vihi]-V[vilo])/dx[0], (V[vihi+1]-V[vilo+1])/dx[0], V[vihi+2]-V[vilo+2]/dx[0],\n          (V[vjhi]-V[vjlo])/dx[1], (V[vjhi+1]-V[vjlo+1])/dx[1], V[vjhi+2]-V[vjlo+2]/dx[1],\n          (V[vkhi]-V[vklo])/dx[2], (V[vkhi+1]-V[vklo+1])/dx[2], V[vkhi+2]-V[vklo+2]/dx[2];\n\n        // construct pressure corrected hessian\n        Matrix<TD,3,3> S=((TD)0.5)*(J+J.transpose());\n        Matrix<TD,3,3> W=((TD)0.5)*(J-J.transpose());\n        Matrix<TD,3,3> HP=S*S+W*W;\n\n        // compute eigen values, lambda\n        Matrix<TD,3,1> e;\n        SelfAdjointEigenSolver<Matrix<TD,3,3> >solver(HP,false);\n        e=solver.eigenvalues();\n\n        // extract lambda-2\n        slowSort(e.data(),0,3);\n        L2[pi]=e(1,0);\n        L2[pi]=(((L2[pi]>=((TD)-1E-5))&&(L2[pi]<=((TD)1E-5)))?TD(0):L2[pi]);\n        // TODO -- this is probably needed because of discrete particle\n        // noise, as such it should not be used unless it's needed.\n        }\n      }\n    }\n}\n\n// input  -> patch input array is defined on\n// output -> patch outpu array is defined on\n// dX     -> grid spacing triple\n// V      -> vector field\n// D      -> divergence\n//*****************************************************************************\ntemplate <typename T>\nvoid Divergence(\n      int *input,\n      int *output,\n      int mode,\n      double *dX,\n      T *V,\n      T *D)\n{\n  // input array bounds.\n  const int ni=input[1]-input[0]+1;\n  const int nj=input[3]-input[2]+1;\n  const int nk=input[5]-input[4]+1;\n  FlatIndex idx(ni,nj,nk,mode);\n\n  const int iok=(ni<3?0:1);\n  const int jok=(nj<3?0:1);\n  const int kok=(nk<3?0:1);\n\n  // output array bounds\n  const int _ni=output[1]-output[0]+1;\n  const int _nj=output[3]-output[2]+1;\n  const int _nk=output[5]-output[4]+1;\n  FlatIndex _idx(_ni,_nj,_nk,mode);\n\n  // stencil deltas\n  const T dx[3]={\n      ((T)dX[0])*((T)2),\n      ((T)dX[1])*((T)2),\n      ((T)dX[2])*((T)2)};\n\n  // loop over output in patch coordinates (both patches are in the same space)\n  for (int r=output[4]; r<=output[5]; ++r)\n    {\n    const int  k=r-input[4];\n    const int _k=r-output[4];\n\n    for (int q=output[2]; q<=output[3]; ++q)\n      {\n      const int  j=q-input[2];\n      const int _j=q-output[2];\n\n      for (int p=output[0]; p<=output[1]; ++p)\n        {\n        const int  i=p-input[0];\n        const int _i=p-output[0];\n        const size_t _pi=_idx.Index(_i,_j,_k);\n\n        //      __   ->\n        //  D = \\/ . V\n        D[_pi]=((T)0);\n        if (iok)\n          {\n          size_t vilo_x=3*idx.Index(i-1,j,k);\n          size_t vihi_x=3*idx.Index(i+1,j,k);\n          D[_pi] += (V[vihi_x]-V[vilo_x])/dx[0];\n          }\n\n        if (jok)\n          {\n          size_t vjlo_y=3*idx.Index(i,j-1,k)+1;\n          size_t vjhi_y=3*idx.Index(i,j+1,k)+1;\n          D[_pi] += (V[vjhi_y]-V[vjlo_y])/dx[1];\n          }\n\n        if (kok)\n          {\n          size_t vklo_z=3*idx.Index(i,j,k-1)+2;\n          size_t vkhi_z=3*idx.Index(i,j,k+1)+2;\n          D[_pi] += (V[vkhi_z]-V[vklo_z])/dx[2];\n          }\n        }\n      }\n    }\n}\n\n// input  -> patch input array is defined on\n// output -> patch outpu array is defined on\n// dX     -> grid spacing triple\n// V      -> vector field\n// D      -> divergence\n//*****************************************************************************\ntemplate <typename TP, typename TD>\nvoid Divergence(\n      int *input,\n      int *output,\n      TP *x,\n      TP *y,\n      TP *z,\n      TD *V,\n      TD *D)\n{\n  // input array bounds.\n  const int ni=input[1]-input[0]+1;\n  const int nj=input[3]-input[2]+1;\n  const int ninj=ni*nj;\n\n  // output array bounds\n  const int _ni=output[1]-output[0]+1;\n  const int _nj=output[3]-output[2]+1;\n  const int _ninj=_ni*_nj;\n\n  // loop over output in patch coordinates (both patches are in the same space)\n  for (int r=output[4]; r<=output[5]; ++r)\n    {\n    for (int q=output[2]; q<=output[3]; ++q)\n      {\n      for (int p=output[0]; p<=output[1]; ++p)\n        {\n        // stencil deltas\n        const TD dx[3] = {\n            ((TD)(x[p+1]-x[p-1])),\n            ((TD)(y[q+1]-y[q-1])),\n            ((TD)(z[r+1]-z[r-1]))};\n\n        // output array indices\n        const int _i=p-output[0];\n        const int _j=q-output[2];\n        const int _k=r-output[4];\n        // index into output array;\n        const int _pi=_k*_ninj+_j*_ni+_i;\n\n        // input array indices\n        const int i=p-input[0];\n        const int j=q-input[2];\n        const int k=r-input[4];\n        // stencil into the input array\n        const int vilo=3*(k*ninj+j*ni+(i-1));\n        const int vihi=3*(k*ninj+j*ni+(i+1));\n        const int vjlo=3*(k*ninj+(j-1)*ni+i);\n        const int vjhi=3*(k*ninj+(j+1)*ni+i);\n        const int vklo=3*((k-1)*ninj+j*ni+i);\n        const int vkhi=3*((k+1)*ninj+j*ni+i);\n\n        //      __   ->\n        //  D = \\/ . V\n        D[_pi]\n           = (V[vihi  ] - V[vilo  ])/dx[0]\n           + (V[vjhi+1] - V[vjlo+1])/dx[1]\n           + (V[vkhi+2] - V[vklo+2])/dx[2];\n        }\n      }\n    }\n}\n\n// input  -> patch input array is defined on\n// output -> patch outpu array is defined on\n// dX     -> grid spacing triple\n// S      -> scalar field\n// L      -> laplacian\n//*****************************************************************************\ntemplate <typename T>\nvoid Laplacian(\n      int *input,\n      int *output,\n      int mode,\n      double *dX,\n      T *S,\n      T *L)\n{\n  // input array bounds.\n  const int ni=input[1]-input[0]+1;\n  const int nj=input[3]-input[2]+1;\n  const int nk=input[5]-input[4]+1;\n  FlatIndex idx(ni,nj,nk,mode);\n\n  const int iok=(ni<3?0:1);\n  const int jok=(nj<3?0:1);\n  const int kok=(nk<3?0:1);\n\n  // output array bounds\n  const int _ni=output[1]-output[0]+1;\n  const int _nj=output[3]-output[2]+1;\n  const int _nk=output[5]-output[4]+1;\n  FlatIndex _idx(_ni,_nj,_nk,mode);\n\n  // stencil deltas\n  const T dx2[3]={\n      ((T)dX[0])*((T)dX[0]),\n      ((T)dX[1])*((T)dX[1]),\n      ((T)dX[2])*((T)dX[2])};\n\n  // loop over output in patch coordinates (both patches are in the same space)\n  for (int r=output[4]; r<=output[5]; ++r)\n    {\n    const int  k=r-input[4];\n    const int _k=r-output[4];\n\n    for (int q=output[2]; q<=output[3]; ++q)\n      {\n      const int  j=q-input[2];\n      const int _j=q-output[2];\n\n      for (int p=output[0]; p<=output[1]; ++p)\n        {\n        const int _i=p-output[0];\n        const size_t _pi=_idx.Index(_i,_j,_k);\n\n        const int  i=p-input[0];\n        const size_t  pi=idx.Index(i,j,k);\n\n        //      __2\n        //  L = \\/ S\n        L[_pi]=((T)0);\n        if (iok)\n          {\n          const size_t ilo=idx.Index(i-1,j,k);\n          const size_t ihi=idx.Index(i+1,j,k);\n          L[_pi] += (S[ihi] + S[ilo] - ((T)2)*S[pi])/dx2[0];\n          }\n\n        if (jok)\n          {\n          const size_t jlo=idx.Index(i,j-1,k);\n          const size_t jhi=idx.Index(i,j+1,k);\n          L[_pi] += (S[jhi] + S[jlo] - ((T)2)*S[pi])/dx2[1];\n          }\n\n        if (kok)\n          {\n          const size_t klo=idx.Index(i,j,k-1);\n          const size_t khi=idx.Index(i,j,k+1);\n          L[_pi] += (S[khi] + S[klo] - ((T)2)*S[pi])/dx2[2];\n          }\n        }\n      }\n    }\n}\n\n// input  -> patch input array is defined on\n// output -> patch outpu array is defined on\n// dX     -> grid spacing triple\n// V      -> vector field\n// W      -> vector curl\n//*****************************************************************************\ntemplate <typename TP, typename TD>\nvoid Laplacian(\n      int *input,\n      int *output,\n      TP *x,\n      TP *y,\n      TP *z,\n      TD *S,\n      TD *L)\n{\n  // input array bounds.\n  const int ni=input[1]-input[0]+1;\n  const int nj=input[3]-input[2]+1;\n  const int ninj=ni*nj;\n\n  // output array bounds\n  const int _ni=output[1]-output[0]+1;\n  const int _nj=output[3]-output[2]+1;\n  const int _ninj=_ni*_nj;\n\n  // loop over output in patch coordinates (both patches are in the same space)\n  for (int r=output[4]; r<=output[5]; ++r)\n    {\n    for (int q=output[2]; q<=output[3]; ++q)\n      {\n      for (int p=output[0]; p<=output[1]; ++p)\n        {\n        // stencil deltas\n        TD dx2[3] = {\n            ((TD)(x[p+1]-x[p-1])),\n            ((TD)(y[q+1]-y[q-1])),\n            ((TD)(z[r+1]-z[r-1]))};\n\n        dx2[0]*=dx2[0];\n        dx2[1]*=dx2[1];\n        dx2[2]*=dx2[2];\n\n        // output array indices\n        const int _i=p-output[0];\n        const int _j=q-output[2];\n        const int _k=r-output[4];\n        // index into output array;\n        const int _pi=_k*_ninj+_j*_ni+_i;\n\n        // input array indices\n        const int i=p-input[0];\n        const int j=q-input[2];\n        const int k=r-input[4];\n        //\n        const int pi=k*ninj+j*ni+i;\n\n        // stencil into the input array\n        const int ilo=k*ninj+j*ni+(i-1);\n        const int ihi=k*ninj+j*ni+(i+1);\n        const int jlo=k*ninj+(j-1)*ni+i;\n        const int jhi=k*ninj+(j+1)*ni+i;\n        const int klo=(k-1)*ninj+j*ni+i;\n        const int khi=(k+1)*ninj+j*ni+i;\n\n        //      __2\n        //  L = \\/ S\n        L[_pi]\n           = (S[ihi] + S[ilo] - TD(2)*S[pi])/dx2[0]\n           + (S[jhi] + S[jlo] - TD(2)*S[pi])/dx2[1]\n           + (S[khi] + S[klo] - TD(2)*S[pi])/dx2[2];\n        }\n      }\n    }\n}\n\n// input  -> patch input array is defined on\n// output -> patch outpu array is defined on\n// dX     -> grid spacing triple\n// S      -> scalar field\n// G      -> gradient\n//*****************************************************************************\ntemplate <typename T>\nvoid Gradient(\n      int *input,\n      int *output,\n      int mode,\n      double *dX,\n      T *S,\n      T *Gx,\n      T *Gy,\n      T *Gz)\n{\n  // input array bounds.\n  const int ni=input[1]-input[0]+1;\n  const int nj=input[3]-input[2]+1;\n  const int nk=input[5]-input[4]+1;\n  FlatIndex idx(ni,nj,nk,mode);\n\n  const int iok=(ni<3?0:1);\n  const int jok=(nj<3?0:1);\n  const int kok=(nk<3?0:1);\n\n  // output array bounds\n  const int _ni=output[1]-output[0]+1;\n  const int _nj=output[3]-output[2]+1;\n  const int _nk=output[5]-output[4]+1;\n  FlatIndex _idx(_ni,_nj,_nk,mode);\n\n  // stencil deltas\n  const T dx[3]={\n      ((T)dX[0])*((T)2),\n      ((T)dX[1])*((T)2),\n      ((T)dX[2])*((T)2)};\n\n  // loop over output in patch coordinates (both patches are in the same space)\n  for (int r=output[4]; r<=output[5]; ++r)\n    {\n    const int  k=r-input[4];\n    const int _k=r-output[4];\n\n    for (int q=output[2]; q<=output[3]; ++q)\n      {\n      const int  j=q-input[2];\n      const int _j=q-output[2];\n\n      for (int p=output[0]; p<=output[1]; ++p)\n        {\n        const int  i=p-input[0];\n        const int _i=p-output[0];\n        const size_t _pi=_idx.Index(_i,_j,_k);\n\n        //      __\n        //  G = \\/ S\n        Gx[_pi]=((T)0);\n        Gy[_pi]=((T)0);\n        Gz[_pi]=((T)0);\n        if (iok)\n          {\n          size_t ilo=idx.Index(i-1,j,k);\n          size_t ihi=idx.Index(i+1,j,k);\n          Gx[_pi] = T((S[ihi]-S[ilo])/dx[0]);\n          }\n\n        if (jok)\n          {\n          size_t jlo=idx.Index(i,j-1,k);\n          size_t jhi=idx.Index(i,j+1,k);\n          Gy[_pi] = T((S[jhi]-S[jlo])/dx[1]);\n          }\n\n        if (kok)\n          {\n          size_t klo=idx.Index(i,j,k-1);\n          size_t khi=idx.Index(i,j,k+1);\n          Gz[_pi] = T((S[khi]-S[klo])/dx[2]);\n          }\n        }\n      }\n    }\n}\n\n// input  -> patch input array is defined on\n// output -> patch outpu array is defined on\n// dX     -> grid spacing triple\n// S      -> scalar field\n// G      -> gardient\n//*****************************************************************************\ntemplate <typename TP, typename TD>\nvoid Gradient(\n      int *input,\n      int *output,\n      TP *x,\n      TP *y,\n      TP *z,\n      TD *S,\n      TD *Gx,\n      TD *Gy,\n      TD *Gz)\n{\n  // input array bounds.\n  const int ni=input[1]-input[0]+1;\n  const int nj=input[3]-input[2]+1;\n  const int ninj=ni*nj;\n\n  // output array bounds\n  const int _ni=output[1]-output[0]+1;\n  const int _nj=output[3]-output[2]+1;\n  const int _ninj=_ni*_nj;\n\n  // loop over output in patch coordinates (both patches are in the same space)\n  for (int r=output[4]; r<=output[5]; ++r)\n    {\n    for (int q=output[2]; q<=output[3]; ++q)\n      {\n      for (int p=output[0]; p<=output[1]; ++p)\n        {\n        // stencil deltas\n        const TP dx[3]\n          = {x[p+1]-x[p-1],y[q+1]-y[q-1],z[r+1]-z[r-1]};\n\n        // output array indices\n        const int _i=p-output[0];\n        const int _j=q-output[2];\n        const int _k=r-output[4];\n        // index into output array;\n        const int _pi=_k*_ninj+_j*_ni+_i;\n\n        // input array indices\n        const int i=p-input[0];\n        const int j=q-input[2];\n        const int k=r-input[4];\n        // stencil into the input array\n        const int ilo=k*ninj+j*ni+(i-1);\n        const int ihi=k*ninj+j*ni+(i+1);\n        const int jlo=k*ninj+(j-1)*ni+i;\n        const int jhi=k*ninj+(j+1)*ni+i;\n        const int klo=(k-1)*ninj+j*ni+i;\n        const int khi=(k+1)*ninj+j*ni+i;\n\n        //      __\n        //  G = \\/ S\n        Gx[_pi] = (S[ihi]-S[ilo])/dx[0];\n        Gy[_pi] = (S[jhi]-S[jlo])/dx[1];\n        Gz[_pi] = (S[khi]-S[klo])/dx[2];\n        }\n      }\n    }\n}\n\n// input  -> patch input array is defined on\n// output -> patch outpu array is defined on\n// dX     -> grid spacing triple\n// V      -> vector field\n// J      -> vector gradient (Jaccobian)\n//*****************************************************************************\ntemplate <typename T>\nvoid Gradient(\n      int *input,\n      int *output,\n      int mode,\n      double *dX,\n      T *V,\n      T *Jxx,\n      T *Jxy,\n      T *Jxz,\n      T *Jyx,\n      T *Jyy,\n      T *Jyz,\n      T *Jzx,\n      T *Jzy,\n      T *Jzz)\n{\n  // input array bounds.\n  const int ni=input[1]-input[0]+1;\n  const int nj=input[3]-input[2]+1;\n  const int nk=input[5]-input[4]+1;\n  FlatIndex idx(ni,nj,nk,mode);\n\n  const int iok=(ni<3?0:1);\n  const int jok=(nj<3?0:1);\n  const int kok=(nk<3?0:1);\n\n  // output array bounds\n  const int _ni=output[1]-output[0]+1;\n  const int _nj=output[3]-output[2]+1;\n  const int _nk=output[5]-output[4]+1;\n  FlatIndex _idx(_ni,_nj,_nk,mode);\n\n  // stencil deltas\n  const T dx[3]={\n      ((T)dX[0])*((T)2),\n      ((T)dX[1])*((T)2),\n      ((T)dX[2])*((T)2)};\n\n  // loop over output in patch coordinates (both patches are in the same space)\n  for (int r=output[4]; r<=output[5]; ++r)\n    {\n    const int  k=r-input[4];\n    const int _k=r-output[4];\n\n    for (int q=output[2]; q<=output[3]; ++q)\n      {\n      const int  j=q-input[2];\n      const int _j=q-output[2];\n\n      for (int p=output[0]; p<=output[1]; ++p)\n        {\n        const int  i=p-input[0];\n        const int _i=p-output[0];\n\n        const size_t _pi=_idx.Index(_i,_j,_k);\n\n        // J: gradient tensor, (jacobian)\n        Jxx[_pi]=((T)0);\n        Jxy[_pi]=((T)0);\n        Jxz[_pi]=((T)0);\n        if (iok)\n          {\n          size_t vilo_x=3*idx.Index(i-1,j,k);\n          size_t vilo_y=vilo_x+1;\n          size_t vilo_z=vilo_y+1;\n\n          size_t vihi_x=3*idx.Index(i+1,j,k);\n          size_t vihi_y=vihi_x+1;\n          size_t vihi_z=vihi_y+1;\n\n          Jxx[_pi] = (V[vihi_x]-V[vilo_x])/dx[0];;\n          Jxy[_pi] = (V[vihi_y]-V[vilo_y])/dx[0];;\n          Jxz[_pi] = (V[vihi_z]-V[vilo_z])/dx[0];;\n          }\n\n        Jyx[_pi]=((T)0);\n        Jyy[_pi]=((T)0);\n        Jyz[_pi]=((T)0);\n        if (jok)\n          {\n          size_t vjlo_x=3*idx.Index(i,j-1,k);\n          size_t vjlo_y=vjlo_x+1;\n          size_t vjlo_z=vjlo_y+1;\n\n          size_t vjhi_x=3*idx.Index(i,j+1,k);\n          size_t vjhi_y=vjhi_x+1;\n          size_t vjhi_z=vjhi_y+1;\n\n          Jyx[_pi] = (V[vjhi_x]-V[vjlo_x])/dx[1];;\n          Jyy[_pi] = (V[vjhi_y]-V[vjlo_y])/dx[1];;\n          Jyz[_pi] = (V[vjhi_z]-V[vjlo_z])/dx[1];;\n          }\n\n        Jzx[_pi]=((T)0);\n        Jzy[_pi]=((T)0);\n        Jzz[_pi]=((T)0);\n        if (kok)\n          {\n          size_t vklo_x=3*idx.Index(i,j,k-1);\n          size_t vklo_y=vklo_x+1;\n          size_t vklo_z=vklo_y+1;\n\n          size_t vkhi_x=3*idx.Index(i,j,k+1);\n          size_t vkhi_y=vkhi_x+1;\n          size_t vkhi_z=vkhi_y+1;\n\n          Jzx[_pi] = (V[vkhi_x]-V[vklo_x])/dx[2];;\n          Jzy[_pi] = (V[vkhi_y]-V[vklo_y])/dx[2];;\n          Jzz[_pi] = (V[vkhi_z]-V[vklo_z])/dx[2];;\n          }\n        }\n      }\n    }\n}\n\n// input  -> patch input array is defined on\n// output -> patch outpu array is defined on\n// dX     -> grid spacing triple\n// V      -> vector field\n// Q      ->\n//*****************************************************************************\ntemplate <typename T>\nvoid QCriteria(\n      int *input,\n      int *output,\n      int mode,\n      double *dX,\n      T *V,\n      T *Q)\n{\n  // input array bounds.\n  const int ni=input[1]-input[0]+1;\n  const int nj=input[3]-input[2]+1;\n  const int nk=input[5]-input[4]+1;\n  FlatIndex idx(ni,nj,nk,mode);\n\n  const int iok=(ni<3?0:1);\n  const int jok=(nj<3?0:1);\n  const int kok=(nk<3?0:1);\n\n  // output array bounds\n  const int _ni=output[1]-output[0]+1;\n  const int _nj=output[3]-output[2]+1;\n  const int _nk=output[5]-output[4]+1;\n  FlatIndex _idx(_ni,_nj,_nk,mode);\n\n  // stencil deltas\n  const T dx[3]={\n      ((T)dX[0])*((T)2),\n      ((T)dX[1])*((T)2),\n      ((T)dX[2])*((T)2)};\n\n  // loop over output in patch coordinates (both patches are in the same space)\n  for (int r=output[4]; r<=output[5]; ++r)\n    {\n    const int  k=r-input[4];\n    const int _k=r-output[4];\n\n    for (int q=output[2]; q<=output[3]; ++q)\n      {\n      const int  j=q-input[2];\n      const int _j=q-output[2];\n\n      for (int p=output[0]; p<=output[1]; ++p)\n        {\n        const int  i=p-input[0];\n        const int _i=p-output[0];\n\n        const size_t _pi=_idx.Index(_i,_j,_k);\n\n        // J: gradient tensor, (jacobian)\n        T Jxx=((T)0);\n        T Jxy=((T)0);\n        T Jxz=((T)0);\n        if (iok)\n          {\n          size_t vilo_x=3*idx.Index(i-1,j,k);\n          size_t vilo_y=vilo_x+1;\n          size_t vilo_z=vilo_y+1;\n\n          size_t vihi_x=3*idx.Index(i+1,j,k);\n          size_t vihi_y=vihi_x+1;\n          size_t vihi_z=vihi_y+1;\n\n          Jxx = (V[vihi_x]-V[vilo_x])/dx[0];;\n          Jxy = (V[vihi_y]-V[vilo_y])/dx[0];;\n          Jxz = (V[vihi_z]-V[vilo_z])/dx[0];;\n          }\n\n        T Jyx=((T)0);\n        T Jyy=((T)0);\n        T Jyz=((T)0);\n        if (jok)\n          {\n          size_t vjlo_x=3*idx.Index(i,j-1,k);\n          size_t vjlo_y=vjlo_x+1;\n          size_t vjlo_z=vjlo_y+1;\n\n          size_t vjhi_x=3*idx.Index(i,j+1,k);\n          size_t vjhi_y=vjhi_x+1;\n          size_t vjhi_z=vjhi_y+1;\n\n          Jyx = (V[vjhi_x]-V[vjlo_x])/dx[1];;\n          Jyy = (V[vjhi_y]-V[vjlo_y])/dx[1];;\n          Jyz = (V[vjhi_z]-V[vjlo_z])/dx[1];;\n          }\n\n        T Jzx=((T)0);\n        T Jzy=((T)0);\n        T Jzz=((T)0);\n        if (kok)\n          {\n          size_t vklo_x=3*idx.Index(i,j,k-1);\n          size_t vklo_y=vklo_x+1;\n          size_t vklo_z=vklo_y+1;\n\n          size_t vkhi_x=3*idx.Index(i,j,k+1);\n          size_t vkhi_y=vkhi_x+1;\n          size_t vkhi_z=vkhi_y+1;\n\n          Jzx = (V[vkhi_x]-V[vklo_x])/dx[2];;\n          Jzy = (V[vkhi_y]-V[vklo_y])/dx[2];;\n          Jzz = (V[vkhi_z]-V[vklo_z])/dx[2];;\n          }\n\n        T divV=Jxx+Jyy+Jzz;\n        Q[_pi]\n          = (divV*divV - (Jxx*Jxx + Jxy*Jyx + Jxz*Jzx\n                           + Jyx*Jxy + Jyy*Jyy + Jyz*Jzy\n                             + Jzx*Jxz + Jzy*Jyz + Jzz*Jzz))/((T)2);\n        }\n      }\n    }\n}\n\n\n// input  -> patch input array is defined on\n// output -> patch outpu array is defined on\n// dX     -> grid spacing triple\n// V      -> vector field\n// M      -> matrix arrays\n// W      -> result\n//*****************************************************************************\ntemplate <typename T>\nvoid VectorMatrixMul(\n      int *input,\n      int *output,\n      int mode,\n      T *V,\n      T *Mxx,\n      T *Mxy,\n      T *Mxz,\n      T *Myx,\n      T *Myy,\n      T *Myz,\n      T *Mzx,\n      T *Mzy,\n      T *Mzz,\n      T *W)\n{\n  // input array bounds.\n  const int ni=input[1]-input[0]+1;\n  const int nj=input[3]-input[2]+1;\n  const int nk=input[5]-input[4]+1;\n  FlatIndex idx(ni,nj,nk,mode);\n\n  // output array bounds\n  const int _ni=output[1]-output[0]+1;\n  const int _nj=output[3]-output[2]+1;\n  const int _nk=output[5]-output[4]+1;\n  FlatIndex _idx(_ni,_nj,_nk,mode);\n\n  // loop over output in patch coordinates (both patches are in the same space)\n  for (int r=output[4]; r<=output[5]; ++r)\n    {\n    const int  k=r-input[4];\n    const int _k=r-output[4];\n\n    for (int q=output[2]; q<=output[3]; ++q)\n      {\n      const int  j=q-input[2];\n      const int _j=q-output[2];\n\n      for (int p=output[0]; p<=output[1]; ++p)\n        {\n        const int  i=p-input[0];\n        const int _i=p-output[0];\n\n        const size_t _pi=_idx.Index(_i,_j,_k);\n        const size_t  pi= 3*idx.Index( i, j, k);\n\n        W[_pi  ] = V[pi  ]*Mxx[_pi] + V[pi+1]*Myx[_pi] + V[pi+2]*Mzx[_pi];\n        W[_pi+1] = V[pi+1]*Mxy[_pi] + V[pi+1]*Myy[_pi] + V[pi+2]*Mzy[_pi];\n        W[_pi+2] = V[pi+2]*Mxz[_pi] + V[pi+1]*Myz[_pi] + V[pi+2]*Mzz[_pi];\n        }\n      }\n    }\n}\n\n// input  -> patch input array is defined on\n// output -> patch outpu array is defined on\n// V      -> vector field\n// W      -> result\n//*****************************************************************************\ntemplate <typename T>\nvoid Normalize(\n      int *input,\n      int *output,\n      int mode,\n      T *V,\n      T *W)\n{\n  // input array bounds.\n  const int ni=input[1]-input[0]+1;\n  const int nj=input[3]-input[2]+1;\n  const int nk=input[5]-input[4]+1;\n  FlatIndex idx(ni,nj,nk,mode);\n\n  // output array bounds\n  const int _ni=output[1]-output[0]+1;\n  const int _nj=output[3]-output[2]+1;\n  const int _nk=output[5]-output[4]+1;\n  FlatIndex _idx(_ni,_nj,_nk,mode);\n\n  // loop over output in patch coordinates (both patches are in the same space)\n  for (int r=output[4]; r<=output[5]; ++r)\n    {\n    const int  k=r-input[4];\n    const int _k=r-output[4];\n\n    for (int q=output[2]; q<=output[3]; ++q)\n      {\n      const int  j=q-input[2];\n      const int _j=q-output[2];\n\n      for (int p=output[0]; p<=output[1]; ++p)\n        {\n        const int  i=p-input[0];\n        const int _i=p-output[0];\n\n        const size_t _pi=_idx.Index(_i,_j,_k);\n        const size_t  pi= 3*idx.Index( i, j, k);\n\n        T mv = ((T)sqrt(V[pi]*V[pi]+V[pi+1]*V[pi+1]+V[pi+2]*V[pi+2]));\n\n        W[_pi  ] /= mv;\n        W[_pi+1] /= mv;\n        W[_pi+2] /= mv;\n        }\n      }\n    }\n}\n\n//*****************************************************************************\ntemplate <typename T>\nvoid EigenvalueDiagnostic(\n      int *input,\n      int *output,\n      int mode,\n      double *dX,\n      T *V,\n      T *L)\n{\n  // input array bounds.\n  const int ni=input[1]-input[0]+1;\n  const int nj=input[3]-input[2]+1;\n  const int nk=input[5]-input[4]+1;\n  FlatIndex idx(ni,nj,nk,mode);\n\n  const int iok=(ni<3?0:1);\n  const int jok=(nj<3?0:1);\n  const int kok=(nk<3?0:1);\n\n  // output array bounds\n  const int _ni=output[1]-output[0]+1;\n  const int _nj=output[3]-output[2]+1;\n  const int _nk=output[5]-output[4]+1;\n  FlatIndex _idx(_ni,_nj,_nk,mode);\n\n  // stencil deltas\n  const T dx[3]={\n      ((T)dX[0])*((T)2),\n      ((T)dX[1])*((T)2),\n      ((T)dX[2])*((T)2)};\n\n  // loop over output in patch coordinates (both patches are in the same space)\n  for (int r=output[4]; r<=output[5]; ++r)\n    {\n    const int _k=r-output[4];\n    const int  k=r-input[4];\n    for (int q=output[2]; q<=output[3]; ++q)\n      {\n      const int _j=q-output[2];\n      const int  j=q-input[2];\n      for (int p=output[0]; p<=output[1]; ++p)\n        {\n        const int _i=p-output[0];\n        const int  i=p-input[0];\n\n        // J: gradient velocity tensor, (jacobian)\n        T j11=((T)0), j12=((T)0), j13=((T)0);\n        if (iok)\n          {\n          size_t vilo_x=3*idx.Index(i-1,j,k);\n          size_t vilo_y=vilo_x+1;\n          size_t vilo_z=vilo_y+1;\n\n          size_t vihi_x=3*idx.Index(i+1,j,k);\n          size_t vihi_y=vihi_x+1;\n          size_t vihi_z=vihi_y+1;\n\n          j11=(V[vihi_x]-V[vilo_x])/dx[0];\n          j12=(V[vihi_y]-V[vilo_y])/dx[0];\n          j13=(V[vihi_z]-V[vilo_z])/dx[0];\n          }\n\n        T j21=((T)0), j22=((T)0), j23=((T)0);\n        if (jok)\n          {\n          size_t vjlo_x=3*idx.Index(i,j-1,k);\n          size_t vjlo_y=vjlo_x+1;\n          size_t vjlo_z=vjlo_y+1;\n\n          size_t vjhi_x=3*idx.Index(i,j+1,k);\n          size_t vjhi_y=vjhi_x+1;\n          size_t vjhi_z=vjhi_y+1;\n\n          j21=(V[vjhi_x]-V[vjlo_x])/dx[1];\n          j22=(V[vjhi_y]-V[vjlo_y])/dx[1];\n          j23=(V[vjhi_z]-V[vjlo_z])/dx[1];\n          }\n\n        T j31=((T)0), j32=((T)0), j33=((T)0);\n        if (kok)\n          {\n          size_t vklo_x=3*idx.Index(i,j,k-1);\n          size_t vklo_y=vklo_x+1;\n          size_t vklo_z=vklo_y+1;\n\n          size_t vkhi_x=3*idx.Index(i,j,k+1);\n          size_t vkhi_y=vkhi_x+1;\n          size_t vkhi_z=vkhi_y+1;\n\n          j31=(V[vkhi_x]-V[vklo_x])/dx[2];\n          j32=(V[vkhi_y]-V[vklo_y])/dx[2];\n          j33=(V[vkhi_z]-V[vklo_z])/dx[2];\n          }\n\n        Matrix<T,3,3> J;\n        J <<\n          j11, j12, j13,\n          j21, j22, j23,\n          j31, j32, j33;\n\n        // compute eigen values, lambda\n        Matrix<std::complex<T>,3,1> e;\n        EigenSolver<Matrix<T,3,3> >solver(J,false);\n        e=solver.eigenvalues();\n\n        std::complex<T> &e1 = e(0);\n        std::complex<T> &e2 = e(1);\n        std::complex<T> &e3 = e(2);\n\n        // see Haimes, and Kenwright VGT and Feature Extraction fig 2\n        // 0 - repelling node\n        // 1 - type 1 saddle\n        // 2 - type 2 saddle\n        // 3 - attracting node\n        // 4 - repelling spiral\n        // 5 - type 1 saddle spiral\n        // 6 - type 2 saddle spiral\n        // 7 - attracting spiral\n        const size_t pi=_idx.Index(_i,_j,_k);\n        if (IsComplex(e1)||IsComplex(e2)||IsComplex(e3))\n          {\n          // spiral flow\n          // one real , one conjugate pair\n\n          int realIdx;\n          int imagIdx1;\n          //int imagIdx2;\n\n          if (IsReal(e1))\n            {\n            realIdx=0;\n            imagIdx1=1;\n            //imagIdx2=2;\n            }\n          else\n          if (IsReal(e2))\n            {\n            realIdx=1;\n            imagIdx1=0;\n            //imagIdx2=2;\n            }\n          else\n          if (IsReal(e3))\n            {\n            realIdx=2;\n            imagIdx1=0;\n            //imagIdx2=1;\n            }\n          else\n            {\n            std::cerr << \"No real eigne value.\" << std::endl;\n            return;\n            }\n\n          bool attracting=(real(e(realIdx))<((T)0));\n          bool type1=(imag(e(imagIdx1))<((T)0));\n\n          if (type1 && attracting)\n            {\n            L[pi]=7;\n            }\n          else\n          if (!type1 && attracting)\n            {\n            L[pi]=5;\n            }\n          else\n          if (type1 && !attracting)\n            {\n            L[pi]=6;\n            }\n          else\n          if (!type1 && !attracting)\n            {\n            L[pi]=4;\n            }\n          }\n        else\n          {\n          // three real\n          int nAttracting=0;\n          for (int i=0; i<3; ++i)\n            {\n            if (real(e(i))<((T)0)) ++nAttracting;\n            }\n          L[pi]=((T)nAttracting);\n          }\n        }\n      }\n    }\n}\n\n#endif\n", "meta": {"hexsha": "d165135e690101ea6d191167656fd049e9114879", "size": 82129, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "Plugins/SciberQuestToolKit/SciberQuest/Numerics.hxx", "max_stars_repo_name": "JamesLinus/ParaView", "max_stars_repo_head_hexsha": "d0dd28e0527c230044f1891db2d8ad0170a04af0", "max_stars_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-04-22T09:09:18.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-22T09:09:18.000Z", "max_issues_repo_path": "Plugins/SciberQuestToolKit/SciberQuest/Numerics.hxx", "max_issues_repo_name": "JamesLinus/ParaView", "max_issues_repo_head_hexsha": "d0dd28e0527c230044f1891db2d8ad0170a04af0", "max_issues_repo_licenses": ["Apache-2.0", "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": "Plugins/SciberQuestToolKit/SciberQuest/Numerics.hxx", "max_forks_repo_name": "JamesLinus/ParaView", "max_forks_repo_head_hexsha": "d0dd28e0527c230044f1891db2d8ad0170a04af0", "max_forks_repo_licenses": ["Apache-2.0", "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.2161498311, "max_line_length": 135, "alphanum_fraction": 0.4720622435, "num_tokens": 27615, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.882427872638409, "lm_q2_score": 0.8006920044739461, "lm_q1q2_score": 0.7065529421465278}}
{"text": "/*\n//@HEADER\n// ************************************************************************\n//\n// tutorial1.cc\n//                     \t\t  Pressio\n//                             Copyright 2019\n//    National Technology & Engineering Solutions of Sandia, LLC (NTESS)\n//\n// Under the terms of Contract DE-NA0003525 with NTESS, the\n// U.S. Government retains certain rights in this software.\n//\n// Pressio is licensed under BSD-3-Clause terms of use:\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions\n// are met:\n//\n// 1. Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//\n// 2. Redistributions in binary form must reproduce the above copyright\n// notice, this list of conditions and the following disclaimer in the\n// documentation and/or other materials provided with the distribution.\n//\n// 3. Neither the name of the copyright holder nor the names of its\n// contributors may be used to endorse or promote products derived\n// from this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING\n// IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n// POSSIBILITY OF SUCH DAMAGE.\n//\n// Questions? Contact Francesco Rizzi (fnrizzi@sandia.gov)\n//\n// ************************************************************************\n//@HEADER\n*/\n\n#include \"pressio/solvers_linear.hpp\"\n#include \"pressio/solvers_nonlinear.hpp\"\n#include <Eigen/Core>\n\nstruct MySystem\n{\n  using scalar_type = double;\n  using state_type = Eigen::VectorXd;\n  using residual_type = state_type;\n  using jacobian_type = Eigen::SparseMatrix<scalar_type>;\n\n  residual_type createResidual() const {\n    return residual_type(2);\n  }\n\n  jacobian_type createJacobian() const {\n    return jacobian_type(2, 2);\n  }\n\n  void residual(const state_type& x,\n                residual_type& res) const\n  {\n    res(0) =  x(0)*x(0)*x(0) + x(1) - 1.0;\n    res(1) = -x(0) + x(1)*x(1)*x(1) + 1.0;\n  }\n\n  void jacobian(const state_type& x, jacobian_type& jac) const {\n    jac.coeffRef(0, 0) = 3.0*x(0)*x(0);\n    jac.coeffRef(0, 1) =  1.0;\n    jac.coeffRef(1, 0) = -1.0;\n    jac.coeffRef(1, 1) = 3.0*x(1)*x(1);\n  }\n};\n\nint main()\n{\n  namespace plog   = pressio::log;\n  namespace pls    = pressio::linearsolvers;\n  namespace pnonls = pressio::nonlinearsolvers;\n\n  plog::initialize(pressio::logto::terminal);\n  plog::setVerbosity({plog::level::info});\n\n  using problem_t  = MySystem;\n  problem_t problemObj;\n\n  using state_t    = problem_t::state_type;\n  state_t y(2);\n  y(0) = 0.001; y(1) = -0.1;\n\n  // linear solver\n  using jacobian_t = problem_t::jacobian_type;\n  using lin_solver_t = pls::Solver<pls::iterative::LSCG, jacobian_t>;\n  lin_solver_t linearSolverObj;\n  // nonlinear solvers\n  auto nonLinSolver = pnonls::create_newton_raphson(problemObj, y, linearSolverObj);\n  nonLinSolver.solve(problemObj, y);\n\n  // check solution\n  std::cout << \"Computed solution: [\"\n            << y(0) << \" \" << y(1) << \" \" << \"] \"\n            << \"Expected solution: [1., 0.] \"\n            << std::endl;\n\n  plog::finalize();\n  return 0;\n}\n", "meta": {"hexsha": "2c638248fe6cc921e779282245c107453839d485", "size": 3839, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tutorials/nonlinsolvers_newtonraphson_1.cc", "max_stars_repo_name": "Pressio/pressio-tutorials", "max_stars_repo_head_hexsha": "5762d17a8cd2990d84ccc80e1f5ba9759b55b5b9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-06T12:06:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T12:06:19.000Z", "max_issues_repo_path": "tutorials/nonlinsolvers_newtonraphson_1.cc", "max_issues_repo_name": "Pressio/pressio-tutorials", "max_issues_repo_head_hexsha": "5762d17a8cd2990d84ccc80e1f5ba9759b55b5b9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2019-09-30T11:34:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-17T20:58:46.000Z", "max_forks_repo_path": "tutorials/nonlinsolvers_newtonraphson_1.cc", "max_forks_repo_name": "Pressio/pressio-tutorials", "max_forks_repo_head_hexsha": "5762d17a8cd2990d84ccc80e1f5ba9759b55b5b9", "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": 33.0948275862, "max_line_length": 84, "alphanum_fraction": 0.662672571, "num_tokens": 987, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382094310355, "lm_q2_score": 0.8198933271118221, "lm_q1q2_score": 0.7063694289643735}}
{"text": "#include <iostream>\nusing std::cout; using std::endl;\nusing std::left; using std::fixed; using std::right; using std::scientific;\n#include <iomanip>\nusing std::setw;\nusing std::setprecision;\n#include <limits>\n\n#include <algorithm>\n#include <string>\n#include <vector>\n\n#include <boost/multiprecision/cpp_dec_float.hpp>\nusing boost::multiprecision::cpp_dec_float_50;\n\n#include <boost/random.hpp>\n#include <boost/random/exponential_distribution.hpp>\n#include <boost/random/uniform_real_distribution.hpp>\n#include <boost/lexical_cast.hpp>\n\n#include <boost/math/special_functions/beta.hpp>\n#include <boost/math/special_functions/binomial.hpp>\n#include <boost/math/special_functions/erf.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n\nvoid gen_x_signed_exp(const double r, boost::random::mt19937& rng, int N, std::vector<cpp_dec_float_50>& vec)\n{\n    boost::random::uniform_real_distribution<> runif;\n    boost::random::exponential_distribution<cpp_dec_float_50> rexp(r);\n\n    for (int i = 0; i < N; ++i)\n    {\n        cpp_dec_float_50 x = rexp(rng);\n        double u = runif(rng);\n        if (u < 0.5)\n        {\n            x = -x;\n        }\n        vec.push_back(x);\n    }\n    std::sort(vec.begin(), vec.end());\n}\n\nvoid gen_x_unsigned_exp(const double r, boost::random::mt19937& rng, int N, std::vector<cpp_dec_float_50>& vec, bool srtd = true)\n{\n    boost::random::uniform_real_distribution<> runif;\n    boost::random::exponential_distribution<cpp_dec_float_50> rexp(r);\n\n    for (int i = 0; i < N; ++i)\n    {\n        cpp_dec_float_50 x = rexp(rng);\n        vec.push_back(x);\n    }\n    if (srtd)\n    {\n        std::sort(vec.begin(), vec.end());\n    }\n}\n\nvoid gen_x_unsigned_unif(boost::random::mt19937& rng, int N, std::vector<cpp_dec_float_50>& vec, bool srtd = true)\n{\n    boost::random::uniform_real_distribution<> runif;\n\n    for (int i = 0; i < N; ++i)\n    {\n        cpp_dec_float_50 x = runif(rng);\n        vec.push_back(x);\n    }\n    if (srtd)\n    {\n        std::sort(vec.begin(), vec.end());\n    }\n}\n\nvoid gen_k_unsigned_exp(const double r, boost::random::mt19937& rng, int N, std::vector<unsigned long>& vec, bool srtd = true)\n{\n    boost::random::uniform_real_distribution<> runif;\n    boost::random::exponential_distribution<double> rexp(r);\n\n    for (int i = 0; i < N; ++i)\n    {\n        double x = rexp(rng);\n        vec.push_back(static_cast<unsigned long>(x));\n    }\n    if (srtd)\n    {\n        std::sort(vec.begin(), vec.end());\n    }\n}\n\nint main(int argc, const char* argv[])\n{\n    std::string fun(argv[1]);\n\n    int N = 200;\n    if (argc >= 4)\n    {\n        N = boost::lexical_cast<unsigned long>(argv[2]);\n    }\n\n    unsigned long S = 17;\n    if (argc >= 5)\n    {\n        S = boost::lexical_cast<unsigned long>(argv[3]);\n        std::cerr << S << endl;\n    }\n    boost::random::mt19937 rng(S);\n\n    std::cout.precision(std::numeric_limits<cpp_dec_float_50>::digits10);\n\n    if (fun == \"beta\")\n    {\n        std::vector<cpp_dec_float_50> A;\n        gen_x_unsigned_exp(0.05, rng, N, A, false);\n        std::vector<cpp_dec_float_50> B;\n        gen_x_unsigned_exp(0.05, rng, N, B, false);\n\n        std::vector<cpp_dec_float_50> Y;\n        for (int i = 0; i < N; ++i)\n        {\n            cpp_dec_float_50 y = boost::math::beta(A[i], B[i]);\n            Y.push_back(y);\n        }\n\n        cout << \"seed:\" << S << endl;\n        cout << \"data:\" << endl;\n        for (int i = 0; i < N; ++i)\n        {\n            cout << \"- [\" << A[i] << \", \" << B[i] << \", \" << Y[i] << \", \" << log(Y[i]) << \"]\" << endl;\n        }\n        return 0;\n    }\n\n    if (fun == \"betaInt\")\n    {\n        std::vector<unsigned long> A;\n        gen_k_unsigned_exp(0.01, rng, N, A, false);\n        std::vector<unsigned long> B;\n        gen_k_unsigned_exp(0.01, rng, N, B, false);\n\n        std::vector<cpp_dec_float_50> Y;\n        for (int i = 0; i < N; ++i)\n        {\n\t    A[i] += 1;\n\t    B[i] += 1;\n            cpp_dec_float_50 y = boost::math::beta(A[i], B[i]);\n            Y.push_back(y);\n        }\n\n        cout << \"seed: \" << S << endl;\n        cout << \"data:\" << endl;\n        for (int i = 0; i < N; ++i)\n        {\n            cout << \"- [\" << A[i] << \", \" << B[i] << \", \" << Y[i] << \", \" << log(Y[i]) << \"]\" << endl;\n        }\n        return 0;\n    }\n\n    if (fun == \"ibetaInt\")\n    {\n        std::vector<unsigned long> A;\n        gen_k_unsigned_exp(0.01, rng, N, A, false);\n        std::vector<unsigned long> B;\n        gen_k_unsigned_exp(0.01, rng, N, B, false);\n\n        std::vector<cpp_dec_float_50> X;\n        gen_x_unsigned_unif(rng, N, X, false);\n\n        std::vector<cpp_dec_float_50> Y;\n        std::vector<cpp_dec_float_50> Z;\n        boost::random::uniform_real_distribution<> runif;\n        for (int i = 0; i < N; ++i)\n        {\n            ++A[i];\n            ++B[i];\n            cpp_dec_float_50 y = boost::math::ibeta(A[i], B[i], X[i]);\n            cpp_dec_float_50 z = boost::math::ibetac(A[i], B[i], X[i]);\n            Y.push_back(y);\n            Z.push_back(z);\n        }\n\n        cout << \"seed: \" << S << endl;\n        cout << \"data:\" << endl;\n        for (int i = 0; i < N; ++i)\n        {\n            cout << \"- [\" << A[i] << \", \" << B[i] << \", \" << X[i] << \", \" << Y[i] << \", \" << log(Y[i]) << \", \"\n                                                          << Z[i] << \", \" << log(Z[i]) << \"]\" << endl;\n        }\n        return 0;\n    }\n\n    if (fun == \"ibeta\")\n    {\n        std::vector<cpp_dec_float_50> A;\n        gen_x_unsigned_exp(0.05, rng, N, A, false);\n        std::vector<cpp_dec_float_50> B;\n        gen_x_unsigned_exp(0.05, rng, N, B, false);\n\n        std::vector<cpp_dec_float_50> X;\n        gen_x_unsigned_unif(rng, N, X, false);\n\n        std::vector<cpp_dec_float_50> Y;\n        std::vector<cpp_dec_float_50> Z;\n        boost::random::uniform_real_distribution<> runif;\n        for (int i = 0; i < N; ++i)\n        {\n            cpp_dec_float_50 y = boost::math::ibeta(A[i], B[i], X[i]);\n            cpp_dec_float_50 z = boost::math::ibetac(A[i], B[i], X[i]);\n            Y.push_back(y);\n            Z.push_back(z);\n        }\n\n        cout << \"seed: \" << S << endl;\n        cout << \"data:\" << endl;\n        for (int i = 0; i < N; ++i)\n        {\n            cout << \"- [\" << A[i] << \", \" << B[i] << \", \" << X[i] << \", \" << Y[i] << \", \" << log(Y[i]) << \", \"\n                                                          << Z[i] << \", \" << log(Z[i]) << \"]\" << endl;\n        }\n        return 0;\n    }\n\n    if (fun == \"choose\")\n    {\n        std::vector<unsigned long> J;\n        std::vector<unsigned long> K;\n        gen_k_unsigned_exp(0.01, rng, N, J);\n        gen_k_unsigned_exp(0.01, rng, N, K, false);\n\n        std::vector<cpp_dec_float_50> C;\n        std::vector<cpp_dec_float_50> D;\n        for (int i = 0; i < N; ++i)\n        {\n            cpp_dec_float_50 c = boost::math::binomial_coefficient<cpp_dec_float_50>(J[i] + K[i], K[i]);\n            cpp_dec_float_50 d = log(c);\n            C.push_back(c);\n            D.push_back(d);\n        }\n\n        cout << \"seed: \" << S << endl;\n        cout << \"data:\" << endl;\n        for (int i = 0; i < N; ++i)\n        {\n            cout << \"- [\" << (J[i] + K[i]) << \", \" << K[i] << \", \" << C[i] << \", \" << D[i] << \"]\" << endl;\n        }\n        return 0;\n    }\n\n    if (fun == \"erf\")\n    {\n        std::vector<cpp_dec_float_50> X;\n        gen_x_signed_exp(0.2, rng, N, X);\n\n        std::vector<cpp_dec_float_50> Y;\n        for (int i = 0; i < N; ++i)\n        {\n            cpp_dec_float_50 y = erf(X[i]);\n            Y.push_back(y);\n        }\n        cout << \"seed: \" << S << endl;\n        cout << \"data:\" << endl;\n        for (int i = 0; i < N; ++i)\n        {\n            cout << \"- [\" << X[i] << \", \" << Y[i] << \"]\" << endl;\n        }\n        return 0;\n    }\n\n    if (fun == \"erfc\")\n    {\n        std::vector<cpp_dec_float_50> X;\n        gen_x_signed_exp(0.2, rng, N, X);\n\n        std::vector<cpp_dec_float_50> Y;\n        for (int i = 0; i < N; ++i)\n        {\n            cpp_dec_float_50 y = erfc(X[i]);\n            Y.push_back(y);\n        }\n\n        cout << \"seed: \" << S << endl;\n        cout << \"data:\" << endl;\n        for (int i = 0; i < N; ++i)\n        {\n            cout << \"- [\" << X[i] << \", \" << Y[i] << \", \" << log(Y[i]) << \"]\" << endl;\n        }\n        return 0;\n    }\n\n    if (fun == \"gamma\")\n    {\n        std::vector<cpp_dec_float_50> X;\n        gen_x_unsigned_exp(0.05, rng, N, X);\n\n        std::vector<cpp_dec_float_50> Y;\n        std::vector<cpp_dec_float_50> Z;\n        for (int i = 0; i < N; ++i)\n        {\n            cpp_dec_float_50 y = tgamma(X[i]);\n            cpp_dec_float_50 z = lgamma(X[i]);\n            Y.push_back(y);\n            Z.push_back(z);\n        }\n\n        cout << \"seed: \" << S << endl;\n        cout << \"data:\" << endl;\n        for (int i = 0; i < N; ++i)\n        {\n            cout << \"- [\" << X[i] << \", \" << Y[i] << \", \" << Z[i] << \"]\" << endl;\n        }\n        cout << \"]\" << endl;\n        return 0;\n    }\n\n    if (fun == \"igamma\")\n    {\n        std::vector<cpp_dec_float_50> A;\n        gen_x_unsigned_exp(0.1, rng, N, A);\n        std::vector<cpp_dec_float_50> X;\n        gen_x_unsigned_exp(0.1, rng, N, X, false);\n\n        std::vector<cpp_dec_float_50> Y;\n        std::vector<cpp_dec_float_50> Z;\n        std::vector<cpp_dec_float_50> U;\n        std::vector<cpp_dec_float_50> V;\n        for (int i = 0; i < N; ++i)\n        {\n            cpp_dec_float_50 y = boost::math::gamma_p(A[i], X[i]);\n            cpp_dec_float_50 z = boost::math::gamma_q(A[i], X[i]);\n            Y.push_back(y);\n            Z.push_back(z);\n        }\n\n        cout << \"seed: \" << S << endl;\n        cout << \"data:\" << endl;\n        for (int i = 0; i < N; ++i)\n        {\n            cout << \"- [\" << A[i] << \", \" << X[i] << \", \" << Y[i] << \", \" << log(Y[i])\n                                                          << \", \" << Z[i] << \", \" << log(Z[i]) << \"]\" << endl;\n        }\n        return 0;\n    }\n\n   return 1;\n}\n", "meta": {"hexsha": "c26fc27668c026849e1c40e4dfd91b07a03053c0", "size": 9907, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "misc/gen_special_test.cpp", "max_stars_repo_name": "drtconway/iid", "max_stars_repo_head_hexsha": "c92a7c2c573a586d25d9eb5e940638de5eb03825", "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": "misc/gen_special_test.cpp", "max_issues_repo_name": "drtconway/iid", "max_issues_repo_head_hexsha": "c92a7c2c573a586d25d9eb5e940638de5eb03825", "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": "misc/gen_special_test.cpp", "max_forks_repo_name": "drtconway/iid", "max_forks_repo_head_hexsha": "c92a7c2c573a586d25d9eb5e940638de5eb03825", "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": 28.6329479769, "max_line_length": 129, "alphanum_fraction": 0.4705763601, "num_tokens": 2973, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837705, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.7062685659873166}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2020-2021 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2020-2021 Nikita Kaskov <nbering@nil.foundation>\n//\n// MIT License\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n//---------------------------------------------------------------------------//\n\n#define BOOST_TEST_MODULE constexpr_matrix_test\n\n#include <boost/test/unit_test.hpp>\n#include <boost/test/data/test_case.hpp>\n#include <boost/test/data/monomorphic.hpp>\n\n#include <nil/crypto3/algebra/matrix/matrix.hpp>\n#include <nil/crypto3/algebra/matrix/math.hpp>\n#include <nil/crypto3/algebra/matrix/operators.hpp>\n#include <nil/crypto3/algebra/matrix/utility.hpp>\n#include <nil/crypto3/algebra/vector/vector.hpp>\n#include <nil/crypto3/algebra/vector/operators.hpp>\n\nusing namespace nil::crypto3::algebra;\n\n// Uniform initialization\nconstexpr matrix<double, 3, 3> m1 = {1., 2., 3., 4., 5., 6., 7., 8., 9.};\n\n// Type deduction\nconstexpr matrix m2 = {{{1., 2.}}};\n\nconstexpr matrix m22 = {{{1., 3.}, {2., 7.}}};\n\nstatic_assert(m1[0][2] == 3, \"matrix[]\");\n\nstatic_assert(m1.row(2) == vector {7., 8., 9.}, \"matrix row\");\n\nstatic_assert(m1.column(2) == vector {3., 6., 9.}, \"matrix column\");\n\nstatic_assert(fill<2, 2>(3.) == matrix {{{3., 3.}, {3., 3.}}}, \"matrix fill\");\n\nstatic_assert(matmul(m1, m1) == matrix {{{30., 36., 42.}, {66., 81., 96.}, {102., 126., 150.}}},\n              \"real matrix multiply\");\n\nstatic_assert(identity<double, 3> == matrix {{{1., 0., 0.}, {0., 1., 0.}, {0., 0., 1.}}}, \"identity\");\n\nstatic_assert(identity<double, 3> == inverse(identity<double, 3>), \"inverse-identity\");\n\nstatic_assert(inverse(m22) == matrix {{{7., -3.}, {-2., 1.}}}, \"inverse\");\n\nstatic_assert(matmul(inverse(m22), matrix<double, 2, 1> {{{1.}, {1.}}}) == matrix {{{4.}, {-1.}}}, \"A^-1*b = x\");\n\nstatic_assert(horzcat(identity<double, 2>, identity<double, 2>) ==\n                  matrix<double, 2, 4> {{{1., 0., 1., 0.}, {0., 1., 0., 1.}}},\n              \"horzcat\");\n\nstatic_assert(submat<2, 2>(m1, 1, 1) == matrix {{{5., 6.}, {8., 9.}}}, \"submat\");\n\nstatic_assert(rref(m1) == matrix {{{1., 0., -1.}, {0., 1., 2.}, {0., 0., 0.}}}, \"rref\");\n\nstatic_assert(rank(m1) == 2, \"rank\");\n", "meta": {"hexsha": "a47c7e2973692d9c1b0f0f5f5e4f88f4fedeb25a", "size": 3261, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/matrix.cpp", "max_stars_repo_name": "JasonCoombs/crypto3-algebra", "max_stars_repo_head_hexsha": "3ddb4eb0ed65dc046660cc49811d17a140a4c72f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-09-20T18:56:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T06:58:28.000Z", "max_issues_repo_path": "test/matrix.cpp", "max_issues_repo_name": "JasonCoombs/crypto3-algebra", "max_issues_repo_head_hexsha": "3ddb4eb0ed65dc046660cc49811d17a140a4c72f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41.0, "max_issues_repo_issues_event_min_datetime": "2020-08-27T18:11:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-20T21:01:55.000Z", "max_forks_repo_path": "test/matrix.cpp", "max_forks_repo_name": "NilFoundation/algebra", "max_forks_repo_head_hexsha": "f211b0ffb2c7d817d44d2a6d1cc586a6db62dc03", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-07-05T13:50:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T03:09:12.000Z", "avg_line_length": 42.3506493506, "max_line_length": 113, "alphanum_fraction": 0.6314014106, "num_tokens": 915, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311355, "lm_q2_score": 0.8128673087708699, "lm_q1q2_score": 0.7062408889105716}}
{"text": "#include <cmath>\n#include <memory>\n#include <iostream>\n#include <random>\n\n#include <Eigen/Core>\n\n#include \"pce/PCExpansion.h\"\n\nint main()\n{\n  // function handle, can be C++11 lambda, regular function pointer, or std::function\n  auto f = [](const Eigen::VectorXd& x) { return pow(x(0), 2) + x(0) * x(1) + pow(x(1), 3); };\n\n  // two iid normal distributed inputs\n  auto vars = {PCExpansion::GermType::Normal, PCExpansion::GermType::Normal};\n\n  // make shared pointer to PCExpansion\n  auto pce = std::make_shared<PCExpansion>(f, vars, 5); // maxOrder = 5\n\n  //\n  // Below are example uses of a PCE\n  //\n\n  // get analytic moments from the PCE\n  auto moments = pce->GetMoments();\n  std::cout << \"Mean: \" << moments.first << \" Variance: \" << moments.second << std::endl;\n\n  // Estimate MSE of PCE expansion using samples\n  double mse = 0;\n  int nsamps = 1000;\n  auto rng = std::mt19937();\n  std::normal_distribution<double> normal(0, 1);\n  Eigen::VectorXd sample(2);\n  for (int i = 0; i < nsamps; ++i) {\n    sample << normal(rng), normal(rng);\n    mse += pow(f(sample) - pce->Evaluate(sample), 2);\n  }\n  std::cout << \"MSE: \" << mse / nsamps << std::endl;\n\n  // make a another PCE to get cross-covariance\n  auto f_other = [](const Eigen::VectorXd& xi) { return xi(0) + xi(0) * pow(xi(1), 3); };\n  auto pce_other = std::make_shared<PCExpansion>(f_other, vars, 5);\n  std::cout << \"cross-covariance: \" << pce->GetCrossCovariance(pce_other) << std::endl;\n\n  return 0;\n}", "meta": {"hexsha": "16bb979d1388fff55c97189cc6c529abf9b532e7", "size": 1459, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/TestPCE.cpp", "max_stars_repo_name": "chi-feng/micro-uq", "max_stars_repo_head_hexsha": "fe357b68848e5ab6d8522d832606655576d0de8c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-08-29T02:39:27.000Z", "max_stars_repo_stars_event_max_datetime": "2017-08-29T02:39:27.000Z", "max_issues_repo_path": "src/TestPCE.cpp", "max_issues_repo_name": "chi-feng/micro-uq", "max_issues_repo_head_hexsha": "fe357b68848e5ab6d8522d832606655576d0de8c", "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/TestPCE.cpp", "max_forks_repo_name": "chi-feng/micro-uq", "max_forks_repo_head_hexsha": "fe357b68848e5ab6d8522d832606655576d0de8c", "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.0425531915, "max_line_length": 94, "alphanum_fraction": 0.6374228924, "num_tokens": 457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087965937711, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.706194752042983}}
{"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, const VectorXdual& p)\n{\n    return x.cwiseProduct(x).sum() * exp(p.sum()); // sum([x(i) * x(i) for i = 1:5]) * exp(sum(p))\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    VectorXdual p(3);    // the input parameter vector p with 3 variables\n    p << 1, 2, 3;        // p = [1, 2, 3]\n\n    dual u;  // the output scalar u = f(x, p) evaluated together with gradient below\n\n    VectorXd gx = gradient(f, wrt(x), at(x, p), u);  // evaluate the function value u and its gradient vector gx = du/dx\n    VectorXd gp = gradient(f, wrt(p), at(x, p), u);  // evaluate the function value u and its gradient vector gp = du/dp\n    VectorXd gpx = gradient(f, wrtpack(p, x), at(x, p), u);  // evaluate the function value u and its gradient vector gp = [du/dp, du/dx]  \n\n    cout << \"u = \" << u << endl;    // print the evaluated output u\n    cout << \"gx = \\n\" << gx << endl;  // print the evaluated gradient vector gx = du/dx\n    cout << \"gp = \\n\" << gp << endl;  // print the evaluated gradient vector gp = du/dp\n    cout << \"gpx = \\n\" << gpx << endl;  // print the evaluated gradient vector gp = [du/dp, du/dx]\n}\n", "meta": {"hexsha": "eece28c09735ef36ceb25fc3ebda1fbce7e8f4d3", "size": 1507, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/forward/example-forward-gradient-derivatives-using-eigen-with-parameters.cpp", "max_stars_repo_name": "ludkinm/autodiff", "max_stars_repo_head_hexsha": "982ee0f63726c71843e2141b8b4b037590c2ad46", "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": "examples/forward/example-forward-gradient-derivatives-using-eigen-with-parameters.cpp", "max_issues_repo_name": "ludkinm/autodiff", "max_issues_repo_head_hexsha": "982ee0f63726c71843e2141b8b4b037590c2ad46", "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": "examples/forward/example-forward-gradient-derivatives-using-eigen-with-parameters.cpp", "max_forks_repo_name": "ludkinm/autodiff", "max_forks_repo_head_hexsha": "982ee0f63726c71843e2141b8b4b037590c2ad46", "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.641025641, "max_line_length": 139, "alphanum_fraction": 0.6164565362, "num_tokens": 480, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094174159129, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.706188178420423}}
{"text": "/**\n * @file upwindfinitevolume.cc\n * @brief NPDE homework UpwindFiniteVolume code\n * @author Philipp Egg\n * @date 08.09.2020\n * @copyright Developed at ETH Zurich\n */\n\n#include \"upwindfinitevolume.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <cmath>\n#include <stdexcept>\n\nnamespace UpwindFiniteVolume {\n\n/* SAM_LISTING_BEGIN_1 */\nEigen::Matrix<double, 2, 3> gradbarycoordinates(\n    const Eigen::Matrix<double, 2, 3> &triangle) {\n  Eigen::Matrix3d X;\n  // Solve for the coefficients of the barycentric coordinate functions\n  X.block<3, 1>(0, 0) = Eigen::Vector3d::Ones();\n  X.block<3, 2>(0, 1) = triangle.transpose();\n  return X.inverse().block<2, 3>(1, 0);\n}\n/* SAM_LISTING_END_1 */\n\n/* SAM_LISTING_BEGIN_2 */\nEigen::Vector2d computeCircumcenters(const Eigen::Vector2d &a1,\n                                     const Eigen::Vector2d &a2,\n                                     const Eigen::Vector2d &a3) {\n#if SOLUTION\n\n  Eigen::Vector2d mp1 = 0.5 * (a1 + a2);\n  Eigen::Vector2d mp2 = 0.5 * (a2 + a3);\n\n  Eigen::Vector2d dir1 = a2 - a1;\n  Eigen::Vector2d dir2 = a3 - a2;\n\n  Eigen::Matrix2d dir;\n  dir << dir1(1), dir2(1), -dir1(0), -dir2(0);\n\n  Eigen::Vector2d p = dir.colPivHouseholderQr().solve(mp2 - mp1);\n\n  Eigen::Vector2d center = mp1 + p(0) * dir.col(0);\n\n  // Barycentric coordinates from\n  // Christer Ericson\u2019s \u2019Real-Time Collision Detection\u2019\n\n  Eigen::Vector2d v0 = a2 - a1, v1 = a3 - a1, v2 = center - a1;\n  double d00 = v0.dot(v0);\n  double d01 = v0.dot(v1);\n  double d11 = v1.dot(v1);\n  double d20 = v2.dot(v0);\n  double d21 = v2.dot(v1);\n\n  double denom = d00 * d11 - d01 * d01;\n  double v = (d11 * d20 - d01 * d21) / denom;\n  double w = (d00 * d21 - d01 * d20) / denom;\n  double u = 1.0 - v - w;\n\n  if (v <= 0 || w <= 0 || u <= 0) {\n    throw std::runtime_error(\"Obtused triangle!\");\n    return Eigen::Vector2d::Zero();\n  } else {\n    return center;\n  }\n\n  // Alternative:\n  /*\n  // Calculate the midpoint of the edges\n  const Eigen::Vector2d midpoint1 = (a1 + a2) * 0.5;\n  const Eigen::Vector2d midpoint2 = (a2 + a3) * 0.5;\n  const Eigen::Vector2d midpoint3 = (a1 + a3) * 0.5;\n\n  // Calculate the slope of the line perpendicular to the edges\n  Eigen::Matrix<double, 2, 3> corners;\n  corners.col(0) = a1;\n  corners.col(1) = a2;\n  corners.col(2) = a3;\n\n  Eigen::MatrixXd barycenters = gradbarycoordinates(corners);\n\n  // Reorder the vectors corresponding to the edges\n  Eigen::Vector2d n1 = barycenters.col(2).normalized();\n  Eigen::Vector2d n2 = barycenters.col(0).normalized();\n  Eigen::Vector2d n3 = barycenters.col(1).normalized();\n\n  // Check obtuse triangle\n  double alpha1 = acos(n1.dot(-n3));\n  double alpha2 = acos(n1.dot(-n2));\n  double alpha3 = acos(n2.dot(-n3));\n\n  double rad_90deg = M_PI / 2.0;\n  if (alpha1 >= rad_90deg || alpha2 >=  rad_90deg || alpha3 >=  rad_90deg) {\n    std::cout << \"Obtused triangle!\" << std::endl;\n    std::cout << \"alpha1 \" << alpha1 * 180.0 / M_PI << \"degree\" << std::endl;\n    std::cout << \"alpha2 \" << alpha2 * 180.0 / M_PI << \"degree\" << std::endl;\n    std::cout << \"alpha3 \" << alpha3 * 180.0 / M_PI << \"degree\" << std::endl;\n    throw std::runtime_error(\"Obtused triangle!\");\n  }\n\n  // Compute intersection the two vectors\n  // midpoint1 + n1 * t1 = midpoint2 + n2 * t2\n  // (midpoint1x - midpoint2x) = t2 * n2x - t1 * n1x\n  // (midpoint1y - midpoint2y) = t2 * n2y - t1 * n1y\n  // solving for t1:\n  double t1 = ((midpoint1[0] - midpoint2[0]) * n2[1] -\n               (midpoint1[1] - midpoint2[1]) * n2[0]) /\n              (n1[1] * n2[0] - n1[0] * n2[1]);\n\n  Eigen::Vector2d intersection = midpoint1 + n1 * t1;\n\n  return intersection;\n  */\n#else\n  //====================\n  // Your code goes here\n  //====================\n  return Eigen::Vector2d::Zero();\n#endif\n}\n/* SAM_LISTING_END_2 */\n\n}  // namespace UpwindFiniteVolume\n", "meta": {"hexsha": "cdfe20179d602220125cac363bce43fb7d945c35", "size": 3800, "ext": "cc", "lang": "C++", "max_stars_repo_path": "developers/UpwindFiniteVolume/mastersolution/upwindfinitevolume.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/UpwindFiniteVolume/mastersolution/upwindfinitevolume.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/UpwindFiniteVolume/mastersolution/upwindfinitevolume.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": 29.9212598425, "max_line_length": 77, "alphanum_fraction": 0.6089473684, "num_tokens": 1305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093975331752, "lm_q2_score": 0.7905303087996142, "lm_q1q2_score": 0.7061881538854983}}
{"text": "#ifndef SE3_HPP_\n#define SE3_HPP_\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#ifdef _MSC_VER\n#define _USE_MATH_DEFINES\n#endif\n#include <math.h>\n\nconst double SMALL_EPS = 1e-10;\n\ntypedef Eigen::Matrix<double, 6, 1, Eigen::ColMajor> Vector6d;\ntypedef Eigen::Matrix<double, 7, 1, Eigen::ColMajor> Vector7d;\n\ninline Eigen::Matrix3d skew(const Eigen::Vector3d&v)\n{\n    Eigen::Matrix3d m;\n    m.fill(0.);\n    m(0,1)  = -v(2);\n    m(0,2)  =  v(1);\n    m(1,2)  = -v(0);\n    m(1,0)  =  v(2);\n    m(2,0) = -v(1);\n    m(2,1) = v(0);\n    return m;\n}\n\ninline Eigen::Vector3d deltaR(const Eigen::Matrix3d& R)\n{\n    Eigen::Vector3d v;\n    v(0)=R(2,1)-R(1,2);\n    v(1)=R(0,2)-R(2,0);\n    v(2)=R(1,0)-R(0,1);\n    return v;\n}\n\n\ninline Eigen::Vector3d toAngleAxis(const Eigen::Quaterniond& quaterd, double* angle=NULL)\n{\n    Eigen::Quaterniond unit_quaternion = quaterd.normalized();\n    double n = unit_quaternion.vec().norm();\n    double w = unit_quaternion.w();\n    double squared_w = w*w;\n\n    double two_atan_nbyw_by_n;\n    // Atan-based log thanks to\n    //\n    // C. Hertzberg et al.:\n    // \"Integrating Generic Sensor Fusion Algorithms with Sound State\n    // Representation through Encapsulation of Manifolds\"\n    // Information Fusion, 2011\n\n    if (n < SMALL_EPS)\n    {\n        // If quaternion is normalized and n=1, then w should be 1;\n        // w=0 should never happen here!\n        assert(fabs(w)>SMALL_EPS);\n\n        two_atan_nbyw_by_n = 2./w - 2.*(n*n)/(w*squared_w);\n    }\n    else\n    {\n        if (fabs(w)<SMALL_EPS)\n        {\n            if (w>0)\n            {\n                two_atan_nbyw_by_n = M_PI/n;\n            }\n            else\n            {\n                two_atan_nbyw_by_n = -M_PI/n;\n            }\n        }\n        two_atan_nbyw_by_n = 2*atan(n/w)/n;\n    }\n    if(angle!=NULL) *angle = two_atan_nbyw_by_n*n;\n    return two_atan_nbyw_by_n * unit_quaternion.vec();\n}\n\ninline Eigen::Quaterniond toQuaterniond(const Eigen::Vector3d& v3d, double* angle = NULL)\n{\n    double theta = v3d.norm();\n    if(angle != NULL)\n        *angle = theta;\n    double half_theta = 0.5*theta;\n\n    double imag_factor;\n    double real_factor = cos(half_theta);\n    if(theta<SMALL_EPS)\n    {\n        double theta_sq = theta*theta;\n        double theta_po4 = theta_sq*theta_sq;\n        imag_factor = 0.5-0.0208333*theta_sq+0.000260417*theta_po4;\n    }\n    else\n    {\n        double sin_half_theta = sin(half_theta);\n        imag_factor = sin_half_theta/theta;\n    }\n\n    return Eigen::Quaterniond(real_factor,\n                              imag_factor*v3d.x(),\n                              imag_factor*v3d.y(),\n                              imag_factor*v3d.z());\n}\n\n\nclass SE3 {\npublic:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n\nprotected:\n\n    Eigen::Quaterniond _r;\n    Eigen::Vector3d _t;\n\npublic:\n    SE3(){\n        _r.setIdentity();\n        _t.setZero();\n    }\n\n    SE3(const Eigen::Matrix3d& R, const Eigen::Vector3d& t):_r(Eigen::Quaterniond(R)),_t(t){\n        normalizeRotation();\n    }\n\n    SE3(const Eigen::Quaterniond& q, const Eigen::Vector3d& t):_r(q),_t(t){\n        normalizeRotation();\n    }\n\n    inline const Eigen::Vector3d& translation() const {return _t;}\n\n    inline Eigen::Vector3d& translation() {return _t;}\n\n    inline void setTranslation(const Eigen::Vector3d& t_) {_t = t_;}\n\n    inline const Eigen::Quaterniond& rotation() const {return _r;}\n\n    inline Eigen::Quaterniond& rotation() {return _r;}\n\n    void setRotation(const Eigen::Quaterniond& r_) {_r=r_;}\n\n    inline SE3 operator* (const SE3& tr2) const{\n        SE3 result(*this);\n        result._t += _r*tr2._t;\n        result._r*=tr2._r;\n        result.normalizeRotation();\n        return result;\n    }\n\n    inline SE3& operator*= (const SE3& tr2){\n        _t+=_r*tr2._t;\n        _r*=tr2._r;\n        normalizeRotation();\n        return *this;\n    }\n\n    inline Eigen::Vector3d operator* (const Eigen::Vector3d& v) const {\n        return _t+_r*v;\n    }\n\n    inline SE3 inverse() const{\n        SE3 ret;\n        ret._r=_r.conjugate();\n        ret._t=ret._r*(_t*-1.);\n        return ret;\n    }\n\n    inline double operator [](int i) const {\n        assert(i<7);\n        if (i<4)\n            return _r.coeffs()[i];\n        return _t[i-4];\n    }\n\n\n    inline Vector7d toVector() const{\n        Vector7d v;\n        v.head<4>() = Eigen::Vector4d(_r.coeffs());\n        v.tail<3>() = _t;\n        return v;\n    }\n\n    inline void fromVector(const Vector7d& v){\n        _r=Eigen::Quaterniond(v[3], v[0], v[1], v[2]);\n        _t=Eigen::Vector3d(v[4], v[5], v[6]);\n    }\n\n\n    Vector6d log() const {\n        Vector6d res;\n\n        double theta;\n        res.head<3>() = toAngleAxis(_r, &theta);\n\n        Eigen::Matrix3d Omega = skew(res.head<3>());\n        Eigen::Matrix3d V_inv;\n        if (theta<SMALL_EPS)\n        {\n            V_inv = Eigen::Matrix3d::Identity()- 0.5*Omega + (1./12.)*(Omega*Omega);\n        }\n        else\n        {\n            V_inv = ( Eigen::Matrix3d::Identity() - 0.5*Omega\n                      + ( 1-theta/(2*tan(theta/2)))/(theta*theta)*(Omega*Omega) );\n        }\n\n        res.tail<3>() = V_inv*_t;\n\n        return res;\n    }\n\n    Eigen::Vector3d map(const Eigen::Vector3d & xyz) const\n    {\n        return _r*xyz + _t;\n    }\n\n\n    static SE3 exp(const Vector6d & update)\n    {\n        Eigen::Vector3d omega(update.data());\n        Eigen::Vector3d upsilon(update.data()+3);\n\n        double theta;\n        Eigen::Matrix3d Omega = skew(omega);\n\n        Eigen::Quaterniond R = toQuaterniond(omega, &theta);\n        Eigen::Matrix3d V;\n        if (theta<SMALL_EPS)\n        {\n            V = R.matrix();\n        }\n        else\n        {\n            Eigen::Matrix3d Omega2 = Omega*Omega;\n\n            V = (Eigen::Matrix3d::Identity()\n                 + (1-cos(theta))/(theta*theta)*Omega\n                 + (theta-sin(theta))/(pow(theta,3))*Omega2);\n        }\n        return SE3(R, V*upsilon);\n    }\n\n    Eigen::Matrix<double, 6, 6, Eigen::ColMajor> adj() const\n    {\n        Eigen::Matrix3d R = _r.toRotationMatrix();\n        Eigen::Matrix<double, 6, 6, Eigen::ColMajor> res;\n        res.block(0,0,3,3) = R;\n        res.block(3,3,3,3) = R;\n        res.block(3,0,3,3) = skew(_t)*R;\n        res.block(0,3,3,3) = Eigen::Matrix3d::Zero(3,3);\n        return res;\n    }\n\n    Eigen::Matrix<double,4,4,Eigen::ColMajor> to_homogeneous_matrix() const\n    {\n        Eigen::Matrix<double,4,4,Eigen::ColMajor> homogeneous_matrix;\n        homogeneous_matrix.setIdentity();\n        homogeneous_matrix.block(0,0,3,3) = _r.toRotationMatrix();\n        homogeneous_matrix.col(3).head(3) = translation();\n\n        return homogeneous_matrix;\n    }\n\n    void normalizeRotation(){\n        if (_r.w()<0){\n            _r.coeffs() *= -1;\n        }\n        _r.normalize();\n    }\n};\n\n#endif // SE3_HPP_\n", "meta": {"hexsha": "55fe18e0c015e1f4c5233e97d7045882c2127ce1", "size": 6761, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "se3.hpp", "max_stars_repo_name": "geoeo/ba_demo_ceres", "max_stars_repo_head_hexsha": "c89b27f6c99b207ae3bf99e8fd992290a253da7a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 137.0, "max_stars_repo_stars_event_min_datetime": "2017-11-19T08:35:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T12:34:43.000Z", "max_issues_repo_path": "se3.hpp", "max_issues_repo_name": "geoeo/ba_demo_ceres", "max_issues_repo_head_hexsha": "c89b27f6c99b207ae3bf99e8fd992290a253da7a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2018-11-10T10:48:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-30T09:18:58.000Z", "max_forks_repo_path": "se3.hpp", "max_forks_repo_name": "geoeo/ba_demo_ceres", "max_forks_repo_head_hexsha": "c89b27f6c99b207ae3bf99e8fd992290a253da7a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2018-05-15T16:11:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T13:34:23.000Z", "avg_line_length": 24.5854545455, "max_line_length": 92, "alphanum_fraction": 0.5553912143, "num_tokens": 2014, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.7879311956428946, "lm_q1q2_score": 0.7061844203967332}}
{"text": "#ifndef RICPAD_SOLVER\n#define RICPAD_SOLVER\n\n#include <iostream>\n#include <vector>\n#include <math.h>\n\n#include <Eigen/Dense>\n\n#include <differentiate.hpp>\n\nusing std::cout;\nusing std::endl;\n\nnamespace solver { \ntemplate<typename num_t>\nclass Solver {\n    private:\n        // Function\n        const std::function<num_t(num_t)> f_;\n        // Derivative of the function\n        const std::function<num_t(num_t)> df_;\n        // Step size\n        num_t h_;\n        // Tolerance of the result\n        num_t tol_;\n\n    public: \n        // Construct a Solver object from the function and its derivative\n        Solver( \n            const std::function<num_t(num_t)> f,\n            const std::function<num_t(num_t)> df\n            ) :\n                \n            f_(f), df_(df)\n            {\n                h_   = std::sqrt(std::numeric_limits<num_t>::epsilon());\n                tol_ = std::sqrt(h_);\n            }\n\n        // Solve f = 0 for the initial value of x0\n        num_t solve(num_t x0) {\n            num_t desv, fx, dfx, x = x0, xold;\n\n            desv = 2*tol_;\n\n            while ( desv > tol_ ) {\n                fx  = f_(x);\n                dfx = df_(x);\n\n                xold = x;\n                x = x - fx/dfx;\n\n                std::cout << x << \"\\n\";\n\n                desv = std::abs(x - xold);\n            }\n\n            return x;\n        }\n};\n\n// Solver for N equations using a real type R\ntemplate <\n    typename C, // complex number type\n    typename R, // real number type (for tolerance parameters, etc.)\n    int N       // number of equations and unknowns\n>\nclass Solver2 {\n    private:\n        // Vector with the functions\n        const std::vector<std::function<C(Eigen::Matrix<C,N,1>&)>> f_;\n        //Eigen::Matrix<C,N,1> x0;\n        // Accepted difference between two iterations\n        R tol_; \n        // Numerical value for the differentiation step (only relevant when\n        // using numerical differentiation)\n        R h_;\n        // Maximum number of iterations\n        int maxiter_ = 100;\n\n    public:\n        //----------------------------------------------------------------------\n        // Construct a Solver2 object from a vector of functions. \n        // Differentiation is performed numerically.\n        Solver2(\n            const std::vector<std::function<C(Eigen::Matrix<C,N,1>&)>> &f\n            ) :\n            \n            f_(f) {\n                //h_   = std::sqrt(std::numeric_limits<R>::epsilon());\n                h_   = 1e-12;\n                tol_ = 1e-8;\n            };\n\n        //----------------------------------------------------------------------\n        // Setters\n        void set_h(R h) {h_ = h;};\n        void set_tol(R tol) {tol_ = tol;};\n        void set_maxiter(int maxiter) {maxiter_ = maxiter;};\n\n        //----------------------------------------------------------------------\n        // Solve for f using x0 as initial value\n        Eigen::Matrix<C,N,1> solve(\n            Eigen::Matrix<C,N,1> x0\n            ) \n        {\n\n            std::cout << \"h = \" << h_ << \"\\n\"\n                << \"tol = \" << tol_ << \"\\n\\n\";\n\n            using solver::differentiate;\n            Eigen::Matrix<C, N, N> jacobian, inv_jacobian;\n            Eigen::Matrix<C, N, 1> x(x0), xold;\n            R desv = tol_ + 1;\n\n            int niter = 0;\n\n            C val;\n\n            while ( desv > tol_ ) {\n                for ( int i = 0; i < x.size(); i++ ) {\n                    for ( int j = 0; j < x.size(); j++ ) {\n                        val = differentiate<C, N>(f_[i], x, j, h_);\n                        jacobian(i, j) = std::move(val);\n                    }\n                }\n\n                inv_jacobian = jacobian.inverse();\n                \n                Eigen::Matrix<C, N, 1> F;\n\n                for ( int i = 0; i < N; i++ ) F(i) = f_[i](x); \n                /*\n                for ( int i = 0; i < N; i++ ) {\n                    std::cout << std::setprecision(15) << x(i) << \" \";\n                }\n                std::cout << \"\\n\";\n                */\n                xold = x;\n                x = x - inv_jacobian * F;\n\n                desv = (x - xold).norm();\n                std::cout << \"desv = \" << desv << \"\\n\";\n\n                if ( niter++ > maxiter_ ) {\n                    std::cout << \"Maximum number of iterations reached.\\n\";\n                    return x;\n                }\n            }\n\n            return x;\n        };\n\n        /* Construct a Solver2 object from a function and its derivative\n        Solver2(\n            const std::function<R(R)> f,\n            const std::function<R(R)> df\n            )\n        */\n};\n\n}; // namespace solver\n\n#endif\n", "meta": {"hexsha": "3ea92a82b01d20449abced3bc60a9a8028a502d7", "size": 4633, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/include/solver.hpp", "max_stars_repo_name": "javierelpianista/solver", "max_stars_repo_head_hexsha": "85dd0757ffeec73620f5c69701ce9be51df70ab1", "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/include/solver.hpp", "max_issues_repo_name": "javierelpianista/solver", "max_issues_repo_head_hexsha": "85dd0757ffeec73620f5c69701ce9be51df70ab1", "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/include/solver.hpp", "max_forks_repo_name": "javierelpianista/solver", "max_forks_repo_head_hexsha": "85dd0757ffeec73620f5c69701ce9be51df70ab1", "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.9096385542, "max_line_length": 80, "alphanum_fraction": 0.4211094323, "num_tokens": 1100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.7879311956428946, "lm_q1q2_score": 0.7061844116627856}}
{"text": "/*\r\nCopyright (c) 2017 InversePalindrome\r\nInPal - MathSolver.hpp\r\nInversePalindrome.com\r\n*/\r\n\r\n\r\n#pragma once\r\n\r\n#include \"Exprtk.hpp\"\r\n#include \"GCD.hpp\"\r\n#include \"LCM.hpp\"\r\n#include \"PrimeTest.hpp\"\r\n\r\n#include <boost/math/constants/constants.hpp>\r\n\r\n#include <iostream>\r\n\r\n\r\ntemplate<typename T>\r\nclass MathSolver\r\n{\r\npublic:\r\n    MathSolver();\r\n    MathSolver(const std::string& task);\r\n\r\n    bool solve();\r\n\r\n    T getValue() const;\r\n    std::string getTask() const;\r\n\r\n    T getVariable(const std::string& variableName);\r\n    std::string getStringVariable(const std::string& variableName);\r\n\r\n    T getDerivative(T& variable);\r\n    T getSecondDerivative(T& variable);\r\n    T getThirdDerivative(T& variable);\r\n\r\n    T getIntegral(T& variable, T initialX, T finalX);\r\n\r\n    void setTask(const std::string& task);\r\n\r\n    void addVariable(const std::string& variableName, T& variable);\r\n    void addConstant(const std::string& constantName, T& constant);\r\n    void addStringVar(const std::string& stringVariableName, std::string& variable);\r\n    void addFunction(const std::string& functionName, exprtk::ifunction<T>& function);\r\n    void addCompositorFunction(const std::string& functionName, const std::vector<std::string>& parameters, const std::string& functionBody);\r\n\r\n    void removeVariable(const std::string& variableName);\r\n    void removeStringVar(const std::string& stringVariableName);\r\n    void removeFunction(const std::string& functionName);\r\n\r\n    void clearTask();\r\n    void clearSymbols();\r\n\r\nprivate:\r\n    exprtk::parser<T> parser;\r\n    exprtk::expression<T> expression;\r\n    exprtk::symbol_table<T> symbolTable;\r\n    exprtk::function_compositor<T> compositor;\r\n\r\n    exprtk::parser_error::type error;\r\n\r\n    std::string task;\r\n\r\n    GCD<T> gcd;\r\n    LCM<T> lcm;\r\n    PrimeTest<T> primeTest;\r\n\r\n    void loadConstants();\r\n    void loadFunctions();\r\n};\r\n\r\n\r\ntemplate<typename T>\r\nMathSolver<T>::MathSolver() :\r\n    MathSolver(\"\")\r\n{\r\n}\r\n\r\ntemplate<typename T>\r\nMathSolver<T>::MathSolver(const std::string& task) :\r\n    parser(),\r\n    expression(),\r\n    symbolTable(),\r\n    compositor(symbolTable),\r\n    task(task),\r\n    error()\r\n{\r\n    expression.register_symbol_table(symbolTable);\r\n\r\n    loadConstants();\r\n    loadFunctions();\r\n}\r\n\r\ntemplate<typename T>\r\nbool MathSolver<T>::solve()\r\n{\r\n    if (!this->parser.compile(this->task, this->expression))\r\n    {\r\n        for (std::size_t i = 0; i < this->parser.error_count(); ++i)\r\n        {\r\n            this->error = this->parser.get_error(i);\r\n\r\n            std::cerr << \"Error: \" << i << \" [LINE]: \" << this->error.line_no << \" [COL]: \" << this->error.column_no << \" [POS]: \" << this->error.token.position\r\n                << \" Type: \" << exprtk::parser_error::to_str(this->error.mode).c_str() << \" Message: \" << this->error.diagnostic.c_str() << \"\\n\";\r\n        }\r\n\r\n        return false;\r\n    }\r\n\r\n    return true;\r\n}\r\n\r\ntemplate<typename T>\r\nT MathSolver<T>::getValue() const\r\n{\r\n    return this->expression.value();\r\n}\r\n\r\ntemplate<typename T>\r\nstd::string MathSolver<T>::getTask() const\r\n{\r\n    return this->task;\r\n}\r\n\r\ntemplate<typename T>\r\nT MathSolver<T>::getVariable(const std::string& variableName)\r\n{\r\n    return this->symbolTable.get_variable(variableName)->ref();\r\n}\r\n\r\ntemplate<typename T>\r\nstd::string MathSolver<T>::getStringVariable(const std::string& variableName)\r\n{\r\n    return this->symbolTable.get_stringvar(variableName)->value();\r\n}\r\n\r\ntemplate<typename T>\r\nT MathSolver<T>::getDerivative(T& variable)\r\n{\r\n    return exprtk::derivative(this->expression, variable);\r\n}\r\n\r\ntemplate<typename T>\r\nT MathSolver<T>::getSecondDerivative(T& variable)\r\n{\r\n    return exprtk::second_derivative(this->expression, variable);\r\n}\r\n\r\ntemplate<typename T>\r\nT MathSolver<T>::getThirdDerivative(T& variable)\r\n{\r\n    return exprtk::third_derivative(this->expression, variable);\r\n}\r\n\r\ntemplate<typename T>\r\nT MathSolver<T>::getIntegral(T& variable, T initialX, T finalX)\r\n{\r\n    return exprtk::integrate(this->expression, variable, initialX, finalX);\r\n}\r\n\r\ntemplate<typename T>\r\nvoid MathSolver<T>::setTask(const std::string& task)\r\n{\r\n    this->task = task;\r\n}\r\n\r\ntemplate<typename T>\r\nvoid MathSolver<T>::addVariable(const std::string& variableName, T& variable)\r\n{\r\n    this->symbolTable.add_variable(variableName, variable);\r\n}\r\n\r\ntemplate<typename T>\r\nvoid MathSolver<T>::addConstant(const std::string& constantName, T& variable)\r\n{\r\n    this->symbolTable.add_constant(constantName, variable);\r\n}\r\n\r\ntemplate<typename T>\r\nvoid MathSolver<T>::addStringVar(const std::string& stringVariableName, std::string& variable)\r\n{\r\n    this->symbolTable.add_stringvar(stringVariableName, variable);\r\n}\r\n\r\ntemplate<typename T>\r\nvoid MathSolver<T>::addFunction(const std::string& functionName, exprtk::ifunction<T>& function)\r\n{\r\n    this->symbolTable.add_function(functionName, function);\r\n}\r\n\r\ntemplate<typename T>\r\nvoid MathSolver<T>::addCompositorFunction(const std::string& functionName, const std::vector<std::string>& parameters, const std::string& functionBody)\r\n{\r\n    exprtk::function_compositor<T>::function function(functionName, functionBody);\r\n\r\n    for (const auto& parameter : parameters)\r\n    {\r\n        function.var(parameter);\r\n    }\r\n\r\n    this->compositor.add(function, true);\r\n}\r\n\r\ntemplate<typename T>\r\nvoid MathSolver<T>::removeVariable(const std::string& variableName)\r\n{\r\n    this->symbolTable.remove_variable(variableName);\r\n}\r\n\r\ntemplate<typename T>\r\nvoid MathSolver<T>::removeStringVar(const std::string& stringVariableName)\r\n{\r\n    this->symbolTable.remove_stringvar(stringVariableName);\r\n}\r\n\r\ntemplate<typename T>\r\nvoid MathSolver<T>::removeFunction(const std::string& functionName)\r\n{\r\n    this->symbolTable.remove_function(functionName);\r\n}\r\n\r\ntemplate<typename T>\r\nvoid MathSolver<T>::clearTask()\r\n{\r\n    this->task.clear();\r\n}\r\n\r\ntemplate<typename T>\r\nvoid MathSolver<T>::clearSymbols()\r\n{\r\n    this->symbolTable.clear();\r\n}\r\n\r\ntemplate<typename T>\r\nvoid MathSolver<T>::loadConstants()\r\n{\r\n    this->symbolTable.add_constants();\r\n    this->symbolTable.add_constant(\"e\", boost::math::constants::e<long double>());\r\n}\r\n\r\ntemplate<typename T>\r\nvoid MathSolver<T>::loadFunctions()\r\n{\r\n    this->symbolTable.add_function(\"gcd\", this->gcd);\r\n    this->symbolTable.add_function(\"lcm\", this->lcm);\r\n    this->symbolTable.add_function(\"is_prime\", this->primeTest);\r\n}\r\n", "meta": {"hexsha": "b13e6c278b06f526150b0757231329f1a1a0e5ec", "size": 6360, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/MathSolver.hpp", "max_stars_repo_name": "saktheeswaranswan/InPalgrapher", "max_stars_repo_head_hexsha": "2afa5d327a9fffbc9aede62d8b826ef76d69405a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-07-21T14:15:20.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-25T21:40:47.000Z", "max_issues_repo_path": "include/MathSolver.hpp", "max_issues_repo_name": "InversePalindrome/Prime-Numbers", "max_issues_repo_head_hexsha": "2afa5d327a9fffbc9aede62d8b826ef76d69405a", "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": "include/MathSolver.hpp", "max_forks_repo_name": "InversePalindrome/Prime-Numbers", "max_forks_repo_head_hexsha": "2afa5d327a9fffbc9aede62d8b826ef76d69405a", "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.44, "max_line_length": 161, "alphanum_fraction": 0.6767295597, "num_tokens": 1446, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929797, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.7061603484764878}}
{"text": "#include <iostream>\n#include <cstdio>\n#include <armadillo>\n#include <ctime>\n#include <limits>\n#include <unistd.h>\n\n#include \"comp_eig.hh\"\n\nusing namespace std;\nusing namespace arma;\n\nconst double rmin = 1e-10;\nconst double rmax = 60;\nconst double epsilon = 1e-10;\n\n// potential function (non-intercting)\nstatic constexpr double V0(double r) {\n  return r * r;\n}\n\n// potential function (interacting)\nstatic constexpr double Vw(double r, double w) {\n  return w * w * r * r + 1 / r;\n}\n\n// calculate maximal off-diagonal element with respect to absolute value\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; // maximal element absolute value\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// 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  // S is similarity transform matrix\n  mat S(size(A));\n\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    // calculate maximal off-diagonal element with respect to absolute value\n    size_t k, l;\n    const double a = maxoff(B, k, l);\n\n    // if less than epsilon, stop\n    if(a < epsilon)\n      break;\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    // 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, double w, const std::function<double(double)> &V) {\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 Armadillo's eig_sym\n  vec eigenvalues;\n  mat eigenvectors;\n  eig_sym(eigenvalues, eigenvectors, A);\n\n  // normalize w.r.t. N\n  eigenvectors /= sqrt(h);\n\n  // find lowest eigenvalue\n  size_t lowest_index = 0;\n  double lowest_eigenvalue = eigenvalues(0);\n  for(size_t i = 1; i < N; i++) {\n    double l = eigenvalues(i);\n    if(l < lowest_eigenvalue) {\n      lowest_index = i; lowest_eigenvalue = l;\n    }\n  }\n\n  // save lowest eigenvector to file\n  char filename[20];\n  snprintf(filename, 20, \"d-%.2lf.dat\", w);\n  FILE *fp = fopen(filename, \"w\");\n  fprintf(fp, \"r          u\\n\");\n  for(size_t i = 0; i < N; i++) {\n    fprintf(fp, \"%-10.5g %-10.5g\\n\", r(i), eigenvectors(i, lowest_index));\n  }\n  fclose(fp);\n}\n\nint main(int argc, char **argv) {\n  const size_t N = 800;\n  const double Wvalues[] = { 0.01, 0.5, 1, 5 };\n  const size_t Wlen = sizeof(Wvalues) / sizeof(*Wvalues);\n\n  // run for non-interacting case\n  std::cout << \"running for non-interactive case\" << std::endl;\n  run_program(N, 0, V0);\n\n  // run for interacting cases\n  for(size_t i = 0; i < Wlen; i++) {\n    double W = Wvalues[i];\n    std::cout << \"running with W = \" << W << std::endl;\n    const auto V = [W] (double r) -> double { return Vw(r, W); };\n    run_program(N, W, V);\n  }\n}\n", "meta": {"hexsha": "b02efb08694aaec6e5b15e0f1ad8f886f938a31d", "size": 5049, "ext": "cc", "lang": "C++", "max_stars_repo_path": "project2/code-fredrik/d.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/d.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/d.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.1578947368, "max_line_length": 133, "alphanum_fraction": 0.5737769855, "num_tokens": 1692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009457116781, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.7061603461143791}}
{"text": "#define BOOST_TEST_MODULE SideMadeTests\n#define BOOST_TEST_DYN_LINK\n#include <Eigen/Dense>\n#include <boost/test/unit_test.hpp>\n#include \"MatrixSolver.hpp\"\n\nusing namespace Eigen;\n\nstruct MatrixSolverFixture {\n  MatrixSolverFixture()\n  {\n    A = MatrixXd(3, 3);\n    A << 1, 2, 3,\n        4, 5, 6,\n        7, 8, 9;\n\n    b = VectorXd(3);\n    b << 3.5, 11, 18.5;\n\n    expectedX = VectorXd(3);\n    expectedX << 2, 0, 0.5;\n  }\n\n  MatrixXd A;\n  VectorXd b;\n  VectorXd expectedX;\n};\n\nBOOST_FIXTURE_TEST_SUITE(MatrixSolverTests, MatrixSolverFixture, *boost::unit_test::tolerance(1e-12))\n\nBOOST_AUTO_TEST_CASE(LU)\n{\n  MatrixSolver solver(MatrixSolver::LU);\n  VectorXd     x(3);\n  solver.solve(A, b, x);\n\n  BOOST_TEST(x(0) == expectedX(0));\n  BOOST_TEST(x(1) == expectedX(1));\n  BOOST_TEST(x(2) == expectedX(2));\n}\n\nBOOST_AUTO_TEST_CASE(QR)\n{\n  MatrixSolver solver(MatrixSolver::QR);\n  VectorXd     x(3);\n  solver.solve(A, b, x);\n\n  BOOST_TEST(x(0) == expectedX(0));\n  BOOST_TEST(x(1) == expectedX(1));\n  BOOST_TEST(x(2) == expectedX(2));\n}\n\nBOOST_AUTO_TEST_CASE(LU2)\n{\n  MatrixSolver solver(MatrixSolver::LU2);\n  VectorXd     x(3);\n  solver.solve(A, b, x);\n\n  BOOST_TEST(x(0) == expectedX(0));\n  BOOST_TEST(x(1) == expectedX(1));\n  BOOST_TEST(x(2) == expectedX(2));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "05596aa89f7867746536ee99ffa785b16cc0d2ba", "size": 1287, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/MatrixSolverTest.cpp", "max_stars_repo_name": "kimkroener/testing-boost-exercise", "max_stars_repo_head_hexsha": "8e71e735624e59142303c1c25c2aed74fbd43e0b", "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/MatrixSolverTest.cpp", "max_issues_repo_name": "kimkroener/testing-boost-exercise", "max_issues_repo_head_hexsha": "8e71e735624e59142303c1c25c2aed74fbd43e0b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2022-01-29T01:07:41.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-15T16:49:23.000Z", "max_forks_repo_path": "tests/MatrixSolverTest.cpp", "max_forks_repo_name": "kimkroener/testing-boost-exercise", "max_forks_repo_head_hexsha": "8e71e735624e59142303c1c25c2aed74fbd43e0b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-01T16:22:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-01T16:22:19.000Z", "avg_line_length": 19.8, "max_line_length": 101, "alphanum_fraction": 0.6542346542, "num_tokens": 419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465152482724, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.7061070971178527}}
{"text": "\n/*!\n * @file \n * @brief \n * @copyright alphya 2021\n * Distributed under the Boost Software License, Version 1.0.\n * (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#ifndef NYARUGA_UTIL_AUTO_DIFF_HPP\n#define NYARUGA_UTIL_AUTO_DIFF_HPP\n\n#pragma once\n\n#include <nyaruga_util/config.hpp>\n\n#ifdef NYARUGA_UTIL_HAS_EIGEN\n\n#include <cmath>\n#include <concepts>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n// \u4e8c\u91cd\u6570\u3092\u7528\u3044\u305f\u81ea\u52d5\u5fae\u5206\u30e9\u30a4\u30d6\u30e9\u30ea\n// TODO: std::xx -> xx (using ADL)\n\nnamespace nyaruga {\n\nnamespace util {\n\nnamespace detail {\n\ntemplate <std::floating_point R = double>\nconstexpr auto make_init_value(int dim, int var_no) noexcept \n{\n    Eigen::Matrix<R,Eigen::Dynamic,1> tmp = Eigen::Matrix<R,Eigen::Dynamic,1>::Zero(dim);\n    tmp(var_no - 1) = 1.;\n    return tmp; \n}\n\n} // namespace detail\n\n\ntemplate <std::floating_point R = double>\nstruct var {\n\tusing value_type = R;\n\tusing diff_value_type = Eigen::Matrix<R,Eigen::Dynamic,1>;\n\tvalue_type val;\n\tdiff_value_type dval;\n\tconstexpr var() noexcept = default;\n\tconstexpr var(value_type val_, size_t dim, size_t var_no) noexcept : val(val_), dval(detail::make_init_value(dim, var_no)) {}\n\tconstexpr var(value_type val_, diff_value_type dval_) noexcept : val(val_), dval(dval_) {}\n\tfriend constexpr auto operator<=>(const var&, const var&) noexcept = default;\n};\n\ntemplate <std::floating_point R>\nconstexpr auto operator + (const var<R>& lhs, const var<R>& rhs) noexcept\n{\n\treturn var(lhs.val + rhs.val, static_cast<var<R>::diff_value_type>(lhs.dval + rhs.dval));\n}\n\ntemplate <std::floating_point R>\nconstexpr auto operator - (const var<R>& lhs, const var<R>& rhs) noexcept\n{\n\treturn var(lhs.val - rhs.val, static_cast<var<R>::diff_value_type>(lhs.dval - rhs.dval));\n}\n\ntemplate <std::floating_point R>\nconstexpr auto operator * (const var<R>& lhs, const var<R>& rhs) noexcept\n{\n\treturn var(lhs.val * rhs.val, static_cast<var<R>::diff_value_type>(rhs.val*lhs.dval + lhs.val*rhs.dval));\n}\n\n// rhs.val != 0\ntemplate <std::floating_point R>\nconstexpr auto operator / (const var<R>& lhs, const var<R>& rhs)\n{\n\treturn var(lhs.val / rhs.val, static_cast<var<R>::diff_value_type>((lhs.dval*rhs.val - lhs.val*rhs.dval)/std::pow(rhs.val,2)));\n}\n\ntemplate <std::floating_point R>\nconstexpr auto sin(const var<R>& x) noexcept\n{\n\treturn var(std::sin(x.val), static_cast<var<R>::diff_value_type>(std::cos(x.val)*x.dval));\n}\n\ntemplate <std::floating_point R>\nconstexpr auto cos(const var<R>& x) noexcept\n{\n\treturn var(std::cos(x.val), static_cast<var<R>::diff_value_type>(-x.dval*std::sin(x.val)));\n}\n\ntemplate <std::floating_point R>\nconstexpr auto exp(const var<R>& x) noexcept\n{\n\treturn var(std::exp(x.val), static_cast<var<R>::diff_value_type>(x.dval*std::exp(x.val)));\n}\n\n// x.val > 0\ntemplate <std::floating_point R>\nconstexpr auto log(const var<R>& x)\n{\n\treturn var(std::log(x.val), static_cast<var<R>::diff_value_type>(x.dval/x.val));\n}\n\n// x.val != 0\ntemplate <std::floating_point R>\nconstexpr auto pow(const var<R>& x, float num)\n{\n\treturn var(std::pow(x.val,num), static_cast<var<R>::diff_value_type>(x.dval*num*std::pow(x.val, num-1)));\n}\n\n} // namespace utiil\n\n} // namespace nyaruga\n\n\n/* how to use \n\n#include \"auto_diff.hpp\"\n\nint main() {\n\n\tvar x1(3.1415926/3,2,1), x2(7.,2,2), y;\n\t\n\ty = x1*x2 + sin(x1)*x2;\n\tprintf(\"%f, %f, %f\\n\", y.val, y.dval(0), y.dval(1));\n}\n\n*/\n\n#endif // #ifdef NYARUGA_UTIL_HAS_EIGEN\n\n#endif // #ifndef NYARUGA_UTIL_AUTO_DIFF_HPP\n", "meta": {"hexsha": "87ad5c87b761833d41f22db9e575225151bba19d", "size": 3429, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "nyaruga_util/auto_diff.hpp", "max_stars_repo_name": "alphya/nyaruga_util", "max_stars_repo_head_hexsha": "a75d388b2fe80100760f9b5fc7e959e4846b590f", "max_stars_repo_licenses": ["BSL-1.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": "nyaruga_util/auto_diff.hpp", "max_issues_repo_name": "alphya/nyaruga_util", "max_issues_repo_head_hexsha": "a75d388b2fe80100760f9b5fc7e959e4846b590f", "max_issues_repo_licenses": ["BSL-1.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": "nyaruga_util/auto_diff.hpp", "max_forks_repo_name": "alphya/nyaruga_util", "max_forks_repo_head_hexsha": "a75d388b2fe80100760f9b5fc7e959e4846b590f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.4, "max_line_length": 128, "alphanum_fraction": 0.7007874016, "num_tokens": 995, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.793105951184112, "lm_q1q2_score": 0.7060976444250808}}
{"text": "// NTNU TDT4200 Fall 2015 Problem Set 1: MPI Intro\n// permve@stud.ntnu.no\n\n#include <boost/mpi.hpp>\n\n#include <chrono>\n#include <cmath>\n#include <cstdio>\n#include <iostream>\n#include <stdexcept>\n#include <utility>\n\nnamespace\n{\n    namespace config\n    {\n        const int master_node = 0;\n        const int result_tag  = 0;\n    }\n}\n\ndouble\nsum_inverse_log_skip_multiples_of_two(\n    const int node_index, const int node_count, const int start, const int stop)\n{\n    double sum = 0.0;\n\n    int end_point = stop;\n\n    double log_of_two = std::log2(2.0);\n    double log_of_e   = std::log2(std::exp(1.0));\n\n    while (true)\n    {\n        // Divide mid-point and start-point by 2:\n        int mid_point = end_point >> 1;\n        int start_point = mid_point >> 1;\n\n        bool is_midpoint_odd = mid_point & 1;\n\n        mid_point &= ~1;\n\n        if (start_point < start || ((mid_point - start_point) < 2 * node_count))\n        {\n            // Not possible to split remaining data. Revert to plain iteration.\n            const int per_node = (end_point - start) / node_count;\n\n            int node_start = start + per_node * node_index;\n            int node_end = node_start + per_node;\n\n            if (node_index == node_count - 1)\n            {\n                node_end = end_point;\n            }\n                \n            for (int x = node_start; x != node_end; ++x)\n            {\n                sum += log_of_e / std::log2(static_cast<double>(x));\n            }\n            \n            return sum;\n        }\n        else\n        {\n            const int per_node = (mid_point - start_point) / node_count;\n\n            int node_start = start_point + per_node * node_index;\n            int node_end = node_start + per_node;\n            \n            if (node_index == node_count - 1)\n            {\n                node_end = mid_point;\n            \n                for (int x = node_start; x != node_end; ++x)\n                {\n                    const auto l = std::log2(static_cast<double>(x));\n                    sum += log_of_e / l + log_of_e / (log_of_two + l) + log_of_e / std::log2(static_cast<double>(2 * x + 1));\n                }\n\n                if (is_midpoint_odd)\n                {\n                    sum += log_of_e / std::log2(static_cast<double>(2 * node_end)) + log_of_e / std::log2(static_cast<double>(2 * node_end + 1));\n                }\n            }\n            else\n            {\n                for (int x = node_start; x != node_end; ++x)\n                {\n                    const auto l = std::log2(static_cast<double>(x));\n                    sum += log_of_e / l + log_of_e / (log_of_two + l) + log_of_e / std::log2(static_cast<double>(2 * x + 1));\n                }\n            }\n\n            if (end_point & 1 && node_index == 0)\n            {\n                sum += log_of_e / std::log2(static_cast<double>(end_point - 1));\n            }\n\n            end_point = start_point;\n        }\n    } \n}\n\nstd::pair<int, int>\nread_user_input(const int argc, const char* argv[])\n{\n    if (argc != 3)\n    {\n        throw std::runtime_error(\n            \"This program requires two parameters:\\n\"\n            \"the start and end specifying a range of positive integers \"\n            \"in which start is 2 or greater, and end is greater than start.\\n\");\n    }\n\n    const int start = std::stoi(argv[1]);\n    const int stop  = std::stoi(argv[2]);\n\n    if (start < 2 || stop <= start)\n    {\n        throw std::runtime_error(\n            \"Start must be greater than 2 and the end must be larger than start.\\n\");\n\t}\n\n    return std::make_pair(start, stop);\n}\n\nint\nmain(const int argc, const char* argv[])\n{\n    boost::mpi::environment  env{};\n    boost::mpi::communicator world{};\n\n    const bool is_master = (world.rank() == config::master_node);\n\n    try\n    {\n        const auto start_stop = read_user_input(argc, argv);\n        \n        const auto t1 = std::chrono::system_clock::now();\n\n        const auto this_node_sum = sum_inverse_log_skip_multiples_of_two(\n            world.rank(), world.size(), start_stop.first, start_stop.second);\n    \n        if (is_master)\n        {\n            // Master node: gather and sum calculations for all nodes\n            // Do not care about order of results; only the number of results\n    \n            double total_node_sum = this_node_sum;\n    \n            for (int i = 1; i != world.size(); ++i)\n            {\n                double received_node_sum;\n                world.recv(boost::mpi::any_source, config::result_tag, received_node_sum);\n                total_node_sum += received_node_sum;\n            }\n            \n            const auto t2 = std::chrono::system_clock::now();\n\n            const auto nanoseconds = std::chrono::duration_cast<std::chrono::nanoseconds>(t2 - t1).count();\n            \n            std::printf(\"%ld %f\\n\", nanoseconds, total_node_sum);\n        }\n        else\n        {\n            // Slave node: send calculation to master\n            world.send(config::master_node, config::result_tag, this_node_sum);\n        }\n    }\n    catch (const std::exception& error)\n    {\n        if (is_master)\n        {\n            std::cerr << error.what();\n        }\n        return 1;\n    }\n    \n    return 0;\n}\n\n", "meta": {"hexsha": "7d0247d313c21b0304407b0ade21f08a84285b04", "size": 5191, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problem_set_1/program/computeMPI.cpp", "max_stars_repo_name": "pveierland/permve-ntnu-tdt4200", "max_stars_repo_head_hexsha": "c705d56ee1147cc5edceda8d14e6c5a048d1cb02", "max_stars_repo_licenses": ["CC0-1.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": "problem_set_1/program/computeMPI.cpp", "max_issues_repo_name": "pveierland/permve-ntnu-tdt4200", "max_issues_repo_head_hexsha": "c705d56ee1147cc5edceda8d14e6c5a048d1cb02", "max_issues_repo_licenses": ["CC0-1.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": "problem_set_1/program/computeMPI.cpp", "max_forks_repo_name": "pveierland/permve-ntnu-tdt4200", "max_forks_repo_head_hexsha": "c705d56ee1147cc5edceda8d14e6c5a048d1cb02", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.521978022, "max_line_length": 145, "alphanum_fraction": 0.5245617415, "num_tokens": 1238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213745668095, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.7060877261891484}}
{"text": "#include <iostream>\n#include <chrono>\n#include <random>\n#include <map>\n\n#include <opencv2/opencv.hpp>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#include \"matplotlibcpp.h\"\n\n\nusing namespace std;\nusing namespace Eigen;\nnamespace plt = matplotlibcpp;\n\ndouble g(double x, double a, double b, double c)\n{\n  // return a*x*x+b*x+c;\n  return std::exp(a * x * x + b * x + c);\n}\n\nint main(int argc, char **argv) {\n  std::cout << \"Newton \\n\";\n\n  double aa = 1.0, bb = 2.0, cc = 1.0;\n  double a = 2.30, b = -1.20, c = 5.50;\n\n  double obs_sigma = 1.0;\n  std::default_random_engine generator;\n  std::normal_distribution<double> obs_noise_distrib(0.0, obs_sigma);\n\n\n  int N = 100;\n  std::vector<double> x_data(N), y_data(N);\n  for (int i = 0; i < N; ++i)\n  {\n    x_data[i] = static_cast<double>(i) / 100.0;\n    y_data[i] = g(x_data[i], aa, bb, cc) + obs_noise_distrib(generator);\n\n  }\n\n  // Optimize\n  int max_iter = 100000;\n  for (int it = 0; it < max_iter; ++it)\n  {\n    std::cout << \"iter \" << it << \" : \";\n    std::cout << \"abc = \" << a << \" \" << b << \" \" << c << \"\\n\";\n    Eigen::Vector3d J(0.0, 0.0, 0.0);\n    Eigen::Matrix3d H = Eigen::Matrix3d::Zero();\n    double total_err = 0.0;\n    for (int i = 0; i < N; ++i)\n    {\n      double x = x_data[i];\n      double gx = g(x, a, b, c);\n      double err = y_data[i] - gx;\n      total_err += err * err;\n\n      // Compute derivative of F(x) = 0.5 * sum(f(x)^2)\n      J[0] += -x * x * gx * err;\n      J[1] += -x * gx * err;\n      J[2] += -gx * err;\n\n      double fe = err * gx;\n      double g2 = g(x, 2*a, 2*b, 2*c);\n      double feg2 = fe-g2;\n\n      H(0, 0) += -std::pow(x, 4) * feg2;\n      H(1, 1) += -std::pow(x, 2) * feg2;\n      H(2, 2) += -feg2;\n\n      H(0, 1) += -std::pow(x, 3) * feg2;\n      H(0, 2) += -std::pow(x, 2) * feg2;\n\n      H(1, 0) += -std::pow(x, 3) * feg2;\n      H(1, 2) += -x * feg2;\n\n      H(2, 0) += -std::pow(x, 2) * feg2;\n      H(2, 1) += -x * feg2;\n    }\n\n    std::cout << \"J = \" << J.transpose() << \"\\n\";\n    std::cout << \"total error: \" << total_err << \"\\n\";\n\n    Eigen::Vector3d delta_x = -H.inverse() * J;\n    std::cout << \"delta_x = \" << delta_x.transpose() << \"\\n\";\n\n    if (delta_x.norm() < 0.0001)\n      break;\n\n    a += delta_x[0];\n    b += delta_x[1];\n    c += delta_x[2];\n  }\n  std::cout << \"final = \" << a << \" \" << b << \" \" << c << \"\\n\";\n\n  vector<double> final_y_data(N);\n  for (int i = 0; i < N; ++i)\n  {\n    final_y_data[i] = g(x_data[i], a, b, c);\n  }\n\n  plt::scatter(x_data, y_data);\n  std::map<std::string, std::string> parameters;\n  parameters[\"c\"] = \"red\";\n  plt::scatter(x_data, final_y_data, 1.0, parameters);\n  plt::show();  \n\n  return 0;\n}\n", "meta": {"hexsha": "17ee991befa91cff7f67031d2358492aa70c385c", "size": 2627, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch6/newton.cpp", "max_stars_repo_name": "zinsmatt/slambook2", "max_stars_repo_head_hexsha": "3648caff838241553d9f3de332068eb0d501a7dc", "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": "ch6/newton.cpp", "max_issues_repo_name": "zinsmatt/slambook2", "max_issues_repo_head_hexsha": "3648caff838241553d9f3de332068eb0d501a7dc", "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": "ch6/newton.cpp", "max_forks_repo_name": "zinsmatt/slambook2", "max_forks_repo_head_hexsha": "3648caff838241553d9f3de332068eb0d501a7dc", "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.6666666667, "max_line_length": 72, "alphanum_fraction": 0.5070422535, "num_tokens": 992, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213745668094, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.7060877261891483}}
{"text": "/**\n * @file\n * @brief NPDE homework ElementMatrixComputation code\n * @author Janik Sch\u00fcttler, edited by Oliver Rietmann\n * @date 03.03.2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"mylinearloadvector.h\"\n\n#include <lf/base/base.h>\n#include <lf/geometry/geometry.h>\n#include <lf/mesh/mesh.h>\n\n#include <Eigen/Core>\n#include <functional>\n\nnamespace ElementMatrixComputation {\n\n    namespace {\n\n/* SAM_LISTING_BEGIN_1 */\n        Eigen::Vector4d computeLoadVector(\n                const Eigen::MatrixXd &vertices,\n                std::function<double(const Eigen::Vector2d &)> f) {\n            // Number of nodes of the element: triangles = 3, rectangles = 4\n            const int num_nodes = vertices.cols();\n            // Vector for returning element vector\n\n            assert(num_nodes == 3 || num_nodes == 4);\n\n            Eigen::Matrix2d side_lengths;\n            side_lengths.col(0) = vertices.col(1) - vertices.col(0);\n            side_lengths.col(1) = vertices.col(2) - vertices.col(0);\n\n            double area = side_lengths.determinant() * (num_nodes == 3 ? 0.5 : 1.);\n\n            Eigen::Vector4d elem_vec = Eigen::Vector4d::Zero();\n\n            for (unsigned i = 0; i < num_nodes; i++) {\n\n                Eigen::Vector2d midpoint_cw = (vertices.col(i) + vertices.col((i - 1 + num_nodes) % num_nodes)) / 2;\n                Eigen::Vector2d midpoint_ccw = (vertices.col(i) + vertices.col((i + 1 + num_nodes) % num_nodes)) / 2;\n\n                elem_vec[i] = area / num_nodes * 0.5 * (f(midpoint_ccw) + f(midpoint_cw));\n            }\n\n            return elem_vec;\n        }\n/* SAM_LISTING_END_1 */\n\n    }  // namespace\n\n    Eigen::Vector4d MyLinearLoadVector::Eval(const lf::mesh::Entity &cell) {\n        // Topological type of the cell\n        const lf::base::RefEl ref_el{cell.RefEl()};\n        const lf::base::size_type num_nodes{ref_el.NumNodes()};\n\n        // Obtain the vertex coordinates of the cell, which completely\n        // describe its shape.\n        const lf::geometry::Geometry *geo_ptr = cell.Geometry();\n\n        // Matrix storing corner coordinates in its columns\n        auto vertices = geo_ptr->Global(ref_el.NodeCoords());\n\n        return computeLoadVector(vertices, f_);\n    }\n\n}  // namespace ElementMatrixComputation\n", "meta": {"hexsha": "11389917920655e769ed04d2dae75000a1b51e6e", "size": 2260, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/ElementMatrixComputation/mysolution/mylinearloadvector.cc", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "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": "homeworks/ElementMatrixComputation/mysolution/mylinearloadvector.cc", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "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": "homeworks/ElementMatrixComputation/mysolution/mylinearloadvector.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "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.2857142857, "max_line_length": 117, "alphanum_fraction": 0.614159292, "num_tokens": 567, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.8267118026095991, "lm_q1q2_score": 0.7059397512640287}}
{"text": "#define BOOST_TEST_MODULE \"Test Euclidean Normalization class\"\n\n#include <boost/test/unit_test.hpp>\n#include <cmath>\n\n#include \"distance/Euclidean.hpp\"\n\nusing namespace genex;\n\n#define TOLERANCE 1e-9\n\nstruct MockData\n{\n  data_t dat_1[5] = {1, 2, 3, 4, 5};\n  data_t dat_2[5] = {11, 2, 3, 4, 5};\n};\n\nBOOST_AUTO_TEST_CASE( euclidean_with_norm, *boost::unit_test::tolerance(TOLERANCE) )\n{\n  MockData data;\n  TimeSeries ts_1 {data.dat_1, 0, 0, 5};\n  TimeSeries ts_2 {data.dat_2, 0, 0, 5};\n  Euclidean dist;\n\n  data_t total = dist.init();\n\n  for (int i = 0; i < ts_1.getLength(); i++) {\n    total = dist.reduce(total, total, ts_1[i], ts_2[i]);\n  }\n\n  BOOST_TEST( dist.norm(total, ts_1, ts_2) == sqrt(100.0 / 5) );\n\n  dist.clean(total);\n}", "meta": {"hexsha": "0bbbb53fe63974ecd01c4af937fbad172b67c354", "size": 731, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/distance/EuclideanNormTest.cpp", "max_stars_repo_name": "mihinsumaria/genex", "max_stars_repo_head_hexsha": "34786b0cf5d573348b82e5d164dbc05e0411d6a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-06-28T07:36:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-11T07:49:24.000Z", "max_issues_repo_path": "test/distance/EuclideanNormTest.cpp", "max_issues_repo_name": "mihinsumaria/genex", "max_issues_repo_head_hexsha": "34786b0cf5d573348b82e5d164dbc05e0411d6a8", "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/distance/EuclideanNormTest.cpp", "max_forks_repo_name": "mihinsumaria/genex", "max_forks_repo_head_hexsha": "34786b0cf5d573348b82e5d164dbc05e0411d6a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-01T20:25:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-01T20:25:42.000Z", "avg_line_length": 21.5, "max_line_length": 84, "alphanum_fraction": 0.6648426813, "num_tokens": 261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.7826624688140726, "lm_q1q2_score": 0.7058994633670684}}
{"text": "#include <stdio.h>\n#include <math.h>\n#include <iostream>\n#include <Eigen/Eigen>\n\n#include \"NNUtil.h\"\n\n/*\n * Function shape\n *\n * @desript Display shape information of given matrix.\n */\nvoid shape(const char *msg, Matrix<float, Dynamic, Dynamic> in)\n{\n  std::cout << msg << \"(\"  << in.rows() << \",\" << in.cols() << \")\" << std::endl;\n}\n\n/*\n * Function loge()\n *\n * @desript Calculate logf() for each items in given matrix.\n */\nMatrix<float, Dynamic, Dynamic> loge(Matrix<float, Dynamic, Dynamic> in)\n{\n  Matrix<float, Dynamic, Dynamic> out = in;\n\n  out = out.array() + 1e-7f;\n\n  for(int i=0; i<in.cols(); i++)\n    {\n      out(0, i) = logf(out(0,i));\n    }\n\n  return out;\n}\n\n/*\n * Function cross_entropy()\n *\n * @desript Calculate Cross Entropy Loss value from 2 input matrix.\n */\nfloat cross_entropy(Matrix<float, Dynamic, Dynamic> output, Matrix<float, Dynamic, Dynamic> expect)\n{\n  Matrix<float, Dynamic, Dynamic> tmp;\n  float out = 0.f;\n  tmp = expect.array() * loge(output).array();\n  out = tmp.sum();\n  return -out;\n};\n\n\n", "meta": {"hexsha": "2fe998c3b90a2914e277197e2562777d8f13811f", "size": 1024, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "eigen_test/NNUtil.cxx", "max_stars_repo_name": "takayoshi-k/marubatsu", "max_stars_repo_head_hexsha": "cfda9544aa02cb23ead41c67b980a8af47d5d50c", "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": "eigen_test/NNUtil.cxx", "max_issues_repo_name": "takayoshi-k/marubatsu", "max_issues_repo_head_hexsha": "cfda9544aa02cb23ead41c67b980a8af47d5d50c", "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": "eigen_test/NNUtil.cxx", "max_forks_repo_name": "takayoshi-k/marubatsu", "max_forks_repo_head_hexsha": "cfda9544aa02cb23ead41c67b980a8af47d5d50c", "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.6923076923, "max_line_length": 99, "alphanum_fraction": 0.625, "num_tokens": 286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625126757597, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.7058570440639432}}
{"text": "\n/*!\n * @file\n * @brief Implementation of automatic differentiation with dual numbers.\n * @copyright shijimi29431 2021\n * Distributed under the Boost Software License, Version 1.0.\n * (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n// TODO: UPDATE\n// TODO: Add Doxygen Comment\n// Look https://github.com/ceres-solver/ceres-solver/blob/master/include/ceres/jet.h\n\n#ifndef SHIJIMI_MATH_AUTO_DIFF_HPP\n#define SHIJIMI_MATH_AUTA_DIFF_HPP\n\n#pragma once\n\n#include <nyaruga_util/config.hpp>\n\n#ifdef NYARUGA_UTIL_HAS_EIGEN\n\n#include <cmath>\n#include <shijimi/math/concepts/field.hpp>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\nnamespace shijimi { namespace math {\n\nnamespace detail {\n\ntemplate <size_t dim, field R = double>\nconstexpr auto make_init_value(int var_no) noexcept \n{\n    Eigen::Matrix<R,dim,1> tmp = Eigen::Matrix<R,dim,1>::Zero();\n    tmp(var_no - 1) = 1.;\n    return tmp; \n}\n\n} // namespace detail\n\ntemplate <size_t dim, field R = double>\nstruct var {\n\tusing value_type = R;\n    static constexpr size_t dimention = dim;\n\tusing diff_value_type = Eigen::Matrix<R,dim,1>;\n\tvalue_type val;\n\tdiff_value_type dval;\n\tconstexpr var() noexcept = default;\n\tconstexpr var(value_type val_, size_t var_no) noexcept : val(val_), dval(detail::make_init_value<dim,R>(var_no)) {}\n\tconstexpr var(const value_type& val_,const diff_value_type& dval_) noexcept : val(val_), dval(dval_) {}\n\tfriend constexpr auto operator<=>(const var&, const var&) noexcept = default;\n};\n\ntemplate <field R, size_t dim>\nconstexpr auto operator + (const var<dim,R>& lhs, const var<dim,R>& rhs) noexcept\n{\n\treturn var<dim,R>(lhs.val + rhs.val, static_cast<var<dim,R>::diff_value_type>(lhs.dval + rhs.dval));\n}\n\ntemplate <field R, size_t dim>\nconstexpr auto operator - (const var<dim,R>& lhs, const var<dim,R>& rhs) noexcept\n{\n\treturn var<dim,R>(lhs.val - rhs.val, static_cast<var<dim,R>::diff_value_type>(lhs.dval - rhs.dval));\n}\n\ntemplate <field R, size_t dim>\nconstexpr auto operator * (const var<dim,R>& lhs, const var<dim,R>& rhs) noexcept\n{\n\treturn var<dim,R>(lhs.val * rhs.val, static_cast<var<dim,R>::diff_value_type>(rhs.val*lhs.dval + lhs.val*rhs.dval));\n}\n\n// rhs.val != 0\ntemplate <field R, size_t dim>\nconstexpr auto operator / (const var<dim,R>& lhs, const var<dim,R>& rhs)\n{\n\treturn var<dim,R>(lhs.val / rhs.val, static_cast<var<dim,R>::diff_value_type>((lhs.dval*rhs.val - lhs.val*rhs.dval)/std::pow(rhs.val,2)));\n}\n\ntemplate <field R, size_t dim>\nconstexpr auto sin(const var<dim,R>& x) noexcept\n{\n\treturn var<dim,R>(std::sin(x.val), static_cast<var<dim,R>::diff_value_type>(std::cos(x.val)*x.dval));\n}\n\ntemplate <field R, size_t dim>\nconstexpr auto cos(const var<dim,R>& x) noexcept\n{\n\treturn var<dim,R>(std::cos(x.val), static_cast<var<dim,R>::diff_value_type>(-x.dval*std::sin(x.val)));\n}\n\ntemplate <field R, size_t dim>\nconstexpr auto exp(const var<dim,R>& x) noexcept\n{\n\treturn var<dim,R>(std::exp(x.val), static_cast<var<dim,R>::diff_value_type>(x.dval*std::exp(x.val)));\n}\n\n// x.val > 0\ntemplate <field R, size_t dim>\nconstexpr auto log(const var<dim,R>& x)\n{\n\treturn var<dim,R>(std::log(x.val), static_cast<var<dim,R>::diff_value_type>(x.dval/x.val));\n}\n\n// x.val != 0\ntemplate <field R, size_t dim>\nconstexpr auto pow(const var<dim,R>& x, float num)\n{\n\treturn var<dim,R>(std::pow(x.val,num), static_cast<var<dim,R>::diff_value_type>(x.dval*num*std::pow(x.val, num-1)));\n}\n\n} // namespace math\n} // namespace shijimi\n\n#endif // #ifdef NYARUGA_UTIL_HAS_EIGEN\n\n#endif // SHIJIMI_MATH_AUTO_DIFF_HPP\n", "meta": {"hexsha": "a66530838a1bd9e8f812b536dbf0788e2b4f6a35", "size": 3528, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/shijimi/math/auto_diff.hpp", "max_stars_repo_name": "Shijimi29431/shijimi_math", "max_stars_repo_head_hexsha": "2edc9204251a906bb70969c935abd6984d57ba80", "max_stars_repo_licenses": ["BSL-1.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": "include/shijimi/math/auto_diff.hpp", "max_issues_repo_name": "Shijimi29431/shijimi_math", "max_issues_repo_head_hexsha": "2edc9204251a906bb70969c935abd6984d57ba80", "max_issues_repo_licenses": ["BSL-1.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": "include/shijimi/math/auto_diff.hpp", "max_forks_repo_name": "Shijimi29431/shijimi_math", "max_forks_repo_head_hexsha": "2edc9204251a906bb70969c935abd6984d57ba80", "max_forks_repo_licenses": ["BSL-1.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.8983050847, "max_line_length": 139, "alphanum_fraction": 0.7120181406, "num_tokens": 986, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625126757597, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.7058570440639431}}
{"text": "// Compile: g++ tie.cpp -o tie -lgmp\n// Run: ./tie\n\n#include <boost/multiprecision/gmp.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n\nusing namespace boost::multiprecision;\n\nmpf_float fact(int int_x) {\n  mpf_float_100 x = int_x;\n  return boost::math::tgamma(x+1);\n}\n\nmpf_float prob(int n) {\n  mpf_float::default_precision(100);\n  mpf_float_100 two = 2;\n  mpf_float_100 a =  fact(n);\n  mpf_float_100 b =  fact(n/2);\n  b *= b;\n  mpf_float_100 c =  pow(two, n);\n  return a / b / c;\n}\n\n#include <iostream>\n\nint main(int argc, char const *argv[]) {\n  int values[] = { 3030, 1000, 500, 200, 100, 50, 10 };\n  for (int *value = values; *value; value++) {\n    int n = *value;\n    mpf_float p = prob(n);\n    std::cout.precision(2);\n    std::cout << n << \" : \" << std::fixed << 100*p << std::endl;\n  }\n  return 0;\n}\n", "meta": {"hexsha": "56c0ab75ea22ee714244b6fef78824c0feaf8be6", "size": 814, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/tie.cpp", "max_stars_repo_name": "jgoizueta/binomial-techniques", "max_stars_repo_head_hexsha": "0c559e481e719dda6184fa17de83003e0f6d0c20", "max_stars_repo_licenses": ["CNRI-Python"], "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/tie.cpp", "max_issues_repo_name": "jgoizueta/binomial-techniques", "max_issues_repo_head_hexsha": "0c559e481e719dda6184fa17de83003e0f6d0c20", "max_issues_repo_licenses": ["CNRI-Python"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/tie.cpp", "max_forks_repo_name": "jgoizueta/binomial-techniques", "max_forks_repo_head_hexsha": "0c559e481e719dda6184fa17de83003e0f6d0c20", "max_forks_repo_licenses": ["CNRI-Python"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.6111111111, "max_line_length": 64, "alphanum_fraction": 0.6203931204, "num_tokens": 279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693716759488, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.705763895788681}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <OneACPose/types.hpp>\n\n#ifndef M_PI\n#define M_PI (3.14159265358979323846)\n#endif\n\nnamespace common\n{\n  inline double R2D(double radian)\n  {\n    return radian / M_PI * 180;\n  }\n\n  template <typename T>\n  inline T Square(const T& x)\n  {\n    return x * x;\n  }\n\n  template <typename T>\n  inline T Cube(const T& x)\n  {\n    return x * x * x;\n  }\n\n  OneACPose::Mat3 LookAt(const OneACPose::Vec3& forward, const OneACPose::Vec3& up = OneACPose::Vec3::UnitY());\n\n  double getRotationMagnitude(const OneACPose::Mat3& R2);\n\n  inline OneACPose::Mat3 cross_product(const OneACPose::Vec3& v)\n  {\n    OneACPose::Mat3 result; result <<\n      0, -v(2), v(1),\n      v(2), 0, -v(0),\n      -v(1), v(0), 0;\n    return result;\n  }\n\n  template<typename TMat>\n  inline double frobenius_normSq(const TMat& A)\n  {\n    return A.array().abs2().sum();\n  }\n\n  template<typename TMat>\n  inline double frobenius_norm(const TMat& A)\n  {\n    return std::sqrt(frobenius_normSq(A));\n  }\n\n  template<typename TMat>\n  inline double matrix_error(const TMat& m1, const TMat& m2)\n  {\n    auto m1n = m1 / FrobeniusNorm(m1);\n    auto m2n = m2 / FrobeniusNorm(m2);\n    return std::min(FrobeniusNorm(m1n - m2n), FrobeniusNorm(m1n + m2n));\n  }\n\n  OneACPose::Mat32 nullspace(const OneACPose::Vec3& N);\n}", "meta": {"hexsha": "4d88f87c6475167a6e62f9eea0b2bf3240b414c0", "size": 1302, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Samples/common/numeric.hpp", "max_stars_repo_name": "eivan/one-ac-pose", "max_stars_repo_head_hexsha": "79451626238f47130578c18b65e37cabd7332de1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-07-31T19:12:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T14:34:48.000Z", "max_issues_repo_path": "src/Samples/common/numeric.hpp", "max_issues_repo_name": "eivan/OneAC", "max_issues_repo_head_hexsha": "79451626238f47130578c18b65e37cabd7332de1", "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/Samples/common/numeric.hpp", "max_forks_repo_name": "eivan/OneAC", "max_forks_repo_head_hexsha": "79451626238f47130578c18b65e37cabd7332de1", "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": 20.6666666667, "max_line_length": 111, "alphanum_fraction": 0.6505376344, "num_tokens": 432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.798186787341014, "lm_q1q2_score": 0.7056284790572848}}
{"text": "#pragma once\n#include <algorithm>    // std::max\n#include <iostream>\n#include <boost/uuid/uuid.hpp>\n#include <boost/uuid/uuid_generators.hpp>\n#include <boost/uuid/uuid_io.hpp>\n#include <math.h>       /* log */\n#include <assert.h> \n#include <limits>\n\n\n\nclass DeterministicInterval {\n\n\tpublic:\n\t\tdouble lower;\n\t\tdouble upper;\n\n\tDeterministicInterval(double lower_, double upper_){\n\t\tlower = lower_;\n\t\tupper = upper_;\n\t}\n\n\tbool containsZero(){\n\t\treturn ((lower<=0) && (upper>=0));\n\t}\n\n\tvoid print(){\n\t\tstd::cout << \"my interval is: [\" << lower << \",\" << upper << \"]\" << std::endl;\n\t}\n\n};\n\n\nDeterministicInterval add(DeterministicInterval a, DeterministicInterval b){\n\tDeterministicInterval res(a.lower+b.lower,a.upper+b.upper);\n\treturn res;\n}\n\n\nDeterministicInterval sub(DeterministicInterval a, DeterministicInterval b){\n\tDeterministicInterval res(a.lower-b.lower,a.upper-b.upper);\n\treturn res;\n}\n\n\nDeterministicInterval mult(DeterministicInterval a, DeterministicInterval b){\n\n\tdouble p1 = a.lower * b.lower;\n\tdouble p2 = a.lower * b.upper;\n\tdouble p3 = a.upper * b.lower;\n\tdouble p4 = a.upper * b.upper;\n\n\tdouble min_ = std::min(std::min(p1,p2),std::min(p3,p4));\n\tdouble max_ = std::max(std::max(p1,p2),std::max(p3,p4));\n\n\tDeterministicInterval res(min_,max_);\n\treturn res;\n}\n\n\n\n\n\nDeterministicInterval max(DeterministicInterval a, DeterministicInterval b){\n\n\tdouble min_ = std::max(a.lower,b.lower);\n\tdouble max_ = std::max(a.upper,b.upper);\n\n\tDeterministicInterval res(min_,max_);\n\treturn res;\n}\n\nDeterministicInterval div(DeterministicInterval a, DeterministicInterval b){\n\n\tif (!b.containsZero()){\n\t\tDeterministicInterval inverse = DeterministicInterval(1./b.upper,1./b.lower);\n\t\treturn mult(a,inverse);\t\t\n\t}\n\telse {\n\t\tDeterministicInterval res(std::numeric_limits<double>::min(),std::numeric_limits<double>::max());\n\t}\n}\n\n\n\n\nDeterministicInterval sqrt_prod(DeterministicInterval a, DeterministicInterval b){\n\n\tDeterministicInterval prod = mult(a,b);\n\tdouble min_ = std::max(prod.lower,0.);\n\tassert(min_>0.0);\n\tdouble max_ = std::max(prod.upper,0.);\n\tassert(min_<max_);\n\tDeterministicInterval res(std::sqrt(min_),std::sqrt(max_));\n\treturn res;\n}\n\n\n\nDeterministicInterval log_(DeterministicInterval a){\n\n\tDeterministicInterval res(std::log(a.lower),std::log(a.upper));\n\treturn res;\n}\n\n\nDeterministicInterval exp_(DeterministicInterval a){\n\n\tDeterministicInterval res(std::exp(a.lower),std::exp(a.upper));\n\treturn res;\n}\n\n\nDeterministicInterval square(DeterministicInterval a){\n\tDeterministicInterval res = mult(a,a);\n\tres.lower = std::max(0.,res.lower);\n\treturn res;\n}\n\n\nDeterministicInterval scale(double c, DeterministicInterval a){\n\tif (c>0.){\n\t\tDeterministicInterval res(a.lower*c,a.upper*c);\n\t\treturn res;\n\t}\n\telse if (c<0.){\n\t\tDeterministicInterval res(a.upper*c,a.lower*c);\n\t\treturn res;\n\t}\n\telse {\n\t\tDeterministicInterval res(0.,0.);\n\t\treturn res;\n\t}\n}\n\n\nDeterministicInterval constant_(double c){\n\n\tDeterministicInterval res(c,c);\n\treturn res;\n\n}\n\n\nDeterministicInterval union_(DeterministicInterval a, DeterministicInterval b){\n\tDeterministicInterval res(std::min(a.lower,b.lower),std::max(a.upper,b.upper));\n\treturn res;\n}\n\n\n", "meta": {"hexsha": "86b62b8a34f41efde67e0f2ca98e943e79401f92", "size": 3139, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "autoppl/program_analysis/UncertainIntervals/IntervalAnalysis.hpp", "max_stars_repo_name": "uiuc-arc/Statheros", "max_stars_repo_head_hexsha": "ca4d3057030a594550ba1d238be695b6a04b0d8f", "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": "autoppl/program_analysis/UncertainIntervals/IntervalAnalysis.hpp", "max_issues_repo_name": "uiuc-arc/Statheros", "max_issues_repo_head_hexsha": "ca4d3057030a594550ba1d238be695b6a04b0d8f", "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": "autoppl/program_analysis/UncertainIntervals/IntervalAnalysis.hpp", "max_forks_repo_name": "uiuc-arc/Statheros", "max_forks_repo_head_hexsha": "ca4d3057030a594550ba1d238be695b6a04b0d8f", "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": 20.6513157895, "max_line_length": 99, "alphanum_fraction": 0.7206116598, "num_tokens": 790, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392909114836, "lm_q2_score": 0.7981867705385762, "lm_q1q2_score": 0.70562846664185}}
{"text": "// Group B - Perpetual American Options\r\n//\r\n// by Scott Sidoli\r\n//\r\n// 6-10-19\r\n//\r\n// NormalDistribution.hpp\r\n//\r\n// Implementation of cdf and pdf for black-scholes. Utililizes boost libraries.\r\n\r\n#ifndef NormalDistribution_hpp\r\n#define NormalDistribution_hpp\r\n\r\n#include <iostream>\r\n\r\nusing namespace std;\r\n#include <boost/math/distributions/normal.hpp>\r\n#include <boost/math/distributions.hpp> \r\nusing namespace boost::math;\r\n\r\n\r\ndouble N(double x)\r\n{\r\n\r\n\tnormal_distribution<> myNormal(0.0, 1.0);\r\n\r\n\treturn cdf(myNormal, x);\r\n\r\n}\r\n\r\ndouble n(double x)\r\n{\r\n\r\n\tnormal_distribution<> myNormal(0.0, 1.0);\r\n\r\n\treturn pdf(myNormal, x);\r\n\r\n}\r\n\r\n#endif\r\n", "meta": {"hexsha": "b312aa4951d932513ba28ad90bf76f4f18eb05ca", "size": 652, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Group B/Group B/NormalDistribution.hpp", "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": "Group B/Group B/NormalDistribution.hpp", "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": "Group B/Group B/NormalDistribution.hpp", "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": 15.9024390244, "max_line_length": 80, "alphanum_fraction": 0.6825153374, "num_tokens": 158, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.7799929104825006, "lm_q1q2_score": 0.7056209998326597}}
{"text": "///\n/// @author  Thomas Lehmann\n/// @file    primes.cxx\n/// @brief   generating primes\n///\n/// Copyright (c) 2015 Thomas Lehmann\n///\n/// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n/// documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation\n/// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,\n/// and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n///\n/// The above copyright notice and this permission notice shall be included in all copies\n/// or substantial portions of the Software.\n///\n/// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n/// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n/// DAMAGES OR OTHER LIABILITY,\n/// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n#include <math/prime/sieve_of_eratosthenes.h>\n#include <math/prime/sieve_of_eratosthenes_optimized.h>\n#include <math/number.h>\n#include <generator/select.h>\n#include <performance/measurement.h>\n\n#include <boost/program_options.hpp>\n#include <string>\n#include <memory>\n#include <iomanip>\n#include <iostream>\n#include <cstdint>\n\n/// @struct options\n/// @brief parsed command line options\nstruct Options {\n    /// type of filter function\n    using filter_function_type = std::function<bool (const uint64_t&)>;\n\n    uint64_t max_number;         ///! the biggest number that should be checked to be a prime.\n    uint64_t start_number;       ///! starting output with first prime >= this number.\n    uint64_t max_columns;        ///! number of columns for printing primes\n    filter_function_type filter; ///! additional filter function\n    std::string sieve;           ///! sieve algorithm\n\n    /// default c'tor initializing defaults\n    Options()\n        : max_number(1000), start_number(2), max_columns(10), filter(nullptr), sieve(\"default\") {}\n};\n\n/// Providing filter as configured.\n/// @param filter_name name of the filter\n/// @return concrete filter function or true function.\nOptions::filter_function_type resolve_filter(const std::string& filter_name) noexcept {\n    if (filter_name == \"pandigital\") {\n        std::cout << \" ... applying 'pandigital' filter\" << std::endl;\n        return [](const uint64_t number) {return math::number<uint64_t>::is_pandigital(number);};\n    }\n    if (filter_name == \"palindrome\") {\n        std::cout << \" ... applying 'palindrome' filter\" << std::endl;\n        return [](const uint64_t number) {return math::number<uint64_t>::is_palindrome(number);};\n    }\n    std::cout << \" ... no additional filter\" << std::endl;\n    return [](const uint64_t) {return true;};\n} \n\n/// @param argc number of parameters\n/// @param argv array of parameters\n/// @param options where to store the parsed command line options\n/// @return true when all is fine and application can use the option(s).\nstatic bool parse(int argc, char** argv, Options& options) {\n    namespace po = boost::program_options;\n    std::string filter_name;\n    po::options_description description(\"Allowed options for tool 'primes'\");\n    description.add_options()\n        (\"help\", \"print this help\")\n        (\"max-number\", po::value<uint64_t>(&options.max_number)->default_value(1000),\n         \"generating primes up to this limit (default: 1000)\")\n        (\"start-number\", po::value<uint64_t>(&options.start_number)->default_value(2),\n         \"printing primes >= this number (default: 2)\")\n        (\"columns\", po::value<uint64_t>(&options.max_columns)->default_value(10),\n         \"number of columns (default: 10)\")\n        (\"filter\", po::value<std::string>(&filter_name)->default_value(\"\"),\n         \"providing filter name (default: none).\")\n        (\"sieve\", po::value<std::string>(&options.sieve)->default_value(\"default\"),\n         \"sieve algorithm short name (default: 'default', other is 'optimized').\")\n        ;\n\n    po::variables_map vm;\n    po::store(po::parse_command_line(argc, argv, description), vm);\n    po::notify(vm);\n\n    if (vm.count(\"help\")) {\n        std::cout << description << std::endl;\n        return false;\n    }\n\n    options.filter = resolve_filter(filter_name);\n\n    if (options.max_columns < 1) {\n        std::cout << \"error: You cannot have 0 columns\" << std::endl;\n        return false;\n    }\n\n    if (options.max_number < 2) {\n        std::cout << \"No primes possible with a limit of \"\n                  << options.max_number << std::endl;\n    }\n\n    return true;\n}\n\n/// @return sieve algorithm depending on command line option\ntemplate <typename T>\nstd::unique_ptr<math::prime::sieve_interface<T>> create_sieve(const Options& options) noexcept {\n    if (options.sieve == \"optimized\") {\n        return std::unique_ptr<math::prime::sieve_interface<T>>(\n            new math::prime::sieve_of_eratosthenes_optimized<T>(options.max_number));\n    }\n\n    return std::unique_ptr<math::prime::sieve_interface<T>>(\n        new math::prime::sieve_of_eratosthenes<T>(options.max_number));\n}\n\n/// Simple example demonstrating how to generate primes.\n///\n/// @param argc number of parameters\n/// @param argv array of parameters\n/// @return 0 when succeeded, 1 when failed or when used the help\nint main(int argc, char** argv) {\n    std::cout << \"prime tool (version \" << VERSION << \")\" << std::endl;\n\n    Options options;\n    // parsing command line options\n    if (!parse(argc, argv, options)) {\n        return 1;\n    }\n\n    std::cout << \" ... creating sieve up to max. number: \" << options.max_number << std::endl;\n    /// initializing maximum 'size' of sieve\n    auto sieve = create_sieve<std::vector<bool>>(options);\n\n    const auto sieve_duration = performance::measure<std::milli>([&sieve]() {\n        /// calculating the primes and none primes\n        sieve->calculate();\n    });\n\n    std::cout << \" ... collecting primes\" << std::endl;\n    std::cout << std::endl;\n\n    /// printing out all primes\n    constexpr auto step = static_cast<uint64_t>(1);\n    const auto primes = generator::select(options.start_number, options.max_number, step)\n           .where([&sieve](const int n){return sieve->is_prime(n);})\n           .where(options.filter)\n           .to_vector();\n\n    const auto width = math::digits<int>::count(*(primes.end()-1)) + 1;\n\n    auto column = static_cast<uint64_t>(0);\n    for (const auto& prime: primes) {\n        std::cout << std::setw(width) << prime;\n        ++column;\n        if (column % options.max_columns == 0) {\n            std::cout << std::endl;\n        }\n    }\n    std::cout << std::endl << std::endl;\n    std::cout << \" ... \" << primes.size() << \" primes found.\" << std::endl;\n    std::cout << \" ... Sieve calculation took \" << sieve_duration << \"ms.\" << std::endl;\n    return 0;\n}\n", "meta": {"hexsha": "0669c0ed042b88d0ba93bba36fa859df15382a81", "size": 7049, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "examples/primes.cxx", "max_stars_repo_name": "Nachtfeuer/demo-cpp", "max_stars_repo_head_hexsha": "6449c99dd43ec862b02d6431fd59f443ba400f62", "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": "examples/primes.cxx", "max_issues_repo_name": "Nachtfeuer/demo-cpp", "max_issues_repo_head_hexsha": "6449c99dd43ec862b02d6431fd59f443ba400f62", "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": "examples/primes.cxx", "max_forks_repo_name": "Nachtfeuer/demo-cpp", "max_forks_repo_head_hexsha": "6449c99dd43ec862b02d6431fd59f443ba400f62", "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.28, "max_line_length": 115, "alphanum_fraction": 0.6586749894, "num_tokens": 1664, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511616741041, "lm_q2_score": 0.8244619242200081, "lm_q1q2_score": 0.7056166955997611}}
{"text": "//compute_returns.cpp\n\n#include<string>\n\n#include <algorithm>\n\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics.hpp>\n\n#include \"pca.h\"\n#include \"compute_returns_eigen.h\"\n\nusing namespace boost::accumulators;\n\nVec computeRiskReturn(const Vec& assetReturns) {\n\taccumulator_set<double, features<tag::mean, tag::variance> > acc;\n\tacc = std::for_each(assetReturns.begin(), assetReturns.end(), acc);\n\n\tVec tmp;\n\ttmp.push_back(boost::accumulators::mean(acc)); //boost mean\n\ttmp.push_back(boost::accumulators::variance(acc)); //boost sigma\n\n\treturn tmp;\n}\n\nComputeReturn::ComputeReturn(unsigned int _period, unsigned int _k)\n:period(_period),k(_k),logRtns(false)\n{\n   \tmPrices.clear(), mAssetReturns.clear(), mMeanReturns.clear();\n   \tmPrices.resize(1,Vec(1)), mAssetReturns.resize(1,Vec(1)), VarCov.resize(0,0);\n}\n\nComputeReturn::ComputeReturn(const Vec& _prices,\n\t\t\t\t  \t  \t  \t unsigned int _period,\n\t\t\t\t  \t  \t  \t unsigned int _k,\n\t\t\t\t\t\t\t bool _logRtns)\n:period(_period),k(_k),logRtns(_logRtns)\n{\n\tmPrices.clear(), mAssetReturns.clear(), mMeanReturns.clear();\n\n\tsize_t n(_prices.size());\n\n\tmPrices.resize(1, Vec(n));\n\tmPrices[0] = _prices;\n\n\t//Compute rtns\n\tmAssetReturns.resize(1, Vec(n));\n\tlogRtns ? this->_geometricReturns() : this->_arithmetricReturns();\n\n\t//Compute average return and volatility\n\tVec tmp = computeRiskReturn(mAssetReturns[0]);\n\n\tmMeanReturns.push_back(tmp[0]);\n\n\tVarCov.resize(1,1);\n\n    VarCov(0,0) = tmp[1];\n}\n\nComputeReturn::ComputeReturn(const Mat& _prices,\n\t\t\t\t  \t\t\t unsigned int _period,\n\t\t\t\t  \t\t\t unsigned int _k ,\n                  \t\t\t bool _logRtns)\n:period(_period),k(_k),logRtns(_logRtns)\n{\n\tmPrices.clear(), mAssetReturns.clear(), mMeanReturns.clear();\n\n\tsize_t m(_prices.size());\n\tsize_t n(_prices[0].size());\n\n\tmPrices.resize(m, Vec(n));\n\tmPrices = _prices;\n\n    mAssetReturns.resize(m, Vec(n));\n\t//Compute rtns\n\tfor(size_t i = 0;i < m;++i)\n\t\tlogRtns ? _geometricReturns(i) : _arithmetricReturns(i);\n\n\t//1. average rtn\n\tfor(size_t i = 0;i < m;++i){\n\n\t\taccumulator_set<double, features<tag::mean> > acc;\n\t\tacc = std::for_each(mAssetReturns[i].begin(), mAssetReturns[i].end(), acc);\n\n\t\tmMeanReturns.push_back(boost::accumulators::mean(acc)); //boost mean\n\t}\n\n\t//Compute Var-Cov matrix\n\n\tVarCov.resize(m,m);\n\n\tfor(size_t i = 0;i <m;++i){\n\t\tfor(size_t j = 0;j <m;++j){\n\n\t\t\t//2. compute covariance\n\t\t\tVec _tmp;\n\n\t\t\tdouble q = mAssetReturns[i].size() < mAssetReturns[j].size() ? mAssetReturns[i].size() : mAssetReturns[j].size();\n\n\t\t\tfor(size_t p = 0;p < q;++p)\n\t\t\t\t_tmp.push_back((mAssetReturns[i][p] - mMeanReturns[i]) * (mAssetReturns[j][p] - mMeanReturns[j]));\n\n\t\t\taccumulator_set<double, features<tag::mean> > acc;\n\t\t\tacc = std::for_each(_tmp.begin(), _tmp.end(), acc);\n\n\t\t\tVarCov(i,j) = boost::accumulators::mean(acc); //boost mean\n\n\t\t}\n\t}\n}\n\n\nComputeReturn::ComputeReturn(const ComputeReturn& other):\n\n    period(other.period), k(other.k), logRtns(other.logRtns),\n\tmPrices(other.mPrices), mAssetReturns(other.mAssetReturns),\n\tmMeanReturns(other.mMeanReturns), VarCov(other.VarCov)\n{}\n\nvoid ComputeReturn::arithmetricReturns(const Vec& _prices)\n{\n    mPrices.resize(1, Vec(_prices.size()));\n\n\tmPrices[0] = _prices;\n\t_arithmetricReturns();\n}\n\nvoid ComputeReturn::geometricReturns(const Vec& _prices)\n{\n    mPrices.resize(1, Vec(_prices.size()));\n\n\tmPrices[0] = _prices;\n\t_geometricReturns();\n}\n\nvoid ComputeReturn::arithmetricReturns(const Mat& _prices){\n\n    mPrices = _prices;\n\n    for(size_t i = 0;i < mPrices.size();++i)\n        _arithmetricReturns(i);\n}\n\nvoid ComputeReturn::geometricReturns(const Mat& _prices){\n\n    mPrices = _prices;\n\n    for(size_t i = 0;i < mPrices.size();++i)\n\t\t _geometricReturns(i);\n}\n\nvoid ComputeReturn::setPeriod(unsigned int _period){\n\n\tperiod = _period;\n\n\tfor(size_t i = 0;i < mPrices.size();++i){\n\t\tlogRtns ? _geometricReturns(i) : _arithmetricReturns(i);\n\t}\n}\n\nvoid ComputeReturn::setWindow(unsigned int _k){\n\n\tk = _k;\n\n\tfor(size_t i = 0;i < mPrices.size();++i){\n\t\tlogRtns ? _geometricReturns(i) : _arithmetricReturns(i);\n\t}\n}\n\nVec ComputeReturn::getReturns(size_t p) const {return mAssetReturns[p];}\n\ndouble ComputeReturn::getMeanReturn(size_t p) const {return mMeanReturns[p];}\n\ndouble ComputeReturn::getStdDev(size_t p) const {return sqrt(VarCov(p,p));}\n\n\nVec ComputeReturn::getRollingMean(size_t p) const {\n\n\tVec RollingMeanReturns;\n\n\tfor(unsigned int i = 0;i < mAssetReturns[p].size() - k;++i){\n\n        Vec _assetReturns;\n\n        for(unsigned int j = i; j < i + k; ++j)\n            _assetReturns.push_back(mAssetReturns[p][j]);\n\n\t\tRollingMeanReturns.push_back(computeRiskReturn(_assetReturns)[0]);\n\t}\n\n\treturn RollingMeanReturns;\n}\n\nVec ComputeReturn::getRollingStdDev(size_t p) const {\n\n\tVec RollingSigmastminus1;\n\n\tfor(unsigned int i = 0;i < mAssetReturns[p].size() - k;++i){\n\n    \tVec _assetReturns;\n\n        for(unsigned int j = i; j < i + k; ++j)\n        \t_assetReturns.push_back(mAssetReturns[p][j]);\n\n\t\tRollingSigmastminus1.push_back(sqrt(computeRiskReturn(_assetReturns)[1]));\n\t}\n\n\treturn RollingSigmastminus1;\n}\n\n\nEigen::MatrixXd ComputeReturn::getCorrelMat(){\n\n\tsize_t m = VarCov.cols();\n\n\tEigen::MatrixXd CorrelMat(m,m);\n\n    for(size_t i = 0;i < m;++i)\n        for(size_t j = 0;j < m;++j)\n            CorrelMat(i,j) = VarCov(i,j)/sqrt(VarCov(i,i) * VarCov(j,j));\n\n    return CorrelMat;\n}\n\nvoid ComputeReturn::setReturns(const Mat& _mAssetReturns){\n\n\tmAssetReturns = _mAssetReturns;\n}\n\nvoid ComputeReturn::correlReweightedRtns(const Eigen::MatrixXd& Chat){\n\n\tEigen::MatrixXd C = this->getCorrelMat();\n\n    Eigen::MatrixXd A( C.llt().matrixL() );\n\n    Eigen::MatrixXd Ahat( Chat.llt().matrixL() );\n\n\tsize_t m = mAssetReturns.size();\n\tsize_t n = mAssetReturns[0].size();\n\n    //Fill correl matrix to Eigen matrix\n    MatrixXd R(m,n);\n    for(size_t i = 0;i <m;++i)\n        for(size_t j = 0;j <n;++j)\n            R(i,j) = mAssetReturns[i][j];\n\n    MatrixXd Rhat(n,m);\n    Rhat = Ahat * A.inverse() * R;\n\n\t//Back to std::vector\n    for(size_t i = 0;i <m;++i)\n        for(size_t j = 0;j <n;++j)\n             mAssetReturns[i][j] = Rhat(i,j);\n\n}\n\nEigen::MatrixXd ComputeReturn::computePC(){\n\n    // convert to req format\n    vector<float> vec;\n\n\tsize_t n = VarCov.rows();\n\tsize_t m = VarCov.cols();\n\n    for(size_t i = 0;i < n;++i)\n        for(size_t j = 0;j < m;++j)\n            vec.push_back(VarCov(i,j));\n\n\tstd::shared_ptr<Pca> pca(new Pca());\n\n  \tint init_result = pca->Calculate(vec, n, m);//, true, true, false);\n  \tif(init_result == 1) cout << \"correl matrix not positive definite\" << endl;\n\n    vector<float> scores = pca->scores(); //Rotated data\n\n  \tunsigned int kaiser = pca->kaiser(); //Kaiser criterion 99%\n\n    unsigned int nrows = pca->nrows();\n\n\tEigen::MatrixXd PC(nrows, kaiser);\n\n\tfor(size_t i = 0;i < nrows;++i)\n\t\tfor(size_t j = 0;j < kaiser;++j)\n\t\t\tPC(i,j) = scores[j + kaiser*i];\n\n\treturn PC;\n}\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "480921cd12dc7bf349930492e75c2e4895da4ba4", "size": 6839, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/compute_returns_eigen.cpp", "max_stars_repo_name": "vigor-ish/riskjs", "max_stars_repo_head_hexsha": "6f0aa646821272f64959553ea042819b74a21efc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-08-31T08:33:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-23T04:26:16.000Z", "max_issues_repo_path": "src/compute_returns_eigen.cpp", "max_issues_repo_name": "vigor-ish/riskjs", "max_issues_repo_head_hexsha": "6f0aa646821272f64959553ea042819b74a21efc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-09-02T02:33:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-02T02:33:13.000Z", "max_forks_repo_path": "src/compute_returns_eigen.cpp", "max_forks_repo_name": "vigor-ish/riskjs", "max_forks_repo_head_hexsha": "6f0aa646821272f64959553ea042819b74a21efc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-11-19T18:21:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-23T04:26:17.000Z", "avg_line_length": 23.0269360269, "max_line_length": 116, "alphanum_fraction": 0.6641321831, "num_tokens": 2000, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972583359805, "lm_q2_score": 0.8104789132480439, "lm_q1q2_score": 0.705600719812872}}
{"text": "#include \"rng.h\"\n#include <boost/random.hpp>\n#include <boost/random/normal_distribution.hpp>\n//#include <eigen3/Eigen/Dense>\n//#include <eigen3/Eigen/Cholesky>\n#include <ctime>\n#include <iostream>\n\n// random number generator engine\nboost::mt19937 rng_g(std::time(0)) ;\nboost::normal_distribution<double> normal_dist ;\nboost::variate_generator< boost::mt19937, boost::normal_distribution<double> > var_gen( rng_g, normal_dist ) ;\nboost::uniform_01<> uni_dist ;\n//bool seeded = false ;\n\n//void seed_rng()\n//{\n//    std::cout << \"seeding rng\" << std::endl ;\n//    rng_g.seed( std::time(0) ) ;\n//    seeded = true;\n//}\n\ndouble randn()\n{\n//    if (!seeded)\n//        seed_rng() ;\n    return var_gen() ;\n}\n\ndouble randu01()\n{\n//    if (!seeded)\n//        seed_rng() ;\n    return uni_dist(rng_g) ;\n}\n\nvoid randmvn3(double* mean, double* cov, int n, double* results){\n    // compute cholesky decomposition of covariance matrix\n    double L11 = sqrt(cov[0]) ;\n    double L21 = cov[1]/L11 ;\n    double L22 = sqrt(cov[4]-pow(L21,2)) ;\n    double L31 = cov[2]/L11 ;\n    double L32 = (cov[5]-L31*L21)/L22 ;\n    double L33 = sqrt(cov[8] - pow(L31,2) - pow(L32,2)) ;\n\n    // multiply uncorrelated normal random samples by decomposition to produce\n    // correlated samples, and add mean\n    for ( int i = 0 ; i < n ; i++ ){\n        double x1 = randn() ;\n        double x2 = randn() ;\n        double x3 = randn() ;\n        results[i] = x1*L11 + mean[0];\n        results[i+n] = x1*L21 + x2*L22 + mean[1] ;\n        results[i+2*n] = x1*L31 + x2*L32 + x3*L33 + mean[2] ;\n    }\n}\n", "meta": {"hexsha": "8addb319a0ee01f22dceba3fe2fd985c0dddf66f", "size": 1559, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/rng.cpp", "max_stars_repo_name": "cheesinglee/cuda-PHDSLAM", "max_stars_repo_head_hexsha": "e3844904a3dae8e1bcfe1d7f3898beccd67178b5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-02-11T18:08:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T07:27:45.000Z", "max_issues_repo_path": "src/rng.cpp", "max_issues_repo_name": "cheesinglee/cuda-PHDSLAM", "max_issues_repo_head_hexsha": "e3844904a3dae8e1bcfe1d7f3898beccd67178b5", "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": "src/rng.cpp", "max_forks_repo_name": "cheesinglee/cuda-PHDSLAM", "max_forks_repo_head_hexsha": "e3844904a3dae8e1bcfe1d7f3898beccd67178b5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-11-19T09:57:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-26T15:21:41.000Z", "avg_line_length": 27.350877193, "max_line_length": 110, "alphanum_fraction": 0.6087235407, "num_tokens": 482, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418178895028, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.7055672781535385}}
{"text": "#include \"problemes.h\"\n#include \"arithmetique.h\"\n\n#include <fstream>\n#include <boost/algorithm/string.hpp>\n\ntypedef unsigned long long nombre;\ntypedef std::vector<nombre> vecteur;\ntypedef std::vector<vecteur> matrice;\n\nENREGISTRER_PROBLEME(81, \"Path sum: two ways\") {\n    // In the 5 by 5 matrix below, the minimal path sum from the top left to the bottom right, by \n    // only moving to the right and down, is indicated in bold red and is equal to 2427.\n    //\t\t      \n    //              131 673 234 103  18\n    //              201  96 342 965 150\n    //              630 803 746 422 111\n    //              537 699 497 121 956\n    //              805 732 524  37 331\n    //\n    // Find the minimal path sum, in matrix.txt (right click and \"Save Link/Target As...\"), a 31K\n    // text file containing a 80 by 80 matrix, from the top left to the bottom right by only moving \n    // right and down.\n    matrice graphe;\n    std::ifstream ifs(\"data/p081_matrix.txt\");\n    std::string ligne;\n    while (ifs >> ligne) {\n        std::vector<std::string> v;\n        boost::split(v, ligne, boost::is_any_of(\",\"));\n        vecteur l;\n        for (const auto &s: v) {\n            l.push_back(std::stoull(s));\n        }\n        graphe.push_back(std::move(l));\n    }\n\n    const nombre taille = graphe.size();\n    matrice chemin(taille, vecteur(taille, 0));\n    for (size_t i = 0; i < taille; ++i)\n        for (size_t j = 0; j < taille; ++j) {\n            if (i == 0 && j == 0)\n                chemin[i][j] = graphe[i][j];\n            else if (i == 0)\n                chemin[i][j] = graphe[i][j] + chemin[i][j - 1];\n            else if (j == 0)\n                chemin[i][j] = graphe[i][j] + chemin[i - 1][j];\n            else\n                chemin[i][j] = graphe[i][j] + std::min(chemin[i][j - 1], chemin[i - 1][j]);\n\n        }\n    return std::to_string(chemin.back().back());\n}\n", "meta": {"hexsha": "0821f8741271f223c3bd66989397a8759152ec79", "size": 1869, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problemes/probleme0xx/probleme081.cpp", "max_stars_repo_name": "ZongoForSpeed/ProjectEuler", "max_stars_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-10-13T17:07:21.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-08T11:50:22.000Z", "max_issues_repo_path": "problemes/probleme0xx/probleme081.cpp", "max_issues_repo_name": "ZongoForSpeed/ProjectEuler", "max_issues_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "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": "problemes/probleme0xx/probleme081.cpp", "max_forks_repo_name": "ZongoForSpeed/ProjectEuler", "max_forks_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "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.2641509434, "max_line_length": 100, "alphanum_fraction": 0.5387907972, "num_tokens": 558, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418241572634, "lm_q2_score": 0.7634837527911057, "lm_q1q2_score": 0.7055672680188055}}
{"text": "// Copyright (c) FIRST and other WPILib contributors.\n// Open Source Software; you can modify and/or share it under the terms of\n// the WPILib BSD license file in the root directory of this project.\n\n#include \"sysid/analysis/OLS.h\"\n\n#include <tuple>\n#include <vector>\n\n#include <Eigen/Cholesky>\n#include <Eigen/Core>\n\nusing namespace sysid;\n\nstd::tuple<std::vector<double>, double> sysid::OLS(\n    const std::vector<double>& data, size_t independentVariables) {\n  // Perform some quick sanity checks regarding the size of the vector.\n  assert(data.size() % (independentVariables + 1) == 0);\n\n  // The linear model can be written as follows:\n  // y = X\u03b2 + u, where y is the dependent observed variable, X is the matrix\n  // of independent variables, \u03b2 is a vector of coefficients, and u is a\n  // vector of residuals.\n\n  // We want to minimize u^2 = u'u = (y - X\u03b2)'(y - X\u03b2).\n  // \u03b2 = (X'X)^-1 (X'y)\n\n  // Get the number of elements.\n  size_t n = data.size() / (independentVariables + 1);\n\n  // Create new variables to make things more readable.\n  size_t rows = n;\n  size_t cols = independentVariables;  // X\n  size_t strd = independentVariables + 1;\n\n  // Create y and X matrices.\n  Eigen::Map<const Eigen::MatrixXd, 0, Eigen::Stride<1, Eigen::Dynamic>> y(\n      data.data() + 0, rows, 1, Eigen::Stride<1, Eigen::Dynamic>(1, strd));\n\n  Eigen::Map<const Eigen::MatrixXd, 0, Eigen::Stride<1, Eigen::Dynamic>> X(\n      data.data() + 1, rows, cols, Eigen::Stride<1, Eigen::Dynamic>(1, strd));\n\n  // Calculate b = \u03b2 that minimizes u'u.\n  Eigen::MatrixXd b = (X.transpose() * X).llt().solve(X.transpose() * y);\n\n  // We will now calculate r^2 or the coefficient of determination, which\n  // tells us how much of the total variation (variation in y) can be\n  // explained by the regression model.\n\n  // We will first calculate the sum of the squares of the error, or the\n  // variation in error (SSE).\n  double SSE = (y - X * b).squaredNorm();\n\n  // Now we will calculate the total variation in y, known as SSTO.\n  double SSTO = ((y.transpose() * y) - (1 / n) * (y.transpose() * y)).value();\n\n  double rSquared = (SSTO - SSE) / SSTO;\n  double adjRSquared = 1 - (1 - rSquared) * ((n - 1.0) / (n - 3));\n\n  return {{b.data(), b.data() + b.rows()}, adjRSquared};\n}\n", "meta": {"hexsha": "595ae10aefde4321af9c3568dccbcc7544e495f9", "size": 2253, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main/native/cpp/analysis/OLS.cpp", "max_stars_repo_name": "KyleQ1/Characterization-Robot-2020", "max_stars_repo_head_hexsha": "f28bb07fab05587e7462937ce3e0f9fe40a5f014", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2021-02-12T02:54:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T22:20:18.000Z", "max_issues_repo_path": "src/main/native/cpp/analysis/OLS.cpp", "max_issues_repo_name": "KyleQ1/Characterization-Robot-2020", "max_issues_repo_head_hexsha": "f28bb07fab05587e7462937ce3e0f9fe40a5f014", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 245.0, "max_issues_repo_issues_event_min_datetime": "2021-02-12T02:56:25.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T23:52:00.000Z", "max_forks_repo_path": "sysid-application/src/main/native/cpp/analysis/OLS.cpp", "max_forks_repo_name": "Piphi5/sysid", "max_forks_repo_head_hexsha": "dcf459d737df946e8397367ae2c16361357f09a9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 23.0, "max_forks_repo_forks_event_min_datetime": "2021-02-12T03:05:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T03:38:07.000Z", "avg_line_length": 36.3387096774, "max_line_length": 78, "alphanum_fraction": 0.6591211718, "num_tokens": 649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418158002492, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.7055672666117165}}
{"text": "#include <trajopt_utils/macros.h>\nTRAJOPT_IGNORE_WARNINGS_PUSH\n#include <Eigen/Core>\nTRAJOPT_IGNORE_WARNINGS_POP\n\nnamespace util\n{\ntemplate <typename VectorT>\nEigen::VectorXi searchsorted(const VectorT& x, const VectorT& y)\n{\n  // y(i-1) <= x(out(i)) < y(i)\n  int nX = x.size();\n  int nY = y.size();\n\n  Eigen::VectorXi out(nX);\n  int iY = 0;\n  for (int iX = 0; iX < nX; iX++)\n  {\n    while (iY < nY && x[iX] > y[iY])\n      iY++;\n    out(iX) = iY;\n  }\n  return out;\n}\n\ntemplate <typename MatrixT, typename VectorT>\nMatrixT interp2d(const VectorT& xNew, const VectorT& xOld, const MatrixT& yOld)\n{\n  int nNew = xNew.size();\n  int nOld = xOld.size();\n  MatrixT yNew(nNew, yOld.cols());\n  Eigen::VectorXi new2old = searchsorted(xNew, xOld);\n  for (int iNew = 0; iNew < nNew; iNew++)\n  {\n    int iOldAbove = new2old(iNew);\n    if (iOldAbove == 0)\n      yNew.row(iNew) = yOld.row(0);\n    else if (iOldAbove == nOld)\n      yNew.row(iNew) = yOld.row(nOld - 1);\n    else\n    {\n      double t = (xNew(iNew) - xOld(iOldAbove - 1)) / (xOld(iOldAbove) - xOld(iOldAbove - 1));\n      yNew.row(iNew) = yOld.row(iOldAbove - 1) * (1 - t) + yOld.row(iOldAbove) * t;\n    }\n  }\n  return yNew;\n}\n}\n", "meta": {"hexsha": "79d7f7550e3b2ed4f52bbd7b1c4058d3d4fc1cc4", "size": 1176, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "moveit_planners/trajopt/trajopt_utils/include/trajopt_utils/interpolation.hpp", "max_stars_repo_name": "adam-vonderviszt/moveit", "max_stars_repo_head_hexsha": "b18b8c66963907aa6d03cbee4450fc3d6e740162", "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": "moveit_planners/trajopt/trajopt_utils/include/trajopt_utils/interpolation.hpp", "max_issues_repo_name": "adam-vonderviszt/moveit", "max_issues_repo_head_hexsha": "b18b8c66963907aa6d03cbee4450fc3d6e740162", "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": "moveit_planners/trajopt/trajopt_utils/include/trajopt_utils/interpolation.hpp", "max_forks_repo_name": "adam-vonderviszt/moveit", "max_forks_repo_head_hexsha": "b18b8c66963907aa6d03cbee4450fc3d6e740162", "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": 24.0, "max_line_length": 94, "alphanum_fraction": 0.6096938776, "num_tokens": 424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.8056321959813275, "lm_q1q2_score": 0.7055622025169669}}
{"text": "//\n// Created by Jakub Tyrcha on 13/11/2017.\n//\n\n#include \"utilities.h\"\n#include <vector>\n#include <numeric>\n#include <boost/hana/functional/compose.hpp>\nnamespace hana = boost::hana;\n\nbool is_prime(size_t i) {\n    for(size_t j = 2; j*j <= i; ++j) {\n        if((i % j) == 0) {\n            return false;\n        }\n    }\n    return true;\n}\n\nsize_t next_prime(size_t v) {\n    while(!is_prime(v++)) {}\n    return --v;\n}\n\nstd::vector<size_t> generate_prime_size() {\n    std::vector<size_t> sizes;\n    sizes.resize(50);\n    std::iota(sizes.begin(), sizes.end(), 0);\n    std::transform(sizes.begin(), sizes.end(), sizes.begin(),\n                   hana::compose([](size_t v){\n                       return next_prime(v);\n                   },[](size_t v){\n                       constexpr size_t exp_b = 10;\n                       if(v < exp_b) {\n                           return 2 << v;\n                       }\n                       else {\n                           return (2 << (exp_b + (v - exp_b) / 2))\n                                  + ((v % 2) ? 2 << (exp_b + (v - exp_b) / 2 - 1) : 0);\n                       }\n                   })\n    );\n    return sizes;\n}\n\nvoid print_prime_tables() {\n    auto sizes = generate_prime_size();\n\n    printf(\"{ \");\n    size_t i=1;\n    for(auto s : sizes) {\n        printf(\"%lu, \", s); if(((i++) % 10) == 0) printf(\"\\n\");\n    }\n    printf(\"};\");\n\n    printf(\"\\n\");\n\n    printf(\"{ \");\n    for(auto s : sizes) {\n        printf(\"case %lu: return hash %% %lu;\\n\", s, s);\n    }\n    printf(\"};\");\n}\n", "meta": {"hexsha": "4b847313c6d3479672719ac3c7ca5b8c6e2e8865", "size": 1531, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "utilities.cpp", "max_stars_repo_name": "jakubtyrcha/notthefastesthashtable", "max_stars_repo_head_hexsha": "5d966cfce2b67ff3e1bf5c746908385a5a936fe0", "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": "utilities.cpp", "max_issues_repo_name": "jakubtyrcha/notthefastesthashtable", "max_issues_repo_head_hexsha": "5d966cfce2b67ff3e1bf5c746908385a5a936fe0", "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": "utilities.cpp", "max_forks_repo_name": "jakubtyrcha/notthefastesthashtable", "max_forks_repo_head_hexsha": "5d966cfce2b67ff3e1bf5c746908385a5a936fe0", "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.921875, "max_line_length": 87, "alphanum_fraction": 0.4337034618, "num_tokens": 405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.938124016006303, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.7054810505688479}}
{"text": "#ifndef RLSS_INTERNAL_SVM_HPP\n#define RLSS_INTERNAL_SVM_HPP\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <Eigen/StdVector>\n#include <qp_wrappers/problem.hpp>\n#include <qp_wrappers/cplex.hpp>\n#include <rlss/internal/Util.hpp>\n#include <absl/strings/str_cat.h>\n\nnamespace rlss {\n\nnamespace internal {\n\n/*\n* Calculate the svm hyperplane between two set of points f and s\n* such that for all points p \\in f, np + d < 0 where n is the normal\n* of the hyperplane and d is the offset of the hyperplane.\n*/\ntemplate<typename T, unsigned int DIM>\nHyperplane<T, DIM> svm(\n    const StdVectorVectorDIM<T,DIM>& f, \n    const StdVectorVectorDIM<T,DIM>& s) {\n\n    QPWrappers::Problem<T> svm_qp(DIM + 1);\n    Matrix<T> Q(DIM+1, DIM+1);\n    Q.setIdentity();\n    Q *= 2;\n    Q(DIM, DIM) = 0;\n\n    svm_qp.add_Q(Q);\n\n    for(const VectorDIM<T,DIM>& pt : f) {\n        Row<T> coeff(DIM+1);\n        coeff.setZero();\n\n        for(unsigned int d = 0; d < DIM; d++) {\n            coeff(d) = pt(d);\n        }\n        coeff(DIM) = 1;\n\n        svm_qp.add_constraint(coeff, std::numeric_limits<T>::lowest(), -1);\n    }\n\n    for(const VectorDIM<T,DIM>& pt : s) {\n        Row<T> coeff(DIM+1);\n        coeff.setZero();\n\n        for(unsigned int d = 0; d < DIM; d++) {\n            coeff(d) = pt(d);\n        }\n        coeff(DIM) = 1;\n\n        svm_qp.add_constraint(coeff, 1, std::numeric_limits<T>::max());\n    }\n\n\n    QPWrappers::RLSS_SVM_QP_SOLVER::Engine<T> solver;\n    solver.setFeasibilityTolerance(1e-8);\n    Vector<T> result(DIM+1);\n    auto ret = solver.init(svm_qp, result);\n//    debug_message(\"svm optimization return value is \", ret);\n    Hyperplane<T, DIM> hp;\n\n    if(ret == QPWrappers::OptReturnType::Optimal) {\n        for(unsigned int d = 0; d < DIM; d++) {\n            hp.normal()(d) = result(d);\n        }\n        hp.offset() = result(DIM);\n    } else {\n        // cplex seems more reliable for svm\n        QPWrappers::CPLEX::Engine<T> solver;\n        solver.setFeasibilityTolerance(1e-8);\n        auto ret = solver.init(svm_qp, result);\n//        debug_message(\"svm optimization CPLEX return value is \", ret);\n        if(ret == QPWrappers::OptReturnType::Optimal) {\n            for(unsigned int d = 0; d < DIM; d++) {\n                hp.normal()(d) = result(d);\n            }\n            hp.offset() = result(DIM);\n        } else {\n            debug_message(\"svm failed\");\n            for(const auto& vec: f) {\n                debug_message(\"f\", vec.transpose());\n            }\n            for(const auto& vec: s) {\n                debug_message(\"s\", vec.transpose());\n            }\n            throw std::runtime_error(\n                absl::StrCat(\n                        \"svm not feasible\"\n                )\n            );\n        }\n    }\n\n    return hp;\n}\n\n} // namespace internal\n} // namespace rlss\n#endif // RLSS_INTERNAL_SVM_HPP", "meta": {"hexsha": "11867a0c3eaf05870ebf2826dc88fe32690cd5a0", "size": 2836, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/rlss/internal/SVM.hpp", "max_stars_repo_name": "sieniven/rlss", "max_stars_repo_head_hexsha": "b1f7ff1abf316242a0644b76559ad921fbca3099", "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/rlss/internal/SVM.hpp", "max_issues_repo_name": "sieniven/rlss", "max_issues_repo_head_hexsha": "b1f7ff1abf316242a0644b76559ad921fbca3099", "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": "include/rlss/internal/SVM.hpp", "max_forks_repo_name": "sieniven/rlss", "max_forks_repo_head_hexsha": "b1f7ff1abf316242a0644b76559ad921fbca3099", "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.8039215686, "max_line_length": 75, "alphanum_fraction": 0.5606488011, "num_tokens": 761, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951625409308, "lm_q2_score": 0.7549149978955811, "lm_q1q2_score": 0.705388922163228}}
{"text": "//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n//% Code implementing the paper \"Accelerated Quadratic Proxy for Geometric Optimization\", SIGGRAPH 2016.\n//% Disclaimer: The code is provided as-is for academic use only and without any guarantees. \n//%             Please contact the author to report any bugs.\n//% Written by Shahar Kovalsky (http://www.wisdom.weizmann.ac.il/~shaharko/)\n//%            Meirav Galun (http://www.wisdom.weizmann.ac.il/~/meirav/)\n//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n#include \"mex.h\"\n#include <Eigen/Dense>\n#include <Eigen/SparseCore>\n#include \"mexHelpers.cpp\"\n#include <svd3x3.h>\n\nusing namespace Eigen;\nusing namespace igl;\n\nvoid projBlockRotation2x2(VectorXd &pA, int dim)\n{\n\tint block_size = dim*dim;\n\tint num_blocks = pA.size() / block_size;\n\tMap<MatrixXd> currA(pA.data(), dim, dim);\n\tVector2d b;\n\n\t// project\n\tfor (int ii = 0; ii < num_blocks; ii++)\n\t{\n\t\t// get current block\n\t\tnew (&currA) Map<MatrixXd>(pA.data() + ii*block_size, dim, dim);\n\t\t// closest similarity\n\t\tb << 0.5*(currA(0, 0) + currA(1, 1)), 0.5*(currA(0, 1) - currA(1, 0)); // first row of B\n\t\t// closest rotation\n\t\tb = b / b.norm();\n\t\tcurrA << b(0), b(1), -b(1), b(0);\n\t}\n}\n\nvoid projBlockRotation3x3(VectorXd &pA, int dim)\n{\n\tint block_size = dim*dim;\n\tint num_blocks = pA.size() / block_size;\n\n\tMatrix3f currAf, R;\n\tMatrix3f U, V;\n\tVector3f s;\n\tMap<Matrix3d> currA(pA.data());\n\n\t// project\n\tfor (int ii = 0; ii < num_blocks; ii++)\n\t{\n\t\t// get current block\n\t\tnew (&currA) Map<MatrixXd>(pA.data() + ii*block_size, dim, dim);\n\t\t//\n\t\tcurrAf = currA.cast<float>(); // double -> single\n\t\tsvd3x3(currAf, U, s, V); // svd\n\t\tR = U * V.transpose(); // polar\n\t\tcurrA = R.cast<double>();\n\t}\n}\n\nvoid mexFunction(int nlhs, mxArray *plhs[],\n\tint nrhs, const mxArray*prhs[])\n\n{\n\t// assign input\n\tint A_rows = mxGetM(prhs[0]); // # rows of A\n\tint A_cols = mxGetN(prhs[0]); // # cols of A\n\tdouble *dim;\n\tconst Map<VectorXd> A(mxGetPr(prhs[0]), A_rows, A_cols);\n\tdim = mxGetPr(prhs[1]);\n\t\n\t// init output\n\tVectorXd pA(A_rows);\n\tpA = A;\n\n\t// project\n\tif (*dim == 2)\n\t\tprojBlockRotation2x2(pA, *dim);\t\n\telse if (*dim == 3)\n\t\tprojBlockRotation3x3(pA, *dim);\n\telse\n\t\tmexErrMsgIdAndTxt(\"MATLAB:wrong_dimension\", \"dim must be either 2 or 3\");\n\t\n\t// assign outputs\n\tmapDenseMatrixToMex(pA, &(plhs[0]));\n\n}", "meta": {"hexsha": "ea255fd3cb4d262002dfbcae9abc9f8f58937a92", "size": 2357, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mex/projectRotationMexFast.cpp", "max_stars_repo_name": "shaharkov/AcceleratedQuadraticProxy", "max_stars_repo_head_hexsha": "876078c2c67c9058b50ba072397013346004f63f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2016-06-08T11:12:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-29T06:45:26.000Z", "max_issues_repo_path": "mex/projectRotationMexFast.cpp", "max_issues_repo_name": "shaharkov/AcceleratedQuadraticProxy", "max_issues_repo_head_hexsha": "876078c2c67c9058b50ba072397013346004f63f", "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": "mex/projectRotationMexFast.cpp", "max_forks_repo_name": "shaharkov/AcceleratedQuadraticProxy", "max_forks_repo_head_hexsha": "876078c2c67c9058b50ba072397013346004f63f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-10-17T12:48:18.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-18T14:03:11.000Z", "avg_line_length": 27.091954023, "max_line_length": 104, "alphanum_fraction": 0.6041578277, "num_tokens": 761, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951588871158, "lm_q2_score": 0.7549149978955811, "lm_q1q2_score": 0.7053889194049082}}
{"text": "/**\n * @file gps.cpp\n * @author WARG\n *\n * @section LICENSE\n *\n *  Copyright (c) 2015-2017, Waterloo Aerial Robotics Group (WARG)\n *  All rights reserved.\n *\n *  This software is licensed under a modified version of the BSD 3 clause license\n *  that should have been included with this software in a file called COPYING.txt\n *  Otherwise it is available at:\n *  https://raw.githubusercontent.com/UWARG/computer-vision/master/COPYING.txt\n */\n\n#include <iomanip>\n#include <boost/log/trivial.hpp>\n#include \"frame.h\"\n\n#define RAD2DEG(rad) ((rad)*180.0/M_PI)\n#define DEG2RAD(deg) ((deg)*M_PI/180.0)\n#define EARTH_RADIUS 6371000\n\n//Based on the GPS location of the image, calculates the\n//GPS location of a certain pixel in the image.\nbool get_gps(cv::Point2d point, Frame* f, cv::Point2d* returnResult){\n    if (f == NULL) {\n        BOOST_LOG_TRIVIAL(error) << \"Frame is null\";\n        return false;\n    }\n    BOOST_LOG_TRIVIAL(trace) << \"get_gps(\" << point << \", \" << f->get_id() << \")\";\n\n    const Metadata* m = f->get_metadata();\n    cv::Mat img = f->get_img();\n    int h = img.cols;\n    int w = img.rows;\n\n    if (w <= 0 || h <= 0){\n        BOOST_LOG_TRIVIAL(error) << \"Invalid frame size w:\" << w << \" h:\" << h;\n        return false;\n    }\n\n    cv::Point2d imgCenter(w/2, h/2);\n\n    //(0,0) is in the center of the image\n    cv::Point2d biasedPoint = point - imgCenter;\n\n    double altitude = m->altitude;\n    double heading = m->heading;\n    double latitude = m->lat;\n    double longitude = m->lon;\n\n    BOOST_LOG_TRIVIAL(trace) << \"Camera FOV: \" << f->get_camera().get_fov();\n\n    BOOST_LOG_TRIVIAL(trace) << \"Dist from Center (pixels: \" << biasedPoint;\n\n    double cameraXEdge = altitude * tan(DEG2RAD(f->get_camera().get_fov().width/2)); //meters from center of photo to edge\n    double cameraYEdge = altitude * tan(DEG2RAD(f->get_camera().get_fov().height/2)); //meters from center of photo to edge\n\n    BOOST_LOG_TRIVIAL(trace) << \"X Edge: \" << cameraXEdge << \" Y Edge: \" << cameraYEdge;\n\n    //Rotation Matrix - Heading\n    //Note: The '-heading' compensates for the fact that directional heading is\n    //a clockwise quantity, but cos(theta) assumes theta is a counterclockwise\n    //quantity.\n    double realX = cos(DEG2RAD(-heading)) * biasedPoint.x/(w/2)*cameraXEdge - sin(DEG2RAD(-heading)) * biasedPoint.y/(h/2)*cameraYEdge;\n    double realY = sin(DEG2RAD(-heading)) * biasedPoint.x/(w/2)*cameraXEdge + cos(DEG2RAD(-heading)) * biasedPoint.y/(h/2)*cameraYEdge;\n\n    BOOST_LOG_TRIVIAL(trace) << \"Real X: \" << realX << \" Real Y: \" << realY;\n    BOOST_LOG_TRIVIAL(trace) << \"Cos:\" << cos(DEG2RAD(-heading));\n    BOOST_LOG_TRIVIAL(trace) << \"Sin:\" << sin(DEG2RAD(-heading));\n    BOOST_LOG_TRIVIAL(trace) << \"X:\" << biasedPoint.x/(w/2)*cameraXEdge;\n    BOOST_LOG_TRIVIAL(trace) << \"Y:\" << biasedPoint.y/(h/2)*cameraYEdge;\n\n    double lon = RAD2DEG(realX/EARTH_RADIUS)/cos(DEG2RAD(latitude)) + longitude;\n    double lat = RAD2DEG(realY/EARTH_RADIUS) + latitude;\n\n    BOOST_LOG_TRIVIAL(trace) << \"Distance from centre: \" << RAD2DEG(realY/EARTH_RADIUS) << \" \" << RAD2DEG(realX/EARTH_RADIUS)/cos(DEG2RAD(latitude));\n\n    BOOST_LOG_TRIVIAL(trace) << std::setprecision(10) << \"Result: \" << lat << \" \" << lon;\n\n    *returnResult = cv::Point2d(lat,lon);\n    return true;\n}\n\ndouble gps_dist(cv::Point2d p1, cv::Point2d p2) {\n    double dLat = DEG2RAD(p2.x-p1.x);\n    double dLon = DEG2RAD(p2.y-p1.y);\n\n    double rLat1 = DEG2RAD(p1.x);\n    double rLat2 = DEG2RAD(p2.x);\n\n    double a = sin(dLat/2) * sin(dLat/2) +\n          sin(dLon/2) * sin(dLon/2) * cos(rLat1) * cos(rLat2);\n    double c = 2 * atan2(sqrt(a), sqrt(1-a));\n    return EARTH_RADIUS * c;\n}\n", "meta": {"hexsha": "f40c0775409844953571a1a9ef14834f1e3dc37d", "size": 3653, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/targetanalysis/src/gps.cpp", "max_stars_repo_name": "benjaminwinger/computer-vision", "max_stars_repo_head_hexsha": "cee34a5c02b482c3e194ef51e289342b3a05c4da", "max_stars_repo_licenses": ["IJG", "FSFAP"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-10-17T17:39:20.000Z", "max_stars_repo_stars_event_max_datetime": "2016-10-17T17:39:20.000Z", "max_issues_repo_path": "modules/targetanalysis/src/gps.cpp", "max_issues_repo_name": "benjaminwinger/computer-vision", "max_issues_repo_head_hexsha": "cee34a5c02b482c3e194ef51e289342b3a05c4da", "max_issues_repo_licenses": ["IJG", "FSFAP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/targetanalysis/src/gps.cpp", "max_forks_repo_name": "benjaminwinger/computer-vision", "max_forks_repo_head_hexsha": "cee34a5c02b482c3e194ef51e289342b3a05c4da", "max_forks_repo_licenses": ["IJG", "FSFAP"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.2755102041, "max_line_length": 149, "alphanum_fraction": 0.6482343279, "num_tokens": 1123, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122288794595, "lm_q2_score": 0.7772998611746911, "lm_q1q2_score": 0.7052536695501034}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  MatrixXd X = MatrixXd::Random(5,5);\nMatrixXd A = X + X.transpose();\ncout << \"Here is a random symmetric 5x5 matrix:\" << endl << A << endl << endl;\nTridiagonalization<MatrixXd> triOfA(A);\nMatrixXd Q = triOfA.matrixQ();\ncout << \"The orthogonal matrix Q is:\" << endl << Q << endl;\nMatrixXd T = triOfA.matrixT();\ncout << \"The tridiagonal matrix T is:\" << endl << T << endl << endl;\ncout << \"Q * T * Q^T = \" << endl << Q * T * Q.transpose() << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "3666dd56c4cd8c2e0c23e5d9812cada2d7a304b5", "size": 596, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_Tridiagonalization_Tridiagonalization_MatrixType.cpp", "max_stars_repo_name": "TANHAIYU/Self-calibration-using-Homography-Constraints", "max_stars_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-03-17T16:34:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-17T18:30:13.000Z", "max_issues_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_Tridiagonalization_Tridiagonalization_MatrixType.cpp", "max_issues_repo_name": "TANHAIYU/planecalib", "max_issues_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "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": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_Tridiagonalization_Tridiagonalization_MatrixType.cpp", "max_forks_repo_name": "TANHAIYU/planecalib", "max_forks_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "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": 27.0909090909, "max_line_length": 78, "alphanum_fraction": 0.6308724832, "num_tokens": 174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312213841788, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.705253667222834}}
{"text": "#include \"render/mesh/MeshFactory.h\"\n#include \"math/Defines.h\"\n\n#include <cmath>\n\n#include <boost/format.hpp>\n\nnamespace epsilon\n{\n\tParametricData Parametric::Sphere(int slices, int stacks)\n\t{\n\t\tParametricData data;\n\t\tfloat theta, phi;\n\t\tint v = 0;\n\t\tint next = 0;\n\n\t\t// Generate Vertices\n\t\tfor (int x = 0; x < (slices+1); x++)\n\t\t{\n\t\t\ttheta = x * PI / slices;\n\t\t\tfor( int y = 0; y < stacks; y++)\n\t\t\t{\n\t\t\t\tphi = y * TWOPI / stacks;\n\t\t\t\tfloat px = sin(theta) * cos(phi);\n\t\t\t\tfloat py = cos(theta);\n\t\t\t\tfloat pz = -sin(theta) * sin(phi);\n\t\t\t\tdata.vertices.push_back( Vector3( px, py, pz) );\n\t\t\t\tdata.normals.push_back( Vector3( px, py, pz).Normalised() );\n\t\t\t}\n\t\t}\n\n\t\t// Generate Faces/Indices\n\t\tfor (int x = 0; x < slices; x++ )\n\t\t{\n\t\t\tfor (int y = 0; y < stacks; y++ )\n\t\t\t{\n\t\t\t\tnext = ( y + 1 ) % stacks;\n\t\t\t\t// first triangle\n\t\t\t\tdata.indices.push_back( v + y + stacks );\n\t\t\t\tdata.indices.push_back( v + next );\n\t\t\t\tdata.indices.push_back( v + y );\n\n\t\t\t\t// second triangle\n\t\t\t\tdata.indices.push_back( v + y + stacks );\n\t\t\t\tdata.indices.push_back( v + next + stacks);\n\t\t\t\tdata.indices.push_back( v + next );\n\t\t\t}\n\t\t\tv += stacks;\n\t\t}\n\n\t\treturn data;\n\t}\n\n\tParametricData Parametric::Plane(int rows, int columns)\n\t{\n\t\tParametricData data;\n\n\t\tfloat c, r;\n\t\tint tl, tr, bl, br;\n\t\tint v = 0;\n\n\t\t// Generate Vertices\n\t\tfor ( int x = 0; x < (columns + 1); x++ )\n\t\t{\n\t\t\tc = x * ( 1.0f / columns );\n\t\t\tfor ( int y = 0; y < (rows + 1); y++ )\n\t\t\t{\n\t\t\t\tr = y * ( 1.0f / rows );\n\t\t\t\tdata.vertices.push_back( Vector3( (-0.5f + c),\n\t\t\t\t\t\t\t\t\t\t\t\t  0.0f,\n\t\t\t\t\t\t\t\t\t\t\t\t  (-0.5f + r) ) );\n\t\t\t}\n\t\t}\n\n\t\t// Generate Normals\n\t\tfor ( int n = 0; n < ((rows + 1) * (columns + 1)); n++ )\n\t\t{\n\t\t\t//data.normals.push_back(Vector3::UP);\n\t\t\tdata.normals.push_back(Vector3(0.0f, 1.0f, 0.0f));\n\t\t\tdata.colours.push_back(Vector4(1.0f, 1.0f, 1.0f, 1.0f));\n\t\t}\n\n\t\t// Generate Faces/Indices\n\t\tfor ( int x = 0; x < columns; x++ )\n\t\t{\n\t\t\tfor ( int y = 0; y < rows; y++ )\n\t\t\t{\n\t\t\t\tbl = v + x + y;\n\t\t\t\ttl = bl + 1;\n\t\t\t\ttr = tl + rows + 1;\n\t\t\t\tbr = tr - 1;\n\t\t\t\tdata.indices.push_back(bl);\n\t\t\t\tdata.indices.push_back(tl);\n\t\t\t\tdata.indices.push_back(tr);\n\n\t\t\t\tdata.indices.push_back(bl);\n\t\t\t\tdata.indices.push_back(tr);\n\t\t\t\tdata.indices.push_back(br);\n\t\t\t}\n\t\t\tv += rows;\n\t\t}\n\t\t\n\t\t// Generate Texture Coordinates\n\t\tfor (int x = 0; x < (columns + 1); x++ )\n\t\t{\n\t\t\tc = x * ( 1.0f / columns);\n\t\t\tfor ( int y = 0; y < (rows + 1); y++ )\n\t\t\t{\n\t\t\t\tr = y * ( 1.0f / rows );\n\t\t\t\tdata.texCoords.push_back(Vector2(c, r));\n\t\t\t}\n\t\t}\n\n\t\treturn data;\n\t}\n\n\tMeshFactory::MeshFactory(void)\n\t{\n\t}\n\n\tMeshFactory::~MeshFactory(void)\n\t{\n\t}\n\tMesh::Ptr MeshFactory::GenerateGrid(int size, int resolution)\n\t{\n\t\tMesh::Ptr newGrid = Mesh::Create(GL_LINES);\n        \n        newGrid->SetMeshType(\"GRID\");\n        newGrid->SetMeshParameters(str(format(\"size=%d|resolution=%d\") % size % resolution));\n\n\t\tVerticesAttrib::List verts;\n\t\t//ColourAttrib::List\n\t\tfloat halfWidth = size / 2.0f;\n\t\t\n\n\t\t// if the resolution doesn't evenly divide into the size\n\t\tif ( (size % resolution) > 0.0f )\n\t\t{\n\t\t\tfloat diff = (float)(size % resolution);\n\n\t\t\t// modify the size so that the resolution evenly fits\n\t\t\thalfWidth -= diff / 2.0f;\n\t\t}\n\n\t\t// Impossible to have a grid smaller than its resolution\n\t\tif ( size > resolution )\n\t\t{\n\t\t\tfloat resStep =  (float)resolution;// / halfWidth;\n\n\t\t\t// 'Vertical' Lines first\n\t\t\tfor ( float x = -halfWidth; x < halfWidth; x += resStep)\n\t\t\t{\n\t\t\t\tverts.push_back(Vector3(x,0,-halfWidth));\n\t\t\t\tverts.push_back(Vector3(x,0,halfWidth));\n\t\t\t}\n\n\t\t\t// 'Horizontal' lines\n\t\t\tfor ( float z = -halfWidth; z < halfWidth; z += resStep)\n\t\t\t{\n\t\t\t\tverts.push_back(Vector3(-halfWidth,0,z));\n\t\t\t\tverts.push_back(Vector3(halfWidth,0,z));\n\t\t\t}\n\n\t\t\t// Border\n\t\t\t// TL -> TR\n\t\t\tverts.push_back(Vector3(-halfWidth,0,halfWidth));\n\t\t\tverts.push_back(Vector3(halfWidth,0,halfWidth));\n\t\t\t// TR - BR\n\t\t\tverts.push_back(Vector3(halfWidth,0,halfWidth));\n\t\t\tverts.push_back(Vector3(halfWidth,0,-halfWidth));\n\t\t\t// BR -> BL\n\t\t\tverts.push_back(Vector3(halfWidth,0,-halfWidth));\n\t\t\tverts.push_back(Vector3(-halfWidth,0,-halfWidth));\n\t\t\t// BL -> TL\n\t\t\tverts.push_back(Vector3(-halfWidth,0,-halfWidth));\n\t\t\tverts.push_back(Vector3(-halfWidth,0,halfWidth));\n\t\t}\n\n\t\tnewGrid->VertexData()\n\t\t\t   ->SetVertices(verts);\n\t\t\t   //->BuildBuffers();\n\n\t\treturn newGrid;\n\t}\n\n\tMesh::Ptr MeshFactory::GenerateCube()\n\t{\n\t\tMesh::Ptr newCube =  Mesh::Create();\n        \n        newCube->SetMeshType(\"CUBE\");\n\n\t\tVerticesAttrib::List verts;\n\t\tNormalAttrib::List norms;\n\t\t//TexCoordAttrib::List texCoords;\n\t\tVertexIndicesBuffer::List faces;\n\n\t\tverts.push_back(Vector3(-0.5, -0.5, -0.5));\n        norms.push_back(Vector3(-0.5, -0.5, -0.5));\n        \n        verts.push_back(Vector3(-0.5, -0.5, 0.5));\n        norms.push_back(Vector3(-0.5, -0.5, 0.5));\n        \n        verts.push_back(Vector3(-0.5, 0.5, -0.5));\n        norms.push_back(Vector3(-0.5, 0.5, -0.5));\n        \n        verts.push_back(Vector3(-0.5, 0.5, 0.5));\n        norms.push_back(Vector3(-0.5, 0.5, 0.5));\n        \n        verts.push_back(Vector3(0.5, -0.5, -0.5));\n        norms.push_back(Vector3(0.5, -0.5, -0.5));\n        \n        verts.push_back(Vector3(0.5, -0.5, 0.5));\n        norms.push_back(Vector3(0.5, -0.5, 0.5));\n        \n        verts.push_back(Vector3(0.5, 0.5, -0.5));\n        norms.push_back(Vector3(0.5, 0.5, -0.5));\n        \n        verts.push_back(Vector3(0.5, 0.5, 0.5));\n        norms.push_back(Vector3(0.5, 0.5, 0.5));\n\n\t\t// left\n\t\tfaces.push_back(0);\n\t\tfaces.push_back(1);\n\t\tfaces.push_back(3);\n\t\tfaces.push_back(3);\n\t\tfaces.push_back(2);\n\t\tfaces.push_back(0); \n\n\t\t// right\n\t\tfaces.push_back(4);\n\t\tfaces.push_back(6);\n\t\tfaces.push_back(7);\n\t\tfaces.push_back(7);\n\t\tfaces.push_back(5);\n\t\tfaces.push_back(4);\n\n\t\t// front\n\t\tfaces.push_back(7);\n\t\tfaces.push_back(3);\n\t\tfaces.push_back(1);\n\t\tfaces.push_back(1);\n\t\tfaces.push_back(5);\n\t\tfaces.push_back(7);\n\n\t\t// back\n\t\tfaces.push_back(0);\n\t\tfaces.push_back(2);\n\t\tfaces.push_back(6);\n\t\tfaces.push_back(6);\n\t\tfaces.push_back(4);\n\t\tfaces.push_back(0);\n\n\t\t// top\n\t\tfaces.push_back(3);\n\t\tfaces.push_back(7);\n\t\tfaces.push_back(2); \n\t\tfaces.push_back(7);\n\t\tfaces.push_back(6);\n\t\tfaces.push_back(2);\n\n\t\t// bottom\n\t\tfaces.push_back(5);\n\t\tfaces.push_back(1);\n\t\tfaces.push_back(4); \n\t\tfaces.push_back(1);\n\t\tfaces.push_back(0);\n\t\tfaces.push_back(4);\n\t\t\n\t\tnewCube->VertexData()\n\t\t\t   ->SetVertices(verts)\n               ->SetNormals(norms)\n\t\t\t   ->SetIndices(faces);\n\t\t\n\t\treturn newCube;\n\t}\n\n\tMesh::Ptr MeshFactory::GenerateWireCube()\n\t{\n\t\tMesh::Ptr newCube = Mesh::Create(GL_LINES);\n        \n\t\tVerticesAttrib::List verts;\n\n\t\tverts.push_back(Vector3(-0.5, -0.5, -0.5));\n\t\tverts.push_back(Vector3(-0.5, -0.5, 0.5));\n\n\t\tverts.push_back(Vector3(-0.5, -0.5, 0.5));\n\t\tverts.push_back(Vector3( 0.5, -0.5, 0.5));\n\n\t\tverts.push_back(Vector3(-0.5, 0.5, -0.5));\n\t\tverts.push_back(Vector3(-0.5, 0.5, 0.5));\n\n\t\tverts.push_back(Vector3(-0.5, 0.5, 0.5));\n\t\tverts.push_back(Vector3( 0.5, 0.5, 0.5));\n\n\t\tverts.push_back(Vector3(0.5, -0.5, -0.5));\n\t\tverts.push_back(Vector3(0.5, -0.5, 0.5));\n\n\t\tverts.push_back(Vector3(-0.5, 0.5, -0.5));\n\t\tverts.push_back(Vector3( 0.5, 0.5, -0.5));\n\n\t\tverts.push_back(Vector3(0.5, 0.5, -0.5));\n\t\tverts.push_back(Vector3(0.5, 0.5, 0.5));\n\n\t\tverts.push_back(Vector3(-0.5, -0.5, -0.5));\n\t\tverts.push_back(Vector3(0.5,  -0.5, -0.5));\n\t\t\t\n\t\t// Corner Verticals\n\t\tverts.push_back(Vector3(-0.5, -0.5, -0.5));\n\t\tverts.push_back(Vector3(-0.5,  0.5, -0.5));\n\n\t\tverts.push_back(Vector3(0.5, -0.5, -0.5));\n\t\tverts.push_back(Vector3(0.5,  0.5, -0.5));\n\n\t\tverts.push_back(Vector3(0.5, -0.5, 0.5));\n\t\tverts.push_back(Vector3(0.5, 0.5,  0.5));\n\n\t\tverts.push_back(Vector3(-0.5, -0.5, 0.5));\n\t\tverts.push_back(Vector3(-0.5,  0.5, 0.5));\n\n\n\t\tnewCube->VertexData()\n\t\t\t->SetVertices(verts);\n\n\t\treturn newCube;\n\t}\n\n\tMesh::Ptr MeshFactory::GenerateSphere(int slices, int stacks)\n\t{\n\t\tVerticesAttrib::List verts;\n\t\tNormalAttrib::List norms;\n\t\tColourAttrib::List colours;\n\n\t\tTexCoordAttrib::List texCoords;\n\t\tVertexIndicesBuffer::List faces;\n\n\t\t// This is used purely for normal generation as it requires random access\n\t\tVecVec raverts;\n\n\t\tMesh::Ptr newSphere = Mesh::Create();\n        \n        newSphere->SetMeshType(\"SPHERE\");\n        newSphere->SetMeshParameters(str(format(\"slices=%d|stacks=%d\") % slices % stacks));\n\t\t\n\t\tint vi, next;\n\t\tfloat x, y, z, u, v, theta, phi, a;\n\n\t\t// Calculate Verts and Tex coords\n\t\tfor ( int i = 0; i < (slices + 1); i++ )\n\t\t{\n\t\t\ttheta = i * PI / stacks;\n\t\t\tfor ( int j = 0; j < stacks; j++ )\n\t\t\t{\n\t\t\t\tphi = j * 2.0f * PI / stacks;\n\n\t\t\t\t// vertices\n\t\t\t\tx = std::sin(theta) * std::cos(phi);\n\t\t\t\ty = std::cos(theta);\n\t\t\t\tz = -std::sin(theta) * std::sin(phi);\n\t\t\t\tverts.push_back( Vector3(x, y, z) );\n                \n                norms.push_back( Vector3(x, y, z) );\n                \n\t\t\t\tcolours.push_back( Vector4(1.0f) );\n\n\t\t\t\traverts.push_back( Vector3(x, y, z) );\n\t\t\t\t// Tex Coord\n\t\t\t\tv = std::acos(z) / PI;\n                \n                a = x / (std::sin(PI*(v)));\n\t\t\t\t\n                if (y >= 0)\n                {\n\t\t\t\t\tu = std::acos( a ) / TWOPI;\n                }\n\t\t\t\telse\n                {\n\t\t\t\t\tu = (PI + std::acos( a ) ) / TWOPI;\n                }\n\t\t\t\ttexCoords.push_back( Vector2(u, v) );\n\t\t\t}\n\t\t}\n\n\t\t// Calculate Faces\n\t\tvi = 0;\n\t\tfor ( int i = 0; i < slices; i++ )\n\t\t{\n\t\t\tfor ( int j = 0; j < stacks; j++ )\n\t\t\t{\n\t\t\t\tnext = (j + 1) % stacks;\n\t\t\t\t\n\t\t\t\tfaces.push_back( vi + j + stacks);\n\t\t\t\tfaces.push_back( vi + next);\n\t\t\t\tfaces.push_back( vi + j );\n\n\t\t\t\tfaces.push_back( vi + j + stacks);\n\t\t\t\tfaces.push_back( vi + next + stacks);\n\t\t\t\tfaces.push_back( vi + next);\n\t\t\t}\n\t\t\tvi += stacks;\n\t\t}\n\n\t\t//norms = MeshFactory::GenerateNormals(raverts, faces);\n\n\t\t//newSphere->SetMeshData(verts, norms, texCoords, faces);\n\t\tnewSphere->VertexData()\n\t\t\t\t ->SetVertices(verts)\n\t\t\t\t ->SetNormals(norms)\n\t\t\t\t ->SetColours(colours)\n\t\t\t\t ->SetTexCoords(texCoords)\n\t\t\t\t ->SetIndices(faces);\n\t\t\t\t //->BuildBuffers();\n\n\t\treturn newSphere;\n\t}\n\n\tMesh::Ptr MeshFactory::GenerateWireSphere()\n\t{\n\t\tMesh::Ptr newSphere = Mesh::Create(GL_LINES);\n\t\tVerticesAttrib::List verts;\n\n\t\tParametricData data;\n\t\tint slices = 8;\n\t\tint stacks = 8;\n\t\tfloat theta, phi;\n\n\t\tVector3 last;\n\t\tVector3 now;\n\t\tVector3 first;\n\t\t// Generate Vertices\n\n\t\tfor (int x = 0; x < (slices + 1); x++)\n\t\t{\n\t\t\ttheta = x * PI / slices;\n\t\t\tfor (int y = 0; y < stacks; y++)\n\t\t\t{\n\t\t\t\tphi = y * TWOPI / stacks;\n\t\t\t\tfloat px = sin(theta) * cos(phi);\n\t\t\t\tfloat py = cos(theta);\n\t\t\t\tfloat pz = -sin(theta) * sin(phi);\n\n\t\t\t\tnow = Vector3(px, py, pz);\n\t\t\t\t\n\t\t\t\tif (y == 0)\n\t\t\t\t{\n\t\t\t\t\tfirst = now;\n\t\t\t\t}\n\t\t\t\telse if ( y % 2 == 0)\n\t\t\t\t{\n\t\t\t\t\tverts.push_back(last);\n\t\t\t\t\tverts.push_back(now);\n\t\t\t\t}\n\t\t\t\telse if (y == (stacks - 1))\n\t\t\t\t{\n\t\t\t\t\tverts.push_back(now);\n\t\t\t\t\tverts.push_back(first);\n\t\t\t\t}\n\t\t\t\tverts.push_back(now);\n\n\t\t\t\tlast = now;\n\t\t\t}\n\t\t}\n\n\t\tnewSphere->VertexData()\n\t\t\t\t ->SetVertices(verts);\n\n\t\treturn newSphere;\n\t}\n\n\tMesh::Ptr MeshFactory::GeneratePlane(int widthSegments, int heightSegments)\n\t{\n\t\tMesh::Ptr newPlane = Mesh::Create();\n\t\t\n\t\tnewPlane->SetMeshType(\"PLANE\");\n\t\tnewPlane->SetMeshParameters(str(format(\"width_segs=%d|height_segs=%d\") % widthSegments % heightSegments));\n\n\t\tParametricData planeData = Parametric::Plane(heightSegments, widthSegments);\n\n\t\tnewPlane->VertexData()\n\t\t\t\t->SetVertices(planeData.vertices)\n\t\t\t\t->SetNormals(planeData.normals)\n\t\t\t\t->SetColours(planeData.colours)\n\t\t\t\t->SetTexCoords(planeData.texCoords)\n\t\t\t\t->SetIndices(planeData.indices);\n\t\t\t\t//->BuildBuffers();\n\n\t\treturn newPlane;\n\t}\n\n\tMesh::Ptr MeshFactory::GenerateTriangle()\n\t{\n\t\t// Create a triangle\n\t\tVerticesAttrib::List verts;\n\t\tNormalAttrib::List norms;\n\t\tColourAttrib::List colours;\n\t\tTexCoordAttrib::List tc;\n\t\tVertexIndicesBuffer::List inds;\n\n\t\tMesh::Ptr newTriangle = Mesh::Create();\n\n\t\tverts.push_back(Vector3(-0.5,-0.5,0));\n\t\tverts.push_back(Vector3(0,0.5,0));\n\t\tverts.push_back(Vector3(0.5,-0.5,0));\n\n\t\tnorms.push_back(Vector3(0,0,-1));\n\t\tnorms.push_back(Vector3(0,0,-1));\n\t\tnorms.push_back(Vector3(0,0,-1));\n\n\t\tcolours.push_back(Vector4(1,0,0,1));\n\t\tcolours.push_back(Vector4(0,1,0,1));\n\t\tcolours.push_back(Vector4(0,0,1,1));\n\n\t\ttc.push_back(Vector2(0,0));\n\t\ttc.push_back(Vector2(0,0));\n\t\ttc.push_back(Vector2(0,0));\n\n\t\tinds.push_back(0);\n\t\tinds.push_back(1);\n\t\tinds.push_back(2);\n\n\t\t//newTriangle->SetMeshData(verts, norms, colours, tc, inds);\n\t\tnewTriangle->VertexData()\n\t\t\t\t   ->SetVertices(verts)\n\t\t\t\t   ->SetNormals(norms)\n\t\t\t\t   ->SetTexCoords(tc)\n\t\t\t\t   ->SetIndices(inds);\n\t\t\t\t   //->BuildBuffers();\n\n\t\treturn newTriangle;\n\t}\n\n\tMesh::Ptr MeshFactory::GenerateIcoHedron()\n\t{\n\t\treturn Mesh::Create();\n\t}\n\n\tMesh::Ptr MeshFactory::GenerateOctohedron()\n\t{\n\t\treturn Mesh::Create();\n\t}\n\n\tNormalAttrib::List MeshFactory::GenerateNormals(VerticesAttrib::List verts, VertexIndicesBuffer::List indices)\n\t{\n\t\tNormalAttrib::List norms;// = VecVec(verts.size());\n\t\tstd::vector<VecVec> vertNorms = std::vector<VecVec>(verts.size());\n\t\tVerticesAttrib::List faceNormals;\n\t\tVector3 faceNormal, v0, v1, v2, a, b;\n\t\tint vec0, vec1, vec2;\n\t\tbool found;\n\n\t\t// Generate face normals\n\t\tfor (VertexIndicesBuffer::List::iterator ind = indices.begin(); ind != indices.end(); ind++ )\n\t\t{\n\t\t\tvec0 = *ind++;\n\t\t\tvec1 = *ind++;\n\t\t\tvec2 = *ind++;\n\n\t\t\tv0 = verts[vec0];\n\t\t\tv1 = verts[vec1];\n\t\t\tv2 = verts[vec2];\n\n\t\t\ta = v0 - v1;\n\t\t\tb = v2 - v1;\n\t\t\tb.Cross(a).Normalise();\n\t\t\t\n\t\t\t// add face normal to the vec positions list in vec0, vec1, vec2\n\t\t\tfound = false;\n\t\t\tfor (VecVec::iterator vnIt = vertNorms[vec0].begin(); vnIt != vertNorms[vec0].end(); vnIt++ )\n\t\t\t{\n\t\t\t\tif ( *vnIt == b )\n\t\t\t\t{\n\t\t\t\t\tfound = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ( !found )\n\t\t\t{\n\t\t\t\tvertNorms[vec0].push_back(b);\n\t\t\t}\n\n\t\t\tfound = false;\n\t\t\tfor (VecVec::iterator vnIt = vertNorms[vec1].begin(); vnIt != vertNorms[vec1].end(); vnIt++ )\n\t\t\t{\n\t\t\t\tif ( *vnIt == b )\n\t\t\t\t{\n\t\t\t\t\tfound = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ( !found )\n\t\t\t{\n\t\t\t\tvertNorms[vec1].push_back(b);\n\t\t\t}\n\n\t\t\tfound = false;\n\t\t\tfor (VecVec::iterator vnIt = vertNorms[vec2].begin(); vnIt != vertNorms[vec2].end(); vnIt++ )\n\t\t\t{\n\t\t\t\tif ( *vnIt == b )\n\t\t\t\t{\n\t\t\t\t\tfound = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ( !found )\n\t\t\t{\n\t\t\t\tvertNorms[vec2].push_back(b);\n\t\t\t}\n\t\t}\n\n\t\t// Calculate the average for all of the face normals for each of the vectors\n\t\tfor ( std::vector<VecVec>::iterator vnIt = vertNorms.begin(); vnIt != vertNorms.end(); vnIt++ )\n\t\t{\n\t\t\tfaceNormal = Vector3();\n\n\t\t\tfor (VecVec::iterator vnFnIt = (*vnIt).begin(); vnFnIt != (*vnIt).end(); vnFnIt++ )\n\t\t\t{\n\t\t\t\tfaceNormal += *vnFnIt;\n\t\t\t}\n\t\t\tfaceNormal.Normalise();\n\t\t\tnorms.push_back(faceNormal);\n\t\t}\n\n\t\treturn norms;\n\n\t\t /*normals = list( MeshUtilities.face_normal(vertices, face) for face in faces )\n            \n            # Normal Generation\n            \n            # Calculate the normals once for each unique vertex and after calcs done, \n            # rebuild the vertex list\n            vertex_normals = []\n            \n            # for each vertex\n            for v_inc in range(len(vertices)):\n                face_normals = []\n                vert_norm = Vector3()\n                \n                # for each face\n                for f_inc in range(len(faces)):\n                    \n                    # if the face contains the current vertex\n                    if v_inc in faces[f_inc]:\n                        # and the faces normal isn't already stored i.e. ignore co-planar face normals\n                        if normals[f_inc] not in face_normals:\n                            # Store it\n                            face_normals.append(normals[f_inc])\n                \n                # Calculate the average for all of the face normals found\n             \n                for f_norm in face_normals:\n                    vert_norm += f_norm\n                vert_norm.normalize()\n                \n                vertex_normals.append(vert_norm)\n            \n            for vi in range(len(self._vert_index)):\n                v_ind = self._vert_index[vi]\n                self._normals.append(vertex_normals[v_ind])*/\n\t}\n\n}", "meta": {"hexsha": "82e8efd6a5d3944ea8bb60df1f74ace90d1f402a", "size": 15916, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/render/mesh/MeshFactory.cpp", "max_stars_repo_name": "freneticmonkey/epsilonc", "max_stars_repo_head_hexsha": "0fb7c6c4c6342a770e2882bfd67ed34719e79066", "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": "source/render/mesh/MeshFactory.cpp", "max_issues_repo_name": "freneticmonkey/epsilonc", "max_issues_repo_head_hexsha": "0fb7c6c4c6342a770e2882bfd67ed34719e79066", "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": "source/render/mesh/MeshFactory.cpp", "max_forks_repo_name": "freneticmonkey/epsilonc", "max_forks_repo_head_hexsha": "0fb7c6c4c6342a770e2882bfd67ed34719e79066", "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.0060331825, "max_line_length": 111, "alphanum_fraction": 0.5777205328, "num_tokens": 5243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.8006920116079209, "lm_q1q2_score": 0.7052471841844895}}
{"text": "#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/point_generators_3.h>\n#include <CGAL/Real_timer.h>\n\n#include <CGAL/compute_average_spacing.h>\n#include <CGAL/grid_simplify_point_set.h>\n#include <CGAL/jet_smooth_point_set.h>\n\n#include <boost/lexical_cast.hpp>\n\n#include <vector>\n#include <fstream>\n\n// Types\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;\ntypedef Kernel::FT FT;\ntypedef Kernel::Point_3 Point;\ntypedef CGAL::Random_points_on_sphere_3<Point> Generator;\n\n// Concurrency\n#ifdef CGAL_LINKED_WITH_TBB\ntypedef CGAL::Parallel_tag Concurrency_tag;\n#else\ntypedef CGAL::Sequential_tag Concurrency_tag;\n#endif\n\n\n// instance of std::function<bool(double)>\nstruct Progress_to_std_cerr_callback\n{\n  mutable std::size_t nb;\n  CGAL::Real_timer timer;\n  double t_start;\n  mutable double t_latest;\n  const std::string name;\n\n  Progress_to_std_cerr_callback (const char* name)\n    : name (name)\n  {\n    timer.start();\n    t_start = timer.time();\n    t_latest = t_start;\n  }\n  \n  bool operator()(double advancement) const\n  {\n    // Avoid calling time() at every single iteration, which could\n    // impact performances very badly\n    ++ nb;\n    if (advancement != 1 && nb % 100 != 0)\n      return true;\n\n    double t = timer.time();\n    if (advancement == 1 || (t - t_latest) > 0.1) // Update every 1/10th of second\n    {\n      std::cerr << \"\\r\" // Return at the beginning of same line and overwrite\n                << name << \": \" << int(advancement * 100) << \"%\";\n      \n      if (advancement == 1)\n        std::cerr << std::endl;\n      t_latest = t;\n    }\n\n    return true;\n  }\n};\n\n\nint main (int argc, char* argv[])\n{\n  int N = (argc > 1) ? boost::lexical_cast<int>(argv[1]) : 1000;\n  \n  // Generate N points on a sphere of radius 100.\n  std::vector<Point> points;\n  points.reserve (N);\n  Generator generator(100.);\n  std::copy_n (generator, N, std::back_inserter(points));\n\n  // Compute average spacing\n  FT average_spacing = CGAL::compute_average_spacing<Concurrency_tag>\n    (points, 6,\n     CGAL::parameters::callback\n     (Progress_to_std_cerr_callback(\"Computing average spacing\")));\n\n  // Simplify on a grid with a size of twice the average spacing\n  points.erase(CGAL::grid_simplify_point_set\n               (points, 2. * average_spacing,\n                CGAL::parameters::callback\n                (Progress_to_std_cerr_callback(\"Grid simplification\"))),\n               points.end());\n\n  // Smooth simplified point set\n  CGAL::jet_smooth_point_set<Concurrency_tag>\n    (points, 6,\n     CGAL::parameters::callback\n     (Progress_to_std_cerr_callback(\"Jet smoothing\")));\n\n  return EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "4004c7e832cd6904ef23f22fde26dab38895ff67", "size": 2654, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CoreSystem/lib/CGAL/examples/Point_set_processing_3/callback_example.cpp", "max_stars_repo_name": "josuehfa/DAASystem", "max_stars_repo_head_hexsha": "a1fe61ffc19f0781eeeddcd589137eefde078a45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-17T01:13:02.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-17T01:13:02.000Z", "max_issues_repo_path": "CoreSystem/lib/CGAL/examples/Point_set_processing_3/callback_example.cpp", "max_issues_repo_name": "josuehfa/DAASystem", "max_issues_repo_head_hexsha": "a1fe61ffc19f0781eeeddcd589137eefde078a45", "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": "CoreSystem/lib/CGAL/examples/Point_set_processing_3/callback_example.cpp", "max_forks_repo_name": "josuehfa/DAASystem", "max_forks_repo_head_hexsha": "a1fe61ffc19f0781eeeddcd589137eefde078a45", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-02T11:11:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-02T11:11:36.000Z", "avg_line_length": 26.2772277228, "max_line_length": 82, "alphanum_fraction": 0.6804822909, "num_tokens": 684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.7052471758063771}}
{"text": "#include \"penrose.h\"\n#include <Eigen/Dense>\n#include \"../../external_libs/quickhull/QuickHull.hpp\"\n\nnamespace quacry{\nusing Vec2 = glm::vec2;\nusing Vec3 = glm::vec3;\nusing Vec4 = glm::vec4;\nusing Mat4 = glm::mat4;\nusing Vec5f = Eigen::Matrix<float,5,1>;\nusing Mat5f = Eigen::Matrix<float,5,5>;\nusing namespace kipod::MeshModels;\n\nauto PenroseRotation() -> Mat5f \n{\n    Mat5f g;\n    double c = std::sqrt(2./5);\n    double t = 2./5 * 3.1415926535;\n    double u = 1./std::sqrt(2.);\n    auto si = [=](int i){ return (float)sin(i*t); };\n    auto co = [=](int i){ return (float)cos(i*t); };\n    for(int j = 0; j<5; ++j)\n        g.col(j) = c*Vec5f(co(j), si(j), co(2*j), si(2*j), u);\n\n    return g;\n}\n\nauto PenroseInternalPolytope(Mat5f g, const Vec5f& gamma) -> std::pair<std::vector<Vec3>,std::vector<unsigned int>>\n{\n    LOG_INFO(\"Creating Internal Penrose Polytope from data g={} and gamma={}\", g,gamma);\n\n    using namespace quickhull;\n    QuickHull<float> qh;\n    auto vertices = std::vector<Vec3>();\n    auto g_penrose = PenroseRotation();\n    g = g*g_penrose;\n    auto unit_cube = std::vector<Vec5f>();\n    auto s = [](int i, int j){ return (i & (1 << j)) == 0 ? -0.5f : 0.5f; };\n    LOG_INFO(\"Creating 5-dim Unitcube:\");\n    for(int i = 0; i<32; ++i){\n       Vec5f v = { s(i,0), s(i,1),s(i,2),s(i,3),s(i,4)}; \n       unit_cube.push_back(v); \n       LOG_INFO(\"{}th vector = {}\", i, v.transpose());\n    }\n    for(auto& v : unit_cube) v = g*(v + gamma);\n    for(const auto& v : unit_cube) vertices.emplace_back(v[2],v[3],v[4]);\n    auto hull = qh.getConvexHull((float*)vertices.data(), vertices.size(), true, false);\n    auto hull_vertices = std::vector<glm::vec3>();\n    auto indices = std::vector<unsigned int>();\n    for(auto& v : hull.getVertexBuffer()) hull_vertices.emplace_back(v.x,v.y,v.z);\n    for(auto& v : hull.getIndexBuffer()) indices.push_back(v);\n    return std::make_pair(hull_vertices, indices);\n}\n\nauto Penrose() -> Quasicrystal23\n{\n    auto [v,i] = PenroseInternalPolytope(Mat5f::Identity(), Vec5f::Constant(0.25f));\n    auto penrose = Quasicrystal23(\"Penrose\", PenroseRotation(), MeshModel(v,i), {-2,2, -2,2, -2,2, -2,2, -2,2});\n\n    return penrose;\n}\n}\n", "meta": {"hexsha": "5fb741dd472e490f6f239adbdc89c4b2109b504a", "size": 2173, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/examples/penrose.cpp", "max_stars_repo_name": "reneruhr/quacry", "max_stars_repo_head_hexsha": "cb2f3448b348a26dd8dec018285e7bf030b4e395", "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/examples/penrose.cpp", "max_issues_repo_name": "reneruhr/quacry", "max_issues_repo_head_hexsha": "cb2f3448b348a26dd8dec018285e7bf030b4e395", "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/examples/penrose.cpp", "max_forks_repo_name": "reneruhr/quacry", "max_forks_repo_head_hexsha": "cb2f3448b348a26dd8dec018285e7bf030b4e395", "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.4920634921, "max_line_length": 115, "alphanum_fraction": 0.6134376438, "num_tokens": 721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172644875641, "lm_q2_score": 0.7431680086124812, "lm_q1q2_score": 0.7052049537872261}}
{"text": "#include \"entropy.hpp\"\n#include <armadillo>\n#include <stdlib.h>\nusing namespace arma;\nusing namespace std;\n\n// von Neumann entropy of the first k qubits\ndouble vNentropy(unsigned int k, cx_dvec &psi)\n{\n  int d = psi.size();\n  cx_dmat sqrtrho = reshape(psi, 1<<k, d/(1<<k));\n  vec s = svd(sqrtrho);\n  psi.reshape(size(psi));\n  double sum = 0.0;\n  for (int i=0; i<(1<<k); i++)\n    {\n      double ent_sq = norm(s(i));\n      sum -= log2(ent_sq) * ent_sq;\n    }\n  return sum;\n}\n\n// Diagonal entropy of the first k qubits\ndouble diagentropy(unsigned int k, cx_dvec &psi)\n{\n  int d = psi.size();\n  double sum = 0.0;\n  for (int i=0; i<(1<<k); i++)\n    {\n      double ent_sq = 0.0;\n      for (int j=0; j<(d/(1<<k)); j++)\n\t{\n\t  ent_sq += norm(psi(i + (j<<k)));\n\t}\n      sum -= log2(ent_sq) * ent_sq;\n    }\n  return sum;\n}\n", "meta": {"hexsha": "22cc9226182486bd94988c12055993710e0791b3", "size": 812, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++/entropy.cpp", "max_stars_repo_name": "ikim-quantum/DecodeInterior", "max_stars_repo_head_hexsha": "c07649e8728c784dc1bd2a25602fec14a344a234", "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": "c++/entropy.cpp", "max_issues_repo_name": "ikim-quantum/DecodeInterior", "max_issues_repo_head_hexsha": "c07649e8728c784dc1bd2a25602fec14a344a234", "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": "c++/entropy.cpp", "max_forks_repo_name": "ikim-quantum/DecodeInterior", "max_forks_repo_head_hexsha": "c07649e8728c784dc1bd2a25602fec14a344a234", "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": 20.8205128205, "max_line_length": 49, "alphanum_fraction": 0.5775862069, "num_tokens": 279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172601537141, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.7052049451686748}}
{"text": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union\u2019s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n\n#include \"../util/FluidEigenMappings.hpp\"\n#include \"../../data/TensorTypes.hpp\"\n#include <Eigen/Core>\n#include <Eigen/SVD>\n#include <cassert>\n#include <cmath>\n\nnamespace fluid {\nnamespace algorithm {\n\nclass PCA\n{\npublic:\n  using MatrixXd = Eigen::MatrixXd;\n  using VectorXd = Eigen::VectorXd;\n  using ArrayXd = Eigen::ArrayXd;\n\n  void init(RealMatrixView in)\n  {\n    using namespace Eigen;\n    using namespace _impl;\n    MatrixXd input = asEigen<Matrix>(in);\n    mNumDataPoints = input.rows();\n    mMean = input.colwise().mean();\n    MatrixXd         X = (input.rowwise() - mMean.transpose());\n    BDCSVD<MatrixXd> svd(X.matrix(), ComputeThinV | ComputeThinU);\n    mBases = svd.matrixV();\n    mValues = svd.singularValues();\n    mExplainedVariance = mValues.array().square() / (mNumDataPoints - 1);\n    mInitialized = true;\n  }\n\n  void init(RealMatrixView bases, RealVectorView values, RealVectorView mean,\n            index numDataPoints = 2)\n  {\n    mBases = _impl::asEigen<Eigen::Matrix>(bases);\n    mValues = _impl::asEigen<Eigen::Matrix>(values);\n    mMean = _impl::asEigen<Eigen::Matrix>(mean);\n    mNumDataPoints = numDataPoints;\n    mExplainedVariance = mValues.array().square() / (mNumDataPoints - 1);\n    mInitialized = true;\n  }\n\n  void processFrame(const RealVectorView in, RealVectorView out, index k,\n                    bool whiten = false) const\n  {\n    using namespace Eigen;\n    using namespace _impl;\n    if (k > mBases.cols()) return;\n    VectorXd input = asEigen<Matrix>(in);\n    input = input - mMean;\n    VectorXd result = input.transpose() * mBases.block(0, 0, mBases.rows(), k);\n\n    if (whiten)\n    {\n      ArrayXd norm = mExplainedVariance.segment(0, k).max(epsilon).rsqrt();\n      result.array() *= norm;\n    }\n     out <<= _impl::asFluid(result);\n  }\n\n  void inverseProcessFrame(RealVectorView in, RealVectorView out, bool whiten = false) const\n  {\n    using namespace Eigen;\n    using namespace _impl;\n    \n    if(!whiten)\n    {\n      asEigen<Matrix>(out) =\n          mMean +\n          (asEigen<Matrix>(in).transpose() * mBases.transpose()).transpose();\n    }\n    else\n    {\n      asEigen<Matrix>(out) = mMean +  (asEigen<Matrix>(in).transpose() *\n            (mExplainedVariance.sqrt().matrix().asDiagonal() * mBases.transpose())).transpose();\n    }    \n  }\n\n  double process(const RealMatrixView in, RealMatrixView out, index k,\n                 bool whiten = false) const\n  {\n    using namespace Eigen;\n    using namespace _impl;\n\n    if (k > mBases.cols()) return 0;\n    MatrixXd input = asEigen<Matrix>(in);\n    MatrixXd result = (input.rowwise() - mMean.transpose()) *\n                      mBases.block(0, 0, mBases.rows(), k);\n    if (whiten)\n    {\n      ArrayXd norm = mExplainedVariance.segment(0, k).max(epsilon).rsqrt();\n      result = result.array().rowwise() * norm.transpose().max(epsilon);\n    }\n    double variance = 0;\n\n    double total = mExplainedVariance.sum();\n    for (index i = 0; i < k; i++) variance += mExplainedVariance[i];\n    out <<= _impl::asFluid(result);\n\n    return variance / total;\n  }\n\n  void inverseProcess(RealMatrixView in, RealMatrixView out, bool whiten = false) const\n  {\n    using namespace Eigen;\n\n    if (in.cols() > dims()) return;\n    if (out.cols() < in.cols()) return;\n\n    if (!whiten)\n      _impl::asEigen<Matrix>(out) =\n          (_impl::asEigen<Matrix>(in) * mBases.transpose()).rowwise() +\n          mMean.transpose();\n\n    else\n    {\n      _impl::asEigen<Matrix>(out) =\n          (_impl::asEigen<Matrix>(in) *\n           (mExplainedVariance.sqrt().matrix().asDiagonal() *\n            mBases.transpose()))\n              .rowwise() +\n          mMean.transpose();\n    }\n  }\n\n  bool  initialized() const { return mInitialized; }\n\n  void  getBases(RealMatrixView out) const { out <<= _impl::asFluid(mBases); }\n  void  getValues(RealVectorView out) const { out <<= _impl::asFluid(mValues); }\n  void  getMean(RealVectorView out) const { out <<= _impl::asFluid(mMean); }\n  index getNumDataPoints() const { return mNumDataPoints; }\n\n  index dims() const { return mBases.rows(); }\n  index size() const { return mBases.cols(); }\n  void  clear()\n  {\n    mBases.setZero();\n    mMean.setZero();\n    mInitialized = false;\n  }\n\n  MatrixXd mBases;\n  VectorXd mValues;\n  ArrayXd  mExplainedVariance;\n  VectorXd mMean;\n  index    mNumDataPoints;\n  bool     mInitialized{false};\n};\n}// namespace algorithm\n}// namespace fluid\n", "meta": {"hexsha": "28362f551fa6f4caebaa48439b83a1cd255b4e1d", "size": 4815, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/public/PCA.hpp", "max_stars_repo_name": "jamesb93/flucoma-core", "max_stars_repo_head_hexsha": "3e964dd569f6fff15bd5249a705dc0da8f7b2ad8", "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": "include/algorithms/public/PCA.hpp", "max_issues_repo_name": "jamesb93/flucoma-core", "max_issues_repo_head_hexsha": "3e964dd569f6fff15bd5249a705dc0da8f7b2ad8", "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": "include/algorithms/public/PCA.hpp", "max_forks_repo_name": "jamesb93/flucoma-core", "max_forks_repo_head_hexsha": "3e964dd569f6fff15bd5249a705dc0da8f7b2ad8", "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": 29.3597560976, "max_line_length": 96, "alphanum_fraction": 0.6444444444, "num_tokens": 1298, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172587090974, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.7052049386973093}}
{"text": "#include \"stats/asphericity.h\"\n#include <Eigen/Core>\n#include <Eigen/SVD>\n#include <xmd/utils/convert.h>\n\nnamespace xmd {\n    void compute_asphericity::operator()() const {\n        vec3r center_of_mass = vec3r::Zero();\n        real total_mass = 0.0;\n        for (int idx = 0; idx < num_particles; ++idx) {\n            center_of_mass += mass[idx] * r[idx];\n            total_mass += mass[idx];\n        }\n        center_of_mass /= total_mass;\n\n        using matrix_t = Eigen::Matrix<real, 3, Eigen::Dynamic>;\n        matrix_t R = matrix_t::Zero(3, num_particles);\n        for (int idx = 0; idx < num_particles; ++idx) {\n            R.col(idx) = convert(r[idx] - center_of_mass);\n        }\n\n        auto lambda = Eigen::JacobiSVD<decltype(R)>(R).singularValues();\n        *asphericity = (real)1.5 * pow(lambda.z(), 2.0)\n            - (real)0.5 * lambda.squaredNorm();\n    }\n}", "meta": {"hexsha": "482af2efce3851405ea1bb60d96d567c8d20a9e6", "size": 872, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "xmd/src/stats/asphericity.cpp", "max_stars_repo_name": "vitreusx/xmd", "max_stars_repo_head_hexsha": "09f7df4b398f41f0e59abdced25998b53470f0a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-16T02:26:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-16T02:26:30.000Z", "max_issues_repo_path": "xmd/src/stats/asphericity.cpp", "max_issues_repo_name": "vitreusx/xmd", "max_issues_repo_head_hexsha": "09f7df4b398f41f0e59abdced25998b53470f0a4", "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": "xmd/src/stats/asphericity.cpp", "max_forks_repo_name": "vitreusx/xmd", "max_forks_repo_head_hexsha": "09f7df4b398f41f0e59abdced25998b53470f0a4", "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.5384615385, "max_line_length": 72, "alphanum_fraction": 0.5756880734, "num_tokens": 241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341975270266, "lm_q2_score": 0.7371581510799253, "lm_q1q2_score": 0.705190696308851}}
{"text": "//test for PS12 problem 1\n#include <Eigen/Dense>\n#include <iostream>\n\n\n\nint main(){\n\t\n\t\n    unsigned int s = 3;\n\tEigen::VectorXd c_(s);\n    Eigen::MatrixXd A_(s,s);\n    Eigen::VectorXd b_(s);\n    A_ << 0,      0,      0,\n         1./3.,  0,      0,\n         0,      2./3.,  0;\n    b_ << 1./4.,  0,      3./4.;\n    \n    short n=A_.rows();\n\tassert(n==b_.size());\n\tc_.resize(n);\n\tstd::cout << n;\n\tfor (int i=0; i<n;i++){\n\t\tc_(i)=0;\n\t\tfor (int j=0;j<i+1;j++){\n\t\t\t\tc_(i)+=A_(i,j);\n\t\t\t}\n\t\t}\n\tstd::cout << A_ << std::endl;\n\tstd::cout << c_ << std::endl;\n\t\n\t\n\t\n\t\n\t\n}\n", "meta": {"hexsha": "e01fb86a6b27bc4e0954e732e291f238c94b2ffb", "size": 559, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/PS12/test.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/PS12/test.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/PS12/test.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": 15.1081081081, "max_line_length": 32, "alphanum_fraction": 0.4436493739, "num_tokens": 217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582612793111, "lm_q2_score": 0.7577943822145998, "lm_q1q2_score": 0.7050960432826262}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\nCopyright (C) 2015 Andres Hernandez\n\nThis file is part of QuantLib, a free-software/open-source library\nfor financial quantitative analysts and developers - http://quantlib.org/\n\nQuantLib is free software: you can redistribute it and/or modify it\nunder the terms of the QuantLib license.  You should have received a\ncopy of the license along with this program; if not, please email\n<quantlib-dev@lists.sf.net>. The license is also available online at\n<http://quantlib.org/license.shtml>.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT\nANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\nFOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n/*! \\file particleswarmoptimization.hpp\n\\brief Implementation based on:\nClerc, M., Kennedy, J. (2002) The particle swarm-explosion, stability and\nconvergence in a multidimensional complex space. IEEE Transactions on Evolutionary\nComputation, 6(2): 58\u201373.\n*/\n\n#ifndef quantlib_optimization_particleswarmoptimization_hpp\n#define quantlib_optimization_particleswarmoptimization_hpp\n\n#include <ql/qldefines.hpp>\n\n#if BOOST_VERSION >= 104700\n\n#include <ql/math/optimization/problem.hpp>\n#include <ql/math/optimization/constraint.hpp>\n#include <ql/math/randomnumbers/mt19937uniformrng.hpp>\n#include <ql/experimental/math/isotropicrandomwalk.hpp>\n#include <ql/experimental/math/levyflightdistribution.hpp>\n\n#include <boost/random/mersenne_twister.hpp>\ntypedef boost::mt19937 base_generator_type;\n\n#include <boost/random/uniform_int_distribution.hpp>\ntypedef boost::random::uniform_int_distribution<QuantLib::Size> uniform_integer;\n\nnamespace QuantLib {\n\n    /*! The process is as follows:\n    M individuals are used to explore the N-dimensional parameter space\n    X_{i}^k = (X_{i, 1}^k, X_{i, 2}^k, \\ldots, X_{i, N}^k) is the kth-iteration for the ith-individual\n    X is updated via the rule\n    X_{i, j}^{k+1} = X_{i, j}^k + V_{i, j}^{k+1}\n    with V being the \"velocity\" that updates the position:\n    V_{i, j}^{k+1} = \\chi\\left(V_{i, j}^k + c_1 r_{i, j}^k (P_{i, j}^k - X_{i, j}^k)\n    + c_2 R_{i, j}^k (G_{i, j}^k - X_{i, j}^k)\\right)\n    where c are constants, r and R are uniformly distributed random numbers in the range [0, 1], and\n    P_{i, j} is the personal best parameter set for individual i up to iteration k\n    G_{i, j} is the global best parameter set for the swarm up to iteration k.\n    c_1 is the self recognition coefficient\n    c_2 is the social recognition coefficient\n\n    This version is known as the PSO with constriction factor (PSO-Co).\n    PSO with inertia factor (PSO-In) updates the velocity according to:\n    V_{i, j}^{k+1} = \\omega V_{i, j}^k + \\hat{c}_1 r_{i, j}^k (P_{i, j}^k - X_{i, j}^k)\n    + \\hat{c}_2 R_{i, j}^k (G_{i, j}^k - X_{i, j}^k)\n    and is accessible from PSO-Co by setting \\omega = \\chi, and \\hat{c}_{1,2} = \\chi c_{1,2}\n\n    These two versions of PSO are normally referred to as canonical PSO.\n\n    Convergence of PSO-Co is improved if \\chi is chosen as\n    \\chi = \\frac{2}{\\vert 2-\\phi-\\sqrt{\\phi^2 - 4\\phi}\\vert}, with \\phi = c_1 + c_2\n    Stable convergence is achieved if \\phi >= 4. Clerc and Kennedy recommend\n    c_1 = c_2 = 2.05 and \\phi = 4.1\n\n    Different topologies can be chosen for G, e.g. instead of it being the best\n    of the swarm, it is the best of the nearest neighbours, or some other form.\n\n    In the canonical PSO, the inertia function is trivial. It is simply a\n    constant (the inertia) multiplying the previous iteration's velocity. The\n    value of the inertia constant determines the weight of a global search over\n    local search. Like in the case of the topology, other possibilities for the\n    inertia function are also possible, e.g. a function that interpolates between a\n    high inertia at the beginning of the optimization (hence prioritizing a global\n    search) and a low inertia towards the end of the optimization (hence prioritizing\n    a local search).\n\n    The optimization stops either because the number of iterations has been reached\n    or because the stationary function value limit has been reached.\n    */\n    class ParticleSwarmOptimization : public OptimizationMethod {\n      public:\n        class Inertia;\n        class Topology;\n        friend class Inertia;\n        friend class Topology;\n        ParticleSwarmOptimization(Size M,\n            boost::shared_ptr<Topology> topology,\n            boost::shared_ptr<Inertia> inertia,\n            Real c1 = 2.05, Real c2 = 2.05,\n            unsigned long seed = 0);\n        ParticleSwarmOptimization(const Size M,\n            boost::shared_ptr<Topology> topology,\n            boost::shared_ptr<Inertia> inertia,\n            Real omega, Real c1, Real c2,\n            unsigned long seed = 0);\n        void startState(Problem &P, const EndCriteria &endCriteria);\n        EndCriteria::Type minimize(Problem &P, const EndCriteria &endCriteria);\n\n      protected:\n        std::vector<Array> X_, V_, pBX_, gBX_;\n        Array pBF_, gBF_;\n        Array lX_, uX_;\n        Size M_, N_;\n        Real c0_, c1_, c2_;\n        MersenneTwisterUniformRng rng_;\n        boost::shared_ptr<Topology> topology_;\n        boost::shared_ptr<Inertia> inertia_;\n    };\n\n    //! Base inertia class used to alter the PSO state\n    /*! This pure virtual base class provides the access to the PSO state\n    which the particular inertia algorithm will change upon each iteration.\n    */\n    class ParticleSwarmOptimization::Inertia {\n        friend class ParticleSwarmOptimization;\n      public:\n        virtual ~Inertia() {}\n        //! initialize state for current problem\n        virtual void setSize(Size M, Size N, Real c0, const EndCriteria &endCriteria) = 0;\n        //! produce changes to PSO state for current iteration\n        virtual void setValues() = 0;\n      protected:\n        ParticleSwarmOptimization *pso_;\n        std::vector<Array> *X_, *V_, *pBX_, *gBX_;\n        Array *pBF_, *gBF_;\n        Array *lX_, *uX_;\n      private:\n        void init(ParticleSwarmOptimization *pso) {\n            pso_ = pso;\n            X_ = &pso_->X_;\n            V_ = &pso_->V_;\n            pBX_ = &pso_->pBX_;\n            gBX_ = &pso_->gBX_;\n            pBF_ = &pso_->pBF_;\n            gBF_ = &pso_->gBF_;\n            lX_ = &pso_->lX_;\n            uX_ = &pso_->uX_;\n        }\n    };\n\n    //! Trivial Inertia\n    /*     Inertia is a static value\n    */\n    class TrivialInertia : public ParticleSwarmOptimization::Inertia {\n      public:\n        inline void setSize(Size M, Size N, Real c0, const EndCriteria &endCriteria) {\n            c0_ = c0;\n            M_ = M;\n        }\n        inline void setValues() {\n            for (Size i = 0; i < M_; i++) {\n                (*V_)[i] *= c0_;\n            }\n        }\n      private:\n        Real c0_;\n        Size M_;\n    };\n\n    //! Simple Random Inertia\n    /*     Inertia value gets multiplied with a random number\n    between (threshhold, 1)\n    */\n    class SimpleRandomInertia : public ParticleSwarmOptimization::Inertia {\n      public:\n        SimpleRandomInertia(Real threshhold = 0.5, unsigned long seed = 0)\n            : threshhold_(threshhold), rng_(seed) {\n            QL_REQUIRE(threshhold_ >= 0.0 && threshhold_ < 1.0, \"Threshhold must be a Real in [0, 1)\");\n        }\n        inline void setSize(Size M, Size N, Real c0, const EndCriteria &endCriteria) {\n            M_ = M;\n            c0_ = c0;\n        }\n        inline void setValues() {\n            for (Size i = 0; i < M_; i++) {\n                Real val = c0_*(threshhold_ + (1.0 - threshhold_)*rng_.nextReal());\n                (*V_)[i] *= val;\n            }\n        }\n      private:\n        Real c0_, threshhold_;\n        Size M_;\n        MersenneTwisterUniformRng rng_;\n    };\n\n    //! Decreasing Inertia\n    /*     Inertia value gets decreased every iteration until it reaches\n    a value of threshhold when iteration reaches the maximum level\n    */\n    class DecreasingInertia : public ParticleSwarmOptimization::Inertia {\n      public:\n        DecreasingInertia(Real threshhold = 0.5)\n            : threshhold_(threshhold) {\n            QL_REQUIRE(threshhold_ >= 0.0 && threshhold_ < 1.0, \"Threshhold must be a Real in [0, 1)\");\n        }\n        inline void setSize(Size M, Size N, Real c0, const EndCriteria &endCriteria) {\n            N_ = N;\n            c0_ = c0;\n            iteration_ = 0;\n            maxIterations_ = endCriteria.maxIterations();\n        }\n        inline void setValues() {\n            Real c0 = c0_*(threshhold_ + (1.0 - threshhold_)*(maxIterations_ - iteration_) / maxIterations_);\n            for (Size i = 0; i < M_; i++) {\n                (*V_)[i] *= c0;\n            }\n        }\n      private:\n        Real c0_, threshhold_;\n        Size M_, N_, maxIterations_, iteration_;\n    };\n\n    //! AdaptiveInertia\n    /*    Alen Lukic, Approximating Kinetic Parameters Using Particle\n    Swarm Optimization.\n    */\n    class AdaptiveInertia : public ParticleSwarmOptimization::Inertia {\n      public:\n        AdaptiveInertia(Real minInertia, Real maxInertia, Size sh = 5, Size sl = 2)\n            :minInertia_(minInertia), maxInertia_(maxInertia),\n            sh_(sh), sl_(sl) {};\n        inline void setSize(Size M, Size N, Real c0, const EndCriteria &endCriteria) {\n            M_ = M;\n            c0_ = c0;\n            adaptiveCounter = 0;\n            best_ = QL_MAX_REAL;\n            started_ = false;\n        }\n        void setValues();\n      private:\n        Real c0_, best_;\n        Real minInertia_, maxInertia_;\n        Size M_;\n        Size sh_, sl_;\n        Size adaptiveCounter;\n        bool started_;\n    };\n\n    //! Levy Flight Inertia\n    /*    As long as the particle keeps getting frequent updates to its\n    personal best value, the inertia behaves like a SimpleRandomInertia,\n    but after a number of iterations without improvement, the behaviour\n    changes to that of a Levy flight ~ u^{-1/\\alpha}\n    */\n    class LevyFlightInertia : public ParticleSwarmOptimization::Inertia {\n      public:\n        typedef IsotropicRandomWalk<LevyFlightDistribution, base_generator_type> IsotropicLevyFlight;\n        LevyFlightInertia(Real alpha, Size threshhold, \n                          unsigned long seed = 0)\n            :flight_(base_generator_type(seed), LevyFlightDistribution(1.0, alpha), \n                1, Array(1, 1.0), seed),\n            threshhold_(threshhold) {};\n        inline void setSize(Size M, Size N, Real c0, const EndCriteria &endCriteria) {\n            M_ = M;\n            N_ = N;\n            c0_ = c0;\n            personalBestF_ = *pBF_;\n            adaptiveCounter_ = std::vector<Size>(M_, 0);\n            flight_.setDimension(N_, *lX_, *uX_);\n        }\n        inline void setValues() {\n            for (Size i = 0; i < M_; i++) {\n                if ((*pBF_)[i] < personalBestF_[i]) {\n                    personalBestF_[i] = (*pBF_)[i];\n                    adaptiveCounter_[i] = 0;\n                }\n                else {\n                    adaptiveCounter_[i]++;\n                }\n                if (adaptiveCounter_[i] <= threshhold_) {\n                    //Simple Random Inertia\n                    (*V_)[i] *= c0_*(0.5 + 0.5*rng_.nextReal());\n                }\n                else {\n                    //If particle has not found a new personal best after threshhold_ iterations\n                    //then trigger a Levy flight pattern for the speed\n                    flight_.nextReal<Real *>(&(*V_)[i][0]);\n                }\n            }\n        }\n      private:\n        MersenneTwisterUniformRng rng_;\n        IsotropicLevyFlight flight_;\n        Array personalBestF_;\n        std::vector<Size> adaptiveCounter_;\n        Real c0_;\n        Size M_, N_;\n        Size threshhold_;\n    };\n\n    //! Base topology class used to determine the personal and global best\n    /*! This pure virtual base class provides the access to the PSO state\n    which the particular topology algorithm will change upon each iteration.\n    */\n    class ParticleSwarmOptimization::Topology {\n        friend class ParticleSwarmOptimization;\n      public:\n        virtual ~Topology() {}\n        //! initialize state for current problem\n        virtual void setSize(Size M) = 0;\n        //! produce changes to PSO state for current iteration\n        virtual void findSocialBest() = 0;\n      protected:\n        ParticleSwarmOptimization *pso_;\n        std::vector<Array> *X_, *V_, *pBX_, *gBX_;\n        Array *pBF_, *gBF_;\n      private:\n        void init(ParticleSwarmOptimization *pso) {\n            pso_ = pso;\n            X_ = &pso_->X_;\n            V_ = &pso_->V_;\n            pBX_ = &pso_->pBX_;\n            gBX_ = &pso_->gBX_;\n            pBF_ = &pso_->pBF_;\n            gBF_ = &pso_->gBF_;\n        }\n    };\n\n    //! Global Topology\n    /*  The global best as seen by each particle is the best from amongst\n    all particles\n    */\n    class GlobalTopology : public ParticleSwarmOptimization::Topology {\n      public:\n        inline void setSize(Size M) { M_ = M; }\n        inline void findSocialBest() {\n            Real bestF = (*pBF_)[0];\n            Size bestP = 0;\n            for (Size i = 1; i < M_; i++) {\n                if (bestF < (*pBF_)[i]) {\n                    bestF = (*pBF_)[i];\n                    bestP = i;\n                }\n            }\n            Array& x = (*pBX_)[bestP];\n            for (Size i = 0; i < M_; i++) {\n                if (i != bestP) {\n                    (*gBX_)[i] = x;\n                    (*gBF_)[i] = bestF;\n                }\n            }\n        }\n\n      private:\n        Size M_;\n    };\n\n    //! K-Neighbor Topology\n    /*  The global best as seen by each particle is the best from amongst\n    the previous K and next K neighbors. For particle I, the best is\n    then taken from amongst the [I - K, I + K] particles.\n    */\n    class KNeighbors : public ParticleSwarmOptimization::Topology {\n      public:\n        KNeighbors(Size K = 1) :K_(K) {\n            QL_REQUIRE(K > 0, \"Neighbors need to be larger than 0\");\n        }\n        inline void setSize(Size M) {\n            M_ = M;\n            if (M_ < 2 * K_ + 1)\n                K_ = (M_ - 1) / 2;\n        }\n        void findSocialBest();\n\n      private:\n        Size K_, M_;\n    };\n\n    //! Clubs Topology\n    /*  H.M. Emara,  Adaptive Clubs-based Particle Swarm Optimization\n    Each particle is originally assigned to a default number of clubs\n    from among the total set. The best as seen by each particle is the\n    best from amongst the clubs to which the particle belongs.\n    Underperforming particles join more clubs randomly (up to a maximum\n    number) to widen the particles that influence them, while\n    overperforming particles leave clubs randomly (down to a minimum\n    number) to avoid early convergence to local minima.\n    */\n    class ClubsTopology : public ParticleSwarmOptimization::Topology {\n      public:\n        ClubsTopology(Size defaultClubs, Size totalClubs,\n            Size maxClubs, Size minClubs,\n            Size resetIteration, unsigned long seed = 0);\n        void setSize(Size M);\n        void findSocialBest();\n\n      private:\n        Size totalClubs_, maxClubs_, minClubs_, defaultClubs_;\n        Size iteration_, resetIteration_;\n        Size M_;\n        std::vector<std::vector<bool> > clubs4particles_;\n        std::vector<std::vector<bool> > particles4clubs_;\n        std::vector<Size> bestByClub_;\n        std::vector<Size> worstByClub_;\n        base_generator_type generator_;\n        uniform_integer distribution_;\n\n        void leaveRandomClub(Size particle, Size currentClubs);\n        void joinRandomClub(Size particle, Size currentClubs);\n    };\n\n}\n\n#endif\n\n#endif\n", "meta": {"hexsha": "86eef6d881e129d5afbb2e2caa212bc0509e7e59", "size": 15700, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/math/particleswarmoptimization.hpp", "max_stars_repo_name": "apfadler/QuantLib", "max_stars_repo_head_hexsha": "ca8db6006776ffbe2694d9ec7ccbd74dd0a9ba46", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-03-28T15:05:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-17T23:05:57.000Z", "max_issues_repo_path": "ql/experimental/math/particleswarmoptimization.hpp", "max_issues_repo_name": "apfadler/QuantLib", "max_issues_repo_head_hexsha": "ca8db6006776ffbe2694d9ec7ccbd74dd0a9ba46", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-02-02T20:32:43.000Z", "max_issues_repo_issues_event_max_datetime": "2015-02-02T20:32:43.000Z", "max_forks_repo_path": "ql/experimental/math/particleswarmoptimization.hpp", "max_forks_repo_name": "apfadler/QuantLib", "max_forks_repo_head_hexsha": "ca8db6006776ffbe2694d9ec7ccbd74dd0a9ba46", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T14:50:24.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-23T07:41:30.000Z", "avg_line_length": 37.6498800959, "max_line_length": 109, "alphanum_fraction": 0.6042675159, "num_tokens": 4053, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110540642804, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.7050036767625741}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_CONSTANT_GOLD_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_GOLD_HPP_INCLUDED\n\n/*!\n  @ingroup group-constant\n  @defgroup constant-Gold Gold (function template)\n\n  Generates the Golden Ratio \\f$\\phi\n\n  @headerref{<boost/simd/constant/gold.hpp>}\n\n  @par Description\n\n  1.  @code\n      template<typename T> T Gold();\n      @endcode\n\n  2.  @code\n      template<typename T> T Gold( boost::simd::as_<T> const& target );\n      @endcode\n\n  Generates a constant that evaluate to the [Golden Ratio](http://mathworld.wolfram.com/GoldenRatio.html)\n  defined as \\f$\\frac{1}{2}(1 + \\sqrt{5})\\f$.\n\n  @par Parameters\n\n  | Name                | Description                                                         |\n  |--------------------:|:--------------------------------------------------------------------|\n  | **target**          | a [placeholder](@ref type-as) value encapsulating the constant type |\n\n  @par Return Value\n  A value of type @c T that evaluates to `T(1.61803398874989484820458683436563811772)`.\n\n  @par Requirements\n  - **T** models IEEEValue\n**/\n\n#include <boost/simd/constant/scalar/gold.hpp>\n#include <boost/simd/constant/simd/gold.hpp>\n\n#endif\n", "meta": {"hexsha": "1b82091f4a78e66064088e6a34d3e77e2e3518c8", "size": 1558, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/constant/gold.hpp", "max_stars_repo_name": "SylvainCorlay/pythran", "max_stars_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-02-25T22:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T15:13:12.000Z", "max_issues_repo_path": "third_party/boost/simd/constant/gold.hpp", "max_issues_repo_name": "SylvainCorlay/pythran", "max_issues_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "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": "third_party/boost/simd/constant/gold.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 29.9615384615, "max_line_length": 105, "alphanum_fraction": 0.5365853659, "num_tokens": 353, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110368115781, "lm_q2_score": 0.7905303260722198, "lm_q1q2_score": 0.7050036697254614}}
{"text": "//\n// OpenTissue, A toolbox for physical based simulation and animation.\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\n//\n#include <OpenTissue/configuration.h>\n\n#include <OpenTissue/core/math/big/big_types.h>\n#include <OpenTissue/core/math/optimization/optimization_compute_index_sets.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <OpenTissue/utility/utility_push_boost_filter.h>\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/test_tools.hpp>\n#include <OpenTissue/utility/utility_pop_boost_filter.h>\n\n\ntemplate <typename T>\nclass BoundFunction\n{\npublic:\n\n  typedef OpenTissue::math::ValueTraits<T> value_traits;\n\n  bool m_is_lower;\n\npublic:\n\n  BoundFunction(bool const & is_lower)\n    : m_is_lower(is_lower)\n  {}\n\n  template<typename vector_type>\n  T operator()(vector_type const & x, size_t const & i) const\n  {\n    return m_is_lower ?  -value_traits::one() : value_traits::one();\n  }\n\n};\n\nBOOST_AUTO_TEST_SUITE(opentissue_math_big_compute_index_sets);\n\nBOOST_AUTO_TEST_CASE(test_case)\n{\n  typedef double                    real_type;\n  typedef ublas::vector<real_type>  vector_type;\n  typedef ublas::vector<size_t>     idx_vector_type;\n\n  vector_type x;\n  vector_type y;\n\n  x.resize(10,false);\n  y.resize(10,false);\n\n  BoundFunction<double> l(true);\n  BoundFunction<double> u(false);\n\n  x(0) =  0.0;   y(0) =  0.0;  // active\n  x(1) = -1.0;   y(1) =  1.0;  // lower\n  x(2) =  1.0;   y(2) = -1.0;  // upper\n  x(3) = -2.0;   y(3) = -1.0;  // active\n  x(4) =  2.0;   y(4) =  1.0;  // active\n  x(5) =  3.0;   y(5) =  0.0;  // upper\n  x(6) = -3.0;   y(6) =  0.0;  // lower\n  x(7) =  0.5;   y(7) =  0.5;  // active\n  x(8) = -0.5;   y(8) = -0.5;  // active\n  x(9) =  0.25;   y(9) = 0.25; // active\n\n  idx_vector_type bitmask;\n  size_t cnt_active;\n  size_t cnt_inactive;\n  OpenTissue::math::optimization::compute_index_sets( y, x, l, u, bitmask, cnt_active, cnt_inactive );\n\n  BOOST_CHECK( cnt_active == 6 );\n  BOOST_CHECK( cnt_inactive == 4 );\n\n  BOOST_CHECK( bitmask(0) == OpenTissue::math::optimization::IN_ACTIVE );\n  BOOST_CHECK( bitmask(1) == OpenTissue::math::optimization::IN_LOWER );\n  BOOST_CHECK( bitmask(2) == OpenTissue::math::optimization::IN_UPPER );\n  BOOST_CHECK( bitmask(3) == OpenTissue::math::optimization::IN_ACTIVE );\n  BOOST_CHECK( bitmask(4) == OpenTissue::math::optimization::IN_ACTIVE );\n  BOOST_CHECK( bitmask(5) == OpenTissue::math::optimization::IN_UPPER );\n  BOOST_CHECK( bitmask(6) == OpenTissue::math::optimization::IN_LOWER );\n  BOOST_CHECK( bitmask(7) == OpenTissue::math::optimization::IN_ACTIVE );\n  BOOST_CHECK( bitmask(8) == OpenTissue::math::optimization::IN_ACTIVE );\n  BOOST_CHECK( bitmask(9) == OpenTissue::math::optimization::IN_ACTIVE );\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "dff7580ecced8eae5a6c0fc653cccbd83d5ca518", "size": 2794, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/core/math/optimization/compute_index_sets/src/unit_compute_index_sets.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:45:06.000Z", "max_issues_repo_path": "unit_tests/core/math/optimization/compute_index_sets/src/unit_compute_index_sets.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-20T14:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T15:26:45.000Z", "max_forks_repo_path": "unit_tests/core/math/optimization/compute_index_sets/src/unit_compute_index_sets.cpp", "max_forks_repo_name": "ricortiz/OpenTissue", "max_forks_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T01:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:06:49.000Z", "avg_line_length": 31.0444444444, "max_line_length": 102, "alphanum_fraction": 0.6850393701, "num_tokens": 881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870287, "lm_q2_score": 0.7905303186696748, "lm_q1q2_score": 0.7050036653969208}}
{"text": "// Author(s): Jan Friso Groote\n// Copyright: see the accompanying file COPYING or copy at\n// https://github.com/mCRL2org/mCRL2/blob/master/COPYING\n//\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/// \\file linear_inequalities_test.cpp\n/// \\brief Test the linear_inequality functionality.\n\n#define BOOST_TEST_MODULE linear_inequalities_test\n#include \"mcrl2/data/fourier_motzkin.h\"\n#include \"mcrl2/data/join.h\"\n#include \"mcrl2/data/linear_inequalities.h\"\n#include \"mcrl2/data/parse.h\"\n#include <boost/test/included/unit_test_framework.hpp>\n\nusing namespace mcrl2;\nusing namespace mcrl2::core;\nusing namespace mcrl2::data;\n\nvoid check(bool result, std::string message)\n{\n  if(!result) {\n    std::cout << message << std::endl;\n  }\n  BOOST_CHECK(result);\n}\n\nvoid test_linear_inequality()\n{\n  data_specification data_spec;\n  data_spec.add_context_sort(sort_real::real_());\n  rewriter rewr(data_spec);\n\n  variable vx(\"x\", sort_real::real_());\n  variable vy(\"y\", sort_real::real_());\n  linear_inequality li;\n  data_expression expr;\n\n  expr = less(real_zero(), real_zero());\n  li = linear_inequality(expr, rewr);\n  check(li.is_false(rewr), \"Expected \" + pp(expr) + \"' to be false\");\n  check(li.lhs().empty(), \"Expected left hand side of '\" + pp(expr) + \"' to be empty \" + pp(li.lhs()));\n\n  expr = less_equal(real_zero(), real_zero());\n  li = linear_inequality(expr, rewr);\n  check(li.is_true(rewr), \"Expected '\" + pp(expr) + \"' to be true\");\n  check(li.lhs().empty(), \"Expected left hand side of '\" + pp(expr) + \"' to be empty\");\n\n  expr = less_equal(sort_real::minus(vx, vx), real_one());\n  li = linear_inequality(expr, rewr);\n  check(li.is_true(rewr), \"Expected '\" + pp(expr) + \"' to be true\");\n  check(li.lhs().empty(), \"Expected left hand side of '\" + pp(expr) + \"' to be empty\");\n\n  expr = less_equal(sort_real::minus(vx, vx), real_one());\n  li = linear_inequality(expr, rewr);\n  check(li.is_true(rewr), \"Expected '\" + pp(expr) + \"' to be true\");\n  check(li.lhs().empty(), \"Expected left hand side of '\" + pp(expr) + \"' to be empty\");\n\n  expr = less_equal(sort_real::plus(vx, vy), vx);\n  li = linear_inequality(expr, rewr);\n  check(!li.is_true(rewr), \"Expected '\" + pp(expr) + \"' to not be true\");\n  check(!li.lhs().empty(), \"Expected left hand side of '\" + pp(expr) + \"' not to be empty\");\n  check(li.transform_to_data_expression() == less_equal(sort_real::times(real_one(), vy), real_zero()),\n    \"Expression '\" + pp(expr) + \"' parsing/output problem \" + pp(li.transform_to_data_expression()));\n\n  bool got_exception = false;\n  try\n  {\n    expr = not_equal_to(vx, vy);\n    li = linear_inequality(expr, rewr);\n  }\n  catch(const mcrl2::runtime_error&)\n  {\n    got_exception = true;\n  }\n  check(got_exception, \"Expected an exception while parsing x != y.\");\n}\n\nvoid split_conjunction_of_inequalities_set(const data_expression& e, std::vector < linear_inequality >& v, const rewriter& r)\n{\n  if (sort_bool::is_and_application(e))\n  {\n    split_conjunction_of_inequalities_set(application(e)[0],v,r);\n    split_conjunction_of_inequalities_set(application(e)[1],v,r);\n  }\n  else\n  {\n    v.push_back(linear_inequality(e,r));\n  }\n}\n\nbool test_consistency_of_inequalities(const std::string& vars,\n                                      const std::string& inequalities,\n                                      const bool expect_consistent)\n{\n  // Take care that reals are part of the data type.\n  data_specification data_spec;\n  variable_list variables=parse_variables(vars);\n  data_spec.add_context_sort(sort_real::real_());\n  const data_expression e=parse_data_expression(inequalities,variables,data_spec);\n\n  rewriter r(data_spec);\n  std::vector < linear_inequality > v_inequalities;\n  split_conjunction_of_inequalities_set(e,v_inequalities,r);\n\n  if (is_inconsistent(v_inequalities,r))\n  {\n    if (expect_consistent)\n    {\n      std::cout << \"Expected consistent, found inconsistent\\n\";\n      std::cout << variables << \": \" << inequalities << \"\\n\";\n      std::cout << \"Internal inequalities: \" << pp_vector(v_inequalities) << \"\\n\";\n      return false;\n    }\n  }\n  else\n  {\n    if (!expect_consistent)\n    {\n      std::cout << \"Expected inconsistent, found consistent\\n\";\n      std::cout << variables << \": \" << inequalities << \"\\n\";\n      std::cout << \"Internal inequalities: \" << pp_vector(v_inequalities) << \"\\n\";\n      return false;\n    }\n  }\n  return true;\n}\n\nbool test_application_of_Fourier_Motzkin(const std::string& vars,\n                                         const std::string& variables_to_be_eliminated,\n                                         const std::string& inequalities,\n                                         const std::string& inconsistent_with,\n                                         bool check_consistent = false)\n{\n  // Take care that reals are part of the data type.\n  data_specification data_spec;\n  data_spec.add_context_sort(sort_real::real_());\n  const variable_list variables=parse_variables(vars);\n  const data_expression e_in=parse_data_expression(inequalities,variables,data_spec);\n  const variable_list v_elim= data::detail::parse_variables(variables_to_be_eliminated);\n\n  rewriter r(data_spec);\n  std::vector < linear_inequality > v_inequalities;\n  split_conjunction_of_inequalities_set(e_in,v_inequalities,r);\n\n  std::vector < linear_inequality> resulting_inequalities;\n  fourier_motzkin(v_inequalities, v_elim.begin(), v_elim.end(), resulting_inequalities, r);\n\n  std::vector < linear_inequality> inconsistent_inequalities=resulting_inequalities;\n  inconsistent_inequalities.push_back(linear_inequality(parse_data_expression(inconsistent_with,variables,data_spec),r));\n  if (!(check_consistent ^ is_inconsistent(inconsistent_inequalities,r, false)))\n  {\n    std::cout << \"Expected set of inequations to be \" << (check_consistent ? \"\" : \"in\") << \"consistent with given inequality after applying Fourier-Motzkin elimination\\n\";\n    std::cout << \"Input: \" << variables << \": \" << inequalities << \"\\n\";\n    std::cout << \"Parsed input : \" << pp_vector(v_inequalities) << \"\\n\";\n    std::cout << \"Variables to be eliminated: \" << v_elim << \"\\n\";\n    std::cout << \"Input after applying Fourier Motzkin: \" << pp_vector(resulting_inequalities) << \"\\n\";\n    std::cout << \"Should be \" << (check_consistent ? \"\" : \"in\") << \"consistent with \" << inconsistent_with << \"\\n\";\n    std::cout << (check_consistent ? \"Consistent\" : \"Inconsistent\")  << \" inequality after parsing \" << pp(linear_inequality(parse_data_expression(inconsistent_with,variables,data_spec),r)) << \"\\n\";\n    return false;\n  }\n  return true;\n}\n\nvoid test_high_level_fourier_motzkin()\n{\n  data_specification data_spec;\n  data_spec.add_context_sort(sort_real::real_());\n  rewriter rewr(data_spec);\n  variable vx(\"x\", sort_real::real_());\n  variable vy(\"y\", sort_real::real_());\n\n  data_expression expr = sort_bool::and_(equal_to(vx, vy), less(vy, sort_real::real_(2)));\n  variable_list elim_vars({variable(\"y\", sort_real::real_())});\n  data_expression out;\n  variable_list vars_out;\n  fourier_motzkin(expr, elim_vars, out, vars_out, rewr);\n\n  BOOST_CHECK(vars_out.empty());\n  BOOST_CHECK(out == less(sort_real::times(real_one(), vx), sort_real::real_(2)));\n}\n\nvoid test_high_level_fourier_motzkin_non_linear()\n{\n  data_specification data_spec;\n  data_spec.add_context_sort(sort_real::real_());\n  rewriter rewr(data_spec);\n  variable vx(\"x\", sort_real::real_());\n\n  data_expression expr = less(sort_real::times(vx,vx), sort_real::real_(0));\n  variable_list elim_vars({vx});\n  data_expression out;\n  variable_list vars_out;\n  fourier_motzkin(expr, elim_vars, out, vars_out, rewr);\n\n  // Fourier Motzkin should fail, because the expression is not linear\n  // Original result should be returned\n  BOOST_CHECK(vars_out == elim_vars);\n  BOOST_CHECK(out == expr);\n}\n\nvoid split_conditions_helper(const std::string& vars,\n                             const std::string& expr,\n                             std::vector< data_expression_list >& real_conditions,\n                             std::vector< data_expression >& non_real_conditions)\n{\n  data_specification data_spec;\n  data_spec.add_context_sort(sort_real::real_());\n  const variable_list variables=parse_variables(vars);\n  const data_expression e_in=parse_data_expression(expr,variables,data_spec);\n\n  data::detail::split_condition(e_in, real_conditions, non_real_conditions);\n}\n\nvoid test_split_conditions()\n{\n  std::vector < data_expression_list > real_conditions;\n  std::vector < data_expression > non_real_conditions;\n\n  split_conditions_helper(\"x,y:Real, a,b,c:Bool;\", \"a && b\", real_conditions, non_real_conditions);\n  BOOST_CHECK(real_conditions.size() == 1);\n  BOOST_CHECK(non_real_conditions.size() == 1);\n  BOOST_CHECK(real_conditions[0].size() == 0);\n  BOOST_CHECK(sort_bool::is_and_application(non_real_conditions[0]));\n  real_conditions.clear(); non_real_conditions.clear();\n\n  split_conditions_helper(\"x,y:Real, a,b,c:Bool;\", \"(a || b) && c\", real_conditions, non_real_conditions);\n  BOOST_CHECK(real_conditions.size() == 1);\n  BOOST_CHECK(non_real_conditions.size() == 1);\n  BOOST_CHECK(real_conditions[0].size() == 0);\n  BOOST_CHECK(sort_bool::is_and_application(non_real_conditions[0]));\n  BOOST_CHECK(sort_bool::is_or_application(sort_bool::left(non_real_conditions[0])));\n  real_conditions.clear(); non_real_conditions.clear();\n\n  split_conditions_helper(\"x,y:Real, a,b,c:Bool;\", \"(a || b) && x < 5\", real_conditions, non_real_conditions);\n  BOOST_CHECK(real_conditions.size() == 1);\n  BOOST_CHECK(non_real_conditions.size() == 1);\n  BOOST_CHECK(real_conditions[0].size() == 1);\n  BOOST_CHECK(is_less_application(real_conditions[0].front()));\n  BOOST_CHECK(sort_bool::is_or_application(non_real_conditions[0]));\n  real_conditions.clear(); non_real_conditions.clear();\n\n  split_conditions_helper(\"x,y:Real, a,b,c:Bool;\", \"(a || b) && (x == 3 || y > 4)\", real_conditions, non_real_conditions);\n  BOOST_CHECK(real_conditions.size() == 2);\n  BOOST_CHECK(non_real_conditions.size() == 2);\n  BOOST_CHECK(real_conditions[0].size() == 1);\n  BOOST_CHECK(real_conditions[1].size() == 1);\n  BOOST_CHECK((is_equal_to_application(real_conditions[0].front()) && is_greater_application(real_conditions[1].front())) ||\n              (is_equal_to_application(real_conditions[1].front()) && is_greater_application(real_conditions[0].front())));\n  BOOST_CHECK(non_real_conditions[0] == non_real_conditions[1]);\n  real_conditions.clear(); non_real_conditions.clear();\n\n  split_conditions_helper(\"x,y:Real, a,b,c:Bool;\", \"(x == y || y < 0) && (x == 3 || y > 4)\", real_conditions, non_real_conditions);\n  BOOST_CHECK(real_conditions.size() == 4);\n  BOOST_CHECK(non_real_conditions.size() == 4);\n  for(int i = 0; i < 4; i++)\n  {\n    BOOST_CHECK(real_conditions[i].size() == 2);\n    BOOST_CHECK(non_real_conditions[i] == sort_bool::true_());\n  }\n  real_conditions.clear(); non_real_conditions.clear();\n\n  split_conditions_helper(\"x,y:Real, a,b,c:Bool;\", \"(x == y || a) && (x == 3 || b)\", real_conditions, non_real_conditions);\n  BOOST_CHECK(real_conditions.size() == 4);\n  BOOST_CHECK(non_real_conditions.size() == 4);\n  for(int i = 0; i < 4; i++)\n  {\n    std::set< data_expression > split_without_true = split_and(non_real_conditions[i]);\n    split_without_true.erase(sort_bool::true_());\n    BOOST_CHECK(real_conditions[i].size() + split_without_true.size() == 2);\n  }\n  real_conditions.clear(); non_real_conditions.clear();\n}\n\nBOOST_AUTO_TEST_CASE(test_main)\n{\n  test_linear_inequality();\n  test_split_conditions();\n\n  BOOST_CHECK(test_consistency_of_inequalities(\"x:Real;\", \"x<3  && x>=4\", false));\n  BOOST_CHECK(test_consistency_of_inequalities(\"x:Real;\", \"x<3  && x>=2\", true));\n  BOOST_CHECK(test_consistency_of_inequalities(\"x:Real;\", \"x<3  && x>=3\", false));\n  BOOST_CHECK(test_consistency_of_inequalities(\"x:Real;\", \"x<=3  && x>=3\", true));\n  BOOST_CHECK(test_consistency_of_inequalities(\"u:Real;\",\"0 <= u && -u <= -4 && -u < 0\",true));\n  BOOST_CHECK(test_consistency_of_inequalities(\"u,t:Real;\",\"u + -t <= 1 && -u <= -4 && t < u && -u < 0 && -t <= 0 \",true));\n  BOOST_CHECK(test_consistency_of_inequalities(\"u,t,l:Real;\",\"u + -t <= 1 && -u <= -4 && -u + l < 0 && -u < 0 && -t <= 0 && -l + t <= 0\",true));\n\n  BOOST_CHECK(test_application_of_Fourier_Motzkin(\"x,y:Real;\", \"y:Real;\", \"-y + x < 0 &&  y < 2\", \"x>=2\"));\n  BOOST_CHECK(test_application_of_Fourier_Motzkin(\"cup1,cup2,add:Real;\", \"add:Real;\", \"add <= 2 && 0 <= add && cup2 + 2 - add <= cup1 + add && 3 < cup1 + add - 2\", \"cup2 - cup1 >= 2\", true));\n  test_high_level_fourier_motzkin();\n  test_high_level_fourier_motzkin_non_linear();\n}\n", "meta": {"hexsha": "43c81c871aa4823effe2e85ba295fb2b9435199b", "size": 12646, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/data/test/linear_inequalities_test.cpp", "max_stars_repo_name": "nouwaarom/mCRL2", "max_stars_repo_head_hexsha": "cd77f9ab46c9568aa655a49d4d49c08d1768e870", "max_stars_repo_licenses": ["BSL-1.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": "libraries/data/test/linear_inequalities_test.cpp", "max_issues_repo_name": "nouwaarom/mCRL2", "max_issues_repo_head_hexsha": "cd77f9ab46c9568aa655a49d4d49c08d1768e870", "max_issues_repo_licenses": ["BSL-1.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": "libraries/data/test/linear_inequalities_test.cpp", "max_forks_repo_name": "nouwaarom/mCRL2", "max_forks_repo_head_hexsha": "cd77f9ab46c9568aa655a49d4d49c08d1768e870", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.722972973, "max_line_length": 198, "alphanum_fraction": 0.6872528863, "num_tokens": 3311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813453, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.7049678157026222}}
{"text": "//include <scottgs/Timing.hpp>\n\n#include <iostream>\n#include <cstdlib>\n#include <algorithm>\n\n#include \"FloatMatrix.hpp\"\n#include \"MatrixMultiply.hpp\"\n\n#include <boost/numeric/ublas/io.hpp>\n\nvoid initRandomMatrix(scottgs::FloatMatrix& m);\n\nint main(int argc, char * argv[])\n{\n\tstd::cout << \"Homework 1\" << std::endl \n\t\t  << \"Grant Scott (scottgs)\" << std::endl;  // CHANGE TO YOUR name AND pawprint\n\n\t// ---------------------------------------------\n\t// BEGIN: Self Test Portion\n\t// ---------------------------------------------\n\tstd::cout << \"Running Self Test\" << std::endl\n\t\t  << \"-----------------\" << std::endl;\n\tscottgs::FloatMatrix l42(4, 2);\n\tl42(0,0) = 2; l42(0,1) = 3;\n\tl42(1,0) = 4; l42(1,1) = 5;\n\tl42(2,0) = 6; l42(2,1) = 7;\n\tl42(3,0) = 8; l42(3,1) = 9;\n\n\tscottgs::FloatMatrix r23(2,3);\n\tr23(0,0) = 2; r23(0,1) = 3; r23(0,2) = 4;\n\tr23(1,0) = 5; r23(1,1) = 6; r23(1,2) = 7;\n\n\t// (19,24,29),(33,42,51),(47,60,73),(61,78,95)\n\tscottgs::FloatMatrix er(4,3);\n\ter(0,0) = 19; er(0,1) = 24; er(0,2) = 29;\n\ter(1,0) = 33; er(1,1) = 42; er(1,2) = 51;\n\ter(2,0) = 47; er(2,1) = 60; er(2,2) = 73;\n\ter(3,0) = 61; er(3,1) = 78; er(3,2) = 95;\n\n\tscottgs::MatrixMultiply mm;\n\tscottgs::FloatMatrix result = mm(l42,r23);\n\tstd::cout << \"Result of \" << std::endl << l42 << std::endl\n\t\t  << \"   times  \" << std::endl << r23 << std::endl\n\t\t  << \"  equals  \" << std::endl << result << std::endl;\n\n\tif ( ! std::equal( er.data().begin(), er.data().end(), result.data().begin() ) )\n\t{\n\t\tstd::cerr << \"Self Test Expected Result: \" << er << std::endl\n\t\t\t  << \"           ... but found : \" << result << std::endl;\n\t\treturn 1;\n\t}\n\n\tscottgs::FloatMatrix result2 = mm.multiply(l42,r23);\n\tstd::cout << \"Result of \" << std::endl << l42 << std::endl\n\t\t  << \"   times  \" << std::endl << r23 << std::endl\n\t\t  << \"  equals  \" << std::endl << result2 << std::endl;\n\n\tif ( ! std::equal( er.data().begin(), er.data().end(), result2.data().begin() ) )\n\t{\n\t\tstd::cerr << \"Self Test Expected Result: \" << er << std::endl\n\t\t\t  << \"           ... but found : \" << result2 << std::endl;\n\t\treturn 1;\n\t}\n\n\tstd::cout << \"Self Test Complete\" << std::endl\n\t\t  << \"==================\" << std::endl;\n\n\t// ---------------------------------------------\n\t// END: Self Test Portion\n\t// ---------------------------------------------\n\n\treturn 0;\n}\n", "meta": {"hexsha": "ae69e10d236171566996e86cbfc5b6253430f1ca", "size": 2295, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Matrix-Multiplication-Speedup/src/hw1.cpp", "max_stars_repo_name": "samkreter/High-Performance-Computing", "max_stars_repo_head_hexsha": "cb8c944fa0ed39aaea41ee4ecb202dd2c18a52a2", "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": "Matrix-Multiplication-Speedup/src/hw1.cpp", "max_issues_repo_name": "samkreter/High-Performance-Computing", "max_issues_repo_head_hexsha": "cb8c944fa0ed39aaea41ee4ecb202dd2c18a52a2", "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": "Matrix-Multiplication-Speedup/src/hw1.cpp", "max_forks_repo_name": "samkreter/High-Performance-Computing", "max_forks_repo_head_hexsha": "cb8c944fa0ed39aaea41ee4ecb202dd2c18a52a2", "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.6, "max_line_length": 82, "alphanum_fraction": 0.4897603486, "num_tokens": 831, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7049446392273846}}
{"text": "/*\nThis file covers basics about using eigen such as initializing a matrix, operations, and functions.\n\nHow to Install / Use Eigen: \n1. go to desired install folder\n2. git clone https://gitlab.com/libeigen/eigen\n3. add path/to/eigen to include directories: Project >> PROJECT Properties >> \n    VC++ Directories >> Include Directories >> (add path here)\n4. start using Eigen\n\nthings to add: \n  * append new row(s)\n  * append new col(s)\n\n*/\n\n#include <iostream>\n#include <Eigen/Dense>\nusing namespace std;\nint main() {\n  namespace eig = Eigen;\n  // create a matrix: can either be a dynamic or static matrix:\n\n  //dynamic matrix (note the \"X\" in the name)\n  eig::MatrixX<double> x1(2, 2);\n  x1 << 0, 1, 2, 3;\n\n  // static matrix (note the delimiting of dimensions in the template)\n  eig::Matrix<double, 2, 2> x2;\n  x2 << 5,2,3,1;\n  \n  eig::MatrixX<double> x3(2, 5);\n  x3 << 0, 1, 2, 3, 4, 5, 6, 7, 8, 9;\n\n  // alternative to matrices are arrays, which function a little bit more like numpy arrays\n  eig::ArrayXX<double> y1(2, 2); // having two 'X's is correct\n  y1 << 2, 3, 4, 5;\n  eig::Array<double, 2, 2> y2; // also has a static option\n  y2 << 5, 6, 7, 8;\n\n  // conversion between the two: \n  eig::MatrixX<double> xtemp = y1.matrix();\n\n  // note there are also vectors, but used to a far lesser extent\n  eig::VectorX<double> v(6);\n  v << 1, 2, 3, 4, 5, 6;\n  cout << \"vector: \" << v << endl;\n\n  // basic per-element operations: \n  cout << \"scalar addition \\n\" << (x1.array() + 10).matrix() << endl; // note: need to be in array\n  cout << \"scalar subtraction \\n\" << (x1.array() - 10).matrix() << endl;\n  cout << \"scalar multiplication \\n\" << x1 * 10 << endl;\n  cout << \"scalar division \\n\" << x1 / 10 << endl;\n  \n  // matrix operations\n  cout << \"matrix addition \\n\" << x1 + x2 << endl;\n  cout << \"matrix subtraction \\n\" << x1 - x2 << endl;\n  cout << \"transpose \\n\" << x1.transpose() << endl;\n  cout << \"inverse \\n\" << x1.inverse() << endl;\n  cout << \"matmult \\n\" << x1 * x2 << endl;\n  cout << \"conjugation \\n\" << x1.conjugate() << endl;\n\n  // WARNING: AVOID TRANSPOSITION ISSUES, WHICH OCCUR WHEN TRANSPOSING IN-PLACE:\n  // a=a.transpose() // DO NOT DO THIS\n  x1.transposeInPlace();\n  x1.transposeInPlace();\n\n  // arithmetic reduction operations:\n  cout << \"sum the matrix: \" << x1.sum() << endl;\n  cout << \"mult the matrix: \" << x1.prod() << endl;\n  cout << \"matrix mean: \" << x1.mean() << endl;\n  cout << \"matrix min: \" << x1.minCoeff() << endl;\n  cout << \"matrix max: \" << x1.maxCoeff() << endl;\n  \n  // matrix properties\n  cout << \"diagonal: \" << x1.diagonal().transpose() << endl;\n  cout << \"shape (should be 2,5): \" << x3.rows() << ',' << x3.cols() << endl;\n  \n  // matrix manipulation\n  eig::Map < eig::MatrixX<double>> x4(x1.data(), 1,x1.size());\n  cout << \"reshape: \" << x4 << endl;\n  // append a row\n  eig::MatrixX<double> x6(2,2);\n  x6 << 0, 1, 2, 3;\n  x6.conservativeResize(x6.cols() + 1, eig::NoChange); // shortcut\n  x6(2, 0) = 5;\n  x6(2, 1) = 6;\n  cout << \"append row: \\n\" << x6 << endl;\n\n  // taking part of matrix: \n  eig::MatrixX<double> x5(5, 5);\n  for (int i = 0; i < x5.size(); i++) x5(i) = i;\n  cout << \"initial \\n\" << x5 << endl;\n\n  cout << \"arbitrary block \\n\" << x5.block(1, 1, 2, 2) << endl;\n  cout << \"column1 \\n\" << x5.block(0, 1, x5.rows(), 1) << endl;\n  cout << \"row3 \\n\" << x5.block(3, 0, 1,x5.cols()) << endl;\n\n  // special matrices. dynamic or static, can be whatever dimensions needed\n  cout << \"identity matrix \\n\" << eig::Matrix<double,3,3>::Identity() << endl;\n  cout << \"zeros \\n\" << eig::Matrix<double, 3, 3>::Zero() << endl;\n  cout << \"ones\\n\" << eig::Matrix<double, 3, 3>::Ones() << endl;\n  cout << \"random\\n\" << eig::MatrixX<double>::Random(3,3) << endl;\n\n  \n\n\n}\n\n\n\n\n", "meta": {"hexsha": "73d767bfdaa6c44f848a723e2f5e9e9a093fc1cd", "size": 3709, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp_sandbox/hello_eigen/main.cpp", "max_stars_repo_name": "kjgonzalez/codefiles", "max_stars_repo_head_hexsha": "b86f25182d1b5553a331f8721dd06b51fa157c3e", "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_sandbox/hello_eigen/main.cpp", "max_issues_repo_name": "kjgonzalez/codefiles", "max_issues_repo_head_hexsha": "b86f25182d1b5553a331f8721dd06b51fa157c3e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2019-10-01T20:48:15.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-14T18:21:09.000Z", "max_forks_repo_path": "cpp_sandbox/hello_eigen/main.cpp", "max_forks_repo_name": "kjgonzalez/codefiles", "max_forks_repo_head_hexsha": "b86f25182d1b5553a331f8721dd06b51fa157c3e", "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.8230088496, "max_line_length": 99, "alphanum_fraction": 0.5936910218, "num_tokens": 1273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424256566558, "lm_q2_score": 0.8333246035907933, "lm_q1q2_score": 0.7049446365209668}}
{"text": "/**\n * Munkres.hpp\n * @author : koide\n * 14/11/03\n **/\n#ifndef KKL_MUNKRES_HPP\n#define KKL_MUNKRES_HPP\n\n#include <cfloat>\n#include <vector>\n#include <iostream>\n#include <Eigen/Dense>\n\nnamespace kkl {\n\tnamespace alg {\n\ntemplate<typename T>\nbool isZero(T value) {\n\treturn value == 0;\n}\ntemplate<>\nbool isZero(float value) {\n\treturn abs(value) <= FLT_EPSILON;\n}\ntemplate<>\nbool isZero(double value) {\n\treturn abs(value) <= DBL_EPSILON;\n}\n\n/************************************************\n * Munkres\n * http://csclab.murraystate.edu/bob.pilgrim/445/munkres.html\n * \n * Munkres<int> munkres\n * auto ans = munkres.solve( cost )\n************************************************/\ntemplate<typename T>\nclass Munkres {\npublic:\n\t/*********************************************************\n\t * solve\n   * cost : cost matrix (cost.rows <= cost.cols)\n   * ret : solution\n\t********************************************************/\n\tEigen::VectorXi solve(const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& cost_) {\n\t\tassert( cost_.rows() <= cost_.cols() );\n\t\tcost = cost_;\n\t\tK = std::min(cost.rows(), cost.cols());\n\n\t\tstarred = Eigen::MatrixXi::Zero(cost.rows(), cost.cols());\n\t\tprimed = Eigen::MatrixXi::Zero(cost.rows(), cost.cols());\n\t\tcovered_rows = Eigen::VectorXi::Zero(cost.rows());\n\t\tcovered_cols = Eigen::VectorXi::Zero(cost.cols());\n\n\t\t// step 1\n\t\tcost.colwise() -= cost.rowwise().minCoeff();\n\n\t\t// step 2\n\t\tfor (int i = 0; i < cost.rows(); i++) {\n\t\t\tfor (int j = 0; j < cost.cols(); j++) {\n\t\t\t\tif (isZero(cost(i, j)) && starred.row(i).count() == 0 && starred.col(j).count() == 0){\n\t\t\t\t\tstarred(i, j) = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// step3 ~ step 6\n\t\tstep3();\n\n\t\t// done, find the starred zeros\n\t\tEigen::VectorXi ret(K);\n\t\tfor (int i = 0; i < K; i++) {\n\t\t\tfor (int j = 0; j < cost.cols(); j++) {\n\t\t\t\tif (starred(i, j)) {\n\t\t\t\t\tret(i) = j;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn ret;\n\t}\n\n\tEIGEN_MAKE_ALIGNED_OPERATOR_NEW\nprivate:\n\t/*****************************\n\t * step3\n\t*****************************/\n\tvoid step3() {\n\t\tfor (int i = 0; i < cost.cols(); i++) {\n\t\t\tif (starred.col(i).count() != 0) {\n\t\t\t\tcovered_cols[i] = 1;\n\t\t\t}\n\t\t}\n\t\t// if K columns are covered, go to done\n\t\tif (covered_cols.count() == K) {\n\t\t\treturn;\n\t\t}\n\t\t// otherwise, go to step 4\n\t\treturn step4();\n\t}\n\n\t/*****************************\n\t * step4\n\t*****************************/\n\tvoid step4() {\n\t\tfor (int i = 0; i < cost.rows(); i++) {\n\t\t\tfor (int j = 0; j < cost.cols(); j++){\n\t\t\t\t// find a noncovered zero and prime it\n\t\t\t\tif (!covered_rows[i] && !covered_cols[j] && isZero(cost(i, j))){\n\t\t\t\t\tprimed(i, j) = 1;\n\n\t\t\t\t\t// if there is no starred zero in the row, go to step 5\n\t\t\t\t\tif (starred.row(i).count() == 0) {\n\t\t\t\t\t\treturn step5(i, j);\n\t\t\t\t\t}\n\t\t\t\t\t// otherwise, cover this row and uncover the column containing the starred zero\n\t\t\t\t\tcovered_rows[i] = 1;\n\t\t\t\t\tfor (int k = 0; k < cost.cols(); k++) {\n\t\t\t\t\t\tif (starred(i, k)) {\n\t\t\t\t\t\t\tcovered_cols[k] = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tT smallest = -1;\n\t\t// continue in this manner until there are no uncovered zeros left\n\t\t// save the smallest uncovered value and go to step 6\n\t\tfor (int i = 0; i < cost.rows(); i++){\n\t\t\tfor (int j = 0; j < cost.cols(); j++) {\n\t\t\t\tif (!covered_rows[i] && !covered_cols[j] && isZero(cost(i, j))){\n\t\t\t\t\treturn step4();\n\t\t\t\t}\n\n\t\t\t\tif (!covered_rows[i] && !covered_cols[j] &&\n\t\t\t\t\t(smallest > cost(i, j) || smallest < 0.0)) {\n\t\t\t\t\tsmallest = cost(i, j);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn step6(smallest);\n\t}\n\n\t/*****************************\n\t * step5\n\t*****************************/\n\tvoid step5(int z0_row, int z0_col) {\n\t\tstd::vector<std::pair<int, int>> series(1);\n\t\tseries[0] = std::make_pair(z0_row, z0_col);\n\n\t\tbool done = false;\n\t\twhile (!done) {\n\t\t\t// z1 : the starred zero in the column of z0\n\t\t\tbool added = false;\n\t\t\tconst auto& z0 = series.back();\n\t\t\tfor (int i = 0; i < cost.rows(); i++) {\n\t\t\t\tif (starred(i, z0.second)) {\n\t\t\t\t\tadded = true;\n\t\t\t\t\tseries.push_back(std::make_pair(i, z0.second));\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!added) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tconst auto& z1 = series.back();\n\t\t\t// z2 : the primed zero in the rows of z1\n\t\t\tfor (int i = 0; i < cost.cols(); i++) {\n\t\t\t\tif (primed(z1.first, i)){\n\t\t\t\t\tseries.push_back(std::make_pair(z1.first, i));\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tdone = true;\n\t\t\tconst auto& z2 = series.back();\n\t\t\tfor (int i = 0; i < cost.rows(); i++){\n\t\t\t\tif (starred(i, z2.second)) {\n\t\t\t\t\tdone = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (int i = 0; i < series.size(); i++) {\n\t\t\tif (i % 2 == 0) {\n\t\t\t\tstarred(series[i].first, series[i].second) = 1;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tstarred(series[i].first, series[i].second) = 0;\n\t\t\t}\n\t\t}\n\n\t\tprimed.setZero();\n\t\tcovered_rows.setZero();\n\t\tcovered_cols.setZero();\n\n\t\treturn step3();\n\t}\n\n\t/*****************************\n\t * step6\n\t*****************************/\n\tvoid step6(T smallest) {\n\t\tfor (int i = 0; i < cost.rows(); i++) {\n\t\t\tif (covered_rows[i]) {\n\t\t\t\tcost.row(i).array() += smallest;\n\t\t\t}\n\t\t}\n\t\tfor (int i = 0; i < cost.cols(); i++) {\n\t\t\tif (!covered_cols[i]) {\n\t\t\t\tcost.col(i).array() -= smallest;\n\t\t\t}\n\t\t}\n\n\t\treturn step4();\n\t}\n\n\t/*****************************\n\t * showState\n\t * show all matrices\n\t*****************************/\n\tvoid showState() const {\n\t\tstd::cout << \"--- cost ---\" << std::endl << cost << std::endl;\n\t\tstd::cout << \"--- starred ---\" << std::endl << starred << std::endl;\n\t\tstd::cout << \"--- primed ---\" << std::endl << primed << std::endl;\n\n\t\tEigen::MatrixXi covered(covered_rows.size(), covered_cols.size());\n\t\tfor (int i = 0; i < covered.rows(); i++) {\n\t\t\tfor (int j = 0; j < covered.cols(); j++) {\n\t\t\t\tcovered(i, j) = covered_rows[i] + covered_cols[j];\n\t\t\t}\n\t\t}\n\t\tstd::cout << \"--- covered ---\" << std::endl << covered << std::endl;\n\t}\n\nprivate:\n\tint K;\n\tEigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> cost;\n\n\tEigen::MatrixXi starred;\n\tEigen::MatrixXi primed;\n\n\tEigen::VectorXi covered_rows;\n\tEigen::VectorXi covered_cols;\n};\n\n\t}\n}\n\n#endif\n", "meta": {"hexsha": "712809d67ccb991423870e9d69926634c171da6d", "size": 5870, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/kkl/alg/munkres.hpp", "max_stars_repo_name": "y-lai/hdl_people_tracking", "max_stars_repo_head_hexsha": "fb7ec799047b8ea833a175abd2599793b8966c24", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 207.0, "max_stars_repo_stars_event_min_datetime": "2018-03-10T14:56:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T07:32:53.000Z", "max_issues_repo_path": "include/kkl/alg/munkres.hpp", "max_issues_repo_name": "y-lai/hdl_people_tracking", "max_issues_repo_head_hexsha": "fb7ec799047b8ea833a175abd2599793b8966c24", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 24.0, "max_issues_repo_issues_event_min_datetime": "2018-02-19T10:50:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T19:44:55.000Z", "max_forks_repo_path": "include/kkl/alg/munkres.hpp", "max_forks_repo_name": "y-lai/hdl_people_tracking", "max_forks_repo_head_hexsha": "fb7ec799047b8ea833a175abd2599793b8966c24", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 91.0, "max_forks_repo_forks_event_min_datetime": "2018-02-23T09:44:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-03T01:38:14.000Z", "avg_line_length": 23.0196078431, "max_line_length": 90, "alphanum_fraction": 0.5117546848, "num_tokens": 1814, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.7049153123062889}}
{"text": "//------------------------------------------------------------------------------\n/// \\file WriterMonad_tests.cpp\n/// \\ref Ivan \u010cuki\u0107, Functional Programming in C++,  Manning Publications;\n/// 1st edition (November 19, 2018). ISBN-13: 978-1617293818\n//------------------------------------------------------------------------------\n#include \"Categories/Monads/WriterMonad.h\"\n\n#include <boost/test/unit_test.hpp>\n#include <string>\n\nusing Categories::Monads::WriterMonad::WriterMonadEndomorphism;\nusing Categories::Monads::WriterMonad::unit;\nusing Categories::Monads::WriterMonad::bind;\n\nBOOST_AUTO_TEST_SUITE(Categories)\nBOOST_AUTO_TEST_SUITE(Monads)\nBOOST_AUTO_TEST_SUITE(WriterMonad_tests)\n\nusing LogEndomorphism = WriterMonadEndomorphism<int, std::string>;\n\n// Test morphisms.\n\ntemplate <int N = 0>\nWriterMonadEndomorphism<int, std::string> add_N(const int x)\n{\n  return WriterMonadEndomorphism<int, std::string>{\n    x + N,\n    \"added \" + std::to_string(N) + \" \"};\n}\n\ntemplate <int N = 0>\nWriterMonadEndomorphism<int, std::string> subtract_N(const int x)\n{\n  return WriterMonadEndomorphism<int, std::string>{\n    x - N,\n    \"subtracted \" + std::to_string(N) + \" \"};\n}\n\nBOOST_AUTO_TEST_SUITE(Construction_tests)\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(CartesianProductExplicitlyConstructs)\n{\n  const WriterMonadEndomorphism<int, std::string> tx {42};\n  BOOST_TEST(tx.value() == 42);\n  BOOST_TEST(tx.log().empty());\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(CartesianProductConstructsWithCartesianProduct)\n{\n  const std::string start_log {\"Start\"};\n  const WriterMonadEndomorphism<int, std::string> tx {42, start_log};\n  BOOST_TEST(tx.value() == 42);\n  BOOST_TEST((tx.log() == start_log));\n}\n\nBOOST_AUTO_TEST_SUITE_END() // Construction_tests\n\nBOOST_AUTO_TEST_SUITE(Morphisms_tests)\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(AddNIsAMorphism)\n{\n  const auto result = add_N<42>(69);\n  BOOST_TEST(result.value() == 42 + 69);\n  BOOST_TEST(result.log() == \"added 42 \");\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(SubtractNIsAMorphism)\n{\n  const auto result = subtract_N<42>(69);\n  BOOST_TEST(result.value() == 69 - 42);\n  BOOST_TEST(result.log() == \"subtracted 42 \");\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(UnitActsAsAUnitAndIsVeryGeneral)\n{\n  const auto result = unit<int, LogEndomorphism>(1608);\n  BOOST_TEST(result.value() == 1608);\n  BOOST_TEST(result.log().empty());\n}\n\nBOOST_AUTO_TEST_SUITE_END() // Morphisms_tests\n\nBOOST_AUTO_TEST_SUITE(Bind_tests)\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(BindIsComposition)\n{\n  const LogEndomorphism previous_actions {42, \"Started at 42,\"};\n\n  const auto result = bind(previous_actions, add_N<69>);\n\n  BOOST_TEST(result.value() == 42 + 69);\n  BOOST_TEST(result.log() == \"Started at 42,added 69 \");\n\n  const auto result2 = bind(result, subtract_N<10>);\n\n  BOOST_TEST(result2.value() == 42 + 69 - 10);\n  BOOST_TEST(result2.log() == \"Started at 42,added 69 subtracted 10 \");\n}\n\nBOOST_AUTO_TEST_SUITE_END() // Morphisms_tests\n\nBOOST_AUTO_TEST_SUITE_END() // WriterMonad_tests\nBOOST_AUTO_TEST_SUITE_END() // Monads\nBOOST_AUTO_TEST_SUITE_END() // Categories", "meta": {"hexsha": "0a7f1f0b0538e615dd0625b0a70246daca50b94d", "size": 3951, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Voltron/Source/UnitTests/Categories/Monads/WriterMonad_tests.cpp", "max_stars_repo_name": "ernestyalumni/HrdwCCppCUDA", "max_stars_repo_head_hexsha": "17ed937dea06431a4d5ca103f993ea69a6918734", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-02-09T19:44:51.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-09T19:44:51.000Z", "max_issues_repo_path": "Voltron/Source/UnitTests/Categories/Monads/WriterMonad_tests.cpp", "max_issues_repo_name": "ernestyalumni/HrdwCCppCUDA", "max_issues_repo_head_hexsha": "17ed937dea06431a4d5ca103f993ea69a6918734", "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": "Voltron/Source/UnitTests/Categories/Monads/WriterMonad_tests.cpp", "max_forks_repo_name": "ernestyalumni/HrdwCCppCUDA", "max_forks_repo_head_hexsha": "17ed937dea06431a4d5ca103f993ea69a6918734", "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.0603448276, "max_line_length": 80, "alphanum_fraction": 0.5297393065, "num_tokens": 776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473647220786, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.7049153002289203}}
{"text": "#include <stan/math/prim/scal.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <gtest/gtest.h>\n#include <limits>\n\nvoid test_log_diff_exp(double a, double b) {\n  using stan::math::log_diff_exp;\n  using std::exp;\n  using std::log;\n  EXPECT_FLOAT_EQ(log(exp(a) - exp(b)), log_diff_exp(a, b));\n}\n\nTEST(MathFunctions, log_diff_exp) {\n  using stan::math::log_diff_exp;\n  test_log_diff_exp(3.0, 2.0);\n  test_log_diff_exp(4.0, 1.0);\n  test_log_diff_exp(3.0, 2.0);\n  test_log_diff_exp(0, -2.1);\n  test_log_diff_exp(-20.0, -23);\n  test_log_diff_exp(-21.2, -32.1);\n  EXPECT_NO_THROW(log_diff_exp(-20.0, 12));\n  EXPECT_NO_THROW(log_diff_exp(-20.0, -12.1));\n  EXPECT_NO_THROW(log_diff_exp(120.0, 120.10));\n  EXPECT_NO_THROW(log_diff_exp(-20.0, 10.2));\n  EXPECT_NO_THROW(log_diff_exp(10, 11));\n  EXPECT_NO_THROW(log_diff_exp(10, 10));\n  EXPECT_NO_THROW(log_diff_exp(-10.21, -10.21));\n\n  // exp(10000.0) overflows\n  EXPECT_FLOAT_EQ(10000.0, log_diff_exp(10000.0, 0.0));\n  EXPECT_FLOAT_EQ(0.0, log_diff_exp(0.0, -10000.0));\n}\n\nTEST(MathFunctions, log_diff_exp_nan) {\n  double nan = std::numeric_limits<double>::quiet_NaN();\n\n  EXPECT_PRED1(boost::math::isnan<double>, stan::math::log_diff_exp(3.0, nan));\n\n  EXPECT_PRED1(boost::math::isnan<double>, stan::math::log_diff_exp(nan, 2.0));\n\n  EXPECT_PRED1(boost::math::isnan<double>, stan::math::log_diff_exp(nan, nan));\n}\n", "meta": {"hexsha": "cdb88d03e45676b567f7af8cc39943299a674786", "size": 1373, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/prim/scal/fun/log_diff_exp_test.cpp", "max_stars_repo_name": "jrmie/math", "max_stars_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "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": "test/unit/math/prim/scal/fun/log_diff_exp_test.cpp", "max_issues_repo_name": "jrmie/math", "max_issues_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "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": "test/unit/math/prim/scal/fun/log_diff_exp_test.cpp", "max_forks_repo_name": "jrmie/math", "max_forks_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "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": 31.9302325581, "max_line_length": 79, "alphanum_fraction": 0.7137654771, "num_tokens": 459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588052782737, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.7048798976334801}}
{"text": "/**\n * @file\n * @brief Test the order of quadrature rules by testing it with monomials\n * @author Raffael Casagrande\n * @date   2018-08-19 06:54:02\n * @copyright MIT License\n */\n\n#include <gtest/gtest.h>\n#include <lf/quad/quad.h>\n#include <boost/math/special_functions/factorials.hpp>\n\nnamespace lf::quad::test {\n\ndouble integrate(QuadRule qr, std::vector<int> monomialCoefficients) {\n  double result = 0;\n  for (int i = 0; i < qr.Points().cols(); ++i) {\n    double temp = 1;\n    for (int j = 0; j < monomialCoefficients.size(); ++j) {\n      temp *= std::pow(qr.Points()(j, i), monomialCoefficients[j]);\n    }\n    result += temp * qr.Weights()(i);\n  }\n  return result;\n}\n\nvoid checkQuadRule(QuadRule qr, double precision = 1e-12,\n                   bool check_order_exact = true) {\n  EXPECT_EQ(qr.Points().cols(), qr.Weights().size());\n  EXPECT_EQ(qr.Points().rows(), qr.RefEl().Dimension());\n\n  auto order = qr.Degree();\n  if (qr.RefEl() == base::RefEl::kSegment()) {\n    for (int i = 0; i <= order; ++i) {\n      // integrate x^i\n      EXPECT_DOUBLE_EQ(integrate(qr, {i}), 1. / (1. + i))\n          << \"Failure for i = \" << i;\n    }\n    // try integrate one order too high:\n    EXPECT_GT(std::abs(integrate(qr, {static_cast<int>(order) + 1}) -\n                       1. / (2. + order)),\n              1e-10);\n  } else if (qr.RefEl() == base::RefEl::kTria()) {\n    // TRIA\n    ///////////////////////////////////////////////////////////////////////////\n    auto exact_value = [](int i, int j) {\n      return boost::math::factorial<double>(i) *\n             boost::math::factorial<double>(j + 1) /\n             ((1 + j) * boost::math::factorial<double>(2 + i + j));\n    };\n    for (int i = 0; i <= order; ++i) {\n      for (int j = 0; j <= order - i; ++j) {\n        // integrate x^i y^j\n        double qr_val = integrate(qr, {i, j});\n        EXPECT_NEAR(qr_val / exact_value(i, j), 1, precision)\n            << \"Failure for x^\" << i << \"*y^\" << j << \": \" << qr_val << \" <-> \"\n            << exact_value(i, j);\n      }\n    }\n    if (check_order_exact) {\n      // Make sure that at least on of the order+1 polynomials is not integrated\n      // correctly\n      bool one_fails = false;\n      for (int i = -1; i <= static_cast<int>(order); ++i) {\n        if (std::abs(integrate(qr, {i + 1, static_cast<int>(order - i)}) -\n                     exact_value(i + 1, order - i)) > 1e-12) {\n          one_fails = true;\n          break;\n        }\n      }\n      EXPECT_TRUE(one_fails) << \"order = \" << (int)order;\n    }\n\n  } else if (qr.RefEl() == base::RefEl::kQuad()) {\n    // QUAD\n    ///////////////////////////////////////////////////////////////////////////\n    for (int i = 0; i <= order; ++i) {\n      for (int j = 0; j <= order; ++j) {\n        // integrate x^i y^j\n        double qr_val = integrate(qr, {i, j});\n        double ext_val = 1. / ((1. + i) * (1. + j));\n        EXPECT_DOUBLE_EQ(qr_val, ext_val)\n            << \"Failure for x^\" << i << \"*y^\" << j << \": \" << qr_val << \" <-> \"\n            << ext_val;\n      }\n    }\n\n    // make sure that not all of the higher polynomials integrate correctly:\n    bool atLeastOneFails = false;\n    for (int i = 0; i <= order + 1; ++i) {\n      if (std::abs(integrate(qr, {static_cast<int>(order + 1), i}) -\n                   1. / ((2. + order) * (1. + i))) > 1e-10) {\n        atLeastOneFails = true;\n        break;\n      }\n      if (std::abs(integrate(qr, {i, static_cast<int>(order + 1)}) -\n                   1. / ((2. + order) * (1. + i))) > 1e-10) {\n        atLeastOneFails = true;\n        break;\n      }\n    }\n    EXPECT_TRUE(atLeastOneFails);\n  }\n}\n\nTEST(qr_IntegrationTest, Segment) {\n  for (int i = 1; i < 10; ++i) {\n    checkQuadRule(make_QuadRule(base::RefEl::kSegment(), i));\n  }\n}\n\nTEST(qr_IntegrationTest, Quad) {\n  checkQuadRule(make_QuadRule(base::RefEl::kQuad(), 1));\n  checkQuadRule(make_QuadRule(base::RefEl::kQuad(), 2));\n  checkQuadRule(make_QuadRule(base::RefEl::kQuad(), 3));\n}\n\nTEST(qr_IntegrationTest, Tria) {\n  // make sure that also the tensor product versions are tested.\n  for (int i = 1; i < 55; ++i) {\n    checkQuadRule(make_QuadRule(base::RefEl::kTria(), i), 1e-12, i < 10);\n  }\n}\n\n// Test midpoint quadrature rule for triangles\nTEST(qr_IntegrationTest, mp) {\n  checkQuadRule(make_TriaQR_EdgeMidpointRule(), 1e-12, true);\n  checkQuadRule(make_QuadQR_EdgeMidpointRule(), 1e-12, true);\n}\n\nTEST(qr_IntegrationTest, P6O4) {\n  checkQuadRule(make_TriaQR_P6O4(), 1e-12, true);\n}\n\n}  // namespace lf::quad::test\n", "meta": {"hexsha": "ba4eccb48c450aa6f122ae6efc9385549b17236d", "size": 4471, "ext": "cc", "lang": "C++", "max_stars_repo_path": "lib/lf/quad/test/make_quad_rule_tests.cc", "max_stars_repo_name": "Pascal-So/lehrfempp", "max_stars_repo_head_hexsha": "e2716e914169eec7ee59e822ea3ab303143eacd1", "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": "lib/lf/quad/test/make_quad_rule_tests.cc", "max_issues_repo_name": "Pascal-So/lehrfempp", "max_issues_repo_head_hexsha": "e2716e914169eec7ee59e822ea3ab303143eacd1", "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": "lib/lf/quad/test/make_quad_rule_tests.cc", "max_forks_repo_name": "Pascal-So/lehrfempp", "max_forks_repo_head_hexsha": "e2716e914169eec7ee59e822ea3ab303143eacd1", "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.875, "max_line_length": 80, "alphanum_fraction": 0.5285171103, "num_tokens": 1388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995483, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.7048798836123777}}
{"text": "/**\n * @file linear_regression_test.cpp\n *\n * Test for linear regression.\n *\n * mlpack is free software; you may redistribute it and/or modify it under the\n * terms of the 3-clause BSD license.  You should have received a copy of the\n * 3-clause BSD license along with mlpack.  If not, see\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n */\n#include <mlpack/core.hpp>\n#include <mlpack/methods/linear_regression/linear_regression.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nusing namespace mlpack;\nusing namespace mlpack::regression;\n\nBOOST_AUTO_TEST_SUITE(LinearRegressionTest);\n\n/**\n * Creates two 10x3 random matrices and one 10x1 \"results\" matrix.\n * Finds B in y=BX with one matrix, then predicts against the other.\n */\nBOOST_AUTO_TEST_CASE(LinearRegressionTestCase)\n{\n  // Predictors and points are 10x3 matrices.\n  arma::mat predictors(3, 10);\n  arma::mat points(3, 10);\n\n  // Responses is the \"correct\" value for each point in predictors and points.\n  arma::vec responses(10);\n\n  // The values we get back when we predict for points.\n  arma::vec predictions(10);\n\n  // We'll randomly select some coefficients for the linear response.\n  arma::vec coeffs;\n  coeffs.randu(4);\n\n  // Now generate each point.\n  for (size_t row = 0; row < 3; row++)\n    predictors.row(row) = arma::linspace<arma::rowvec>(0, 9, 10);\n\n  points = predictors;\n\n  // Now add a small amount of noise to each point.\n  for (size_t elem = 0; elem < points.n_elem; elem++)\n  {\n    // Max added noise is 0.02.\n    points[elem] += math::Random() / 50.0;\n    predictors[elem] += math::Random() / 50.0;\n  }\n\n  // Generate responses.\n  for (size_t elem = 0; elem < responses.n_elem; elem++)\n    responses[elem] = coeffs[0] +\n        dot(coeffs.rows(1, 3), arma::ones<arma::rowvec>(3) * elem);\n\n  // Initialize and predict.\n  LinearRegression lr(predictors, responses);\n  lr.Predict(points, predictions);\n\n  // Output result and verify we have less than 5% error from \"correct\" value\n  // for each point.\n  for (size_t i = 0; i < predictions.n_cols; ++i)\n    BOOST_REQUIRE_SMALL(predictions(i) - responses(i), .05);\n}\n\n/**\n * Check the functionality of ComputeError().\n */\nBOOST_AUTO_TEST_CASE(ComputeErrorTest)\n{\n  arma::mat predictors;\n  predictors << 0 << 1 << 2 << 4 << 8 << 16 << arma::endr\n             << 16 << 8 << 4 << 2 << 1 << 0 << arma::endr;\n  arma::vec responses = \"0 2 4 3 8 8\";\n\n  // http://www.mlpack.org/trac/ticket/298\n  // This dataset gives a cost of 1.189500337 (as calculated in Octave).\n  LinearRegression lr(predictors, responses);\n\n  BOOST_REQUIRE_CLOSE(lr.ComputeError(predictors, responses), 1.189500337,\n      1e-3);\n}\n\n/**\n * Ensure that the cost is 0 when a perfectly-fitting dataset is given.\n */\nBOOST_AUTO_TEST_CASE(ComputeErrorPerfectFitTest)\n{\n  // Linear regression should perfectly model this dataset.\n  arma::mat predictors;\n  predictors << 0 << 1 << 2 << 1 << 6 << 2 << arma::endr\n             << 0 << 1 << 2 << 2 << 2 << 6 << arma::endr;\n  arma::vec responses = \"0 2 4 3 8 8\";\n\n  LinearRegression lr(predictors, responses);\n\n  BOOST_REQUIRE_SMALL(lr.ComputeError(predictors, responses), 1e-25);\n}\n\n/**\n * Test ridge regression using an empty dataset, which is not invertible.  But\n * the ridge regression part should make it invertible.\n */\nBOOST_AUTO_TEST_CASE(RidgeRegressionTest)\n{\n  // Create empty dataset.\n  arma::mat data;\n  data.zeros(10, 5000); // 10-dimensional, 5000 points.\n  arma::vec responses;\n  responses.zeros(5000); // 5000 points.\n\n  // Any lambda greater than 0 works to make the predictors covariance matrix\n  // invertible.  If ridge regression is not working correctly, then the matrix\n  // will not be invertible and the test should segfault (or something else\n  // ugly).\n  LinearRegression lr(data, responses, 0.0001);\n\n  // Now just make sure that it predicts some more zeros.\n  arma::vec predictedResponses;\n  lr.Predict(data, predictedResponses);\n\n  for (size_t i = 0; i < 5000; ++i)\n    BOOST_REQUIRE_SMALL((double) predictedResponses[i], 1e-20);\n}\n\n/**\n * Creates two 10x3 random matrices and one 10x1 \"results\" matrix.\n * Finds B in y=BX with one matrix, then predicts against the other, but uses\n * ridge regression with an extremely small lambda value.\n */\nBOOST_AUTO_TEST_CASE(RidgeRegressionTestCase)\n{\n  // Predictors and points are 10x3 matrices.\n  arma::mat predictors(3, 10);\n  arma::mat points(3, 10);\n\n  // Responses is the \"correct\" value for each point in predictors and points.\n  arma::vec responses(10);\n\n  // The values we get back when we predict for points.\n  arma::vec predictions(10);\n\n  // We'll randomly select some coefficients for the linear response.\n  arma::vec coeffs;\n  coeffs.randu(4);\n\n  // Now generate each point.\n  for (size_t row = 0; row < 3; row++)\n    predictors.row(row) = arma::linspace<arma::rowvec>(0, 9, 10);\n\n  points = predictors;\n\n  // Now add a small amount of noise to each point.\n  for (size_t elem = 0; elem < points.n_elem; elem++)\n  {\n    // Max added noise is 0.02.\n    points[elem] += math::Random() / 50.0;\n    predictors[elem] += math::Random() / 50.0;\n  }\n\n  // Generate responses.\n  for (size_t elem = 0; elem < responses.n_elem; elem++)\n    responses[elem] = coeffs[0] +\n        dot(coeffs.rows(1, 3), arma::ones<arma::rowvec>(3) * elem);\n\n  // Initialize and predict with very small lambda.\n  LinearRegression lr(predictors, responses, 0.001);\n  lr.Predict(points, predictions);\n\n  // Output result and verify we have less than 5% error from \"correct\" value\n  // for each point.\n  for (size_t i = 0; i < predictions.n_cols; ++i)\n    BOOST_REQUIRE_SMALL(predictions(i) - responses(i), .05);\n}\n\n/**\n * Test that a LinearRegression model trained in the constructor and trained in\n * the Train() method give the same model.\n */\nBOOST_AUTO_TEST_CASE(LinearRegressionTrainTest)\n{\n  // Random dataset.\n  arma::mat dataset = arma::randu<arma::mat>(5, 1000);\n  arma::vec responses = arma::randu<arma::vec>(1000);\n\n  LinearRegression lr(dataset, responses, 0.3);\n  LinearRegression lrTrain;\n  lrTrain.Lambda() = 0.3;\n\n  lrTrain.Train(dataset, responses);\n\n  BOOST_REQUIRE_EQUAL(lr.Parameters().n_elem, lrTrain.Parameters().n_elem);\n  for (size_t i = 0; i < lr.Parameters().n_elem; ++i)\n    BOOST_REQUIRE_CLOSE(lr.Parameters()[i], lrTrain.Parameters()[i], 1e-5);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "eba31c42b66bcc31dd6feeced31401a1f943179d", "size": 6334, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/linear_regression_test.cpp", "max_stars_repo_name": "NaxAlpha/mlpack-build", "max_stars_repo_head_hexsha": "1f0c1454d4b35eb97ff115669919c205cee5bd1c", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-05-21T11:08:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T07:52:14.000Z", "max_issues_repo_path": "src/mlpack/tests/linear_regression_test.cpp", "max_issues_repo_name": "okmegy/Mlpack", "max_issues_repo_head_hexsha": "ac9abef3c1353f483ed1af42ba5a7432f291ca1a", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "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/mlpack/tests/linear_regression_test.cpp", "max_forks_repo_name": "okmegy/Mlpack", "max_forks_repo_head_hexsha": "ac9abef3c1353f483ed1af42ba5a7432f291ca1a", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "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": 31.2019704433, "max_line_length": 79, "alphanum_fraction": 0.6872434481, "num_tokens": 1755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587846530938, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.7048798812755271}}
{"text": "// Implementing the class that is defined in the header file: Option.hpp\r\n//\r\n// (c) Sudhansh Dua\r\n\r\n\r\n#include \"Option.hpp\"\r\n#include <cmath>\r\n#include <boost/math/distributions.hpp>\r\n\r\n\r\nusing namespace std;\r\nusing namespace boost::math;\r\n\r\n\r\n//\tGaussian functions using boost libraries\r\ndouble Option::N(double x) const\r\n{\r\n\tnormal_distribution<> Standard_normal(0.0, 1.0);\r\n\treturn cdf(Standard_normal, x);\r\n}\r\n\r\ndouble Option::n(double x) const\r\n{\r\n\tnormal_distribution<> Standard_normal(0.0, 1.0);\r\n\treturn pdf(Standard_normal, x);\r\n}\r\n\r\n//\tKernel functions\r\ndouble Option::CallPrice() const\r\n{\r\n\treturn ::CallPrice(S, K, T, r, sig, b);\r\n}\r\n\r\ndouble Option::PutPrice() const\r\n{\r\n\treturn ::PutPrice(S, K, T, r, sig, b);\r\n}\r\n\r\n\r\n//\tInitialising all the default values\r\nvoid Option::init()\r\n{\r\n\t//\tDefault values\r\n\tr = 0.03;\r\n\tsig = 0.2;\r\n\tK = 100;\r\n\tS = 95;\t\t\t\t//\tDefault stock price \r\n\tT = 1;\r\n\tb = r;\t\t\t\t//\tBlack - Scholes(1973) stock option model : b = r\r\n\ttype = \"C\";\t\t\t//\tCall option as the default\r\n}\r\n\r\n\r\nvoid Option::copy(const Option& option)\r\n{\r\n\tS = option.S;\r\n\tK = option.K;\r\n\tT = option.T;\r\n\tr = option.r;\r\n\tsig = option.sig;\r\n\tb = option.b;\r\n\ttype = option.type;\r\n}\r\n\r\n\r\n//\tConstructors and destructor\r\nOption::Option()\t\t\t\t\t\t//\tDefault constructor\r\n{\r\n\tinit();\r\n}\r\n\r\nOption::Option(const Option& option)\t\t\t\t//\tCopy constructor\r\n{\r\n\tcopy(option);\r\n}\r\n\r\n//\tConstructor that accepts values\r\nOption::Option(const double& S1, const double& K1, const double& T1, const double& r1,\r\n\tconst double& sig1, const double& b1, const string type1) : S(S1), K(K1), T(T1), r(r1), sig(sig1), b(b1), type(type1) {}\r\n\r\nOption::~Option() {}\t\t\t\t\t\t//\tDestructor\r\n\r\n\r\n//\tAssignment operator\r\nOption& Option::operator = (const Option& option)\r\n{\r\n\tif (this == &option)\r\n\t{\r\n\t\treturn *this;\r\n\t}\r\n\tcopy(option);\r\n\treturn *this;\r\n}\r\n\r\n\r\n//\tFunctions that calculate option price and sensitivities\r\ndouble Option::Price() const\r\n{\r\n\tif (type == \"C\")\r\n\t{\r\n\t\treturn CallPrice();\r\n\t\r\n\t}\r\n\telse\r\n\t{\r\n\t\treturn PutPrice();\r\n\t}\r\n}\r\n\r\n\r\n// Modifier functions\r\nvoid Option::toggle()\t\t\t\t//\tChange the option type\r\n{\r\n\ttype = ((type == \"C\") ? \"P\" : \"C\");\r\n}\r\n\r\n\r\n//\tGlobal Functions\r\ndouble CallPrice(const double S, const double K, const double T, const double r, const double sig, const double b)\r\n{\r\n\tdouble d1 = (log(S / K) + (b + (sig * sig) * 0.5) * T) / (sig * sqrt(T));\r\n\tdouble d2 = d1 - (sig * sqrt(T));\r\n\tnormal_distribution<> standard_normal(0.0, 1.0);\r\n\r\n\treturn (S * exp((b - r) * T) * cdf(standard_normal, d1)) - (K * exp(-r * T) * cdf(standard_normal, d2));\r\n}\r\n\r\ndouble PutPrice(const double S, const double K, const double T, const double r, const double sig, const double b)\r\n{\r\n\tdouble d1 = (log(S / K) + (b + (sig * sig) * 0.5) * T) / (sig * sqrt(T));\r\n\tdouble d2 = d1 - (sig * sqrt(T));\r\n\tnormal_distribution<> standard_normal(0.0, 1.0);\r\n\r\n\treturn (K * exp(-r * T) * cdf(standard_normal, -d2)) - (S * exp((b - r) * T) * cdf(standard_normal, -d1));\r\n}\r\n", "meta": {"hexsha": "15840a48ce890eb3aed413b1ba496fe6f1517db5", "size": 2954, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Option.cpp", "max_stars_repo_name": "sudhanshdua/Option_Classes", "max_stars_repo_head_hexsha": "b483d71ac78cd5cdd3c69205eb0ee37bca3ae668", "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": "Option.cpp", "max_issues_repo_name": "sudhanshdua/Option_Classes", "max_issues_repo_head_hexsha": "b483d71ac78cd5cdd3c69205eb0ee37bca3ae668", "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": "Option.cpp", "max_forks_repo_name": "sudhanshdua/Option_Classes", "max_forks_repo_head_hexsha": "b483d71ac78cd5cdd3c69205eb0ee37bca3ae668", "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.7205882353, "max_line_length": 122, "alphanum_fraction": 0.6100203114, "num_tokens": 870, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787536, "lm_q2_score": 0.7826624738835051, "lm_q1q2_score": 0.7048108660300697}}
{"text": "#include <iostream>\n#include <vector>\n#include <fstream>\n#include <string>\n#include <algorithm>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/vector_proxy.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\nusing namespace boost::numeric;\n\ntemplate<class type>\ninline static void rotate(type c, type s, type &r, type &h)\n{\n    type tmp = c * r + s * h;\n    h        = c * h - s * r;\n    r        = tmp;\n}\n\ntemplate<class type>\nint gmres(ublas::vector<type> &y, ublas::matrix<type> &A, ublas::vector<type> &x, type tol, size_t m)\n{\n    using namespace ublas;\n\n    typedef vector<type> Vec;\n    typedef matrix<type> Mat;\n\n    int size = y.size();\n    unit_vector<type> e_1(size + 1, 0);\n\n    m = (m > size) ?size :m;\n\n    // Lower case name for vector\n    Vec x_i(x);\n    Vec r_i = y - prod(A, x);\n    Vec v_i = r_i / norm_2(r_i);\n    Vec e_i = e_1 * norm_2(r_i);\n\n    // Givens rotation args\n    Vec c(m + 1, 0);\n    Vec s(m + 1, 0);\n\n    // Upper case name for matrix, V = V^t, R = Q^t * H\n    Mat V(m, size, 0);\n    Mat R(size + 1, m, 0);\n\n    for(int i = 0; i < size; i++)\n    {\n        type beta = norm_2(r_i);\n        Vec  v_i  = r_i / beta;\n        Vec  e_i  = e_1 * beta;\n\n        int dim = 0;\n        V.clear();\n        for(int j = 0; j < m; j++)\n        {\n            row(V, j) = v_i;\n            v_i       = prod(A, v_i);\n            for(int k = 0; k <= j; k++)\n            {\n                R(k, j) = inner_prod(v_i, row(V, k));\n                v_i    -= R(k, j) * row(V, k);\n            }\n\n            // Re-orthogonalization\n            #pragma omp parallel for\n            for(int k = 0; k <= j; k++)\n            {\n                type tmp   = inner_prod(v_i, row(V, k));\n                row(V, k) -= tmp * v_i;\n            }\n\n            R(j + 1, j) = norm_2(v_i);\n\n            dim++;\n            if(R(j + 1, j) > tol)\n            {\n                v_i /= R(j + 1, j);\n            }\n            else\n            {\n                R(j + 1, j) = (type) 0;\n                v_i.clear();\n                break;\n            }\n        }\n\n        // Apply givens rotation\n        for(int j = 0; j < m; j++)\n        {\n            type r = std::sqrt(R(j, j) * R(j, j) + R(j + 1, j) * R(j + 1, j));\n            if(r > tol)\n            {\n                c(j)   = R(j, j)     / r;\n                s(j)   = R(j + 1, j) / r;\n            }\n            else\n            {\n                c(j) = (type) 1;\n                s(j) = (type) 0;\n            }\n\n            rotate(c(j), s(j), R(j, j), R(j + 1, j));\n            rotate(c(j), s(j), e_i(j), e_i(j + 1));\n        }\n\n        // Solve for y_i\n        Vec y_i(solve(subrange(R, 0, dim, 0, dim), subrange(e_i, 0, dim), upper_tag()));\n\n        // Update x\n        x_i += prod(y_i, subrange(V, 0, dim, 0, size));\n        r_i  = y - prod(A, x_i);\n\n        if(norm_2(r_i) < tol) break;\n    }\n\n    x = x_i;\n    return 0;\n}\n\nint main(int argc, char **argv)\n{\n    std::cout.precision(15);\n\n    int size, nnz;\n    std::string filename;\n    if(argc == 2) filename = argv[1];\n    else filename = \"prob.mtx\";\n\n    std::ifstream prob(filename);\n    if(!prob.is_open()) exit(0);\n    prob >> size;\n    prob >> size >> nnz;\n\n    std::cout << \"Problem size : \" << size << std::endl;\n\n    ublas::vector<double> x(size, 0.0);\n    ublas::vector<double> y(size, 1.0);\n    ublas::matrix<double> A(size, size, 0.0);\n\n    // Set up problem\n    for(int i = 0; i < nnz; i++)\n    {\n        int tmpRow, tmpCol;\n        double tmpVal;\n\n        prob >> tmpRow >> tmpCol >> tmpVal;\n        A(tmpRow - 1, tmpCol - 1) = tmpVal;\n    }\n\n    // GMRES\n    if(gmres(y, A, x, 1e-12, y.size()) != 0)\n    {\n        std::cout << \"GMRES not converged\" << std::endl;\n    }\n    else\n    {\n        double r = norm_2(y - prod(A, x));\n        std::cout << \"r   = \" << r << std::endl;\n        std::cout << \"err = \" << r / norm_2(y) << std::endl;\n    }\n\n    std::cout << x << std::endl;\n\n    return 0;\n}\n\n", "meta": {"hexsha": "5d4ac0c0d4609a945dea2e4ae296014de14b56bc", "size": 4057, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gmres.cpp", "max_stars_repo_name": "nanaHa1003/uBLAS.GMRES", "max_stars_repo_head_hexsha": "d30c71d6122a03c1acfa63c3c2795708126b6d41", "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": "gmres.cpp", "max_issues_repo_name": "nanaHa1003/uBLAS.GMRES", "max_issues_repo_head_hexsha": "d30c71d6122a03c1acfa63c3c2795708126b6d41", "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": "gmres.cpp", "max_forks_repo_name": "nanaHa1003/uBLAS.GMRES", "max_forks_repo_head_hexsha": "d30c71d6122a03c1acfa63c3c2795708126b6d41", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-16T08:03:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-16T08:03:13.000Z", "avg_line_length": 23.7251461988, "max_line_length": 101, "alphanum_fraction": 0.4446635445, "num_tokens": 1298, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380482, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.7047988527471201}}
{"text": "#include <minres.hpp>\n\n#include <armadillo>\n\nbool test_minres()\n{\n    // finite difference helmholtz: -u''(x) - k*u(x) == x^2, u(-1) == u(1) == 0 {k is chosen so the system is indefinite}\n    int n = 20;\n    double k = 2;\n    arma::vec x = arma::linspace(-1, 1, n);\n    double h = x[1] - x[0];\n    arma::vec D2 = {-1.0, 2.0, -1.0};\n    D2 /= h*h;\n    auto L = [&D2,k](const arma::vec& u) -> arma::vec\n    {\n        return arma::conv(u, D2, \"same\") - k*u;\n    };\n    arma::vec f = x%x;\n\n    arma::vec u = arma::zeros(n);\n    double tol = 1e-5;\n    auto rslts = minres(u, L, f, arma::dot<arma::vec,arma::vec>, IdentityPreconditioner{}, n, tol);\n\n    bool success = true;\n    if (arma::norm(L(u) - f) > tol * arma::norm(f)) {\n        std::cout << \"pcg returned bad residual\\n\";\n        success = false;\n    }\n\n    return success;\n}", "meta": {"hexsha": "80bd355a1bf3abff38efb20f080c2ba4bd49ffe2", "size": 828, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/minres.cpp", "max_stars_repo_name": "arotem3/SchrodingerSEM", "max_stars_repo_head_hexsha": "b1d5c5a959efe46cb8d473f284d150c3c7f0beb6", "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": "tests/minres.cpp", "max_issues_repo_name": "arotem3/SchrodingerSEM", "max_issues_repo_head_hexsha": "b1d5c5a959efe46cb8d473f284d150c3c7f0beb6", "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": "tests/minres.cpp", "max_forks_repo_name": "arotem3/SchrodingerSEM", "max_forks_repo_head_hexsha": "b1d5c5a959efe46cb8d473f284d150c3c7f0beb6", "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": 26.7096774194, "max_line_length": 121, "alphanum_fraction": 0.5241545894, "num_tokens": 298, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425399873764, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.704716232303752}}
{"text": "/* adcpp_eigen_forward.test.cpp\n *\n *  Created on: 21 Aug 2019\n *      Author: Fabian Meyer\n */\n\n#include <catch2/catch.hpp>\n#include <adcpp/adcpp_eigen.hpp>\n#include <Eigen/Geometry>\n#include <Eigen/Eigenvalues>\n\nusing namespace adcpp;\n\nTEST_CASE(\"Eigen forward algorithmic differentiation\")\n{\n    double eps = 1e-6;\n\n    SECTION(\"exp\")\n    {\n        fwd::Vector2d x;\n        x << fwd::Double(3,1), fwd::Double(2,0);\n\n        Eigen::Vector2d valExp;\n        valExp <<\n            std::exp(x(0).value()),std::exp(x(1).value());\n        Eigen::Matrix2d jacExp;\n        jacExp << std::exp(x(0).value()), 0,\n            0, std::exp(x(1).value());\n\n        fwd::Vector2d fx = x.array().exp();\n\n        x << fwd::Double(3,0), fwd::Double(2,1);\n        fwd::Vector2d fy = x.array().exp();\n\n        REQUIRE(Approx(valExp(0)).margin(eps) == fx(0).value());\n        REQUIRE(Approx(valExp(1)).margin(eps) == fx(1).value());\n        REQUIRE(Approx(valExp(0)).margin(eps) == fy(0).value());\n        REQUIRE(Approx(valExp(1)).margin(eps) == fy(1).value());\n\n        REQUIRE(Approx(jacExp(0, 0)).margin(eps) == fx(0).derivative());\n        REQUIRE(Approx(jacExp(1, 0)).margin(eps) == fx(1).derivative());\n        REQUIRE(Approx(jacExp(0, 1)).margin(eps) == fy(0).derivative());\n        REQUIRE(Approx(jacExp(1, 1)).margin(eps) == fy(1).derivative());\n    }\n\n    SECTION(\"singular value decomposition\")\n    {\n        fwd::Matrix4d A;\n        A << fwd::Double(2, 1), 3, 11, 5,\n            1, 1, 5, 2,\n            2, 1, -3, 2,\n            1, 1, -3, 4;\n        fwd::Vector4d b;\n        b << 2, 1, -3, -3;\n\n        fwd::Vector4d resultAct;\n        Eigen::Vector4d valExp;\n        Eigen::Vector4d gradExp;\n        valExp << -0.5, -0.1875, 0.4375, -0.25;\n        gradExp << -0.205283, 0.687338, -0.0722404, -0.117474;\n\n        Eigen::JacobiSVD<fwd::Matrix4d, Eigen::FullPivHouseholderQRPreconditioner>\n            solver(A, Eigen::ComputeFullU | Eigen::ComputeFullV);\n        resultAct = solver.solve(b);\n\n        REQUIRE(Approx(valExp(0)).margin(eps) == resultAct(0).value());\n        REQUIRE(Approx(valExp(1)).margin(eps) == resultAct(1).value());\n        REQUIRE(Approx(valExp(2)).margin(eps) == resultAct(2).value());\n        REQUIRE(Approx(valExp(3)).margin(eps) == resultAct(3).value());\n\n        REQUIRE(Approx(gradExp(0)).margin(eps) == resultAct(0).derivative());\n        REQUIRE(Approx(gradExp(1)).margin(eps) == resultAct(1).derivative());\n        REQUIRE(Approx(gradExp(2)).margin(eps) == resultAct(2).derivative());\n        REQUIRE(Approx(gradExp(3)).margin(eps) == resultAct(3).derivative());\n    }\n\n    // SECTION(\"eigen value decomposition\")\n    // {\n    //     fwd::Matrix4d A;\n    //     A << fwd::Double(2, 1), 3, 11, 5,\n    //         1, 1, 5, 2,\n    //         2, 1, -3, 2,\n    //         1, 1, -3, 4;\n    //     fwd::Vector4d b;\n    //     b << 2, 1, -3, -3;\n    //\n    //     Eigen::Vector4d eigvalsExp;\n    //     eigvalsExp << 7.27048, -5.64984, -0.291657, 2.67103;\n    //     Eigen::Vector4d eiggradExp;\n    //     eiggradExp <<  0.536189,  0.463811, 0, 0;\n    //\n    //     Eigen::EigenSolver<fwd::Matrix4d> solver(A);\n    //     fwd::Vector4d eigvals = solver.eigenvalues().real();\n    //     fwd::Matrix4d eigvecs = solver.eigenvectors().real();\n    //\n    //     REQUIRE(Approx(eigvalsExp(0)).margin(eps) == eigvals(0).value());\n    //     REQUIRE(Approx(eigvalsExp(1)).margin(eps) == eigvals(1).value());\n    //     REQUIRE(Approx(eigvalsExp(2)).margin(eps) == eigvals(2).value());\n    //     REQUIRE(Approx(eigvalsExp(3)).margin(eps) == eigvals(3).value());\n    //\n    //     REQUIRE(Approx(eiggradExp(0)).margin(eps) == eigvals(0).derivative());\n    //     REQUIRE(Approx(eiggradExp(1)).margin(eps) == eigvals(1).derivative());\n    //     REQUIRE(Approx(eiggradExp(2)).margin(eps) == eigvals(2).derivative());\n    //     REQUIRE(Approx(eiggradExp(3)).margin(eps) == eigvals(3).derivative());\n    // }\n\n    SECTION(\"multiple outputs\")\n    {\n        fwd::Vector2d x;\n        x << fwd::Double(3,1), fwd::Double(2,0);\n\n        fwd::Matrix2d c;\n        c << fwd::Double(2.1), fwd::Double(3.4),\n            fwd::Double(1.6), fwd::Double(2.3);\n\n        Eigen::Vector2d valExp;\n        valExp <<\n            x(0).value() * c(0, 0).value() +  x(1).value() * c(0, 1).value(),\n            x(0).value() * c(1, 0).value() +  x(1).value() * c(1, 1).value();\n        Eigen::Matrix2d jacExp;\n        jacExp << c(0, 0).value(), c(0, 1).value(),\n            c(1, 0).value(), c(1, 1).value();\n\n        fwd::Vector2d fx = c * x;\n\n        x << fwd::Double(3,0), fwd::Double(2,1);\n        fwd::Vector2d fy = c * x;\n\n        REQUIRE(Approx(valExp(0)).margin(eps) == fx(0).value());\n        REQUIRE(Approx(valExp(1)).margin(eps) == fx(1).value());\n        REQUIRE(Approx(valExp(0)).margin(eps) == fy(0).value());\n        REQUIRE(Approx(valExp(1)).margin(eps) == fy(1).value());\n\n        REQUIRE(Approx(jacExp(0, 0)).margin(eps) == fx(0).derivative());\n        REQUIRE(Approx(jacExp(1, 0)).margin(eps) == fx(1).derivative());\n        REQUIRE(Approx(jacExp(0, 1)).margin(eps) == fy(0).derivative());\n        REQUIRE(Approx(jacExp(1, 1)).margin(eps) == fy(1).derivative());\n    }\n}\n", "meta": {"hexsha": "27ca6caf1f1ed66253aaa1180aab73f8c3028885", "size": 5167, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/src/adcpp_eigen_forward.test.cpp", "max_stars_repo_name": "Rookfighter/algorithmic-differentiation", "max_stars_repo_head_hexsha": "6392ff3c94f8d0e97986f1023a7478786ab76a9a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-10-08T10:31:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-16T21:54:12.000Z", "max_issues_repo_path": "tests/src/adcpp_eigen_forward.test.cpp", "max_issues_repo_name": "Rookfighter/algorithmic-differentiation-cpp", "max_issues_repo_head_hexsha": "6392ff3c94f8d0e97986f1023a7478786ab76a9a", "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/src/adcpp_eigen_forward.test.cpp", "max_forks_repo_name": "Rookfighter/algorithmic-differentiation-cpp", "max_forks_repo_head_hexsha": "6392ff3c94f8d0e97986f1023a7478786ab76a9a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-10-02T04:34:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-16T22:17:54.000Z", "avg_line_length": 36.9071428571, "max_line_length": 82, "alphanum_fraction": 0.5413199148, "num_tokens": 1730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.7047162221776601}}
{"text": "/*\nThis file implements a simple neural network class and wrapppers to access it fom Python. \nWe use the mean square error as loss function and a sigmoid as activation function. \n(We use that, if f is the sigmoid, f' = (1-f)*f.)\nWe assume that\n\t* the number of neurons in the first layer is equal to the number of inputs,\n\t* there is exactly one neuron in the last layer.\n*/\n\n#include <iostream>\n#include <fstream>\n#include <math.h>\n#include <random>\n#include <vector>\n#include <boost/python.hpp>\n\nusing namespace std;\nusing namespace boost::python;\n\ntemplate <typename T>\nvector<T> python_list_to_vector(list& l, T x){ // second argument used for template deduction\n\tvector<T> res;\n\tfor(int i=0; i < len(l); i++){\n\t\tres.push_back(extract<T>(l[i]));\n\t}\n\treturn res;\n}\n\ntemplate <typename T>\nlist vector_to_python_list(vector<T> v){\n\tlist res;\n\tfor(int i=0; i<v.size(); i++){\n\t\tres.append(v[i]);\n\t}\n\treturn res;\n}\n\ntemplate <typename T>\nvector<vector<T>> python_list_of_lists_to_vector(list& l, T x){ // second argument used for template deduction\n\tvector<vector<T>> res;\n\tfor(int i=0; i < len(l); i++){\n\t\tvector<T> line;\n\t\tfor(int j=0; j < len(l[i]); j++){\n\t\t\tline.push_back(extract<T>(l[i][j]));\n\t\t}\n\t\tres.push_back(line);\n\t}\n\treturn res;\n}\n\ndouble sigmoid(double x){\n\treturn (1. / (1. + exp(-x)));\n}\n\nclass NeuralNetwork1{\n\n\tprivate:\n\n\t\tint N_layers;\n\t\tvector<int> layers; \n\t\tvector<vector<vector<double>>> weights;\n\t\tvector<vector<double>> bias;\n\n\tpublic:\n\t\t\n\t\t// constructor with random weights and bias\n\n\t\tvoid build_network(vector<int> layers_){\n\t\t\tN_layers = layers_.size();\n\t\t\tdefault_random_engine generator(time(0));\n\t\t\tnormal_distribution<double> distribution(0.,1.);\n\t\t\tint N_k;\n\t\t\tfor(int i=0; i<N_layers; i++){\n\t\t\t\tlayers.push_back(layers_[i]);\n\t\t\t\tvector<vector<double>> weights_layer;\n\t\t\t\tvector<double> bias_layer;\n\t\t\t\tfor(int j=0; j<layers[i]; j++){\n\t\t\t\t\tvector<double> weights_neuron;\n\t\t\t\t\tif(i > 0){\n\t\t\t\t\t\tN_k = layers[i-1];\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\tN_k = layers[0]; // assume the first layer as as many neurons as there are inputs\n\t\t\t\t\t}\n\t\t\t\t\tfor(int k=0; k<N_k; k++){\n\t\t\t\t\t\tweights_neuron.push_back(distribution(generator));\n\t\t\t\t\t}\n\t\t\t\t\tweights_layer.push_back(weights_neuron);\n\t\t\t\t\tbias_layer.push_back(distribution(generator));\n\t\t\t\t}\n\t\t\t\tweights.push_back(weights_layer);\n\t\t\t\tbias.push_back(bias_layer);\n\t\t\t}\n\t\t}\n\n\t\tNeuralNetwork1(vector<int> layers_){\n\t\t\tbuild_network(layers);\n\t\t}\n\t\t\n\t\t// constructor with random weights and bias - python case\n\t\tNeuralNetwork1(list& layers_l){\n\t\t\tbuild_network(python_list_to_vector(layers_l, 0));\n\t\t}\n\t\t\n\t\t// constructor with given weights and bias\n\t\tNeuralNetwork1(vector<int> layers_, \n\t\t\t          vector<vector<vector<double>>> weights_, \n\t\t              vector<vector<double>> bias_){\n\t\t\tN_layers = layers_.size();\n\t\t\tlayers = layers_;\n\t\t\tweights = weights_;\n\t\t\tbias = bias_;\n\t\t}\n\n\t\t// constructor accepting Python lists instead of vectors\n\t\tNeuralNetwork1(list& layers_, \n\t\t\t          list& weights_, \n\t\t              list& bias_){\n\t\t\tN_layers = len(layers_);\n\t\t\tfor(int i=0; i<N_layers; i++){\n\t\t\t\tlayers.push_back(extract<int>(layers_[i]));\n\t\t\t\tvector<vector<double>> weights_layer;\n\t\t\t\tvector<double> bias_layer;\n\t\t\t\tfor(int j=0; j<layers[i]; j++){\n\t\t\t\t\tvector<double> weights_neuron;\n\t\t\t\t\tfor(int k=0; k<len(weights_[i][j]); k++){\n\t\t\t\t\t\tweights_neuron.push_back(extract<double>(weights_[i][j][k]));\n\t\t\t\t\t}\n\t\t\t\t\tweights_layer.push_back(weights_neuron);\n\t\t\t\t\tbias_layer.push_back(extract<double>(bias_[i][j]));\n\t\t\t\t}\n\t\t\t\tweights.push_back(weights_layer);\n\t\t\t\tbias.push_back(bias_layer);\n\t\t\t}\n\t\t}\n\n\t\tvector<double> feedforward(vector<double> x){\n\t\t\tfor(int i=0; i<N_layers; i++){\n\t\t\t\tvector<double> y;\n\t\t\t\tfor(int j=0; j<layers[i]; j++){\n\t\t\t\t\tdouble z = bias[i][j];\n\t\t\t\t\tfor(int k=0; k<x.size(); k++){\n\t\t\t\t\t\tz += weights[i][j][k]*x[k];\n\t\t\t\t\t}\n\t\t\t\t\ty.push_back(sigmoid(z));\n\t\t\t\t}\n\t\t\t\tx = y;\n\t\t\t}\n\t\t\treturn x;\n\t\t}\n\t\n\t\t// feedforward using a Python list as input\n\t\tlist feedforward_python(list& x){\n\t\t\tvector<double> y = feedforward(python_list_to_vector(x, 0.));\n\t\t\treturn vector_to_python_list(y);\n\t\t}\n\n\t\t// evaluating the loss function\n\t\tdouble loss(vector<vector<double>> data, vector<double> y_true_all){\n\t\t\tdouble res = 0.;\n\t\t\tfor(int i=0; i<y_true_all.size(); i++){\n\t\t\t\tres += pow(feedforward(data[i])[0] - y_true_all[i], 2);\n\t\t\t}\n\t\t\treturn res / y_true_all.size();\n\t\t}\n\t\t\n\t\t// evaluating the loss function - Python\n\t\tdouble loss_python(list& data, list& y_true_all){\n\t\t\treturn loss(python_list_of_lists_to_vector(data ,0.), python_list_to_vector(y_true_all, 0.));\n\t\t}\n\t\t\n\t\t// training function\n\t\tvoid train(vector<vector<double>> data, vector<double> y_true_all, double learn_rate, long epochs){\n\t\t\tfor(long epoch = 0; epoch < epochs; epoch++){\n\t\t\t\tfor(int index_data = 0; index_data < y_true_all.size(); index_data++){\n\t\t\t\t\tvector<double> x = data[index_data];\n\t\t\t\t\tdouble y_true = y_true_all[index_data];\n\t\t\t\t\t\n\t\t\t\t\t// feedforward, retaining the state of each neuron\n\t\t\t\t\tvector<vector<double>> states;\n\t\t\t\t\tstates.push_back(x);\n\t\t\t\t\tfor(int i=0; i<N_layers; i++){\n\t\t\t\t\t\tvector<double> y;\n\t\t\t\t\t\tfor(int j=0; j<layers[i]; j++){\n\t\t\t\t\t\t\tdouble z = bias[i][j];\n\t\t\t\t\t\t\tfor(int k=0; k<x.size(); k++){\n\t\t\t\t\t\t\t\tz += weights[i][j][k]*x[k];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ty.push_back(sigmoid(z));\n\t\t\t\t\t\t}\n\t\t\t\t\t\tstates.push_back(y);\n\t\t\t\t\t\tx = y;\n\t\t\t\t\t}\n\n\t\t\t\t\t//predicted value: state of the last neuron (the last layer is assumed to contain only one neuron)\n\t\t\t\t\tdouble y_pred = states[N_layers][0]; \n\n\t\t\t\t\t// derivative of the loss function with respect to y_pred\n\t\t\t\t\tdouble d_L_d_ypred = 2.*(y_pred - y_true);\n\n\t\t\t\t\t// partial derivatives\n\t\t\t\t\tvector<vector<vector<double>>> d_ypred_d_x;\n\t\t\t\t\tvector<vector<vector<double>>> d_ypred_d_weights;\n\t\t\t\t\tvector<vector<double>> d_ypred_d_bias;\n\n\t\t\t\t\t//partial derivatives - output layer\n\t\t\t\t\tdouble state = states[N_layers][0];\n\t\t\t\t\tvector<vector<double>> d_ypred_d_x_layer;\n\t\t\t\t\tvector<double> d_ypred_d_x_neuron;\n\t\t\t\t\tvector<vector<double>> d_ypred_d_weights_layer;\n\t\t\t\t\tvector<double> d_ypred_d_weights_neuron;\n\t\t\t\t\tvector<double> d_ypred_d_bias_layer;\n\t\t\t\t\tfor(int k=0; k<layers[N_layers-2]; k++){\n\t\t\t\t\t\td_ypred_d_x_neuron.push_back(weights[N_layers-1][0][k]*state*(1.-state));\n\t\t\t\t\t\td_ypred_d_weights_neuron.push_back(states[N_layers-1][k]*state*(1.-state));\n\t\t\t\t\t}\n\t\t\t\t\td_ypred_d_x_layer.push_back(d_ypred_d_x_neuron);\n\t\t\t\t\td_ypred_d_weights_layer.push_back(d_ypred_d_weights_neuron);\n\t\t\t\t\td_ypred_d_bias_layer.push_back(state*(1.-state));\n\n\t\t\t\t\td_ypred_d_x.insert(d_ypred_d_x.begin(), d_ypred_d_x_layer);\n\t\t\t\t\td_ypred_d_weights.insert(d_ypred_d_weights.begin(), d_ypred_d_weights_layer);\n\t\t\t\t\td_ypred_d_bias.insert(d_ypred_d_bias.begin(), d_ypred_d_bias_layer);\n\t\t\t\t\t\n\t\t\t\t\t//partial derivatives - other layers\n\t\t\t\t\tfor(int i=2; i<N_layers+1; i++){\n\t\t\t\t\t\tvector<vector<double>> d_ypred_d_x_layer;\n\t\t\t\t\t\tvector<vector<double>> d_ypred_d_weights_layer;\n\t\t\t\t\t\tvector<double> d_ypred_d_bias_layer;\n\t\t\t\t\t\tfor(int j=0; j<layers[N_layers - i]; j++){\n\t\t\t\t\t\t\tdouble d_ypred_d_yint = 0.;\n\t\t\t\t\t\t\tfor(int k=0; k<layers[N_layers-i+1]; k++){\n\t\t\t\t\t\t\t\td_ypred_d_yint += d_ypred_d_x[0][k][j];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tdouble state = states[N_layers-i+1][j];\n\t\t\t\t\t\t\tvector<double> d_ypred_d_x_neuron;\n\t\t\t\t\t\t\tvector<double> d_ypred_d_weights_neuron;\n\t\t\t\t\t\t\tfor(int k=0; k<weights[N_layers-i][j].size(); k++){\n\t\t\t\t\t\t\t\td_ypred_d_x_neuron.push_back(weights[N_layers-i][j][k]*state*(1.-state)*d_ypred_d_yint);\n\t\t\t\t\t\t\t\td_ypred_d_weights_neuron.push_back(states[N_layers-i][k]*state*(1.-state)*d_ypred_d_yint);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\td_ypred_d_x_layer.push_back(d_ypred_d_x_neuron);\n\t\t\t\t\t\t\td_ypred_d_weights_layer.push_back(d_ypred_d_weights_neuron);\n\t\t\t\t\t\t\td_ypred_d_bias_layer.push_back(state*(1.-state)*d_ypred_d_yint);\n\t\t\t\t\t\t}\n\t\t\t\t\t\td_ypred_d_x.insert(d_ypred_d_x.begin(), d_ypred_d_x_layer);\n\t\t\t\t\t\td_ypred_d_weights.insert(d_ypred_d_weights.begin(), d_ypred_d_weights_layer);\n\t\t\t\t\t\td_ypred_d_bias.insert(d_ypred_d_bias.begin(), d_ypred_d_bias_layer);\n\t\t\t\t\t}\n\n\t\t\t\t\t// update weights and bias\n\t\t\t\t\tfor(int i=0; i<N_layers; i++){\n\t\t\t\t\t\tfor(int j=0; j<layers[i]; j++){\n\t\t\t\t\t\t\tfor(int k=0; k<weights[i][j].size(); k++){\n\t\t\t\t\t\t\t\tweights[i][j][k] -= learn_rate * d_L_d_ypred * d_ypred_d_weights[i][j][k];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbias[i][j] -= learn_rate * d_L_d_ypred * d_ypred_d_bias[i][j];\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t// training function - Python\n\t\tvoid train_python(list& data, list& y_true_all, double learn_rate, long epochs){\n\t\t\ttrain(python_list_of_lists_to_vector(data ,0.), python_list_to_vector(y_true_all, 0.), learn_rate, epochs);\n\t\t}\n\n\t\t// save the neural network to a file\n\t\tvoid save(char* filename){\n\t\t\tofstream file;\n\t\t\tfile.open(filename);\n\t\t\tfile << N_layers << '\\n';\n\t\t\tfor(int i=0; i<N_layers; i++){\n\t\t\t\tfile << layers[i] << '\\t';\n\t\t\t}\n\t\t\tfile << '\\n';\n\t\t\tfor(int i=0; i<N_layers; i++){\n\t\t\t\tfor(int j=0; j<layers[i]; j++){\n\t\t\t\t\tfile << weights[i][j].size() << '\\t';\n\t\t\t\t\tfor(int k=0; k<weights[i][j].size(); k++){\n\t\t\t\t\t\tfile << weights[i][j][k] << '\\t';\n\t\t\t\t\t}\n\t\t\t\t\tfile << bias[i][j] << '\\t';\n\t\t\t\t}\n\t\t\t}\n\t\t\tfile.close();\n\t\t}\n\t\t\n\t\t// load the neural network from a file\n\t\tvoid load(char* filename){\n\t\t\tifstream file;\n\t\t\tfile.open(filename);\n\t\t\tfile >> N_layers;\n\t\t\tlayers.clear();\n\t\t\tlong n_neurons;\n\t\t\tlong n_weights;\n\t\t\tdouble weight_;\n\t\t\tdouble bias_;\n\t\t\tfor(int i=0; i<N_layers; i++){\n\t\t\t\tfile >> n_neurons;\n\t\t\t\tlayers.push_back(n_neurons);\n\t\t\t}\n\t\t\tweights.clear();\n\t\t\tbias.clear();\n\t\t\tfor(int i=0; i<N_layers; i++){\n\t\t\t\tvector<vector<double>> weights_layer;\n\t\t\t\tvector<double> bias_layer;\n\t\t\t\tfor(int j=0; j<layers[i]; j++){\n\t\t\t\t\tvector<double> weights_neuron;\n\t\t\t\t\tfile >> n_weights;\n\t\t\t\t\tfor(int k=0; k<n_weights; k++){\n\t\t\t\t\t\tfile >> weight_;\n\t\t\t\t\t\tweights_neuron.push_back(weight_);\n\t\t\t\t\t}\n\t\t\t\t\tfile >> bias_;\n\t\t\t\t\tbias_layer.push_back(bias_);\n\t\t\t\t\tweights_layer.push_back(weights_neuron);\n\t\t\t\t}\n\t\t\t\tweights.push_back(weights_layer);\n\t\t\t\tbias.push_back(bias_layer);\n\t\t\t}\n\t\t\tfile.close();\n\t\t}\n\n\t\t// implement load\n};\n\n\nBOOST_PYTHON_MODULE(NN1)\n{\n    class_<NeuralNetwork1>(\"NeuralNetwork1\", init<list&>())\n\t\t.def(init<list&, list&, list&>())\n\t\t.def(\"feedforward\", &NeuralNetwork1::feedforward_python)\n\t\t.def(\"loss\", &NeuralNetwork1::loss_python)\n\t\t.def(\"train\", &NeuralNetwork1::train_python)\n\t\t.def(\"save\", &NeuralNetwork1::save)\n\t\t.def(\"load\", &NeuralNetwork1::load)\n\t;\n}\n", "meta": {"hexsha": "2c623dcaedfe6fd71c7e12c3b7beb733fe022ab4", "size": 10258, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "C++/NN1.cpp", "max_stars_repo_name": "FlorentCLMichel/learning_data_science", "max_stars_repo_head_hexsha": "d9ccc0a85609406b2c77a91db96dba8c97fc9ac4", "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": "C++/NN1.cpp", "max_issues_repo_name": "FlorentCLMichel/learning_data_science", "max_issues_repo_head_hexsha": "d9ccc0a85609406b2c77a91db96dba8c97fc9ac4", "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": "C++/NN1.cpp", "max_forks_repo_name": "FlorentCLMichel/learning_data_science", "max_forks_repo_head_hexsha": "d9ccc0a85609406b2c77a91db96dba8c97fc9ac4", "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.082111437, "max_line_length": 110, "alphanum_fraction": 0.6467147592, "num_tokens": 2977, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.7047162221776601}}
{"text": "#pragma once\n/*!\n* \\file GrapheneFloquet.hpp\n*\n* \\brief Functions associated to Floquet Hamiltonian calculations\n*\n* \\author Author: D. Gagnon <denisg6@hotmail.com>\n*/\n// Include some headers\n#include <complex>\n#include <armadillo>\n#include <boost/numeric/odeint.hpp>\n\nusing namespace std::complex_literals; // Complex literals\n\ntypedef std::complex<double> c_state_type; // Type of container used to hold the state vector\ntypedef boost::numeric::odeint::runge_kutta_cash_karp54< c_state_type > error_stepper_type; // Error stepper for odeint\n\n/// Real part of gamma factor appearing in the tight-binding Hamiltonian\ndouble Re_Gamma (double kx, double ky)\n{\n    return 1.0 + 2.0*cos(0.5*sqrt(3.0)*kx)*cos(0.5*3.0*ky);\n}\n\n/// Imaginary part of gamma factor appearing in the tight-binding Hamiltonian\ndouble Im_Gamma (double kx, double ky)\n{\n    return 2.0*cos(0.5*sqrt(3.0)*kx)*sin(0.5*3.0*ky);\n}\n\n/*!\n* \\class gamma_integrand\n*\n* \\brief Base class for the integrand used in gamma factor calculations\n*\n* \\author Author: D. Gagnon <denisg6@hotmail.com>\n*/\nclass gamma_integrand {\n\n    // Parameters of the Hamiltonian\n    double m_kx,m_ky,m_omega,m_E0,m_index;\n\nprivate:\n\n    // Physical constants definitions\n    double hbar = 6.5821195140e-16;                             // Planck constant over 2 pi in eV s\n    double lat_constant = 2.4e-10/sqrt(3.0);                    // Lattice constant in meters\n    double v_Fermi = 0.003646*2.9979245800e+08;                 // Fermi velocity in graphene\n\npublic:\n\n    /// Constructor taking as input the parameters of the Hamiltonian\n    /// @param kx float, x-component of the momentum\n    /// @param ky float, y-component of the momentum\n    /// @param omega float, angular frequency of the field in rad/s\n    /// @param E0 float, electric field peak value in V/m\n    /// @param index int, index of Fourier coefficients\n    gamma_integrand(double kx, double ky, double omega, double E0, int index)\n        : m_kx(kx)\n        , m_ky(ky)\n        , m_omega(omega)\n        , m_E0(E0)\n        , m_index(index) { }\n\n    /// Overload of operator() for ODE integration\n    void operator() ( const c_state_type &z, c_state_type &dzdt, const double t)\n    {\n\n        // Conversion factor\n        double factor = lat_constant*m_E0/(hbar*m_omega);\n\n        // Peierls substitution\n        double kx_field = m_kx + factor*std::cos(t);\n        double ky_field = m_ky;\n\n        // Compute gamma factors\n        double Re_Gamma_t = Re_Gamma(kx_field, ky_field);\n        double Im_Gamma_t = Im_Gamma(kx_field, ky_field);\n\n        // Rhs of the ODE system\n        dzdt = (Re_Gamma_t + 1i*Im_Gamma_t)*std::exp(-1i*m_index*t);\n\n    }\n\n    /// Function updating the value of the index\n    void SetIndex(int m)\n    {\n        this->m_index = m;\n    }\n\n};\n\n/// Function returning the Fourier coefficients to be used in Floquet Hamiltonian\nstd::vector< c_state_type > GammaValues(double kx, double ky, double omega, double E0, int max_index)\n{\n    std::vector< c_state_type > Gamma(2*max_index + 1, 0.0);\n\n    for (int vec_index = 0; vec_index < 2*max_index + 1; vec_index ++)\n    {\n\n        // State variable to solve result\n        c_state_type z(0.0,0.0);\n\n        // Define integrand\n        gamma_integrand integrand(kx,ky,omega,E0, vec_index - max_index);\n\n        // Adaptive integration\n        boost::numeric::odeint::integrate_adaptive(\n            boost::numeric::odeint::make_controlled< error_stepper_type >( 1.0e-10, 1.0e-6 ),\n            integrand,\n            z, 0.0, 2.0*M_PI, 2.0*M_PI/10000.0 );\n\n        // Assign value to \"Gamma\" vector\n        Gamma[vec_index] = (0.5/M_PI)*z;\n\n    }\n\n    return Gamma;\n}\n\n/// Compute Floquet eigen-energies and probabilities\narma::vec QuasiEnergies(double kx, double ky, double omega, double E0,\n                        int blocks, double &prob, double &prob_sigma)\n{\n\n    // Physical constants definitions\n    double hbar = 6.5821195140e-16;                             // Planck constant over 2 pi in eV s\n    double lat_constant = 2.4e-10/sqrt(3.0);                    // Lattice constant in meters\n    double v_Fermi = 0.003646*2.9979245800e+08;                 // Fermi velocity in graphene\n\n    double freq = hbar*omega;                        // Frequency in eV\n    double tb = - 2*(hbar*v_Fermi)/(3.0*lat_constant); // Tight-binding energy of graphene\n\n    // Total number of blocks including\n    // zeroth block\n    int totalblocks = 2*blocks + 1;\n\n    // Pre-calculate Fourier coefficients of Hamiltonian\n    auto Gamma = GammaValues(kx,ky,omega,E0,2*blocks);\n\n    // Initialize Tmatrix which is to be filled by [totalblocks] 2 x 2 matrices\n    arma::Mat<double> zeromat(2*totalblocks,2*totalblocks, arma::fill::zeros);\n    arma::cx_mat Ham(zeromat,zeromat); // Hamiltonian\n\n    // FILL MAIN DIAGONAL OF HAMILTONIAN\n    // Initialize index m\n    int m = -blocks;\n\n    for (int j_= 0; j_ < 2*totalblocks; j_ = j_ + 2)\n    {\n        Ham.diag(0)[j_] = m*freq;\n        Ham.diag(0)[j_ + 1] = m*freq;\n\n        // Increment m\n        m++;\n    }\n\n    // FILL UPPER AND LOWER DIAGONAL OF HAMILTONIAN\n\n    int nm = 0; // Initialize index (n-m)\n    int index_shift = 2*blocks; // Index shift (for gamma vector)\n\n    for (int i_= 1; i_ < 2*totalblocks; i_ = i_ + 2) // Loop on diagonals\n    {\n        int index0 = nm;\n        int index1 = nm + 1;\n\n        //std::cout << i_ << std::endl;\n\n        for (int j_ = 0; j_ < 2*totalblocks - i_; j_ ++) // Loop on elements of diagonals\n        {\n\n            //std::cout << j_ << std::endl;\n\n            if (j_ % 2 == 0) // If j_ is even do\n            {\n                Ham.diag( i_)[j_] = tb*std::conj(Gamma[-index0 + index_shift]);\n                Ham.diag(-i_)[j_] = tb*Gamma[index0 + index_shift];\n\n                //std::cout << \"Even j\" << std::endl;\n                //std::cout << Ham.diag( i_)[j_] << std::endl;\n                //std::cout << Ham.diag( -i_)[j_] << std::endl;\n\n            }\n            else // If j_ is odd do\n            {\n                Ham.diag( i_)[j_] = tb*Gamma[-index1 + index_shift];\n                Ham.diag(-i_)[j_] = tb*std::conj(Gamma[index1 + index_shift]);\n\n                //std::cout << \"Odd j\" << std::endl;\n                //std::cout << Ham.diag( i_)[j_] << std::endl;\n                //std::cout << Ham.diag( -i_)[j_] << std::endl;\n            }\n        }\n\n        nm++; // Increment (n-m) as we shift to the next non-zero diagonal\n\n    }\n\n    // std::cout << Ham << std::endl;\n\n    // arma::mat realpart = arma::real(Ham);\n    // arma::mat imagpart = arma::imag(Ham);\n\n    // realpart.save(\"Hamreal.dat\",arma::raw_ascii);\n    // imagpart.save(\"Hamimag.dat\",arma::raw_ascii);\n\n    // Initialize eigenvalue vector and eigenvector matrix and\n    arma::vec eigval;\n    arma::cx_mat eigvec;\n\n    // Compute eigenvalues\n    bool status = arma::eig_sym(eigval, eigvec, Ham);\n    if (status == false)\n    {\n        std::cout << \"Eigenvalue decomposition failed\" << std::endl;\n    }\n\n    // std::cout << eigvec << std::endl;\n\n    // COMPUTE TRANSITION PROBABILITY\n\n    // Variables to be used in loop\n    prob = 0.0;\n    prob_sigma = 0.0; // Passed by reference, will change\n    std::complex<double> alphazero, betazero; // Ground state amplitude\n    std::complex<double> alphan, betan; // Excited state amplitude\n    std::complex<double> pos; // Positive energy state amplitude\n    std::complex<double> neg; // Negative energy state amplitude\n    arma::cx_vec the_eigenvec;\n\n    // Compute \"no-field\" phase factor\n    double angle = std::atan2(Im_Gamma(kx,ky), Re_Gamma(kx,ky) );\n    std::complex<double> phase_factor = std::exp(1i*angle);\n\n    // Loop on every eigenvector\n    for (size_t i_= 0; i_ < eigvec.n_cols; i_ ++)\n    {\n        the_eigenvec = eigvec.col(i_); // Slice eigenvectors\n\n        alphazero = the_eigenvec[the_eigenvec.n_elem/2 - 1];\n        betazero = the_eigenvec[the_eigenvec.n_elem/2];\n\n        // Negative energy state\n        neg = 0.5*std::sqrt(2.0)*(alphazero - phase_factor*betazero);\n\n        // Loop on elements\n        for (size_t j_= 0; j_ < the_eigenvec.n_elem; j_ ++)\n        {\n\n            if (j_ % 2 != 0) // If j is odd do, else do nothing\n            {\n                alphan = the_eigenvec[j_ - 1];\n                betan  = the_eigenvec[j_];\n\n                // Positive energy state\n                pos = 0.5*std::sqrt(2.0)*(alphan + phase_factor*betan);\n\n                // Fermi's rule\n                prob += std::norm(std::conj(pos)*neg); // Transition between eigenstates\n                prob_sigma += std::norm(std::conj(betan)*alphazero); // Transition between sigma_z eigenstates\n            }\n        }\n    }\n\n\n    return eigval;\n\n\n\n}\n", "meta": {"hexsha": "444c04d86d248c67d806c35c38d9c19f19ccefce", "size": 8641, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/GrapheneFloquet.hpp", "max_stars_repo_name": "DenGagn/phdm", "max_stars_repo_head_hexsha": "1412cd8730806f08d80e5faa00d854b95559207d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-24T02:07:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-24T02:07:41.000Z", "max_issues_repo_path": "include/GrapheneFloquet.hpp", "max_issues_repo_name": "DenGagn/phdm", "max_issues_repo_head_hexsha": "1412cd8730806f08d80e5faa00d854b95559207d", "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": "include/GrapheneFloquet.hpp", "max_forks_repo_name": "DenGagn/phdm", "max_forks_repo_head_hexsha": "1412cd8730806f08d80e5faa00d854b95559207d", "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.7683823529, "max_line_length": 119, "alphanum_fraction": 0.5975002893, "num_tokens": 2500, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308147331957, "lm_q2_score": 0.7549149758396752, "lm_q1q2_score": 0.7046609009523187}}
{"text": "#include <iostream>\n#include <vector>\n#include <Eigen/Dense>\n#include \"../simple_lib/include/simple_activation.h\"\n\nusing namespace Eigen;\n\ndouble cross_entropy_error(MatrixXd &, MatrixXd &); // \u30d7\u30ed\u30c8\u30bf\u30a4\u30d7\u5ba3\u8a00\n\nclass simpleNet\n{\nprivate:\n    MatrixXd W = MatrixXd::Random(2, 3); // \u4e71\u6570\u3067\u521d\u671f\u5316(\u672c\u6765\u306fXavier\u306e\u521d\u671f\u5024\u3068\u304b\u306b\u3057\u305f\u3044\uff1f)\n\npublic:\n    simpleNet(); // \u30b3\u30f3\u30b9\u30c8\u30e9\u30af\u30bf\n    MatrixXd predict(MatrixXd &);\n    double loss(MatrixXd &, MatrixXd &);\n    MatrixXd gradient(MatrixXd&, MatrixXd&);\n\n    void print_W(void);\n};\n\n\nint main(){\n    using std::cout;\n    using std::endl;\n    \n    simpleNet net;\n    net.print_W();\n\n    MatrixXd X = MatrixXd::Zero(2, 1);\n    MatrixXd P;\n\n    X << 0.6, 0.9;\n\n    P = net.predict(X);\n    cout << \"--- predict result ---\" << endl;\n    cout << P << endl;\n    cout << \"--- softmax ---\" << endl;\n    cout << MyDL::softmax(P) << endl;\n\n    MatrixXd t = MatrixXd::Zero(1, 3);\n    t << 0, 0, 1; // \u3053\u306e\u66f8\u304d\u65b9\u3092\u3059\u308b\u306b\u306f\u3001\u4e0a\u8a18\u306e\u3088\u3046\u306b\u30e1\u30e2\u30ea\u78ba\u4fdd\u3092\u3057\u3066\u304a\u304f\u5fc5\u8981\u304c\u3042\u308b(\u3067\u306a\u3044\u3068\u30bb\u30b0\u30d5\u30a9\u306b\u306a\u308b)\n\n    double loss;\n    loss = net.loss(X, t);\n\n    cout << \"--- loss ---\" << endl;\n    cout << loss << endl;\n\n    MatrixXd dW = MatrixXd::Zero(2, 3);\n\n    dW = net.gradient(X, t);\n\n    cout << \"--- dW ---\" << endl;\n    cout << dW << endl; // 0.2, 0.2, -0.4; 0.3, 0.3, -0.6 (W\u3092\u3059\u3079\u30661\u3067\u521d\u671f\u5316\u3057\u305f\u5834\u5408)\u304c\u6b63\u89e3\n\n    return 0;\n}\n\nsimpleNet::simpleNet(){\n    // W << 0.47355232, 0.9977393, 0.84668094, 0.85557411, 0.03563661, 0.69422093;\n    W << 1,1,1,1,1,1;\n}\n\nMatrixXd simpleNet::predict(MatrixXd& X){\n    return X.transpose() * W;\n}\n\ndouble simpleNet::loss(MatrixXd& X, MatrixXd& t){\n    MatrixXd Y, Z;\n    Z = simpleNet::predict(X);\n    Y = MyDL::softmax(Z);\n\n    double loss;\n    loss = cross_entropy_error(Y, t);\n\n    return loss;\n}\n\nvoid simpleNet::print_W(void){\n    using std::cout;\n    using std::endl;\n\n    cout << \" --- simpleNet parameter W --- \" << endl;\n    cout << \"W = \" << W << endl;\n}\n\nMatrixXd simpleNet::gradient(MatrixXd& x, MatrixXd& t)\n{\n    double h = 1e-4;\n    MatrixXd grad = MatrixXd::Zero(2, 3);\n\n    for (int i = 0; i < 6; i++)\n    {\n        double tmp_val = W(i);\n        double f_xh1;\n        double f_xh2;\n        // f(x+h) \u306e\u8a08\u7b97\n        W(i) = tmp_val + h; // \u5909\u6570x\u306ei\u756a\u76ee\u306e\u8981\u7d20\u3060\u3051\u5897\u5206\u3092\u53d6\u3063\u305f\u5f62\u306b\u5909\u66f4\n        f_xh1 = simpleNet::loss(x, t);\n        // f(x-h)\u306e\u8a08\u7b97\n        W(i) = tmp_val - h;\n        f_xh2 = simpleNet::loss(x, t);\n\n        grad(i) = (f_xh1 - f_xh2) / (2 * h);\n        W(i) = tmp_val; // \u5143\u306e\u5024\u306b\u623b\u3059\n    }\n\n    return grad;\n}\n\n// one-hot label\u30d0\u30fc\u30b8\u30e7\u30f3\u306e \u306e\u30df\u30cb\u30d0\u30c3\u30c1\u5b9f\u88c5\ndouble cross_entropy_error(MatrixXd &y, MatrixXd &t)\n{\n    int batch_size = y.rows();\n    double ret = (t.array() * y.array().log()).sum() / batch_size;\n    return -ret;\n}\n", "meta": {"hexsha": "707c1c3bef8543a09c7881fcbf60e7cdaeec5021", "size": 2575, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch4/simpleNet.cpp", "max_stars_repo_name": "potedo/zeroDL_cpp", "max_stars_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-22T15:26:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-22T15:26:20.000Z", "max_issues_repo_path": "ch4/simpleNet.cpp", "max_issues_repo_name": "potedo/zeroDL_cpp", "max_issues_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "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/simpleNet.cpp", "max_forks_repo_name": "potedo/zeroDL_cpp", "max_forks_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "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.2809917355, "max_line_length": 82, "alphanum_fraction": 0.5646601942, "num_tokens": 944, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554444, "lm_q2_score": 0.7956580976404296, "lm_q1q2_score": 0.7046598584722614}}
{"text": "#include <cmath>\n#include <unordered_map>\n#include <vector>\n#include <string>\n#include <armadillo>\n#include <algorithm>\n\nusing std::vector;\nusing arma::dmat;\n\n\n\n\n// input peakDays check: they cant be on day 0 or _dOI by definition (debugging)\nbool PeakCheck(const int peak, const int dOI) { \n\tif ((peak<=0)||(peak>=dOI)) return 1;\n\telse return 0;\n}\n\n// Finds the closest boundary between end and beginning of illnes and\n// peak day \nint MinDist(const int dOI, const int peakDay) { return std::min(peakDay, dOI-peakDay); }\n\n// Finds the gaussian integral between -inf and x\ndouble CumGauss(const double& x) {\n    double PAYLOAD;\n    PAYLOAD = 0.5*(erf(10) + erf(x));\n    return PAYLOAD;\n}\n\n\n// Cretes a square matrix of zeros setting the first row equal to the\n// vector<double> given as argument (broadcast).\n// NB: it converts std::vectors tu arma::dmat-s\ndmat CastVecMat(const vector<double>& vec) {\n\t// we need to make vec a row vector first\n\tarma::drowvec temp(vec);\n\t\n\t// building the payload\n\tint size = temp.n_elem;\n\tdmat PAYLOAD(temp);\n\tPAYLOAD.resize(size, size);\n\t\n\t// initializing setting to zero the zero elements\n\tPAYLOAD(1,0,arma::size(size-1,size)) = arma::zeros(size-1,size);\n\treturn PAYLOAD;\n}\n\n\n// Very specific function, build the propagation matrix of a status change\n// given its discrete cumulative function. \ndmat BuildDistribMat(vector<double> vec) {\n\t\n\t// calculate the distribution from a cumulative\n\tfor (int i= vec.size()-1; i!=0; i--) vec[i] -= vec[i-1];\n\t\n\t// insert a zero at the beginning (as the model requires it)\n\tvec.insert(vec.begin(),0);\n\t\n\t// now add the zeroes underneath to make it a matrix\n\tdmat PAYLOAD(CastVecMat(vec));\n\t\n\treturn PAYLOAD;\n}\n\n\t\n\n// Computes the discrete cumulative probability function of a status change given \n// its parameters\nvector<double> CumProbFunc(const int dOI, const int peakDay, const double finalProb,const std::string type) {\n\n\t// Dictionary {1 = Gaussian, 2 = Uniform}\n\tstd::unordered_map<std::string, int> Map;\n\t\tMap[\"Gaussian\"] = 1;\n\t\tMap[\"Uniform\"] = 2;\n\t\n\tvector<double> PAYLOAD(dOI);\n\t\n    // switch depending on what type the distribution is\n\tswitch(Map[type]) {\n                case 1: {\n\t\t\t\t\t\t// we assume that the distance between end/beginning of illness and\n\t\t\t\t\t\t// the peak day of a status change is 5 sigma\n                        double sigma = static_cast<double>(MinDist(dOI, peakDay))/5;\n                        // filling the gaussian cumulative\n                        for (int i=0; i<dOI; i++)\n                            PAYLOAD[i] = finalProb*CumGauss((i-peakDay+1)/sqrt(2)/sigma);\n                        break;\n                }\n                case 2: {\n\t\t\t\t\t\t// slope\n                        double distrValue = 1./static_cast<double>(dOI)*finalProb;\n                        // filling the uniform cumulative\n\t\t\t\t\t\tfor (int i=0; i<dOI; i++)\n\t\t\t\t\t\t\tPAYLOAD[i] = distrValue*static_cast<double>(i+1);\n                        break;\n                }\n\t};\t\n\t\n\treturn PAYLOAD;\n}\n\n\n\n\n\n\n\t\n", "meta": {"hexsha": "73f4f9b7c5a0e75c241bbc312c67a7705905d692", "size": 2983, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Core/utils.cpp", "max_stars_repo_name": "PizzaGitHub/Plague", "max_stars_repo_head_hexsha": "60d742512127564f6aedea29f1bfa4835261f046", "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": "Core/utils.cpp", "max_issues_repo_name": "PizzaGitHub/Plague", "max_issues_repo_head_hexsha": "60d742512127564f6aedea29f1bfa4835261f046", "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": "Core/utils.cpp", "max_forks_repo_name": "PizzaGitHub/Plague", "max_forks_repo_head_hexsha": "60d742512127564f6aedea29f1bfa4835261f046", "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": 27.3669724771, "max_line_length": 109, "alphanum_fraction": 0.6349312772, "num_tokens": 766, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037282594921, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.7045935304520052}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n\nusing namespace std;\nusing namespace Eigen;\n\nint main()\n{\n   MatrixXd A = MatrixXd::Random(100,100);\n   MatrixXd b = MatrixXd::Random(100,50);\n   MatrixXd x = A.fullPivLu().solve(b);\n   double relative_error = (A*x - b).norm() / b.norm(); // norm() is L2 norm\n   cout << \"The relative error is:\\n\" << relative_error << endl;\n}\n", "meta": {"hexsha": "f362fb71a62b1055a3fd89def1bf657058cec0b9", "size": 371, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Eigen-3.3/doc/examples/TutorialLinAlgExComputeSolveError.cpp", "max_stars_repo_name": "shareq2005/CarND-MPC-Project", "max_stars_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3457.0, "max_stars_repo_stars_event_min_datetime": "2018-06-09T15:36:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-01T22:09:25.000Z", "max_issues_repo_path": "src/Eigen-3.3/doc/examples/TutorialLinAlgExComputeSolveError.cpp", "max_issues_repo_name": "shareq2005/CarND-MPC-Project", "max_issues_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 851.0, "max_issues_repo_issues_event_min_datetime": "2017-11-27T15:09:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:26:38.000Z", "max_forks_repo_path": "src/Eigen-3.3/doc/examples/TutorialLinAlgExComputeSolveError.cpp", "max_forks_repo_name": "shareq2005/CarND-MPC-Project", "max_forks_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1380.0, "max_forks_repo_forks_event_min_datetime": "2017-06-12T23:58:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:52:48.000Z", "avg_line_length": 24.7333333333, "max_line_length": 76, "alphanum_fraction": 0.6522911051, "num_tokens": 107, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9263037302939516, "lm_q2_score": 0.7606506418255928, "lm_q1q2_score": 0.7045935269735352}}
{"text": "// smooth: Lie Theory for Robotics\n// https://github.com/pettni/smooth\n//\n// Licensed under the MIT License <http://opensource.org/licenses/MIT>.\n//\n// Copyright (c) 2021 Petter Nilsson\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#ifndef SMOOTH__SE3_HPP_\n#define SMOOTH__SE3_HPP_\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include <complex>\n\n#include \"internal/lie_group_base.hpp\"\n#include \"internal/macro.hpp\"\n#include \"internal/se3.hpp\"\n#include \"lie_group.hpp\"\n#include \"map.hpp\"\n#include \"so3.hpp\"\n\nnamespace smooth {\n\ntemplate<typename Scalar>\nclass SE2;\n\n/**\n * @brief Base class for SE3 Lie group types.\n *\n * Internally represented as \\f$\\mathbb{S}^3 \\times \\mathbb{R}^3\\f$.\n *\n * Memory layout\n * -------------\n *\n * - Group:    \\f$ \\mathbf{x} = [x, y, z, q_x, q_y, q_z, q_w] \\f$\n * - Tangent:  \\f$ \\mathbf{a} = [v_x, v_y, v_z, \\omega_x, \\omega_y, \\omega_z] \\f$\n *\n * Constraints\n * -----------\n *\n * - Group:   \\f$q_x^2 + q_y^2 + q_z^2 + q_w^2 = 1 \\f$\n * - Tangent: \\f$ -\\pi < \\omega_x, \\omega_y, \\omega_z \\leq \\pi \\f$\n *\n * Lie group matrix form\n * ---------------------\n *\n * \\f[\n * \\mathbf{X} =\n * \\begin{bmatrix}\n *   R & T \\\\\n *   0 & 1\n * \\end{bmatrix} \\in \\mathbb{R}^{4 \\times 4}\n * \\f]\n *\n * where \\f$R\\f$ is a 3x3 rotation matrix and \\f$ T = [x, y, z]^T \\f$.\n *\n *\n * Lie algebra matrix form\n * -----------------------\n *\n * \\f[\n * \\mathbf{a}^\\wedge =\n * \\begin{bmatrix}\n *   0        & -\\omega_z & \\omega_y  & v_x \\\\\n *  \\omega_z  & 0         & -\\omega_x & v_y \\\\\n *  -\\omega_y & \\omega_x  & 0         & v_y \\\\\n *  0         & 0         & 0         & 0\n * \\end{bmatrix} \\in \\mathbb{R}^{4 \\times 4}\n * \\f]\n */\ntemplate<typename _Derived>\nclass SE3Base : public LieGroupBase<_Derived>\n{\n  using Base = LieGroupBase<_Derived>;\n\nprotected:\n  SE3Base() = default;\n\npublic:\n  SMOOTH_INHERIT_TYPEDEFS;\n\n  /**\n   * @brief Access SO(3) part.\n   */\n  Map<SO3<Scalar>> so3() requires is_mutable\n  {\n    return Map<SO3<Scalar>>(static_cast<_Derived &>(*this).data() + 3);\n  }\n\n  /**\n   * @brief Const access SO(3) part.\n   */\n  Map<const SO3<Scalar>> so3() const\n  {\n    return Map<const SO3<Scalar>>(static_cast<const _Derived &>(*this).data() + 3);\n  }\n\n  /**\n   * @brief Access R3 part.\n   */\n  Eigen::Map<Eigen::Vector3<Scalar>> r3() requires is_mutable\n  {\n    return Eigen::Map<Eigen::Vector3<Scalar>>(static_cast<_Derived &>(*this).data());\n  }\n\n  /**\n   * @brief Const access R3 part.\n   */\n  Eigen::Map<const Eigen::Vector3<Scalar>> r3() const\n  {\n    return Eigen::Map<const Eigen::Vector3<Scalar>>(static_cast<const _Derived &>(*this).data());\n  }\n\n  /**\n   * @brief Return as 3D Eigen transform.\n   */\n  Eigen::Transform<Scalar, 3, Eigen::Isometry> isometry() const\n  {\n    return Eigen::Translation<Scalar, 3>(r3()) * so3().quat();\n  }\n\n  /**\n   * @brief Tranformation action on 3D vector.\n   */\n  template<typename EigenDerived>\n  Eigen::Vector3<Scalar> operator*(const Eigen::MatrixBase<EigenDerived> & v) const\n  {\n    return so3() * v + r3();\n  }\n\n  /**\n   * @brief Project to SE2.\n   *\n   * @note SE2 header must be included.\n   */\n  SE2<Scalar> project_se2() const\n  {\n    return SE2<Scalar>(so3().project_so2(), r3().template head<2>());\n  }\n};\n\n// \\cond\ntemplate<typename _Scalar>\nclass SE3;\n// \\endcond\n\n// \\cond\ntemplate<typename _Scalar>\nstruct liebase_info<SE3<_Scalar>>\n{\n  static constexpr bool is_mutable = true;\n\n  using Impl   = SE3Impl<_Scalar>;\n  using Scalar = _Scalar;\n\n  template<typename NewScalar>\n  using PlainObject = SE3<NewScalar>;\n};\n// \\endcond\n\n/**\n * @brief Storage implementation of SE3 Lie group.\n *\n * @see SE3Base for memory layout.\n */\ntemplate<typename _Scalar>\nclass SE3 : public SE3Base<SE3<_Scalar>>\n{\n  using Base = SE3Base<SE3<_Scalar>>;\n\n  SMOOTH_GROUP_API(SE3);\n\npublic:\n  /**\n   * @brief Construct from SO3 and translation.\n   *\n   * @param so3 orientation component.\n   * @param r3 translation component.\n   */\n  template<typename SO3Derived, typename T3Derived>\n  SE3(const SO3Base<SO3Derived> & so3, const Eigen::MatrixBase<T3Derived> & r3)\n  {\n    Base::so3() = static_cast<const SO3Derived &>(so3);\n    Base::r3()  = static_cast<const T3Derived &>(r3);\n  }\n\n  /**\n   * @brief Construct from Eigen transform.\n   */\n  SE3(const Eigen::Transform<Scalar, 3, Eigen::Isometry> & t)\n  {\n    Base::so3() = smooth::SO3<Scalar>(Eigen::Quaternion<Scalar>(t.rotation()));\n    Base::r3()  = t.translation();\n  }\n};\n\n// \\cond\ntemplate<typename _Scalar>\nstruct liebase_info<Map<SE3<_Scalar>>> : public liebase_info<SE3<_Scalar>>\n{};\n// \\endcond\n\n/**\n * @brief Memory mapping of SE3 Lie group.\n *\n * @see SE3Base for memory layout.\n */\ntemplate<typename _Scalar>\nclass Map<SE3<_Scalar>> : public SE3Base<Map<SE3<_Scalar>>>\n{\n  using Base = SE3Base<Map<SE3<_Scalar>>>;\n\n  SMOOTH_MAP_API();\n};\n\n// \\cond\ntemplate<typename _Scalar>\nstruct liebase_info<Map<const SE3<_Scalar>>> : public liebase_info<SE3<_Scalar>>\n{\n  static constexpr bool is_mutable = false;\n};\n// \\endcond\n\n/**\n * @brief Const memory mapping of SE3 Lie group.\n *\n * @see SE3Base for memory layout.\n */\ntemplate<typename _Scalar>\nclass Map<const SE3<_Scalar>> : public SE3Base<Map<const SE3<_Scalar>>>\n{\n  using Base = SE3Base<Map<const SE3<_Scalar>>>;\n\n  SMOOTH_CONST_MAP_API();\n};\n\nusing SE3f = SE3<float>;   ///< SE3 with float\nusing SE3d = SE3<double>;  ///< SE3 with double\n\n}  // namespace smooth\n\n#endif  // SMOOTH__SE3_HPP_\n", "meta": {"hexsha": "4a598b428ce6c7ec7f73a42408e31b62128096b6", "size": 6392, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/smooth/se3.hpp", "max_stars_repo_name": "tgurriet/smooth", "max_stars_repo_head_hexsha": "c19e35e23c8e0084314726729d0cf6729192240f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2021-07-06T21:05:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T13:26:44.000Z", "max_issues_repo_path": "include/smooth/se3.hpp", "max_issues_repo_name": "tgurriet/smooth", "max_issues_repo_head_hexsha": "c19e35e23c8e0084314726729d0cf6729192240f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23.0, "max_issues_repo_issues_event_min_datetime": "2021-07-07T21:13:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T04:40:37.000Z", "max_forks_repo_path": "include/smooth/se3.hpp", "max_forks_repo_name": "tgurriet/smooth", "max_forks_repo_head_hexsha": "c19e35e23c8e0084314726729d0cf6729192240f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2021-07-09T07:16:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-12T14:29:44.000Z", "avg_line_length": 24.3969465649, "max_line_length": 97, "alphanum_fraction": 0.6475281602, "num_tokens": 1873, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941962904956, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.7045630599473262}}
{"text": "/*\nAuthor: Rohan Chetan Thanki\nDate created: 16-Oct-2021\n*/\n\n// This file contains the 'main' function. Program execution begins and ends there.\n\n#include \"Hedging_Portfolio.hpp\"\n#include \"Utilities.cpp\"\n#include <iostream>\n#include <string>\n#include <vector>\n#include <iterator>\n#include<boost/tokenizer.hpp>\n#include <boost/date_time.hpp>\n#include<boost/tokenizer.hpp>\n#include <boost/date_time.hpp>\n\n/*********************************************** PART 1 ******************************************************/\ninline void run_part_1(void)\n{\n    cout << \"\\nStart of part 1\\n\";\n    // creating variables\n    unsigned int numPaths = 1000;\n    unsigned int N = 100;\n    double T = 0.4;\n    double u = 0.05;\n    double sigma = 0.24;\n    double r = 0.025;\n    double S0 = 100;\n    double K = 105;\n    char optionFlag = 'c';\n\n    vector<vector<double>> stockPrices = simulateStockPrices(numPaths, N, S0, T, u, sigma);\n    vector<vector<Hedging_Portfolio>> hedgedPortfolioAllStates = computeHedgingErrors(stockPrices, K, r, T, sigma, 'c');\n\n    vector<vector<double>> callOptionPrices = getHedgedPortfolioParam(hedgedPortfolioAllStates, \"V\");\n    vector<vector<double>> deltas = getHedgedPortfolioParam(hedgedPortfolioAllStates, \"DELTA\");\n    vector<vector<double>> B = getHedgedPortfolioParam(hedgedPortfolioAllStates, \"B\");\n    vector<vector<double>> hedgingErrors = getHedgedPortfolioParam(hedgedPortfolioAllStates, \"HE\");\n\n    write2DVectorToCSV(stockPrices, \"Output_Files/Part1/Stock_Prices.csv\");\n    write2DVectorToCSV(callOptionPrices, \"Output_Files/Part1/Call_Option_Prices.csv\");\n    write2DVectorToCSV(deltas, \"Output_Files/Part1/Call_Option_Deltas.csv\");\n    write2DVectorToCSV(B, \"Output_Files/Part1/B.csv\");\n    write2DVectorToCSV(hedgingErrors, \"Output_Files/Part1/Hedging_Errors.csv\");\n\n    cout << \"End of part 1\\n\\n\";\n}\n\n/*********************************************** PART 2 ******************************************************/\ninline void run_part_2(void)\n{\n    // reading interest rate data\n    vector<vector<string>> interestRateData = readCSV(\"Data/interest.csv\", 1, 2);\n    //vector<boost::gregorian::date> interestRateDateVec = stringtoDateVect(interestRateData[0]);\n    vector<string> interestRateDateVec = interestRateData[0];\n    vector<double> interestRateVec = stringToDoubleVect(interestRateData[1]);\n\n    // reading stock data\n    vector<vector<string>> stockData = readCSV(\"Data/sec_GOOG.csv\", 1, 2);\n    //vector<boost::gregorian::date> stockDateVec = stringtoDateVect(stockData[0]);\n    vector<string> stockDateVec = stockData[0];\n    vector<double> stockPriceVec = stringToDoubleVect(stockData[1]);\n\n    // reading option data\n    //vector<vector<string>> optionData = readCSV(\"Data/op_GOOG.csv\", 1, 6);\n    string optionFilePath = \"Data/op_GOOG.csv\";\n    ifstream infile(optionFilePath);\n    string line;\n    vector<vector<string>> csvData;\n\n    // get user input\n    string startDateUser, endDateUser, expDateUser;\n    char optionFlagUser;\n    double strikePriceUser;\n\n    /*startDateUser = \"2011-07-05\";\n    endDateUser = \"2011-07-29\";\n    expDateUser = \"2011-09-17\";\n    optionFlagUser = 'c';\n    strikePriceUser = 500;*/\n\n    std::cout << \"Enter start date in YYYY-MM-DD format: \"; cin >> startDateUser;\n    std::cout << \"Enter end date in YYYY-MM-DD format: \"; cin >> endDateUser;\n    std::cout << \"Enter maturity date in YYYY-MM-DD format: \"; cin >> expDateUser;\n    std::cout << \"Enter option Flag: \"; cin >> optionFlagUser;\n    std::cout << \"Enter strike price of the option: \"; cin >> strikePriceUser;\n\n    // Read options data line by line\n    getline(infile, line);                              // skipping the first line\n    vector<Hedging_Portfolio> allHedgingPortfolios;     // creating a vector to store the hedging portfolio at each date\n    while (getline(infile, line))\n    {\n        // tokenising the row data\n        vector<string> rowData = string_splitter(line, ',');\n\n        // reading data in each row\n        string date = rowData[0];\n        string expDate = rowData[1];\n        char flag = toupper(rowData[2][0]);\n        double strikePrice = stod(rowData[3]);\n        double bidPrice = stod(rowData[4]);\n        double askPrice = stod(rowData[5]);\n        double marketPrice = (bidPrice + askPrice) / 2;\n\n        // skipping the loop if the details donot match user input\n        if (!(strikePrice == strikePriceUser && expDate == expDateUser && flag == toupper(optionFlagUser) && date >= startDateUser && date <= endDateUser))\n            continue;\n\n        // creating a hedging portfolio object\n        Hedging_Portfolio rowobj;\n\n        //setting values in the object\n        rowobj.setDate(date);                               // setting date\n        rowobj.setExpDate(rowData[1]);                      // setting expiration date\n        rowobj.setFlag(rowData[2][0]);                      // setting flag of the option\n        rowobj.setStrikePrice(stod(rowData[3]));            // setting strike price\n        rowobj.setOptionPrice(marketPrice);                 // setting market price        \n\n        // setting the interest rate\n        try\n        {\n            double rate = findVal(interestRateDateVec, interestRateVec, rowobj.getDate()) / 100;\n            rowobj.setRiskFreeRate(rate);\n        }\n        catch (...)\n        {\n            std::cout << \"No interest rate found for date \" << rowobj.getDate() << endl;\n        }\n\n        // setting the stock price\n        try\n        {\n            double spotPrice = findVal(stockDateVec, stockPriceVec, rowobj.getDate());\n            rowobj.setSpotPrice(spotPrice);\n        }\n        catch (...)\n        {\n            std::cout << \"No interest rate found for date \" << rowobj.getDate() << endl;\n        }\n\n        // setting time to maturity\n        rowobj.setTimeToMaturity(countWeekDays(rowobj.getDate(), rowobj.getDate()) * 1.0 / 252);\n\n        // setting implied volatility\n        double maxVol = 100;\n        double impliedVol = rowobj.computeImpliedVol(maxVol);\n        rowobj.setVolatility(impliedVol);\n        //cout << date << \"\\t\" << expDate << \"\\t\" << flag << \"\\t\" << strikePrice << \"\\t\" << rowobj.getRiskFreeRate() << \"\\t\" << rowobj.getSpotPrice() << \"\\t\" << impliedVol << endl;\n\n        // setting delta\n        double delta = rowobj.computeDelta();\n        rowobj.setDelta(delta);\n\n        // add the object to the vector\n        allHedgingPortfolios.push_back(rowobj);\n    }\n    infile.close();\n\n    // creating a filestream object to write to a csv file\n    string outputFilePath = \"Output_Files/Part2/Real_Market_Data_Hedging.csv\";\n    vector<string> outputFileHeaders{ \"Date\", \"Stock Price\", \"Option Price\", \"Implied Volatility\", \"Option Delta\", \"Hedging Error\", \"PNL Naked Short Call\", \"PNL Hedged Portfolio\" };\n    std::ofstream outfile(outputFilePath);\n    for (int i = 0; i <= outputFileHeaders.size() - 1; i++)\n        outfile << outputFileHeaders[i] << \",\";\n    outfile << \"\\n\";\n\n    // iterating through the vector to compute hedging errors\n    for (int j = 0; j <= allHedgingPortfolios.size() - 1; j++)\n    {\n        // creating variables\n        double S = allHedgingPortfolios[j].getSpotPrice();\n        double TMat = allHedgingPortfolios[j].getTimeToMaturity();\n        double delta = allHedgingPortfolios[j].getDelta();\n        double V = allHedgingPortfolios[j].getOptionPrice();\n        double dt = 1.0 / 252;\n        double deltaPrev, BPrev, rPrev, B, HE;\n\n        // setting B\n        if (j == 0)\n            B = V - delta * S;\n        else\n        {\n            rPrev = allHedgingPortfolios[j - 1].getRiskFreeRate();\n            deltaPrev = allHedgingPortfolios[j - 1].getDelta();\n            BPrev = allHedgingPortfolios[j - 1].getB();\n            B = ((deltaPrev - delta) * S) + BPrev * exp(rPrev * dt);\n        }\n        allHedgingPortfolios[j].setB(B);\n\n        // setting Hedging Error\n        if (j == 0)\n            HE = 0;\n        else\n            HE = deltaPrev * S + BPrev * exp(rPrev * dt) - V;\n\n        allHedgingPortfolios[j].setHedgingError(HE);\n\n        // Setting PNL for naked short call\n        double pnlNaked =  allHedgingPortfolios[0].getOptionPrice() - allHedgingPortfolios[j].getOptionPrice();\n        allHedgingPortfolios[j].setpnlNaked(pnlNaked);\n\n        // Setting PNL for hedged portfolio\n        double pnlHedged = HE;\n        allHedgingPortfolios[j].setpnlHedged(pnlHedged);\n\n        // writing to output file\n        outfile << allHedgingPortfolios[j].getDate() << \",\";\n        outfile << allHedgingPortfolios[j].getSpotPrice() << \",\";\n        outfile << allHedgingPortfolios[j].getOptionPrice() << \",\";\n        outfile << allHedgingPortfolios[j].getVolatility() << \",\";\n        outfile << allHedgingPortfolios[j].getDelta() << \",\";\n        outfile << allHedgingPortfolios[j].getHedgingError() << \",\";\n        outfile << allHedgingPortfolios[j].getpnlNaked() << \",\";\n        outfile << allHedgingPortfolios[j].getpnlHedged() << endl;\n    }\n\n    outfile.close();\n    cout << \"\\nEnd of part 2\\n\";\n}", "meta": {"hexsha": "f5a202a2d5e708b1557bcb0c27b2570ca9951899", "size": 8992, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Sys_Comp_Midterm_Project/Sys_Comp_Midterm_Project/Project_Parts.cpp", "max_stars_repo_name": "rohanthanki/delta_hedging", "max_stars_repo_head_hexsha": "f1c2b8e9965ccea594466e6a32e1c8f82036763e", "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": "Sys_Comp_Midterm_Project/Sys_Comp_Midterm_Project/Project_Parts.cpp", "max_issues_repo_name": "rohanthanki/delta_hedging", "max_issues_repo_head_hexsha": "f1c2b8e9965ccea594466e6a32e1c8f82036763e", "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": "Sys_Comp_Midterm_Project/Sys_Comp_Midterm_Project/Project_Parts.cpp", "max_forks_repo_name": "rohanthanki/delta_hedging", "max_forks_repo_head_hexsha": "f1c2b8e9965ccea594466e6a32e1c8f82036763e", "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": 40.6877828054, "max_line_length": 181, "alphanum_fraction": 0.6175489324, "num_tokens": 2296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382236515259, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7043716638374287}}
{"text": "//\n// OpenTissue, A toolbox for physical based simulation and animation.\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\n//\n#include <OpenTissue/configuration.h>\n\n#include <OpenTissue/core/math/math_random.h>\n#include <OpenTissue/core/math/big/big_types.h>\n#include <OpenTissue/core/math/big/big_moore_penrose_pseudoinverse.h>\n#include <OpenTissue/core/math/big/big_generate_random.h>\n\n\n#define BOOST_AUTO_TEST_MAIN\n#include <OpenTissue/utility/utility_push_boost_filter.h>\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n#include <OpenTissue/utility/utility_pop_boost_filter.h>\n\n\n\ntemplate<typename matrix_type,typename vector_type>\nvoid test(matrix_type const & A, vector_type  & x, vector_type const & b, vector_type const & y)\n{\n  using std::min;\n  using std::max;\n\n  typedef typename matrix_type::value_type real_type;\n  typedef typename matrix_type::size_type  size_type;\n\n  real_type const tol = boost::numeric_cast<real_type>(0.01);\n\n  matrix_type invA;  \n  OpenTissue::math::big::svd_moore_penrose_pseudoinverse(A,invA);\n  {\n    ublas::noalias(x) = ublas::prod( invA, b);\n    vector_type tst;\n    tst.resize( b.size(), false);\n    ublas::noalias(tst) = ublas::prod( A, x);\n    for(size_type i = 0; i < b.size(); ++i)\n      BOOST_CHECK_CLOSE( real_type( tst(i) ), real_type( b(i) ), tol );\n  }\n\n  OpenTissue::math::big::lu_moore_penrose_pseudoinverse(A,invA);\n  {\n    ublas::noalias(x) = ublas::prod( invA, b);\n    vector_type tst;\n    tst.resize( b.size(), false);\n    ublas::noalias(tst) = ublas::prod( A, x);\n    for(size_type i = 0; i < b.size(); ++i)\n      BOOST_CHECK_CLOSE( real_type( tst(i) ), real_type( b(i) ), tol );\n  }\n}\n\nBOOST_AUTO_TEST_SUITE(opentissue_math_big_svd);\n\n\nBOOST_AUTO_TEST_CASE(logic_and_valid_arguments_testing)\n{\n  typedef ublas::compressed_matrix<double> matrix_type;\n  typedef ublas::vector<double>            vector_type;\n  typedef vector_type::size_type           size_type;\n\n  {\n    matrix_type A;\n    matrix_type invA;\n    BOOST_CHECK_THROW( OpenTissue::math::big::lu_moore_penrose_pseudoinverse(A, invA), std::invalid_argument );\n    BOOST_CHECK_THROW( OpenTissue::math::big::svd_moore_penrose_pseudoinverse(A, invA), std::invalid_argument );\n  }\n}\n\nBOOST_AUTO_TEST_CASE(random_test_case)\n{\n\n  typedef ublas::compressed_matrix<double> matrix_type;\n  typedef ublas::vector<double>            vector_type;\n  typedef vector_type::size_type           size_type;\n\n  for(size_type tst=0;tst<10;++tst)\n  {\n\n    size_t M = 10;\n    size_t N = 5;\n\n    matrix_type A;\n    vector_type x;\n    vector_type b;\n    vector_type y;\n\n    // square system\n    OpenTissue::math::big::generate_random( M, M, A); // A may not be invertibel\n    OpenTissue::math::big::generate_random( M, x);\n    b.resize(M,false);\n    y.resize(M,false);\n    ublas::noalias(b) = ublas::prod(A,x);\n    y.assign(x);\n    x.clear();\n    test(A,x,b,y);\n\n    // more rows than columns\n    OpenTissue::math::big::generate_random( M, N, A);  // A must have full column rank\n    OpenTissue::math::big::generate_random( N, x);\n    b.resize(M,false);\n    y.resize(N,false);\n    ublas::noalias(b) = ublas::prod(A,x);\n    y.assign(x);\n    x.clear();\n    test(A,x,b,y);\n\n    // more columns than rows\n    OpenTissue::math::big::generate_random( N, M, A);  // A must have full row rank\n    OpenTissue::math::big::generate_random( M, x);\n    b.resize(N,false);\n    y.resize(M,false);\n    ublas::noalias(b) = ublas::prod(A,x);\n    y.assign(x);\n    x.clear();\n    test(A,x,b,y);\n  }\n\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "3a446f5a75f548203e6bacb4f32e85b71fdb321d", "size": 3657, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/core/math/big/pseudoinverse/src/unit_pseudoinverse.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:45:06.000Z", "max_issues_repo_path": "unit_tests/core/math/big/pseudoinverse/src/unit_pseudoinverse.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-20T14:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T15:26:45.000Z", "max_forks_repo_path": "unit_tests/core/math/big/pseudoinverse/src/unit_pseudoinverse.cpp", "max_forks_repo_name": "ricortiz/OpenTissue", "max_forks_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T01:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:06:49.000Z", "avg_line_length": 29.256, "max_line_length": 112, "alphanum_fraction": 0.6874487285, "num_tokens": 1019, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278788223265, "lm_q2_score": 0.7981867849406659, "lm_q1q2_score": 0.7043422715392043}}
{"text": "/* \n * Copyright (c) 1990 Michael E. Hohmeyer, \n *       hohmeyer@icemcfd.com\n * Permission is granted to modify and re-distribute this code in any manner\n * as long as this notice is preserved.  All standard disclaimers apply.\n * \n * R. Seidel's algorithm for solving LPs (linear programs.)\n */\n\n/* \n * Copyright (c) 2021 Zhepei Wang,\n *       wangzhepei@live.com\n * 1. Bug fix in \"move_to_front\" function that \"prev[m]\" is illegally accessed\n *    while \"prev\" originally has only m ints. It is fixed by allocating a \n *    \"prev\" with m + 1 ints.  \n * 2. Add Eigen interface.\n * 3. Resursive template.\n * Permission is granted to modify and re-distribute this code in any manner\n * as long as this notice is preserved.  All standard disclaimers apply.\n * \n * Ref: Seidel, R. (1991), \"Small-dimensional linear programming and convex \n *      hulls made easy\", Discrete & Computational Geometry 6 (1): 423\u2013434, \n *      doi:10.1007/BF02574699\n */\n\n#ifndef SDLP_HPP\n#define SDLP_HPP\n\n#include <Eigen/Eigen>\n#include <cmath>\n#include <random>\n\nnamespace sdlp\n{\n    constexpr double eps = 1.0e-12;\n\n    enum\n    {\n        /* minimum attained */\n        MINIMUM = 0,\n        /* no feasible region */\n        INFEASIBLE,\n        /* unbounded solution */\n        UNBOUNDED,\n        /* only a vertex in the solution set */\n        AMBIGUOUS,\n    };\n\n    inline double dot2(const double a[2],\n                       const double b[2])\n    {\n        return a[0] * b[0] + a[1] * b[1];\n    }\n\n    inline double cross2(const double a[2],\n                         const double b[2])\n    {\n        return a[0] * b[1] - a[1] * b[0];\n    }\n\n    inline bool unit2(const double a[2],\n                      double b[2])\n    {\n        const double mag = std::sqrt(a[0] * a[0] +\n                                     a[1] * a[1]);\n        if (mag < 2.0 * eps)\n        {\n            return true;\n        }\n        b[0] = a[0] / mag;\n        b[1] = a[1] / mag;\n        return false;\n    }\n\n    /* unitize a d + 1 dimensional point */\n    template <int d>\n    inline bool unit(double *a)\n    {\n        double mag = 0.0;\n        for (int i = 0; i <= d; i++)\n        {\n            mag += a[i] * a[i];\n        }\n        if (mag < (d + 1) * eps * eps)\n        {\n            return true;\n        }\n        mag = 1.0 / std::sqrt(mag);\n        for (int i = 0; i <= d; i++)\n        {\n            a[i] *= mag;\n        }\n        return false;\n    }\n\n    /* optimize the unconstrained objective */\n    template <int d>\n    inline int lp_no_con(const double *n_vec,\n                         const double *d_vec,\n                         double *opt)\n    {\n        double n_dot_d = 0.0;\n        double d_dot_d = 0.0;\n        for (int i = 0; i <= d; i++)\n        {\n            n_dot_d += n_vec[i] * d_vec[i];\n            d_dot_d += d_vec[i] * d_vec[i];\n        }\n        if (d_dot_d < eps * eps)\n        {\n            n_dot_d = 0.0;\n            d_dot_d = 1.0;\n        }\n        for (int i = 0; i <= d; i++)\n        {\n            opt[i] = -n_vec[i] +\n                     d_vec[i] * n_dot_d / d_dot_d;\n        }\n        /* normalize the optimal point */\n        if (unit<d>(opt))\n        {\n            opt[d] = 1.0;\n            return AMBIGUOUS;\n        }\n        else\n        {\n            return MINIMUM;\n        }\n    }\n\n    /* returns the plane index that is in i's place */\n    inline int move_to_front(const int i,\n                             int *next,\n                             int *prev)\n    {\n        if (i == 0 || i == next[0])\n        {\n            return i;\n        }\n        const int previ = prev[i];\n        /* remove i from it's current position */\n        next[prev[i]] = next[i];\n        prev[next[i]] = prev[i];\n        /* put i at the front */\n        next[i] = next[0];\n        prev[i] = 0;\n        prev[next[i]] = i;\n        next[0] = i;\n        return previ;\n    }\n\n    inline void lp_min_lin_rat(const bool degen,\n                               const double cw_vec[2],\n                               const double ccw_vec[2],\n                               const double n_vec[2],\n                               const double d_vec[2],\n                               double opt[2])\n    {\n        /* linear rational function case */\n        const double d_cw = dot2(cw_vec, d_vec);\n        const double d_ccw = dot2(ccw_vec, d_vec);\n        const double n_cw = dot2(cw_vec, n_vec);\n        const double n_ccw = dot2(ccw_vec, n_vec);\n        if (degen)\n        {\n            /* if degenerate simply compare values */\n            if (n_cw / d_cw < n_ccw / d_ccw)\n            {\n                opt[0] = cw_vec[0];\n                opt[1] = cw_vec[1];\n            }\n            else\n            {\n                opt[0] = ccw_vec[0];\n                opt[1] = ccw_vec[1];\n            }\n            /* check CW/CCW bounds are not near a poles */\n        }\n        else if (std::fabs(d_cw) > 2.0 * eps &&\n                 std::fabs(d_ccw) > 2.0 * eps)\n        {\n            /* the valid region does not contain a poles */\n            if (d_cw * d_ccw > 0.0)\n            {\n                /* find which end has the minimum value */\n                if (n_cw / d_cw < n_ccw / d_ccw)\n                {\n                    opt[0] = cw_vec[0];\n                    opt[1] = cw_vec[1];\n                }\n                else\n                {\n                    opt[0] = ccw_vec[0];\n                    opt[1] = ccw_vec[1];\n                }\n            }\n            else\n            {\n                /* the valid region does contain a poles */\n                if (d_cw > 0.0)\n                {\n                    opt[0] = -d_vec[1];\n                    opt[1] = d_vec[0];\n                }\n                else\n                {\n                    opt[0] = d_vec[1];\n                    opt[1] = -d_vec[0];\n                }\n            }\n        }\n        else if (std::fabs(d_cw) > 2.0 * eps)\n        {\n            /* CCW bound is near a pole */\n            if (n_ccw * d_cw > 0.0)\n            {\n                /* CCW bound is a positive pole */\n                opt[0] = cw_vec[0];\n                opt[1] = cw_vec[1];\n            }\n            else\n            {\n                /* CCW bound is a negative pole */\n                opt[0] = ccw_vec[0];\n                opt[1] = ccw_vec[1];\n            }\n        }\n        else if (std::fabs(d_ccw) > 2.0 * eps)\n        {\n            /* CW bound is near a pole */\n            if (n_cw * d_ccw > 2.0 * eps)\n            {\n                /* CW bound is at a positive pole */\n                opt[0] = ccw_vec[0];\n                opt[1] = ccw_vec[1];\n            }\n            else\n            {\n                /* CW bound is at a negative pole */\n                opt[0] = cw_vec[0];\n                opt[1] = cw_vec[1];\n            }\n        }\n        else\n        {\n            /* both bounds are near poles */\n            if (cross2(d_vec, n_vec) > 0.0)\n            {\n                opt[0] = cw_vec[0];\n                opt[1] = cw_vec[1];\n            }\n            else\n            {\n                opt[0] = ccw_vec[0];\n                opt[1] = ccw_vec[1];\n            }\n        }\n    }\n\n    inline int wedge(const double (*halves)[2],\n                     const int m,\n                     int *next,\n                     int *prev,\n                     double cw_vec[2],\n                     double ccw_vec[2],\n                     bool *degen)\n    {\n        int i;\n        double d_cw, d_ccw;\n        bool offensive;\n\n        *degen = false;\n        for (i = 0; i != m; i = next[i])\n        {\n            if (!unit2(halves[i], ccw_vec))\n            {\n                /* CW */\n                cw_vec[0] = ccw_vec[1];\n                cw_vec[1] = -ccw_vec[0];\n                /* CCW */\n                ccw_vec[0] = -cw_vec[0];\n                ccw_vec[1] = -cw_vec[1];\n                break;\n            }\n        }\n        if (i == m)\n        {\n            return UNBOUNDED;\n        }\n        i = 0;\n        while (i != m)\n        {\n            offensive = false;\n            d_cw = dot2(cw_vec, halves[i]);\n            d_ccw = dot2(ccw_vec, halves[i]);\n            if (d_ccw >= 2.0 * eps)\n            {\n                if (d_cw <= -2.0 * eps)\n                {\n                    cw_vec[0] = halves[i][1];\n                    cw_vec[1] = -halves[i][0];\n                    unit2(cw_vec, cw_vec);\n                    offensive = true;\n                }\n            }\n            else if (d_cw >= 2.0 * eps)\n            {\n                if (d_ccw <= -2.0 * eps)\n                {\n                    ccw_vec[0] = -halves[i][1];\n                    ccw_vec[1] = halves[i][0];\n                    unit2(ccw_vec, ccw_vec);\n                    offensive = true;\n                }\n            }\n            else if (d_ccw <= -2.0 * eps &&\n                     d_cw <= -2.0 * eps)\n            {\n                return INFEASIBLE;\n            }\n            else if (d_cw <= -2.0 * eps ||\n                     d_ccw <= -2.0 * eps ||\n                     cross2(cw_vec, halves[i]) < 0.0)\n            {\n                /* degenerate */\n                if (d_cw <= -2.0 * eps)\n                {\n                    unit2(ccw_vec, cw_vec);\n                }\n                else if (d_ccw <= -2.0 * eps)\n                {\n                    unit2(cw_vec, ccw_vec);\n                }\n                *degen = true;\n                offensive = true;\n            }\n            /* place this offensive plane in second place */\n            if (offensive)\n            {\n                i = move_to_front(i, next, prev);\n            }\n            i = next[i];\n            if (*degen)\n            {\n                break;\n            }\n        }\n        if (*degen)\n        {\n            while (i != m)\n            {\n                d_cw = dot2(cw_vec, halves[i]);\n                d_ccw = dot2(ccw_vec, halves[i]);\n                if (d_cw < -2.0 * eps)\n                {\n                    if (d_ccw < -2.0 * eps)\n                    {\n                        return INFEASIBLE;\n                    }\n                    else\n                    {\n                        cw_vec[0] = ccw_vec[0];\n                        cw_vec[1] = ccw_vec[1];\n                    }\n                }\n                else if (d_ccw < -2.0 * eps)\n                {\n                    ccw_vec[0] = cw_vec[0];\n                    ccw_vec[1] = cw_vec[1];\n                }\n                i = next[i];\n            }\n        }\n        return MINIMUM;\n    }\n\n    /* return the minimum on the projective line */\n    inline int lp_base_case(const double (*halves)[2], /* halves --- half lines */\n                            const int m,               /* m      --- terminal marker */\n                            const double n_vec[2],     /* n_vec  --- numerator funciton */\n                            const double d_vec[2],     /* d_vec  --- denominator function */\n                            double opt[2],             /* opt    --- optimum  */\n                            int *next,                 /* next, prev  --- double linked list of indices */\n                            int *prev)\n    {\n        double cw_vec[2], ccw_vec[2];\n        bool degen;\n        int status;\n\n        /* find the feasible region of the line */\n        status = wedge(halves, m, next, prev, cw_vec, ccw_vec, &degen);\n\n        if (status == INFEASIBLE)\n        {\n            return status;\n        }\n        /* no non-trivial constraints one the plane: return the unconstrained optimum */\n        if (status == UNBOUNDED)\n        {\n            return lp_no_con<1>(n_vec, d_vec, opt);\n        }\n\n        if (std::fabs(cross2(n_vec, d_vec)) < 2.0 * eps * eps)\n        {\n            if (dot2(n_vec, n_vec) < 2.0 * eps * eps ||\n                dot2(d_vec, d_vec) > 2.0 * eps * eps)\n            {\n                /* numerator is zero or numerator and denominator are linearly dependent */\n                opt[0] = cw_vec[0];\n                opt[1] = cw_vec[1];\n                status = AMBIGUOUS;\n            }\n            else\n            {\n                /* numerator is non-zero and denominator is zero minimize linear functional on circle */\n                if (!degen &&\n                    cross2(cw_vec, n_vec) <= 0.0 &&\n                    cross2(n_vec, ccw_vec) <= 0.0)\n                {\n                    /* optimum is in interior of feasible region */\n                    opt[0] = -n_vec[0];\n                    opt[1] = -n_vec[1];\n                }\n                else if (dot2(n_vec, cw_vec) > dot2(n_vec, ccw_vec))\n                {\n                    /* optimum is at CCW boundary */\n                    opt[0] = ccw_vec[0];\n                    opt[1] = ccw_vec[1];\n                }\n                else\n                {\n                    /* optimum is at CW boundary */\n                    opt[0] = cw_vec[0];\n                    opt[1] = cw_vec[1];\n                }\n                status = MINIMUM;\n            }\n        }\n        else\n        {\n            /* niether numerator nor denominator is zero */\n            lp_min_lin_rat(degen, cw_vec, ccw_vec, n_vec, d_vec, opt);\n            status = MINIMUM;\n        }\n        return status;\n    }\n\n    /* find the largest coefficient in a plane */\n    template <int d>\n    inline void findimax(const double *pln,\n                         int *imax)\n    {\n        *imax = 0;\n        double rmax = std::fabs(pln[0]);\n        for (int i = 1; i <= d; i++)\n        {\n            const double ab = std::fabs(pln[i]);\n            if (ab > rmax)\n            {\n                *imax = i;\n                rmax = ab;\n            }\n        }\n    }\n\n    template <int d>\n    inline void vector_up(const double *equation,\n                          const int ivar,\n                          const double *low_vector,\n                          double *vector)\n    {\n        vector[ivar] = 0.0;\n        for (int i = 0; i <= d; i++)\n        {\n            if (i != ivar)\n            {\n                const int j = i < ivar ? i : i - 1;\n                vector[i] = low_vector[j];\n                vector[ivar] -= equation[i] * low_vector[j];\n            }\n        }\n        vector[ivar] /= equation[ivar];\n    }\n\n    template <int d>\n    inline void vector_down(const double *elim_eqn,\n                            const int ivar,\n                            const double *old_vec,\n                            double *new_vec)\n    {\n        double ve = 0.0;\n        double ee = 0.0;\n        for (int i = 0; i <= d; i++)\n        {\n            ve += old_vec[i] * elim_eqn[i];\n            ee += elim_eqn[i] * elim_eqn[i];\n        }\n        const double fac = ve / ee;\n        for (int i = 0; i <= d; i++)\n        {\n            if (i != ivar)\n            {\n                new_vec[i < ivar ? i : i - 1] =\n                    old_vec[i] - elim_eqn[i] * fac;\n            }\n        }\n    }\n\n    template <int d>\n    inline void plane_down(const double *elim_eqn,\n                           const int ivar,\n                           const double *old_plane,\n                           double *new_plane)\n    {\n        const double crit = old_plane[ivar] / elim_eqn[ivar];\n        for (int i = 0; i <= d; i++)\n        {\n            if (i != ivar)\n            {\n                new_plane[i < ivar ? i : i - 1] =\n                    old_plane[i] - elim_eqn[i] * crit;\n            }\n        }\n    }\n\n    template <int d>\n    inline int linfracprog(const double *halves, /* halves  --- half spaces */\n                           const int max_size,   /* max_size --- size of halves array */\n                           const int m,          /* m       --- terminal marker */\n                           const double *n_vec,  /* n_vec   --- numerator vector */\n                           const double *d_vec,  /* d_vec   --- denominator vector */\n                           double *opt,          /* opt     --- optimum */\n                           double *work,         /* work    --- work space (see below) */\n                           int *next,            /* next    --- array of indices into halves */\n                           int *prev)            /* prev    --- array of indices into halves */\n    /*\n    **\n    ** half-spaces are in the form\n    ** halves[i][0]*x[0] + halves[i][1]*x[1] + \n    ** ... + halves[i][d-1]*x[d-1] + halves[i][d]*x[d] >= 0\n    **\n    ** coefficients should be normalized\n    ** half-spaces should be in random order\n    ** the order of the half spaces is 0, next[0] next[next[0]] ...\n    ** and prev[next[i]] = i\n    **\n    ** halves: (max_size)x(d+1)\n    **\n    ** the optimum has been computed for the half spaces\n    ** 0 , next[0], next[next[0]] , ... , prev[0]\n    ** the next plane that needs to be tested is 0\n    **\n    ** m is the index of the first plane that is NOT on the list\n    ** i.e. m is the terminal marker for the linked list.\n    **\n    ** the objective function is dot(x,nvec)/dot(x,dvec)\n    ** if you want the program to solve standard d dimensional linear programming\n    ** problems then n_vec = ( x0, x1, x2, ..., xd-1, 0)\n    ** and           d_vec = (  0,  0,  0, ...,    0, 1)\n    ** and halves[0] = (0, 0, ... , 1)\n    **\n    ** work points to (max_size+3)*(d+2)*(d-1)/2 double space\n    */\n    {\n        int status, imax;\n        double *new_opt, *new_n_vec, *new_d_vec, *new_halves, *new_work;\n        const double *plane_i;\n\n        double val = 0.0;\n        for (int j = 0; j <= d; j++)\n        {\n            val += d_vec[j] * d_vec[j];\n        }\n        const bool d_vec_zero = (val < (d + 1) * eps * eps);\n\n        /* find the unconstrained minimum */\n        status = lp_no_con<d>(n_vec, d_vec, opt);\n        if (m <= 0)\n        {\n            return status;\n        }\n\n        /* allocate memory for next level of recursion */\n        new_opt = work;\n        new_n_vec = new_opt + d;\n        new_d_vec = new_n_vec + d;\n        new_halves = new_d_vec + d;\n        new_work = new_halves + max_size * d;\n        for (int i = 0; i != m; i = next[i])\n        {\n            /* if the optimum is not in half space i then project the problem onto that plane */\n            plane_i = halves + i * (d + 1);\n            /* determine if the optimum is on the correct side of plane_i */\n            val = 0.0;\n            for (int j = 0; j <= d; j++)\n            {\n                val += opt[j] * plane_i[j];\n            }\n            if (val < -(d + 1) * eps)\n            {\n                /* find the largest of the coefficients to eliminate */\n                findimax<d>(plane_i, &imax);\n                /* eliminate that variable */\n                if (i != 0)\n                {\n                    const double fac = 1.0 / plane_i[imax];\n                    for (int j = 0; j != i; j = next[j])\n                    {\n                        const double *old_plane = halves + j * (d + 1);\n                        const double crit = old_plane[imax] * fac;\n                        double *new_plane = new_halves + j * d;\n                        for (int k = 0; k <= d; k++)\n                        {\n                            const int l = k < imax ? k : k - 1;\n                            new_plane[l] = k != imax ? old_plane[k] - plane_i[k] * crit : new_plane[l];\n                        }\n                    }\n                }\n                /* project the objective function to lower dimension */\n                if (d_vec_zero)\n                {\n                    vector_down<d>(plane_i, imax, n_vec, new_n_vec);\n                    for (int j = 0; j < d; j++)\n                    {\n                        new_d_vec[j] = 0.0;\n                    }\n                }\n                else\n                {\n                    plane_down<d>(plane_i, imax, n_vec, new_n_vec);\n                    plane_down<d>(plane_i, imax, d_vec, new_d_vec);\n                }\n                /* solve sub problem */\n                status = linfracprog<d - 1>(new_halves, max_size, i, new_n_vec,\n                                            new_d_vec, new_opt, new_work, next, prev);\n                /* back substitution */\n                if (status != INFEASIBLE)\n                {\n                    vector_up<d>(plane_i, imax, new_opt, opt);\n\n                    /* inline code for unit */\n                    double mag = 0.0;\n                    for (int j = 0; j <= d; j++)\n                    {\n                        mag += opt[j] * opt[j];\n                    }\n                    mag = 1.0 / sqrt(mag);\n                    for (int j = 0; j <= d; j++)\n                    {\n                        opt[j] *= mag;\n                    }\n                }\n                else\n                {\n                    return status;\n                }\n                /* place this offensive plane in second place */\n                i = move_to_front(i, next, prev);\n            }\n        }\n        return status;\n    }\n\n    template <>\n    inline int linfracprog<1>(const double *halves,\n                              const int max_size,\n                              const int m,\n                              const double *n_vec,\n                              const double *d_vec,\n                              double *opt,\n                              double *work,\n                              int *next,\n                              int *prev)\n    {\n        if (m > 0)\n        {\n            return lp_base_case((const double(*)[2])halves, m,\n                                n_vec, d_vec, opt, next, prev);\n        }\n        else\n        {\n            return lp_no_con<1>(n_vec, d_vec, opt);\n        }\n    }\n\n    inline void rand_permutation(const int n,\n                                 int *p)\n    {\n        typedef std::uniform_int_distribution<int> rand_int;\n        typedef rand_int::param_type rand_range;\n        static std::mt19937_64 gen;\n        static rand_int rdi(0, 1);\n        int j, k;\n        for (int i = 0; i < n; i++)\n        {\n            p[i] = i;\n        }\n        for (int i = 0; i < n; i++)\n        {\n            rdi.param(rand_range(0, n - i - 1));\n            j = rdi(gen) + i;\n            k = p[j];\n            p[j] = p[i];\n            p[i] = k;\n        }\n    }\n\n    template <int d>\n    inline double linprog(const Eigen::Matrix<double, d, 1> &c,\n                          const Eigen::Matrix<double, -1, d> &A,\n                          const Eigen::Matrix<double, -1, 1> &b,\n                          Eigen::Matrix<double, d, 1> &x)\n    /*\n    **  min cTx, s.t. Ax<=b\n    **  dim(x) << dim(b)\n    */\n    {\n        int m = b.size() + 1;\n        x.setZero();\n        if (m <= 1)\n        {\n            return c.cwiseAbs().maxCoeff() > 0.0 ? -INFINITY : 0.0;\n        }\n\n        Eigen::VectorXi perm(m - 1);\n        Eigen::VectorXi next(m);\n        /* original allocated size is m, here changed to m + 1 for legal tail accessing */\n        Eigen::VectorXi prev(m + 1);\n        Eigen::Matrix<double, d + 1, 1> n_vec;\n        Eigen::Matrix<double, d + 1, 1> d_vec;\n        Eigen::Matrix<double, d + 1, 1> opt;\n        Eigen::Matrix<double, d + 1, -1, Eigen::ColMajor> halves(d + 1, m);\n        Eigen::VectorXd work((m + 3) * (d + 2) * (d - 1) / 2);\n\n        halves.col(0).setZero();\n        halves(d, 0) = 1.0;\n        halves.topRightCorner(d, m - 1) = -A.transpose();\n        halves.bottomRightCorner(1, m - 1) = b.transpose();\n        /* normalize all halves as required in linfracprog */\n        halves.colwise().normalize();\n        n_vec.head(d) = c;\n        n_vec(d) = 0.0;\n        d_vec.setZero();\n        d_vec(d) = 1.0;\n\n        /* randomize the input planes */\n        rand_permutation(m - 1, perm.data());\n        /* previous to 0 is actually never used */\n        prev(0) = 0;\n        /* link the zero position in at the beginning */\n        next(0) = perm(0) + 1;\n        prev(perm(0) + 1) = 0;\n        /* link the other planes */\n        for (int i = 0; i < m - 2; i++)\n        {\n            next(perm(i) + 1) = perm(i + 1) + 1;\n            prev(perm(i + 1) + 1) = perm(i) + 1;\n        }\n        /* flag the last plane */\n        next(perm(m - 2) + 1) = m;\n\n        int status = sdlp::linfracprog<d>(halves.data(), m, m,\n                                          n_vec.data(), d_vec.data(),\n                                          opt.data(), work.data(),\n                                          next.data(), prev.data());\n\n        /* handle states for linprog whose definitions differ from linfracprog */\n        double minimum = INFINITY;\n        if (status != sdlp::INFEASIBLE)\n        {\n            if (opt(d) != 0.0 && status != sdlp::UNBOUNDED)\n            {\n                x = opt.head(d) / opt(d);\n                minimum = c.dot(x);\n            }\n\n            if (opt(d) == 0.0 || status == sdlp::UNBOUNDED)\n            {\n                x = opt.head(d);\n                minimum = -INFINITY;\n            }\n        }\n\n        return minimum;\n    }\n\n} // namespace sdlp\n\n#endif\n", "meta": {"hexsha": "f595b87690e2cb9977485738a7167b3f629fa951", "size": 24812, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "gcopter/include/gcopter/sdlp.hpp", "max_stars_repo_name": "RENyunfan/GCOPTER", "max_stars_repo_head_hexsha": "3b49c46b7467fd0b6b1abb2141912a1357e8da39", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-28T11:17:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T11:17:51.000Z", "max_issues_repo_path": "gcopter/include/gcopter/sdlp.hpp", "max_issues_repo_name": "RENyunfan/GCOPTER", "max_issues_repo_head_hexsha": "3b49c46b7467fd0b6b1abb2141912a1357e8da39", "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": "gcopter/include/gcopter/sdlp.hpp", "max_forks_repo_name": "RENyunfan/GCOPTER", "max_forks_repo_head_hexsha": "3b49c46b7467fd0b6b1abb2141912a1357e8da39", "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.4075949367, "max_line_length": 106, "alphanum_fraction": 0.3902144124, "num_tokens": 6231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.882427872638409, "lm_q2_score": 0.7981867777396211, "lm_q1q2_score": 0.7043422602488805}}
{"text": "#include <Eigen/Dense>\n#include \"gtest/gtest.h\"\n\n#include \"math/matrix/gauss_jordan.h\"\n\nnamespace GraphSfM {\nusing RowMajorMatrixXd =\n    Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\n\nTEST(GaussJordan, FullDiagonalizationOnSquaredRowMajorMatrix) {\n  const int kNumRows = 32;\n  RowMajorMatrixXd mat = RowMajorMatrixXd::Random(kNumRows, kNumRows);\n  GaussJordan(&mat);\n  // Trace of matrix must be equals to the number of rows.\n  EXPECT_NEAR(mat.trace(), static_cast<double>(kNumRows), 1e-6);\n  // Verify that the lower triangular part sums to the trace.\n  EXPECT_NEAR(mat.sum(), mat.trace(), 1e-6);\n}\n\nTEST(GaussJordan, FullDiagonalizationOnSquaredColumnMajorMatrix) {\n  const int kNumRows = 32;\n  Eigen::MatrixXd mat = Eigen::MatrixXd::Random(kNumRows, kNumRows);\n  GaussJordan(&mat);\n  // Trace of matrix must be equals to the number of rows.\n  EXPECT_NEAR(mat.trace(), static_cast<double>(kNumRows), 1e-6);\n  // Verify that the lower triangular part sums to the trace.\n  EXPECT_NEAR(mat.sum(), mat.trace(), 1e-6);\n}\n\nTEST(GaussJordan, EliminationOnFatMatrix) {\n  const int kNumRows = 32;\n  const int kNumCols = kNumRows + 4;\n  RowMajorMatrixXd mat = RowMajorMatrixXd::Random(kNumRows, kNumCols);\n  GaussJordan(&mat);\n  // Verify that the left-block (rows, rows) is diagonalized.\n  EXPECT_NEAR(mat.block(0, 0, kNumRows, kNumRows).sum(),\n              mat.block(0, 0, kNumRows, kNumRows).trace(), 1e-6);\n}\n\nTEST(GaussJordan, PartialEliminationOnFatMatrix) {\n  const int kNumRows = 32;\n  const int kNumCols = kNumRows + 4;\n  const int kNumRowsToProcess = kNumRows - 4;\n  const int kLastRowToProcess = kNumRowsToProcess - 1;\n  RowMajorMatrixXd mat = RowMajorMatrixXd::Random(kNumRows, kNumCols);\n  GaussJordan(kLastRowToProcess, &mat);\n  // Verify that the left-block (rows, rows) is diagonalized.\n  EXPECT_NEAR(mat.block(0, 0, kNumRowsToProcess, kNumRowsToProcess).trace(),\n              static_cast<double>(kNumRowsToProcess),\n              1e-6);\n}\n\nTEST(GaussJordan, PartialDiagonalizationOnFatMatrix) {\n  const int kNumRows = 32;\n  const int kNumCols = kNumRows + 4;\n  const int kLastRowToProcess = 2;\n  RowMajorMatrixXd mat = RowMajorMatrixXd::Random(kNumRows, kNumCols);\n  GaussJordan(kNumRows - 1, kLastRowToProcess, &mat);\n  // Verify that the left-block (rows, rows) is partially diagonalized.\n  EXPECT_NEAR(mat.block(kLastRowToProcess, kLastRowToProcess,\n                        kNumRows - kLastRowToProcess,\n                        kNumRows - kLastRowToProcess).sum(),\n              kNumRows - kLastRowToProcess, 1e-6);\n  EXPECT_NEAR(mat.block(kLastRowToProcess, kLastRowToProcess,\n                        kNumRows - kLastRowToProcess,\n                        kNumRows - kLastRowToProcess).sum(),\n              mat.block(kLastRowToProcess, kLastRowToProcess,\n                        kNumRows - kLastRowToProcess,\n                        kNumRows - kLastRowToProcess).trace(),\n              1e-6);\n  EXPECT_NE(mat.block(0, 0, kNumRows, kNumRows).sum(),\n            mat.block(kLastRowToProcess, kLastRowToProcess,\n                      kNumRows - kLastRowToProcess,\n                      kNumRows - kLastRowToProcess).sum());\n}\n\nTEST(GaussJordan, FullDiagonalizationOnLargeSquaredMatrix) {\n  const int kNumRows = 400;\n  const int kNumCols = kNumRows;\n  RowMajorMatrixXd mat = RowMajorMatrixXd::Random(kNumRows, kNumCols);\n  GaussJordan(&mat);\n  EXPECT_NEAR(mat.sum(), mat.trace(), 1e-6);\n}\n\n}  // namespace GraphSfM\n", "meta": {"hexsha": "2b73535def7db2211870660c7ebe95dc53b0c9b3", "size": 3451, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/math/gauss_jordan_test.cpp", "max_stars_repo_name": "LumanYang/GraphSfM", "max_stars_repo_head_hexsha": "c04a63578ce63065eb76278f358812c099d4eeef", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-17T06:18:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-17T06:18:43.000Z", "max_issues_repo_path": "src/math/gauss_jordan_test.cpp", "max_issues_repo_name": "longchao343/GraphSfM", "max_issues_repo_head_hexsha": "c4cac7885f1ee383d9d0031a390bd1dbf3ee0104", "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/math/gauss_jordan_test.cpp", "max_forks_repo_name": "longchao343/GraphSfM", "max_forks_repo_head_hexsha": "c4cac7885f1ee383d9d0031a390bd1dbf3ee0104", "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": 40.1279069767, "max_line_length": 76, "alphanum_fraction": 0.69168357, "num_tokens": 964, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834277, "lm_q2_score": 0.7772998611746911, "lm_q1q2_score": 0.7042257616097216}}
{"text": "#include <Eigen/Dense>\n#include \"simple_layer.h\"\n#include \"simple_activation.h\"\n#include \"simple_loss.h\"\n\nnamespace MyDL{\n\n    using namespace Eigen;\n\n    // -------------------------------------------------\n    //          MulLayer\n    // -------------------------------------------------\n    MatrixXd MulLayer::forward(MatrixXd& x, MatrixXd& y){\n        _x = x;\n        _y = y;\n\n        return x.array() * y.array();\n    }\n\n    void MulLayer::backward(MatrixXd& dout, MatrixXd& dx, MatrixXd& dy){\n        dx = dout.array() * _y.array();\n        dy = dout.array() * _x.array();\n    }\n\n    // -------------------------------------------------\n    //          AddLayer\n    // -------------------------------------------------\n    MatrixXd AddLayer::forward(MatrixXd& x, MatrixXd& y){\n        return x + y;\n    }\n\n    void AddLayer::backward(MatrixXd& dout, MatrixXd& dx, MatrixXd& dy){\n        dx = dout;\n        dy = dout;        \n    }\n\n    // -------------------------------------------------\n    //          ReLU\n    // -------------------------------------------------\n    MatrixXd ReLU::forward(MatrixXd& x){\n        mask = x.unaryExpr([](double p){return p >= 0;}).cast<double>();\n        return x.array() * mask.array();\n    }\n\n    MatrixXd ReLU::backward(MatrixXd& dout){\n        return dout.array() * mask.array();\n    }\n\n    // -------------------------------------------------\n    //          Sigmoid\n    // -------------------------------------------------\n    MatrixXd Sigmoid::forward(MatrixXd& x){\n        _y = x.unaryExpr([](double p){return 1/(1 + exp(-p));});\n        return _y; // \u5185\u90e8\u5909\u6570\u306b\u683c\u7d0d\u3059\u308b\u306e\u5fd8\u308c\u304c\u3061\n    }\n\n    MatrixXd Sigmoid::backward(MatrixXd& dout){\n        return dout.array() * (MatrixXd::Ones(dout.rows(), dout.cols()).array() - _y.array()) * _y.array();\n    }\n\n    // -------------------------------------------------\n    //          Affine\n    // -------------------------------------------------\n    Affine::Affine(MatrixXd& W, VectorXd& b){\n        _W = W;\n        _b = b;\n    }\n\n    MatrixXd Affine::forward(MatrixXd& X){\n        MatrixXd Y;\n        _X = X; // \u5185\u90e8\u5909\u6570\u306b\u683c\u7d0d\u3059\u308b\u306e\u5fd8\u308c\u304c\u3061\n        Y = (X * _W).rowwise() + _b.transpose();\n        return Y;\n    }\n\n    MatrixXd Affine::backward(MatrixXd& dout){\n        MatrixXd dX;\n        dX = dout * _W.transpose();\n        dW = _X.transpose() * dout;\n        db = dout.colwise().sum();\n        return dX;\n    }\n\n    // -------------------------------------------------\n    //          SoftmaxWithLoss\n    // -------------------------------------------------\n    double SoftmaxWithLoss::forward(MatrixXd& X, MatrixXd& t){\n        _t = t;\n        _Y = softmax(X);\n        _loss = cross_entropy_error(_Y, t);\n        return _loss;\n    }\n\n    MatrixXd SoftmaxWithLoss::backward(double dout){\n        double batch_size = _t.rows();\n        MatrixXd dx;\n        dx = (_Y - _t) / batch_size;\n\n        return dx;\n    }\n    \n\n}", "meta": {"hexsha": "1541172fc04cdb5707c3ea22a8a1bed337e8cd99", "size": 2885, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "simple_lib/src/simple_layer.cpp", "max_stars_repo_name": "potedo/zeroDL_cpp", "max_stars_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-22T15:26:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-22T15:26:20.000Z", "max_issues_repo_path": "simple_lib/src/simple_layer.cpp", "max_issues_repo_name": "potedo/zeroDL_cpp", "max_issues_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "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": "simple_lib/src/simple_layer.cpp", "max_forks_repo_name": "potedo/zeroDL_cpp", "max_forks_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "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.0097087379, "max_line_length": 107, "alphanum_fraction": 0.4051993068, "num_tokens": 684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898229217591, "lm_q2_score": 0.7772998508568416, "lm_q1q2_score": 0.7042257542348997}}
{"text": "// weighted_die.cpp\n//\n// Copyright (c) 2009\n// Steven Watanabe\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n//[weighted_die\n/*`\n    For the source of this example see\n    [@boost://libs/random/example/weighted_die.cpp weighted_die.cpp].\n*/\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_real.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n\nboost::mt19937 gen;\n\n/*`\n   This time, instead of a fair die, the probability of\n   rolling a 1 is 50% (!).  The other five faces are all\n   equally likely.\n*/\nstatic const double probabilities[] = {\n    0.5, 0.1, 0.1, 0.1, 0.1, 0.1\n};\n\n/*`\n  Now define a function that simulates rolling this die.\n  Note that the C++0x library contains a `discrete_distribution`\n  class which would be a better way to do this.\n*/\nint roll_weighted_die() {\n    std::vector<double> cumulative;\n    std::partial_sum(&probabilities[0], &probabilities[0] + 6,\n                     std::back_inserter(cumulative));\n    boost::uniform_real<> dist(0, cumulative.back());\n    boost::variate_generator<boost::mt19937&, boost::uniform_real<> > die(gen, dist);\n    /*<< Find the position within the sequence and add 1\n         (to make sure that the result is in the range [1,6]\n         instead of [0,5])\n    >>*/\n    return (std::lower_bound(cumulative.begin(), cumulative.end(), die()) - cumulative.begin()) + 1;\n}\n\n//]\n\n#include <iostream>\n\nint main() {\n    for(int i = 0; i < 10; ++i) {\n        std::cout << roll_weighted_die() << std::endl;\n    }\n}\n", "meta": {"hexsha": "4a0b5a8209561cbd6ee9fe8a8929570d3396e497", "size": 1674, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/random/example/weighted_die.cpp", "max_stars_repo_name": "tizenorg/external.boost", "max_stars_repo_head_hexsha": "661689c2058551ef4644aa48a24612d5a4bd41a7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-06-25T23:20:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-14T19:38:34.000Z", "max_issues_repo_path": "libs/random/example/weighted_die.cpp", "max_issues_repo_name": "ksundberg/boost-svn", "max_issues_repo_head_hexsha": "5694e7831f7afc8f6e25d03d0fd375e7be758d0f", "max_issues_repo_licenses": ["BSL-1.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/random/example/weighted_die.cpp", "max_forks_repo_name": "ksundberg/boost-svn", "max_forks_repo_head_hexsha": "5694e7831f7afc8f6e25d03d0fd375e7be758d0f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-07-26T08:07:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-25T23:20:21.000Z", "avg_line_length": 27.9, "max_line_length": 100, "alphanum_fraction": 0.6642771804, "num_tokens": 461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7040185416013076}}
{"text": "/********************************************************************************\n * Copyright 2009 The Robotics Group, The Maersk Mc-Kinney Moller Institute,\n * Faculty of Engineering, University of Southern Denmark\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n ********************************************************************************/\n\n#ifndef RW_MATH_EAA_HPP\n#define RW_MATH_EAA_HPP\n\n/**\n * @file EAA.hpp\n */\n#if !defined(SWIG)\n#include <rw/common/Serializable.hpp>\n#include <rw/math/Constants.hpp>\n#include <rw/math/Rotation3D.hpp>\n#include <rw/math/Rotation3DVector.hpp>\n#include <rw/math/Vector3D.hpp>\n\n#include <Eigen/Core>\n#endif\nnamespace rw { namespace math {\n    /** @addtogroup math */\n    /*@{*/\n\n    /**\n     * @brief A class for representing an equivalent angle-axis rotation\n     *\n     * This class defines an equivalent-axis-angle orientation vector also known\n     * as an @f$ \\thetak @f$ vector or \"axis+angle\" vector\n     *\n     * The equivalent-axis-angle vector is the product of a unit vector @f$\n     * \\hat{\\mathbf{k}} @f$ and an angle of rotation around that axis @f$ \\theta\n     * @f$\n     *\n     * @note given two EAA vectors @f$ \\theta_1\\mathbf{\\hat{k}}_1 @f$ and @f$\n     * \\theta_2\\mathbf{\\hat{k}}_2 @f$ it is generally not possible to subtract\n     * or add these vectors, except for the special case when @f$\n     * \\mathbf{\\hat{k}}_1 == \\mathbf{\\hat{k}}_2 @f$ this is why this class does\n     * not have any subtraction or addition operators\n     */\n    template< class T = double > class EAA : public rw::math::Rotation3DVector< T >\n    {\n      public:\n        /**\n         * @brief Extracts Equivalent axis-angle vector from Rotation matrix\n         *\n         * @param R [in] A 3x3 rotation matrix @f$ \\mathbf{R} @f$\n         *\n         * @f$\n         * \\theta = arccos(\\frac{1}{2}(Trace(\\mathbf{R})-1)=arccos(\\frac{r_{11}+r_{22}+r_{33}-1}{2})\n         * @f$\n         *\n         * @f$\n         * \\thetak=log(\\mathbf{R})=\\frac{\\theta}{2 sin \\theta}(\\mathbf{R}-\\mathbf{R}^T) =\n         * \\frac{\\theta}{2 sin \\theta}\n         * \\left[\n         * \\begin{array}{c}\n         * r_{32}-r_{23}\\\\\n         * r_{13}-r_{31}\\\\\n         * r_{21}-r_{12}\n         * \\end{array}\n         * \\right]\n         * @f$\n         *\n         * @f$\n         * \\thetak=\n         * \\left[\n         * \\begin{array}{c}\n         * 0\\\\\n         * 0\\\\\n         * 0\n         * \\end{array}\n         * \\right]\n         * @f$ if @f$ \\theta = 0 @f$\n         *\n         * @f$\n         * \\thetak=\\pi\n         * \\left[\n         * \\begin{array}{c}\n         * \\sqrt{(R(0,0)+1.0)/2.0}\\\\\n         * \\sqrt{(R(1,1)+1.0)/2.0}\\\\\n         * \\sqrt{(R(2,2)+1.0)/2.0}\n         * \\end{array}\n         * \\right]\n         * @f$ if @f$ \\theta = \\pi @f$\n         *\n         */\n        explicit EAA (const rw::math::Rotation3D< T >& R);\n\n        /**\n         * @brief Constructs an EAA vector initialized to \\f$\\{0,0,0\\}\\f$\n         */\n        EAA () : _eaa (0, 0, 0) {}\n\n        /**\n         * @brief Constructs an initialized EAA vector\n         * @param axis [in] \\f$ \\mathbf{\\hat{k}} \\f$\n         * @param angle [in] \\f$ \\theta \\f$\n         * @pre norm_2(axis) = 1\n         */\n        EAA (const rw::math::Vector3D< T >& axis, T angle) : _eaa (axis * angle) {}\n\n        /**\n         * @brief Constructs an initialized EAA vector\n         * @f$ \\thetak =\n         * \\left[\\begin{array}{c}\n         *    \\theta k_x\\\\\n         *    \\theta k_y\\\\\n         *    \\theta k_z\n         * \\end{array}\\right]\n         * @f$\n         * @param thetakx [in] @f$ \\theta k_x @f$\n         * @param thetaky [in] @f$ \\theta k_y @f$\n         * @param thetakz [in] @f$ \\theta k_z @f$\n         */\n        EAA (T thetakx, T thetaky, T thetakz) :\n            _eaa (rw::math::Vector3D< T > (thetakx, thetaky, thetakz))\n        {}\n\n        /**\n         * @brief Constructs an EAA vector that will rotate v1 into\n         * v2. Where v1 and v2 are normalized and described in the same reference frame.\n         * @param v1 [in] normalized vector\n         * @param v2 [in] normalized vector\n         */\n        EAA (const rw::math::Vector3D< T >& v1, const rw::math::Vector3D< T >& v2);\n\n        /**\n         * @brief Constructs an initialized EAA vector\n         *\n         * The angle of the EAA are \\f$\\|eaa\\|\\f$ and the axis is \\f$\\frac{eaa}{\\|eaa\\|}\\f$\n         * @param eaa [in] Values to initialize the EAA\n         */\n        explicit EAA (rw::math::Vector3D< T > eaa) : _eaa (eaa) {}\n        \n        /**\n         * @brief Copy Constructor\n         * @param eaa [in] Values to initialize the EAA\n         */\n        EAA (const rw::math::EAA< T >& eaa) : _eaa (eaa._eaa) {}\n\n        /**\n         * @brief Constructs an initialized EAA vector\n         *\n         * The angle of the EAA are \\f$\\|eaa\\|\\f$ and the axis is \\f$\\frac{eaa}{\\|eaa\\|}\\f$\n         * @param eaa [in] Values to initialize the EAA\n         */\n        template< class R > explicit EAA (const Eigen::MatrixBase< R >& r) : _eaa (r) {}\n\n        //! @brief destructor\n        virtual ~EAA () {}\n\n        /**\n         * @brief Get the size of the EAA.\n         * @return the size (always 3).\n         */\n        size_t size () const { return 3; }\n\n        // ###################################################\n        // #                Acces Operators                  #\n        // ###################################################\n#if !defined(SWIGJAVA)\n        /**\n         * @copydoc Rotation3DVector::toRotation3D()\n         *\n         * @f$\n         * \\mathbf{R} = e^{[\\mathbf{\\hat{k}}],\\theta}=\\mathbf{I}^{3x3}+[\\mathbf{\\hat{k}}]\n         * sin\\theta+[{\\mathbf{\\hat{k}}}]^2(1-cos\\theta) = \\left[ \\begin{array}{ccc}\n         *      k_xk_xv\\theta + c\\theta & k_xk_yv\\theta - k_zs\\theta & k_xk_zv\\theta + k_ys\\theta \\\\\n         *      k_xk_yv\\theta + k_zs\\theta & k_yk_yv\\theta + c\\theta & k_yk_zv\\theta - k_xs\\theta\\\\\n         *      k_xk_zv\\theta - k_ys\\theta & k_yk_zv\\theta + k_xs\\theta & k_zk_zv\\theta + c\\theta\n         *    \\end{array}\n         *  \\right]\n         * @f$\n         *\n         * where:\n         * - @f$ c\\theta = cos \\theta @f$\n         * - @f$ s\\theta = sin \\theta @f$\n         * - @f$ v\\theta = 1-cos \\theta @f$\n         */\n\n#endif \n        virtual const rw::math::Rotation3D< T > toRotation3D () const;\n\n        /**\n         * @brief Extracts the angle of rotation @f$ \\theta @f$\n         * @return @f$ \\theta @f$\n         */\n        T angle () const { return _eaa.norm2 (); }\n\n        /**\n         * @brief change the angle of the EAA\n         * @param angle [in] the new angle\n         * @return this object\n         */\n        EAA< T >& setAngle (const T& angle)\n        {\n            (*this) = EAA< T > (this->axis (), angle);\n            return (*this);\n        }\n\n        /**\n         * @brief Extracts the axis of rotation vector @f$ \\mathbf{\\hat{\\mathbf{k}}} @f$\n         * @return @f$ \\mathbf{\\hat{\\mathbf{k}}} @f$\n         */\n        const rw::math::Vector3D< T > axis () const\n        {\n            T theta = angle ();\n            if (theta < 1e-6)\n                return rw::math::Vector3D< T > (0, 0, 0);\n            else\n                return _eaa / theta;\n        }\n\n        /**\n         * @brief get the underling Vector\n         * @return the vector\n         */\n        rw::math::Vector3D< T >& toVector3D () { return this->_eaa; }\n\n        /**\n         * @brief get the underling Vector\n         * @return the vector\n         */\n        rw::math::Vector3D< T > toVector3D () const { return this->_eaa; }\n\n        /**\n         * @brief get as eigen vector\n         * @return Eigenvector\n         */\n        Eigen::Matrix< T, 3, 1 >& e () { return this->_eaa.e (); }\n\n        /**\n         * @brief get as eigen vector\n         * @return Eigenvector\n         */\n        Eigen::Matrix< T, 3, 1 > e () const { return this->_eaa.e (); }\n\n#if !defined(SWIG)\n        /**\n         * @brief Returns element of EAA\n         * @param i [in] index (@f$ 0 < i < 3 @f$)\n         * @return the @f$ i @f$'th element\n         */\n        const T& operator[] (size_t i) const\n        {\n            assert (i < 3);\n            return _eaa[i];\n        }\n\n        /**\n         * @brief Returns element of EAA\n         * @param i [in] index (@f$ 0 < i < 3 @f$)\n         * @return the @f$ i @f$'th element\n         */\n        T& operator[] (size_t i)\n        {\n            assert (i < 3);\n            return _eaa[i];\n        }\n\n        /**\n         * @brief Returns element of EAA\n         * @param i [in] index (@f$ 0 < i < 3 @f$)\n         * @return the @f$ i @f$'th element\n         */\n        const T& operator() (size_t i) const\n        {\n            assert (i < 3);\n            return _eaa[i];\n        }\n\n        /**\n         * @brief Returns element of EAA\n         * @param i [in] index (@f$ 0 < i < 3 @f$)\n         * @return the @f$ i @f$'th element\n         */\n        T& operator() (size_t i)\n        {\n            assert (i < 3);\n            return _eaa[i];\n        }\n#else\n        ARRAYOPERATOR (T);\n#endif\n        // ###################################################\n        // #                 Math Operators                  #\n        // ###################################################\n\n        // ########## Eigen Operations\n\n        /**\n         * @brief element wise division.\n         * @param rhs [in] the vector being devided with\n         * @return the resulting Vector3D\n         */\n        template< class R > EAA< T > elemDivide (const Eigen::MatrixBase< R >& rhs) const\n        {\n            EAA< T > ret = *this;\n            for (size_t i = 0; i < size (); i++) {\n                ret._eaa[i] /= rhs[i];\n            }\n            return ret;\n        }\n\n        /**\n         * @brief Elementweise multiplication.\n         * @param rhs [in] vector\n         * @return the element wise product\n         */\n        template< class R > EAA< T > elemMultiply (const Eigen::MatrixBase< R >& rhs) const\n        {\n            EAA< T > ret = *this;\n            for (size_t i = 0; i < size (); i++) {\n                ret._eaa[i] *= rhs[i];\n            }\n            return ret;\n        }\n\n        /**\n         * @brief Vector subtraction.\n         */\n        template< class R > EAA< T > operator- (const Eigen::MatrixBase< R >& rhs) const\n        {\n            return EAA< T > (_eaa - rhs);\n        }\n\n        /**\n         * @brief Vector subtraction.\n         */\n        template< class R >\n        friend EAA< T > operator- (const Eigen::MatrixBase< R >& lhs, const EAA< T >& rhs)\n        {\n            return EAA< T > (lhs - rhs.e ());\n        }\n\n        /**\n         * @brief Vector addition.\n         */\n        template< class R > EAA< T > operator+ (const Eigen::MatrixBase< R >& rhs) const\n        {\n            return EAA< T > (_eaa + rhs);\n        }\n\n        /**\n         * @brief Vector subtraction.\n         */\n        template< class R >\n        friend EAA< T > operator+ (const Eigen::MatrixBase< R >& lhs, const EAA< T >& rhs)\n        {\n            return EAA< T > (lhs + rhs.e ());\n        }\n\n        // ########### EAA Operators\n\n        /**\n         * @brief Unary minus.\n         * @brief negative version\n         */\n        EAA< T > operator- () const { return EAA< T > (-_eaa); }\n\n        /**\n         * @brief element wise addition\n         * @param rhs [in] the EAA to be added\n         * @return the sum of the two EAA's\n         */\n        EAA< T > elemAdd (const EAA< T >& rhs) const { return EAA< T > (this->_eaa + rhs._eaa); }\n\n        /**\n         * @brief element wise subtraction\n         * @param rhs [in] the EAA to be subtracted\n         * @return the difference between the two EAA's\n         */\n        EAA< T > elemSubtract (const EAA< T >& rhs) const\n        {\n            return EAA< T > (this->_eaa - rhs._eaa);\n        }\n\n        /**\n         * @brief element wise devision ( \\b this / \\b rhs )\n         * @param rhs [in] the EAA to be devided with\n         * @return the result of division\n         */\n        EAA< T > elemDivide (const EAA< T >& rhs) const\n        {\n            return EAA< T > (this->_eaa.elemDivide (rhs._eaa));\n        }\n\n        /**\n         * @brief element wise multiplication\n         * @param rhs [in] the EAA to be multiplyed with\n         * @return the result of division\n         */\n        EAA< T > elemMultiply (const EAA< T >& rhs) const\n        {\n            return EAA< T > (this->_eaa.elemMultiply (rhs._eaa));\n        }\n\n        /**\n         * @brief This is rotation multiplcation, and it is multiplication of two EAA's first\n         * converted to a Rotation3D\n         * @param rhs [in] the eaa to multiply with\n         * @return the new rotation\n         */\n        EAA< T > operator* (const EAA< T >& rhs) const\n        {\n            return EAA< T > (this->toRotation3D () * rhs.toRotation3D ());\n        }\n\n        // ########### Rotation3D Operators\n#if !defined(SWIG)\n        /**\n         * @brief Calculates \\f$ \\robabx{a}{c}{\\thetak} =\n         * \\robabx{a}{b}{\\mathbf{R}} \\robabx{b}{c}{\\mathbf{\\thetak}} \\f$\n         *\n         * @param aRb [in] \\f$ \\robabx{a}{b}{\\mathbf{R}} \\f$\n         * @param bTKc [in] \\f$ \\robabx{b}{c}{\\thetak} \\f$\n         * @return \\f$ \\robabx{a}{c}{\\thetak} \\f$\n         */\n        friend EAA< T > operator* (const rw::math::Rotation3D< T >& aRb, const EAA< T >& bTKc)\n        {\n            return EAA (aRb * bTKc._eaa);\n        }\n#endif\n\n        /**\n         * @brief matrix multiplication converting EAA to rotation\n         * @param rhs [in] the roation matrix to multiply with\n         * @return EAA ( this->toRotation3D() * rhs)\n         */\n        template< class R > EAA< T > operator* (const rw::math::Rotation3D< R >& rhs)\n        {\n            return EAA (this->toRotation3D () * rhs);\n        }\n\n        // ########### Scalar operators\n\n        /**\n         * @brief scalar multiplication\n         * @param rhs [in] the scalar to multiply with\n         * @return the product\n         */\n        EAA< T > elemMultiply (const T& rhs) const { return EAA< T > (this->_eaa * rhs); }\n\n        /**\n         * @brief scalar devision\n         * @param rhs [in] the scalar to devide with\n         * @return the resulting EAA\n         */\n        EAA< T > elemDivide (const T& rhs) const { return EAA< T > (this->_eaa / rhs); }\n\n        /**\n         * @brief Scalar subtraction.\n         */\n        EAA< T > elemSubtract (const T rhs) const { return EAA< T > (_eaa.elemSubtract (rhs)); }\n\n        /**\n         * @brief Scalar addition.\n         */\n        EAA< T > elemAdd (const T rhs) const { return EAA< T > (_eaa.elemAdd (rhs)); }\n\n        /**\n         * @brief scale the angle, keeping the axis the same\n         * @param scale [in] how much the angle should change\n         * @return a new EAA with the scaled angle\n         */\n        EAA< T > scaleAngle (const T& scale)\n        {\n            return EAA< T > (this->axis (), this->angle () * scale);\n        }\n\n        // ############ Vector3D Operators\n\n        /**\n         * @brief element wise multiplication.\n         * @param rhs [in] the vector being devided with\n         * @return the resulting EAA\n         */\n        EAA< T > operator+ (const rw::math::Vector3D< T >& rhs) const\n        {\n            return EAA< T > (this->_eaa + rhs);\n        }\n\n#if !defined(SWIG)\n        /**\n         * @brief Vector addition\n         * @param lhs [in] left side value\n         * @param rhs [in] right side value\n         * @return the resulting EAA\n         */\n        friend EAA< T > operator+ (const rw::math::Vector3D< T >& lhs, const EAA< T >& rhs)\n        {\n            return EAA< T > (lhs + rhs._eaa);\n        }\n#endif\n\n        /**\n         * @brief Vector addition\n         * @param rhs [in] the vector being added\n         * @return the resulting EAA\n         */\n        EAA< T > operator- (const rw::math::Vector3D< T >& rhs) const\n        {\n            return EAA< T > (this->_eaa - rhs);\n        }\n\n#if !defined(SWIG)\n        /**\n         * @brief Vector addition\n         * @param lhs [in] left side value\n         * @param rhs [in] right side value\n         * @return the resulting EAA\n         */\n        friend EAA< T > operator- (const rw::math::Vector3D< T >& lhs, const EAA< T >& rhs)\n        {\n            return EAA< T > (lhs - rhs._eaa);\n        }\n#endif\n        /**\n         * @brief element wise devision ( \\b this / \\b rhs )\n         * @param rhs [in] the Vector to be devided with\n         * @return the result of division\n         */\n        EAA< T > elemDivide (const rw::math::Vector3D< T >& rhs) const\n        {\n            return EAA< T > (this->_eaa.elemDivide (rhs));\n        }\n\n        /**\n         * @brief element wise multiplication\n         * @param rhs [in] the Vector to be multiplyed with\n         * @return the result of division\n         */\n        EAA< T > elemMultiply (const rw::math::Vector3D< T >& rhs) const\n        {\n            return EAA< T > (this->_eaa.elemMultiply (rhs));\n        }\n\n        // ############ Ostream operators\n\n#if !defined(SWIG)\n        /**\n         * @brief Ouputs EAA to stream\n         * @param os [in/out] stream to use\n         * @param eaa [in] equivalent axis-angle\n         * @return the resulting stream\n         */\n        friend std::ostream& operator<< (std::ostream& os, const EAA< T >& eaa)\n        {\n            return os << \" EAA( \" << eaa (0) << \", \" << eaa (1) << \", \" << eaa (2) << \")\";\n        }\n#else\n        TOSTRING (rw::math::EAA< T >);\n#endif\n        // ############ Math Operations\n\n        /**\n         * @brief Calculates the cross product and returns the result\n         * @param v [in] a Vector3D\n         * @return the resulting 3D vector\n         */\n        rw::math::Vector3D< T > cross (const rw::math::Vector3D< T >& v) const\n        {\n            return rw::math::cross (this->_eaa, v);\n        }\n\n        /**\n         * @brief Calculates the cross product and returns the result\n         * @param eaa [in] a EAA\n         * @return the resulting 3D vector\n         */\n        EAA< T > cross (const EAA< T >& eaa) const\n        {\n            return EAA< T > (rw::math::cross (this->_eaa, eaa._eaa));\n        }\n\n        /**\n         * @brief Calculates the dot product and returns the result\n         * @param v [in] a Vector3D\n         * @return the resulting scalar\n         */\n        T dot (const rw::math::Vector3D< T >& v) { return rw::math::dot (this->_eaa, v); }\n\n        /**\n         * @brief Calculates the cross product and returns the result\n         * @param eaa [in] a EAA\n         * @return the resulting 3D vector\n         */\n        T dot (const EAA< T >& eaa) { return rw::math::dot (this->_eaa, eaa._eaa); }\n\n        /**\n         * @brief Returns the Euclidean norm (2-norm) of the vector\n         * @return the norm\n         */\n        T norm2 () const { return _eaa.norm2 (); }\n\n        /**\n         * @brief Returns the Manhatten norm (1-norm) of the vector\n         * @return the norm\n         */\n        T norm1 () const { return _eaa.norm1 (); }\n\n        /**\n         * @brief Returns the infinte norm (\\f$\\inf\\f$-norm) of the vector\n         * @return the norm\n         */\n        T normInf () const { return _eaa.normInf (); }\n\n        // ###################################################\n        // #             assignement Operators               #\n        // ###################################################\n\n        /**\n         * @brief copy operator\n         * @param rhs [in] the EAA to be copied\n         * @return reference to this EAA\n         */\n        EAA< T >& operator= (const EAA< T >& rhs)\n        {\n            this->_eaa = rhs._eaa;\n            return *this;\n        }\n\n        /**\n         * @brief assign vector to EAA\n         * @param rhs [in] the vector to asign\n         * @return reference to this EAA\n         */\n        EAA< T >& operator= (const rw::math::Vector3D< T >& rhs)\n        {\n            this->_eaa = rhs;\n            return *this;\n        }\n\n        /**\n         * @brief addition operator\n         * @param rhs [in] the right hand side of the operation\n         * @return reference to this EAA\n         */\n        EAA< T >& operator+= (const rw::math::Vector3D< T >& rhs)\n        {\n            this->_eaa += rhs;\n            return *this;\n        }\n\n        /**\n         * @brief subtraction operator\n         * @param rhs [in] the right hand side of the operation\n         * @return reference to this EAA\n         */\n        EAA< T >& operator-= (const rw::math::Vector3D< T >& rhs)\n        {\n            this->_eaa -= rhs;\n            return *this;\n        }\n#if !defined(SWIG)\n        /**\n         * @brief Implicit converter to Vector3D\n         */\n        operator rw::math::Vector3D< T > () const { return _eaa; }\n\n        /**\n         * @brief Implicit converter to Vector3D\n         */\n        operator rw::math::Vector3D< T > & () { return _eaa; }\n#endif\n        /**\n         * @brief copy a vector from eigen type\n         * @param r [in] an Eigen Vector\n         */\n        template< class R > EAA< T >& operator= (const Eigen::MatrixBase< R >& r)\n        {\n            _eaa = r;\n            return *this;\n        }\n\n        /**\n         * @brief Vector addition.\n         */\n        template< class R > EAA< T >& operator+= (const Eigen::MatrixBase< R >& r)\n        {\n            _eaa += r;\n            return *this;\n        }\n\n        /**\n         * @brief Vector subtraction.\n         */\n        template< class R > EAA< T >& operator-= (const Eigen::MatrixBase< R >& r)\n        {\n            _eaa -= r;\n            return *this;\n        }\n#if !defined(SWIG)\n        /**\n         * @brief implicit conversion to EigenVector\n         */\n        operator Eigen::Matrix< T, 3, 1 > () const { return this->e (); }\n\n        /**\n         * @brief implicit conversion to EigenVector\n         */\n        operator Eigen::Matrix< T, 3, 1 > & () { return this->e (); }\n#endif\n\n        /**\n         * @brief copy operator\n         * @param rhs [in] the Rotation3D to be copied\n         * @return reference to this EAA\n         */\n        EAA< T >& operator= (const rw::math::Rotation3D< T >& rhs)\n        {\n            return (*this) = EAA< T > (rhs);\n        }\n\n        // ###################################################\n        // #                    Comparetors                  #\n        // ###################################################\n\n        /**\n         * @brief Compare with \\b rhs for equality.\n         * @param rhs [in] other vector.\n         * @return True if a equals b, false otherwise.\n         */\n        bool operator== (const rw::math::Vector3D< T >& rhs) const { return _eaa == rhs; }\n\n#if !defined(SWIG)\n        /**\n         * @brief Compare with \\b rhs for equality.\n         * @param lhs [in] first Vector\n         * @param rhs [in] second vector.\n         * @return True if a equals b, false otherwise.\n         */\n        friend bool operator== (const rw::math::Vector3D< T >& lhs, const EAA< T >& rhs)\n        {\n            return lhs == rhs._eaa;\n        }\n#endif\n\n        /**\n         *  @brief Compare with \\b rhs for inequality.\n         *  @param rhs [in] other vector.\n         *  @return True if a and b are different, false otherwise.\n         */\n        bool operator!= (const rw::math::Vector3D< T >& rhs) const { return _eaa != rhs; }\n\n#if !defined(SWIG)\n        /**\n         *  @brief Compare with \\b rhs for inequality.\n         * @param lhs [in] first Vector\n         * @param rhs [in] second vector.\n         *  @return True if a and b are different, false otherwise.\n         */\n        friend bool operator!= (const rw::math::Vector3D< T >& lhs, const EAA< T >& rhs)\n        {\n            return lhs != rhs._eaa;\n        }\n#endif\n\n        /**\n         * @brief Compare with \\b rhs for equality.\n         * @param rhs [in] other vector.\n         * @return True if a equals b, false otherwise.\n         */\n        bool operator== (const EAA< T >& rhs) const { return _eaa == rhs._eaa; }\n\n        /**\n         *  @brief Compare with \\b rhs for inequality.\n         *  @param rhs [in] other vector.\n         *  @return True if a and b are different, false otherwise.\n         */\n        bool operator!= (const EAA< T >& rhs) const { return _eaa != rhs._eaa; }\n\n        /**\n         * @brief Compare with \\b rhs for equality.\n         * @param rhs [in] other vector.\n         * @return True if a equals b, false otherwise.\n         */\n        template< class R > bool operator== (const Eigen::MatrixBase< R >& rhs) const\n        {\n            return this->_eaa == rhs;\n        }\n\n        /**\n         * @brief Compare with \\b rhs for equality.\n         * @param rhs [in] other vector.\n         * @return True if a equals b, false otherwise.\n         */\n        template< class R >\n        friend bool operator== (const Eigen::MatrixBase< R >& lhs, const EAA< T >& rhs)\n        {\n            return lhs == rhs._eaa;\n        }\n\n        /**\n         *  @brief Compare with \\b rhs for inequality.\n         *  @param b [in] other vector.\n         *  @return True if a and b are different, false otherwise.\n         */\n        template< class R > bool operator!= (const Eigen::MatrixBase< R >& rhs) const\n        {\n            return !(*this == rhs);\n        }\n\n        /**\n         *  @brief Compare with \\b rhs for inequality.\n         *  @param b [in] other vector.\n         *  @return True if a and b are different, false otherwise.\n         */\n        template< class R >\n        friend bool operator!= (const Eigen::MatrixBase< R >& lhs, const EAA< T >& rhs)\n        {\n            return !(lhs == rhs);\n        }\n\n      private:\n        rw::math::Vector3D< T > _eaa;\n    };\n\n    template< class T >\n    rw::math::Vector3D< T > cross (const rw::math::Vector3D< T >& v1, const EAA< T >& v2)\n    {\n        return rw::math::cross (v1, v2.axis () * v2.angle ());\n    }\n\n    /**\n     * @brief Casts EAA<T> to EAA<Q>\n     * @param eaa [in] EAA with type T\n     * @return EAA with type Q\n     */\n    template< class Q, class T > const EAA< Q > cast (const EAA< T >& eaa)\n    {\n        return EAA< Q > (\n            static_cast< Q > (eaa (0)), static_cast< Q > (eaa (1)), static_cast< Q > (eaa (2)));\n    }\n\n    using EAAd = EAA< double >;\n    using EAAf = EAA< float >;\n\n    /*@}*/\n\n}}    // namespace rw::math\n\n#if !defined(SWIG)\nextern template class rw::math::EAA< double >;\nextern template class rw::math::EAA< float >;\n#else\nSWIG_DECLARE_TEMPLATE (EAAd, rw::math::EAA< double >);\nSWIG_DECLARE_TEMPLATE (EAAf, rw::math::EAA< float >);\n#endif\n\nnamespace rw { namespace common {\n    class OutputArchive;\n    class InputArchive;\n    namespace serialization {\n        /**\n         * @copydoc rw::common::serialization::write\n         * @relatedalso rw::math::EAA\n         */\n        template<>\n        void write (const rw::math::EAA< double >& sobject, rw::common::OutputArchive& oarchive,\n                    const std::string& id);\n\n        /**\n         * @copydoc rw::common::serialization::write\n         * @relatedalso rw::math::EAA\n         */\n        template<>\n        void write (const rw::math::EAA< float >& sobject, rw::common::OutputArchive& oarchive,\n                    const std::string& id);\n\n        /**\n         * @copydoc rw::common::serialization::read\n         * @relatedalso rw::math::EAA\n         */\n        template<>\n        void read (rw::math::EAA< double >& sobject, rw::common::InputArchive& iarchive,\n                   const std::string& id);\n\n        /**\n         * @copydoc rw::common::serialization::read\n         * @relatedalso rw::math::EAA\n         */\n        template<>\n        void read (rw::math::EAA< float >& sobject, rw::common::InputArchive& iarchive,\n                   const std::string& id);\n    }    // namespace serialization\n}}       // namespace rw::common\n\n#endif    // end include guard\n", "meta": {"hexsha": "21fdfa6e8db2bcb003f567674cfec053ff904be8", "size": 28235, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "RobWork/src/rw/math/EAA.hpp", "max_stars_repo_name": "ZLW07/RobWork", "max_stars_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-29T14:16:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T14:16:27.000Z", "max_issues_repo_path": "RobWork/src/rw/math/EAA.hpp", "max_issues_repo_name": "ZLW07/RobWork", "max_issues_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "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": "RobWork/src/rw/math/EAA.hpp", "max_forks_repo_name": "ZLW07/RobWork", "max_forks_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "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": 31.2679955703, "max_line_length": 100, "alphanum_fraction": 0.4733132637, "num_tokens": 7716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423873, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.7039257904840602}}
{"text": "/************************************************************************/\n/*                   QR-PCA-FaceRec  by John Hany                       */\n/*\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t*/\n/*\tA face recognition algorithm using QR based PCA.              \t\t*/\n/*\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t*/\n/*\tReleased under MIT license.\t\t\t\t\t\t\t\t\t\t\t*/\n/*\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t*/\n/*\tContact me at johnhany@163.com\t\t\t\t\t\t\t\t\t\t*/\n/*\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t*/\n/*\tWelcome to my blog http://johnhany.net/, if you can read Chinese:)\t*/\n/*\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t*/\n/************************************************************************/\n\n#include <opencv2/opencv.hpp>\n#include <armadillo>\n#include <iostream>\n\nusing namespace std;\n\nint component_num = 7;\n\nstring orl_path = \"G:\\\\Datasets\\\\orl_faces\";\n\nenum distance_type {ECULIDEAN = 0, MANHATTAN, MAHALANOBIS};\n//double distance_criterion[3] = { 10.0, 30.0, 3.0};\ndouble distance_criterion[3] = { 1000.0, 1000.0, 1000.0};\n\nbool compDistance(pair<int, double> a, pair<int, double> b);\ndouble calcuDistance(const arma::vec vec1, const arma::vec vec2, distance_type dis_type);\ndouble calcuDistance(const arma::vec vec1, const arma::vec vec2, const arma::mat cov2, distance_type dis_type);\n\nint main(int argc, const char *argv[]) {\n\t\n\tint class_num = 40;\n\tint sample_num = 10;\n\n\tint img_cols = 92;\n\tint img_rows = 112;\n\tcv::Size sample_size(img_cols, img_rows);\n\n\tarma::mat mat_sample(img_rows*img_cols, sample_num*class_num);\n\n\t//Load samples in one matrix `mat_sample`.\n\n\tfor(int class_idx = 0; class_idx < class_num; class_idx++) {\n\t\tfor(int sample_idx = 0; sample_idx < sample_num; sample_idx++) {\n\n\t\t\tstring filename = orl_path + \"\\\\s\" + to_string(class_idx+1) + \"\\\\\" + to_string(sample_idx+1) + \".pgm\";\n\t\t\tcv::Mat img_frame = cv::imread(filename, CV_LOAD_IMAGE_GRAYSCALE);\n\t\t\tcv::Mat img_sample;\n\t\t\tcv::resize(img_frame, img_sample, sample_size);\n\n\t\t\tfor(int i = 0; i < img_rows; i++) {\n\t\t\t\tuchar* pframe = img_sample.ptr<uchar>(i);\n\t\t\t\tfor(int j = 0; j < img_cols; j++) {\n\t\t\t\t\tmat_sample(i*img_cols+j, class_idx*sample_num+sample_idx) = (double)pframe[j]/255.0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n//\tcout <<\tmat_sample.n_rows << endl << mat_sample.n_cols << endl << mat_sample(img_rows*img_cols/2, 0) << endl;\n\n\t//Calculate PCA transform matrix `mat_pca`.\n\n\tarma::mat H = mat_sample;\n\tarma::mat mean_x = arma::mean(mat_sample, 1);\n\n\tfor(int j = 0; j < class_num * sample_num; j++) {\n\t\tH.col(j) -= mean_x.col(0);\n\t}\n\tH *= 1.0/sqrt(sample_num-1);\n\n\tarma::mat Q, R;\n\tarma::qr_econ(Q, R, H);\n\n\tarma::mat U, V;\n\tarma::vec d;\n\tarma::svd_econ(U, d, V, R.t());\n\n//\tcout << \"d\" << endl << d << endl;\n\n//\tarma::rowvec vec_eigen = d.head(component_num).t();\n//\tcout << \"vec_eigen\" << endl << vec_eigen << endl;\n\n\tarma::mat V_h(V.n_rows, component_num);\n\tif(component_num == 1) {\n\t\tV_h = V.col(0);\n\t}else {\n\t\tV_h = V.cols(0, component_num-1);\n\t}\n\n\tarma::mat mat_pca = Q * V_h;\n\n\t//Calculate eigenfaces `mat_eigen_vec`.\n\n\tarma::mat mat_eigen = mat_pca.t() * mat_sample;\n//\tcout << \"mat_eigen\" << endl << mat_eigen << endl;\n\tarma::mat mat_eigen_vec(component_num, class_num, arma::fill::zeros);\n\tvector<arma::mat> mat_cov_list;\n\n\tfor(int class_idx = 0; class_idx < class_num; class_idx++) {\n\n\t\tarma::vec eigen_sum(component_num, arma::fill::zeros);\n\t\tfor(int sample_idx = 0; sample_idx < sample_num; sample_idx++) {\n\t\t\teigen_sum += mat_eigen.col(class_idx*sample_num+sample_idx);\n\t\t}\n\t\teigen_sum /= (double)sample_num;\n\t\tmat_eigen_vec.col(class_idx) = eigen_sum;\n\n\t\tmat_cov_list.push_back(arma::cov((mat_eigen.cols(class_idx*sample_num, class_idx*sample_num+sample_num-1)).t()));\n\n//\t\tcout << mat_cov_list[class_idx] << endl;\n\n\t}\n\n//\tcout << \"mat_eigen_vec\" << endl << mat_eigen_vec << endl;\n\n/*\n\tcout << \"dis within class\" << endl;\n\tfor(int class_idx = 0; class_idx < class_num; class_idx++) {\n\t\tfor(int sample_idx = 0; sample_idx < sample_num; sample_idx++) {\n\t\t\tdouble dis = calcuDistance(mat_eigen.col(class_idx*sample_num+sample_idx), mat_eigen_vec.col(class_idx), mat_cov_list[class_idx], distance_type::MAHALANOBIS);\n\t\t\tcout << dis << \" \";\n\t\t}\n\t\tcout << endl;\n\t}\n\n\tcout << \"dis between classes\" << endl;\n\tfor(int class_idx = 0; class_idx < class_num; class_idx++) {\n\t\tfor(int sample_idx = 0; sample_idx < class_num; sample_idx++) {\n\t\t\tdouble dis = calcuDistance(mat_eigen.col(sample_idx*sample_num), mat_eigen_vec.col(class_idx), mat_cov_list[class_idx], distance_type::MAHALANOBIS);\n\t\t\tcout << dis << \" \";\n\t\t}\n\t\tcout << endl;\n\t}\n*/\n\n\t//Classify new sample.\n\n\tint correct_count = 0;\n\n\tdouble max_dis = 0.0;\n\n\tfor(int class_idx = 0; class_idx < class_num; class_idx++){\n\t\tfor(int sample_idx = 0; sample_idx < sample_num; sample_idx++) {\n\t\t\tarma::mat mat_new_sample(img_rows*img_cols, 1);\n\n\t\t\tstring filename = orl_path + \"\\\\s\" + to_string(class_idx+1) + \"\\\\\" + to_string(sample_idx+1) + \".pgm\";\n\t\t\tcv::Mat img_new_frame = cv::imread(filename, CV_LOAD_IMAGE_GRAYSCALE);\n\t\t\tcv::Mat img_new_sample;\n\t\t\tcv::resize(img_new_frame, img_new_sample, sample_size);\n\n\t\t\tfor(int i = 0; i < img_rows; i++) {\n\t\t\t\tuchar* pframe = img_new_sample.ptr<uchar>(i);\n\t\t\t\tfor(int j = 0; j < img_cols; j++) {\n\t\t\t\t\tmat_new_sample(i*img_cols+j, 0) = (double)pframe[j]/255.0;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tarma::mat mat_new_eigen = mat_pca.t() * mat_new_sample;\n\n\t\t\tvector<pair<int, double>> dis_list;\n\t\t\tfor(int new_class_idx = 0; new_class_idx < class_num; new_class_idx++) {\n\t\t\t\tdouble dis = calcuDistance(mat_new_eigen.col(0), mat_eigen_vec.col(new_class_idx), mat_cov_list[new_class_idx], distance_type::MAHALANOBIS);\n\t\t\t\tdis_list.push_back(make_pair(new_class_idx, dis));\n\t\t\t}\n\t\t\tsort(dis_list.begin(), dis_list.end(), compDistance);\n\n\t\t\tif(dis_list[0].first == class_idx && dis_list[0].second <= distance_criterion[distance_type::MAHALANOBIS]) {\n\t\t\t\tcorrect_count++;\n\t\t\t}\n\n\t\t\tif(dis_list.back().second > max_dis) {\n\t\t\t\tmax_dis = dis_list.back().second;\n\t\t\t}\n\t\t}\n\t}\n\n\tcout << \"Maximum distance: \" << max_dis << endl;\n\n\tdouble correct_ratio = (double)correct_count / (class_num * sample_num);\n\tcout << \"Correctness ratio: \" << correct_ratio * 100.0 << \"%\" << endl;\n\n\tcin.get();\n\n\treturn 0;\n}\n\nbool compDistance(pair<int, double> a, pair<int, double> b) {\n\treturn (a.second < b.second);\n}\n\ndouble calcuDistance(const arma::vec vec1, const arma::vec vec2, distance_type dis_type) {\n\n\tif(dis_type == ECULIDEAN) {\n\t\treturn arma::norm(vec1-vec2, 2);\n\t}else if(dis_type == MANHATTAN) {\n\t\treturn arma::norm(vec1-vec2, 1);\n\t}else if(dis_type == MAHALANOBIS) {\n\t\tarma::mat tmp = (vec1-vec2).t() * (vec1 - vec2);\n\t\treturn sqrt(tmp(0,0));\n\t}\n\n\treturn -1.0;\n}\n\ndouble calcuDistance(const arma::vec vec1, const arma::vec vec2, const arma::mat cov2, distance_type dis_type) {\n\n\tif(dis_type == ECULIDEAN) {\n\t\treturn arma::norm(vec1-vec2, 2);\n\t}else if(dis_type == MANHATTAN) {\n\t\treturn arma::norm(vec1-vec2, 1);\n\t}else if(dis_type == MAHALANOBIS) {\n\t\tarma::mat tmp = (vec1-vec2).t() * cov2.i() * (vec1 - vec2);\n\t\treturn sqrt(tmp(0,0));\n\t}\n\n\treturn -1.0;\n}\n", "meta": {"hexsha": "e3d7f991d2a47187e7b440a387738a581d27b624", "size": 6869, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QR-PCA-FaceRec/QR-PCA-FaceRec.cpp", "max_stars_repo_name": "johnhany/QR-PCA-FaceRec", "max_stars_repo_head_hexsha": "7476f218d7c7d8ebfed9df5d2e195ae5c6444f0f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2016-05-10T14:29:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-05T10:17:17.000Z", "max_issues_repo_path": "QR-PCA-FaceRec/QR-PCA-FaceRec.cpp", "max_issues_repo_name": "johnhany/QR-PCA-FaceRec", "max_issues_repo_head_hexsha": "7476f218d7c7d8ebfed9df5d2e195ae5c6444f0f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-17T02:54:26.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-17T02:54:26.000Z", "max_forks_repo_path": "QR-PCA-FaceRec/QR-PCA-FaceRec.cpp", "max_forks_repo_name": "johnhany/QR-PCA-FaceRec", "max_forks_repo_head_hexsha": "7476f218d7c7d8ebfed9df5d2e195ae5c6444f0f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2016-05-10T14:40:55.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-31T05:26:08.000Z", "avg_line_length": 31.2227272727, "max_line_length": 161, "alphanum_fraction": 0.638520891, "num_tokens": 2070, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533107374444, "lm_q2_score": 0.7549149758396752, "lm_q1q2_score": 0.703922968546983}}
{"text": "#pragma once\n\n#include \"util/random.h\"\n\n#include \"util/point_util.h\"\n\n#include <boost/math/constants/constants.hpp>\n\nnamespace metternich {\n\ndouble random::generate_radian_angle()\n{\n\treturn random::generate_in_range(0., 1.) * 2. * boost::math::constants::pi<double>();\n}\n\nQPointF random::generate_circle_position()\n{\n\tconst double angle = random::generate_radian_angle();\n\treturn point::get_radian_angle_direction(angle);\n}\n\n}\n", "meta": {"hexsha": "9c3d9fcab9a498fb815142110b394d2ab44c211f", "size": 427, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "util/random.cpp", "max_stars_repo_name": "Andrettin/Metternich", "max_stars_repo_head_hexsha": "513a7d3cddacad5d5efd2fa5faeed03bc55a190c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2019-08-03T05:58:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T20:46:41.000Z", "max_issues_repo_path": "util/random.cpp", "max_issues_repo_name": "Andrettin/Metternich", "max_issues_repo_head_hexsha": "513a7d3cddacad5d5efd2fa5faeed03bc55a190c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-08-03T11:46:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-22T10:20:32.000Z", "max_forks_repo_path": "util/random.cpp", "max_forks_repo_name": "Andrettin/Metternich", "max_forks_repo_head_hexsha": "513a7d3cddacad5d5efd2fa5faeed03bc55a190c", "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.5652173913, "max_line_length": 86, "alphanum_fraction": 0.7470725995, "num_tokens": 98, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218305645895, "lm_q2_score": 0.7634837743174789, "lm_q1q2_score": 0.7038723588251321}}
{"text": "//\n// \tCopyright (c) 2018, Cem Bassoy, cem.bassoy@gmail.com\n// \tCopyright (c) 2019, Amit Singh, amitsingh19975@gmail.com\n//\n//  Distributed under the Boost Software License, Version 1.0. (See\n//  accompanying file LICENSE_1_0.txt or copy at\n//  http://www.boost.org/LICENSE_1_0.txt)\n//\n//  The authors gratefully acknowledge the support of\n//  Google and Fraunhofer IOSB, Ettlingen, Germany\n//\n\n\n#include <boost/numeric/ublas/tensor.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <iostream>\n\nint main()\n{\n  namespace ublas = boost::numeric::ublas;\n  using value   = float;\n  using layout  = ublas::layout::first_order; // storage format\n  using tensor  = ublas::tensor_dynamic<value,layout>;\n  using shape   = typename tensor::extents_type;\n  using matrix  = ublas::matrix<value,layout>;\n\n  constexpr auto ones = ublas::ones<value,layout>{};\n\n  // NOLINTNEXTLINE(google-build-using-namespace)\n  using namespace boost::numeric::ublas::index;\n\n  using namespace boost::numeric::ublas::index;\n  using tensor  = boost::numeric::ublas::tensor_dynamic<float>;\n  auto fones    = boost::numeric::ublas::ones<float>{};\n\n\n  tensor X = fones(3,4,5);\n  tensor Y = fones(4,6,3,2);\n\n  tensor Z = 2*ones(5,6,2) + X(_i,_j,_k)*Y(_j,_l,_i,_m) + 5;\n\n  // Matlab Compatible Formatted Output\n  std::cout << \"C=\" << Z << \";\" << std::endl;\n\n\n  // Tensor-Vector-Multiplications - Including Transposition\n  try {\n\n    auto n  = shape{3,4,2};\n\n    tensor A  = ones(n);\n    matrix B1 = 2*matrix(n[1],n[2]);\n    tensor v1 = 2*ones(n[0],1);\n    tensor v2 = 2*ones(n[1],1);\n    //      auto v3 = tensor(shape{n[2],1},2);\n\n    // C1(j,k) = B1(j,k) + A(i,j,k)*v1(i);\n    // tensor C1 = B1 + prod(A,vector_t(n[0],1),1);\n    tensor C1 = B1 + A(_i,_,_) * v1(_i,_);\n\n    // C2(i,k) = A(i,j,k)*v2(j) + 4;\n    //tensor C2 = prod(A,vector_t(n[1],1),2) + 4;\n    tensor C2 = A(_,_i,_) * v2(_i,_) + 4;\n\n    // not yet implemented!\n    // C3() = A(i,j,k)*T1(i)*T2(j)*T2(k);\n        // tensor C3 = prod(prod(prod(A,v1,1),v2,1),v3,1);\n    // tensor C3 = A(_i,_j,_k) * v1(_i,_) * v2(_j,_) * v3(_k,_);\n\n    // formatted output\n    std::cout << \"% --------------------------- \" << std::endl;\n    std::cout << \"% --------------------------- \" << std::endl << std::endl;\n    std::cout << \"% C1(j,k) = B1(j,k) + A(i,j,k)*v1(i);\" << std::endl << std::endl;\n    std::cout << \"C1=\" << C1 << \";\" << std::endl << std::endl;\n\n    // formatted output\n    std::cout << \"% --------------------------- \" << std::endl;\n    std::cout << \"% --------------------------- \" << std::endl << std::endl;\n    std::cout << \"% C2(i,k) = A(i,j,k)*v2(j) + 4;\" << std::endl << std::endl;\n    std::cout << \"C2=\" << C2 << \";\" << std::endl << std::endl;\n\n  } catch (const std::exception& e) {\n    std::cerr << \"Cought exception \" << e.what();\n    std::cerr << \"in the main function of multiply-tensor-einstein-notation when doing tensor-vector multiplication.\" << std::endl;\n  }\n\n  // Tensor-Matrix-Multiplications - Including Transposition\n  try {\n    auto n  = shape{3,4,2};\n    auto m  = 5u;\n    tensor A  = 2*ones(n);\n    tensor B  = 2*ones(n[1],n[2],m);\n    tensor B1 =   ones(m,n[0]);\n    tensor B2 =   ones(m,n[1]);\n\n\n    // C1(l,j,k) = B(j,k,l) + A(i,j,k)*B1(l,i);\n    // tensor C1 = B + prod(A,B1,1);\n    tensor C1 = B + A(_i,_,_) * B1(_,_i);\n\n    // C2(i,l,k) = A(i,j,k)*B2(l,j) + 4;\n    // tensor C2 = prod(A,B2) + 4;\n    tensor C2 =  A(_,_j,_) * B2(_,_j) + 4;\n\n    // C3(i,l1,l2) = A(i,j,k)*T1(l1,j)*T2(l2,k);\n    // not yet implemented.\n\n    // formatted output\n    std::cout << \"% --------------------------- \" << std::endl;\n    std::cout << \"% --------------------------- \" << std::endl << std::endl;\n    std::cout << \"% C1(l,j,k) = B(j,k,l) + A(i,j,k)*B1(l,i);\" << std::endl << std::endl;\n    std::cout << \"C1=\" << C1 << \";\" << std::endl << std::endl;\n\n    // formatted output\n    std::cout << \"% --------------------------- \" << std::endl;\n    std::cout << \"% --------------------------- \" << std::endl << std::endl;\n    std::cout << \"% C2(i,l,k) = A(i,j,k)*B2(l,j) + 4;\" << std::endl << std::endl;\n    std::cout << \"C2=\" << C2 << \";\" << std::endl << std::endl;\n\n    // formatted output\n    //        std::cout << \"% --------------------------- \" << std::endl;\n    //        std::cout << \"% --------------------------- \" << std::endl << std::endl;\n    //        std::cout << \"% C3(i,l1,l2) = A(i,j,k)*T1(l1,j)*T2(l2,k);\" << std::endl << std::endl;\n    //        std::cout << \"C3=\" << C3 << \";\" << std::endl << std::endl;\n  } catch (const std::exception& e) {\n    std::cerr << \"Cought exception \" << e.what();\n    std::cerr << \"in the main function of multiply-tensor-einstein-notation when doing tensor-matrix multiplication.\" << std::endl;\n  }\n\n\n  // Tensor-Tensor-Multiplications Including Transposition\n  try {\n    auto na = shape{3,4,5};\n    auto nb = shape{4,6,3,2};\n    tensor A  = 2*ones(na);\n    tensor B  = 3*ones(nb);\n    tensor T1 = 2*ones(na[2],na[2]);\n    tensor T2 = 2*ones(na[2],nb[1],nb[3]);\n\n\n    // C1(j,l) = T1(j,l) + A(i,j,k)*A(i,j,l) + 5;\n    // tensor C1 = T1 + prod(A,A,perm_t{1,2}) + 5;\n    tensor C1 = T1 + A(_i,_j,_m)*A(_i,_j,_l) + 5;\n\n    // formatted output\n    std::cout << \"% --------------------------- \" << std::endl;\n    std::cout << \"% --------------------------- \" << std::endl << std::endl;\n    std::cout << \"% C1(k,l) = T1(k,l) + A(i,j,k)*A(i,j,l) + 5;\" << std::endl << std::endl;\n    std::cout << \"C1=\" << C1 << \";\" << std::endl << std::endl;\n\n\n    // C2(k,l,m) = T2(k,l,m) + A(i,j,k)*B(j,l,i,m) + 5;\n    //tensor C2 = T2 + prod(A,B,perm_t{1,2},perm_t{3,1}) + 5;\n    tensor C2 = T2 + A(_i,_j,_k)*B(_j,_l,_i,_m) + 5;\n\n    // formatted output\n    std::cout << \"% --------------------------- \" << std::endl;\n    std::cout << \"% --------------------------- \" << std::endl << std::endl;\n    std::cout << \"%  C2(k,l,m) = T2(k,l,m) + A(i,j,k)*B(j,l,i,m) + 5;\" << std::endl << std::endl;\n    std::cout << \"C2=\" << C2 << \";\" << std::endl << std::endl;\n\n  } catch (const std::exception& e) {\n    std::cerr << \"Cought exception \" << e.what();\n    std::cerr << \"in the main function of multiply-tensor-einstein-notation when doing transpose.\" << std::endl;\n  }\n}\n", "meta": {"hexsha": "c7ba3c2c61a6ecd1233d1f74c316009dd091e830", "size": 6178, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/tensor/multiply_tensors_einstein_notation.cpp", "max_stars_repo_name": "samd2/ublas", "max_stars_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 96.0, "max_stars_repo_stars_event_min_datetime": "2015-01-23T10:15:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T18:31:02.000Z", "max_issues_repo_path": "examples/tensor/multiply_tensors_einstein_notation.cpp", "max_issues_repo_name": "samd2/ublas", "max_issues_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 105.0, "max_issues_repo_issues_event_min_datetime": "2015-01-14T09:01:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-05T06:10:39.000Z", "max_forks_repo_path": "examples/tensor/multiply_tensors_einstein_notation.cpp", "max_forks_repo_name": "samd2/ublas", "max_forks_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 157.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T13:35:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T11:12:27.000Z", "avg_line_length": 36.7738095238, "max_line_length": 131, "alphanum_fraction": 0.500485594, "num_tokens": 2135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218262741297, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.7038723406652108}}
{"text": "#include <state_estimation/utilities/plotting_utilities.h>\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n\nnamespace state_estimation {\n\nstd::vector<Eigen::Vector2d> getEllipsePoints(double a, double b, const Eigen::Vector2d& offset,\n                                              double angle, uint32_t num_pts) {\n    std::vector<Eigen::Vector2d> pts(num_pts);\n\n    // Sample the points evenly with respect to angle around the ellipse\n    const Eigen::Rotation2D<double> R(angle);\n    for (int i = 0; i < num_pts; ++i) {\n        const double theta = i * 2.0 * M_PI / num_pts;\n\n        const Eigen::Vector2d pos(a * cos(theta), b * sin(theta));\n        pts[i] = R * pos + offset;\n    }\n\n    return pts;\n}\n\nstd::vector<Eigen::Vector2d> get2DCovarianceEllipsePoints(const Eigen::Matrix2d& cov,\n                                                          const Eigen::Vector2d& offset,\n                                                          uint32_t num_pts) {\n    // Get the eigen vectors\n    Eigen::SelfAdjointEigenSolver<Eigen::Matrix<double, 2, 2>> solver(cov);\n    Eigen::Matrix<double, 2, 2> vectors = solver.eigenvectors();\n    Eigen::Matrix<double, 2, 1> values = solver.eigenvalues();\n\n    // The major axis corresponds to the first eigen vector, and the orientation of the ellipse is\n    // the directory of the first eigen vector\n    const double a = values(0);\n    const double b = values(1);\n    const double angle = atan2(vectors(1, 0), vectors(0, 0));\n    return getEllipsePoints(a, b, offset, angle, num_pts);\n}\n\n}  // namespace state_estimation\n", "meta": {"hexsha": "2b0c2bd70d31b430d7ccd794f6b373a1b984299d", "size": 1561, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/utilities/plotting_utilities.cpp", "max_stars_repo_name": "MarbleInc/state_estimation", "max_stars_repo_head_hexsha": "05b3f0bbceda695b4420594ac9ff3cd22001a577", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-05T06:19:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-05T06:19:45.000Z", "max_issues_repo_path": "src/utilities/plotting_utilities.cpp", "max_issues_repo_name": "stevendaniluk/state_estimation", "max_issues_repo_head_hexsha": "05b3f0bbceda695b4420594ac9ff3cd22001a577", "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/utilities/plotting_utilities.cpp", "max_forks_repo_name": "stevendaniluk/state_estimation", "max_forks_repo_head_hexsha": "05b3f0bbceda695b4420594ac9ff3cd22001a577", "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.025, "max_line_length": 98, "alphanum_fraction": 0.6175528507, "num_tokens": 391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094174159129, "lm_q2_score": 0.7879311956428946, "lm_q1q2_score": 0.7038663573435778}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  MatrixXd X = MatrixXd::Random(4,4);\nMatrixXd A = X * X.transpose();\ncout << \"Here is a random positive-definite matrix, A:\" << endl << A << endl << endl;\n\nSelfAdjointEigenSolver<MatrixXd> es(A);\ncout << \"The inverse square root of A is: \" << endl;\ncout << es.operatorInverseSqrt() << endl;\ncout << \"We can also compute it with operatorSqrt() and inverse(). That yields: \" << endl;\ncout << es.operatorSqrt().inverse() << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "ee764679e3a711b794deef1262298694e4374a01", "size": 577, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_SelfAdjointEigenSolver_operatorInverseSqrt.cpp", "max_stars_repo_name": "TANHAIYU/Self-calibration-using-Homography-Constraints", "max_stars_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-03-17T16:34:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-17T18:30:13.000Z", "max_issues_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_SelfAdjointEigenSolver_operatorInverseSqrt.cpp", "max_issues_repo_name": "TANHAIYU/planecalib", "max_issues_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "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": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_SelfAdjointEigenSolver_operatorInverseSqrt.cpp", "max_forks_repo_name": "TANHAIYU/planecalib", "max_forks_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "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": 26.2272727273, "max_line_length": 90, "alphanum_fraction": 0.6707105719, "num_tokens": 155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.893309411735131, "lm_q2_score": 0.7879311931529758, "lm_q1q2_score": 0.7038663506432447}}
{"text": "#include \"main.hpp\"\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <limits>\n#include <mimkl/data_structures.hpp>\n#include <mimkl/definitions.hpp>\n#include <mimkl/io.hpp>\n#include <mimkl/kernels.hpp>\n#include <mimkl/linear_algebra.hpp>\n#include <mimkl/models/easy_mkl.hpp>\n#include <mimkl/solvers/komd.hpp>\n#include <mimkl/utilities.hpp>\n#include <numeric>\n#include <spdlog/fmt/ostr.h>\n#include <spdlog/spdlog.h>\n\nusing dlib::mat;\nusing mimkl::data_structures::DataFrame;\nusing mimkl::data_structures::indexing_from_vector;\nusing mimkl::data_structures::range;\nusing mimkl::definitions::Indexing;\nusing mimkl::utilities::check_invocable;\nusing mimkl::utilities::print_type;\n\n//#define SPDLOG_DEBUG_ON\n//#define SPDLOG_TRACE_ON\n\n// Compile time log levels\n// define SPDLOG_DEBUG_ON or SPDLOG_TRACE_ON\n// SPDLOG_TRACE(console, \"Enabled only #ifdef SPDLOG_TRACE_ON..{} ,{}\",\n// 1, 3.23);  SPDLOG_DEBUG(console, \"Enabled only #ifdef SPDLOG_DEBUG_ON.. {}\n// ,{}\", 1, 3.23);\n\nint main(int argc, char **argv)\n{\n\n    // Runtime log levels\n    spdlog::set_level(spdlog::level::trace); // Set global log level to info\n    auto console = spdlog::stdout_color_mt(\"console\");\n\n    const Index rows = 6; // 3 to reproduce single member in class  error\n    const Index dims = 2;\n\n    MATRIX(double) X(rows, 2);\n    //\tX << 1., 1., 3., 1., 1., 2.;\n    X << 1., 1., 3., 1., 1., 4., 3., 2., 1., -1., 3., -1.;\n    console->info(\"X\\n{}\", X);\n\n    std::vector<std::string> labels;\n    labels.reserve(rows);\n    labels.push_back(\"a\");\n    labels.push_back(\"b\");\n    labels.push_back(\"a\");\n    labels.push_back(\"b\");\n    labels.push_back(\"c\");\n    labels.push_back(\"c\");\n\n    Eigen::SparseMatrix<double> L(2, 2);\n    mimkl::linear_algebra::fill_sparse_diagonal(L, 1.0);\n\n    Eigen::SparseMatrix<double> L1(dims, dims);\n    typedef Eigen::Triplet<double> TripletDouble; // (row,col,coef)\n    std::vector<TripletDouble> triplet_list;\n    triplet_list.reserve(4);\n    triplet_list.push_back(TripletDouble(0, 1, 1.));\n    //  triplet_list.push_back(TripletDouble(1, 2, 1.));\n    triplet_list.push_back(TripletDouble(1, 0, 1.));\n    //  triplet_list.push_back(TripletDouble(2, 1, 1.));\n    L1.setFromTriplets(triplet_list.begin(), triplet_list.end());\n\n    std::vector<Eigen::SparseMatrix<double>> inducer_vec;\n    inducer_vec.reserve(2);\n    inducer_vec.push_back(L);\n    inducer_vec.push_back(L1);\n\n    typedef std::function<MATRIX(double)(const MATRIX(double) &, const MATRIX(double) &,\n                                         const Eigen::SparseMatrix<double>)>\n    InducerFunction;\n    typedef std::function<MATRIX(double)(const MATRIX(double) &,\n                                         const MATRIX(double) &)>\n    InducedFunction;\n\n    const double degree = 1.;\n    const double offset = 0.;\n\n    auto lambda_logger = spdlog::stdout_color_mt(\"lambda\");\n    InducerFunction k_poly =\n    [degree, offset](const MATRIX(double) & lhs, const MATRIX(double) & rhs,\n                     const Eigen::SparseMatrix<double> inducer) {\n        //\t spdlog::get(\"lambda\")->debug(\"before actual inducer function\n        // call\" \t\t\t \"lhs rows {}  cols {} \\n\"\n        //\t\t\t \"rhs rows {}  cols {} \\n\"\n        //\t\t\t \"kernel rows {}  cols {} \\n\"\n        //\t\t\t \"inducer rows {}  cols {} \\n\",\n        //\t\t\t lhs.rows(), lhs.cols(),\n        //\t\t\t rhs.rows(), rhs.cols(),\n        //\t\t\t kernel_matrix.rows(), kernel_matrix.cols(),\n        //\t\t\t inducer.rows(), inducer.cols()\n        //\t\t\t );\n        return mimkl::induction::induce_polynomial_kernel<MATRIX(double)>(\n        lhs, rhs, inducer, degree, offset);\n    };\n\n    MATRIX(double) K(rows, rows);\n    console->info(\"\\e[1;32mtype: \\e[0m \\n{}\",\n                  print_type<decltype(k_poly(X, X, L))>());\n    console->info(\"\\e[1;32mtype: \\e[0m \\n{}\", print_type(k_poly));\n    console->info(\"check_invocable? {}\", check_invocable(k_poly));\n\n    std::vector<InducedFunction> function_vec =\n    mimkl::induction::inducer_combination(k_poly, inducer_vec);\n    //// \t==inducer_combination:\n    //\t  for (Eigen::SparseMatrix<double> inducer : inducer_vec) {\n    //\t\t  function_vec.push_back(\n    //\t\t\t[&,inducer](const MATRIX(double) &lhs,\n    //\t\t\t\t\t  const MATRIX(double)&rhs,\n    //\t\t\t\t\t  const MATRIX(double) &kernel_matrix) {\n    //\t\t\t  k_poly(lhs, rhs, kernel_matrix, inducer);\n    //\t\t\t});\n    //\n    //\t  }\n    std::vector<MATRIX(double)> kernel_vec;\n    kernel_vec.reserve(2);\n\n    MATRIX(double) K2 = function_vec[0](X, X);\n    console->info(\"a kernel from function (linear kernel with identity):\\n{}\",\n                  K2);\n    kernel_vec.push_back(K2);\n\n    MATRIX(double) K_norm = mimkl::linear_algebra::normalize_kernel(K2);\n    console->info(\"normalized above kernel:\\n{}\", K_norm);\n\n    MATRIX(double) X_norm = X;\n    X_norm.rowwise().normalize();\n    console->info(\"normalized above kernel by means of centralizing the \"\n                  \"original \"\n                  \"data (works for linear kernel as feature space is original \"\n                  \"space):\\n{}\",\n                  function_vec[0](X_norm, X_norm));\n    console->trace(\"where the normalized data is:\\n{}\", X_norm);\n\n    assert(((K_norm - function_vec[0](X_norm, X_norm)).norm() <= 0.0000001) &&\n           \"normalize_kernels not equal to normalization in original space for \"\n           \"linear kernel\");\n\n    assert(\n    ((K_norm - mimkl::linear_algebra::normalize_kernel_prediction(K2, K2, K2))\n     .norm() == 0.0) &&\n    \"normalize_kernels not equal to normalize_kernels_prediction\");\n\n    MATRIX(double) K_center = mimkl::linear_algebra::centralize_kernel(K2);\n    console->info(\"centralized above kernel:\\n{}\", K_center);\n\n    MATRIX(double) X_center = X;\n    X_center = X.rowwise() - X.colwise().mean(); // in each dimension remove mean\n    console->info(\"centralized above kernel by means of centralizing the \"\n                  \"original data (works for linear kernel as feature space is \"\n                  \"original space):\\n{}\",\n                  function_vec[0](X_center, X_center));\n    console->trace(\"where the centered data is:\\n{}\", X_center);\n\n    assert(\n    ((K_center - function_vec[0](X_center, X_center)).norm() == 0.0) &&\n    \"centralize_kernels not equal to centralization in original space for \"\n    \"linear kernel\");\n\n    console->info(\"centralized normalized_kernel:\\n{}\",\n                  mimkl::linear_algebra::centralize_kernel(K_norm));\n    console->info(\"normalized centralized_kernel:\\n{}\",\n                  mimkl::linear_algebra::normalize_kernel(K_center));\n\n    MATRIX(double) K3 = function_vec[1](X, X);\n    console->info(\"another kernel from function:\\n{}\", K3);\n    kernel_vec.push_back(K3);\n\n    MATRIX(double) kernel_sum_reference(rows, rows);\n    kernel_sum_reference << 4., 8., 10., 10., 0., 4., 8., 16., 20., 20., 0., 8.,\n    10., 20., 25., 25., 0., 10., 10., 20., 25., 25., 0., 10., 0., 0., 0., 0.,\n    0., 0., 4., 8., 10., 10., 0., 4.;\n    // TODO normalize samples/Kernel/kernel_trace/...\n\n    spdlog::stdout_color_mt(\"lin_alg\");\n\n    COLUMN(double) c = COLUMN(double)::Constant(function_vec.size(), 1);\n    MATRIX(double)\n    kernel_weighted_sum =\n    mimkl::linear_algebra::aggregate_weighted_kernels(X, X, function_vec, c);\n    MATRIX(double)\n    kernel_sum = mimkl::linear_algebra::aggregate_kernels(X, X, function_vec);\n    console->trace(\"sum of kernels:\\n{}\", kernel_sum);\n    console->trace(\"sum of (same) weighted kernels:\\n{}\", kernel_weighted_sum);\n\n    assert(((kernel_sum_reference - kernel_sum).norm() == 0.0) &&\n           \"aggregate_kernels\");\n    assert(((kernel_sum_reference - kernel_weighted_sum).norm() == 0.0) &&\n           \"aggregate_weighted_kernels\");\n\n    //  test mapping\n\n    double pi = 3.14159265358979323846; // std::atan(1.)*4. ;\n    console->info(\n    \"testing/debugging the mapping between eigen and dlib, pi: {}\", pi);\n    COLUMN(double) to_map = COLUMN(double)::Constant(4, pi);\n    console->info(\"initial (to_map):\\n{}\\n sum: {}\", to_map, to_map.sum());\n    dlib::matrix<double, 0, 1> mapped = dlib::mat(to_map);\n    change_dlib_mat(mapped);\n    console->info(\"mapped and assigned to dlib (mapped):\\n{}\\n sum: {}\", mapped,\n                  dlib::sum(mapped));\n    console->info(\"change in original? (to_map):\\n{}\\n sum: {}\", to_map,\n                  to_map.sum());\n    //  change_dlib_mat(dlib::mat(to_map));\n    //  console->info(\"change in original when mapping changed without\n    //  assignment?\n    //  (to_map):\\n{}\\n sum: {}\", to_map, to_map.sum());\n\n    COLUMN(double) back_mapped = mimkl::linear_algebra::dlib_to_eigen(mapped);\n    console->info(\"backmapped with assignment (back_mapped):\\n{}\\n sum: {}\",\n                  back_mapped, back_mapped.sum());\n\n    MATRIX(double) M;\n    mimkl::linear_algebra::squared_euclidean_distances(X, M);\n    M = M.array().sqrt();\n    console->info(\"euclidean distances:\\n{}\", M);\n\n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "907445a5a2b4e965852e0d549311cc4e32fe1487", "size": 8842, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/linear_algebra/main.cpp", "max_stars_repo_name": "vishalbelsare/mimkl", "max_stars_repo_head_hexsha": "53a5a9db5aa09c6e8808ba5b845601c5768d23e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2019-05-28T23:18:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T20:00:03.000Z", "max_issues_repo_path": "test/linear_algebra/main.cpp", "max_issues_repo_name": "vishalbelsare/mimkl", "max_issues_repo_head_hexsha": "53a5a9db5aa09c6e8808ba5b845601c5768d23e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2019-05-18T13:21:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T22:20:55.000Z", "max_forks_repo_path": "test/linear_algebra/main.cpp", "max_forks_repo_name": "vishalbelsare/mimkl", "max_forks_repo_head_hexsha": "53a5a9db5aa09c6e8808ba5b845601c5768d23e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2019-07-24T09:39:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-29T14:40:27.000Z", "avg_line_length": 38.9515418502, "max_line_length": 88, "alphanum_fraction": 0.6263288849, "num_tokens": 2413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093946927837, "lm_q2_score": 0.7879311956428946, "lm_q1q2_score": 0.7038663394393155}}
{"text": "#include <boost/test/unit_test.hpp>\n#include <ayla/thread_pool.hpp>\n\n#include <iostream>\n\nBOOST_AUTO_TEST_SUITE(ayla)\nBOOST_AUTO_TEST_SUITE(thread_pool)\n\nnamespace {\n\tSizeType _factorial(SizeType n) {\n\t\tif (n == 0u) {\n\t\t\treturn 1u;\n\t\t}\n\n\t\treturn n*_factorial(n-1);\n\t}\n}\n\nclass FactorialCalculator final : public ThreadPool::Task {\npublic:\n\tFactorialCalculator(SizeType n)\n\t\t: _n(n), _result(0u)\n\t{ }\n\n\tvirtual void execute() override {\n\t\t_result = _factorial(_n);\n\t}\n\n\tinline SizeType getResult() { return _result; }\n\tinline SizeType getN() const { return _n; }\n\nprivate:\n\tSizeType _n;\n\tSizeType _result;\n};\n\n\nBOOST_AUTO_TEST_CASE( factorialTest ) {\n\tBOOST_CHECK(_factorial(0) == 1);\n\tBOOST_CHECK(_factorial(5) == 120);\n\tBOOST_CHECK(_factorial(6) == 720);\n\t\n\tconst SizeType numOfTasks = 12u;\n\n\tThreadPool::TasksGroup group;\n\tThreadPool pool;\n\t\n\t// create tasks group\n\tfor (SizeType i = 0u; i < numOfTasks; ++i) {\n\t\tgroup.push_back(std::make_unique<FactorialCalculator>(rand() % numOfTasks));\n\t}\n\n\t// force the same execution some times\n\tfor (SizeType i = 0u; i < 7u; ++i) {\n\t\tpool.execute(group);\n\t}\n\n\t// check results\n\tfor (auto it = group.begin(); it != group.end(); ++it) {\n\t\tconst auto task = static_cast<FactorialCalculator*>(it->get());\n\t\tBOOST_CHECK(_factorial(task->getN()) == task->getResult());\n\t}\n}\n\n////////////////////////////////////////////////////////////////////\n\n#define MATRIX_ORDER 100\n#define MAX_MATRIX_VALUE 100\n#define MIN_MATRIX_VALUE -100\n\ntypedef std::vector<std::vector<Float> > TestMatrix;\n\nvoid printM(const TestMatrix& m) {\n\tfor (SizeType i = 0u; i < MATRIX_ORDER; ++i) {\n\t\tfor (SizeType j = 0u; j < MATRIX_ORDER; ++j) {\n\t\t\tstd::cout << m[i][j] << \" \";\n\t\t}\n\t\t\n\t\tstd::cout << std::endl;\n\t}\n\t\n\tstd::cout << std::endl;\n}\n\nFloat multiplyRowColumn(const TestMatrix& mA, SizeType aRow, const TestMatrix& mB, SizeType bCol) {\n\tFloat sum = 0.0f;\n\t\n\tfor (SizeType k = 0u; k < MATRIX_ORDER; ++k) {\n\t\tsum += mA[aRow][k] * mB[k][bCol];\n\t}\n\t\n\treturn sum;\n}\n\nvoid multiply(const TestMatrix& mA, const TestMatrix& mB, TestMatrix& result) {\n\tfor (SizeType i = 0u; i < MATRIX_ORDER; ++i) {\n\t\tfor (SizeType j = 0u; j < MATRIX_ORDER; ++j) {\t\t\n\t\t\tresult[i][j] = multiplyRowColumn(mA, i, mB, j);\n\t\t}\n\t}\n}\n\nclass ParallelMatrixMult : public ThreadPool::Task {\npublic:\n\tParallelMatrixMult(const TestMatrix& mA, SizeType aRow, const TestMatrix& mB, SizeType bCol, TestMatrix& result)\n\t\t: mA(mA), mB(mB), result(result), aRow(aRow), bCol(bCol)\n\t{ }\n\n\tvirtual void execute() {\n\t\tresult[aRow][bCol] = multiplyRowColumn(mA, aRow, mB, bCol);\n\t}\n\nprivate:\n\tconst TestMatrix& mA;\n\tconst TestMatrix& mB;\n\tTestMatrix& result;\n\t\n\tSizeType aRow, bCol;\n};\n\nBOOST_AUTO_TEST_CASE( matrixMultiplicationTest ) {\n\t// initialize matrices and other data:\n\t\n\tTestMatrix m0( MATRIX_ORDER, std::vector<Float>(MATRIX_ORDER, 0.0f) );\n\tTestMatrix m1( MATRIX_ORDER, std::vector<Float>(MATRIX_ORDER, 0.0f) );\n\tTestMatrix r( MATRIX_ORDER, std::vector<Float>(MATRIX_ORDER, 0.0f) ); // multiplication result\n\tTestMatrix mt_r( MATRIX_ORDER, std::vector<Float>(MATRIX_ORDER, 0.0f) ); // multithread multiplication result\n\t\n\tfor (SizeType i = 0u; i < MATRIX_ORDER; ++i) { // initialize matrices\n\t\tfor (SizeType j = 0u; j < MATRIX_ORDER; ++j) {\n\t\t\tm0[i][j] = Float(MIN_MATRIX_VALUE + ( rand()%(MAX_MATRIX_VALUE-MIN_MATRIX_VALUE) ));\n\t\t\tm1[i][j] = Float(MIN_MATRIX_VALUE + ( rand()%(MAX_MATRIX_VALUE-MIN_MATRIX_VALUE) ));\n\t\t}\n\t}\n\t\t\n\t// initialize thread pool:\n\t\n\tThreadPool pool(5u);\n\tBOOST_CHECK_EQUAL(pool.getNumberOfThreads(), 5u);\n\n\tThreadPool::TasksGroup group;\n\t\t\n\tfor (SizeType i = 0u; i < MATRIX_ORDER; ++i) { // initialize matrices\n\t\tfor (SizeType j = 0u; j < MATRIX_ORDER; ++j) {\n\t\t\tgroup.push_back(std::make_unique<ParallelMatrixMult>(m0, i, m1, j, mt_r));\n\t\t}\n\t}\n\t\n\tfor (SizeType i = 0u; i < 3u; ++i) { // force same execution some times\n\t\t// run serial:\n\t\tmultiply(m0, m1, r);\n\t\t\n\t\t// run parallel:\n\t\tpool.execute(group);\n\t\t\n\t\t// compare serial and multithread results:\n\t\tfor (SizeType i = 0u; i < MATRIX_ORDER; ++i) { // initialize matrices\n\t\t\tfor (SizeType j = 0u; j < MATRIX_ORDER; ++j) {\n\t\t\t\tBOOST_CHECK( mt_r[i][j] == r[i][j] );\t\t\n\t\t\t}\n\t\t}\n\t}\n\t\n\t// printM(m0);\n\t// printM(m1);\n\t// printM(r);\n\t// printM(mt_r);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "28bd51f0649764d74f00cf56e9b08180dc4c1992", "size": 4259, "ext": "cc", "lang": "C++", "max_stars_repo_path": "epoch/ayla/tests/thread_pool.cc", "max_stars_repo_name": "oprogramadorreal/vize", "max_stars_repo_head_hexsha": "042c16f96d8790303563be6787200558e1ec00b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 47.0, "max_stars_repo_stars_event_min_datetime": "2020-03-30T14:36:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T07:44:54.000Z", "max_issues_repo_path": "epoch/ayla/tests/thread_pool.cc", "max_issues_repo_name": "oprogramadorreal/vize", "max_issues_repo_head_hexsha": "042c16f96d8790303563be6787200558e1ec00b2", "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": "epoch/ayla/tests/thread_pool.cc", "max_forks_repo_name": "oprogramadorreal/vize", "max_forks_repo_head_hexsha": "042c16f96d8790303563be6787200558e1ec00b2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2020-04-01T01:22:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-02T13:06:09.000Z", "avg_line_length": 24.761627907, "max_line_length": 113, "alphanum_fraction": 0.6597792909, "num_tokens": 1315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7038648780842074}}
{"text": "/**\n * @file burgersequation.cc\n * @brief NPDE homework BurgersEquation code\n * @author Oliver Rietmann\n * @date 15.04.2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"burgersequation.h\"\n\n#include <Eigen/Core>\n#include <cmath>\n\nnamespace BurgersEquation {\n/* SAM_LISTING_BEGIN_1 */\nconstexpr double PI = 3.14159265358979323846;\n\ndouble Square(double x) { return x * x; }\n\ndouble w0(double x) {\n  return 0.0 <= x && x <= 1.0 ? Square(std::sin(PI * x)) : 0.0;\n}\n\ndouble f(double x) { return 2.0 / 3.0 * std::sqrt(x * x * x); }\n\nEigen::VectorXd solveBurgersGodunov(double T, unsigned int N) {\n  double h = 5.0 / N;           // meshwidth\n  double tau = h;               // timestep = meshwidth by CFL condition\n  int m = std::round(T / tau);  // no. of timesteps\n\n  // initialize vector with initial nodal values\n  Eigen::VectorXd x = Eigen::VectorXd::LinSpaced(N + 1, -1.0, 4.0);\n  Eigen::VectorXd mu = x.unaryExpr(&w0);\n\n#if SOLUTION\n  for (int i = 0; i < m; ++i) {\n    for (int j = N; 0 < j; --j) {\n      // Standard fully discrete evolution based on explicit Euler timestepping\n      mu(j) = mu(j) - tau / h * (f(mu(j)) - f(mu(j - 1)));\n    }\n    // truncation to a finite vector. Only required on one side, because all\n    // information flows from left to right.\n    mu(0) = 0.0;  // Value of u0 to the left of x=0\n  }\n#else\n  //====================\n  // Your code goes here\n  //====================\n#endif\n\n  return mu;\n}\n/* SAM_LISTING_END_1 */\n\n/**\n * @brief Converts a large vector on  a grid to a smaller vector correponding to\n * a sub-grid.\n *\n * @param mu vector of function values on a spacial grid of size N_large\n * @param N divides the size N_large of mu\n * @return a vector mu_sub of size N, that represents mu on a sub-grid of size N\n */\n/* SAM_LISTING_BEGIN_2 */\nEigen::VectorXd reduce(const Eigen::VectorXd &mu, unsigned int N) {\n  Eigen::VectorXd mu_sub(N + 1);\n  int fraction = mu.size() / N;\n  for (int j = 0; j < N + 1; ++j) {\n    mu_sub(j) = mu(j * fraction);\n  }\n  return mu_sub;\n}\n\nEigen::Matrix<double, 3, 4> numexpBurgersGodunov() {\n  const unsigned int N_large = 3200;\n  Eigen::Vector2d T{0.3, 3.0};\n  Eigen::Vector4i N{5 * 10, 5 * 20, 5 * 40, 5 * 80};\n  Eigen::Vector4d h;\n  for (int i = 0; i < 4; ++i) h(i) = 5.0 / N(i);\n\n  Eigen::Matrix<double, 3, 4> result;\n  result.row(0) = h.transpose();\n\n#if SOLUTION\n  for (int k = 0; k < 2; ++k) {\n    Eigen::VectorXd mu_ref = solveBurgersGodunov(T(k), N_large);\n    Eigen::Vector4d error;\n    for (int i = 0; i < 4; ++i) {\n      Eigen::VectorXd mu = solveBurgersGodunov(T(k), N(i));\n      Eigen::VectorXd mu_ref_sub = reduce(mu_ref, N(i));\n      error(i) = h(i) * (mu - mu_ref_sub).lpNorm<1>();\n    }\n    result.row(k + 1) = error.transpose();\n  }\n#else\n  //====================\n  // Your code goes here\n  //====================\n#endif\n\n  return result;\n}\n/* SAM_LISTING_END_2 */\n\n}  // namespace BurgersEquation\n", "meta": {"hexsha": "442a72b0c1f3a3d88f63179cd1b9e0cc82110a13", "size": 2895, "ext": "cc", "lang": "C++", "max_stars_repo_path": "developers/BurgersEquation/mastersolution/burgersequation.cc", "max_stars_repo_name": "padomu/NPDECODES", "max_stars_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "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": "developers/BurgersEquation/mastersolution/burgersequation.cc", "max_issues_repo_name": "padomu/NPDECODES", "max_issues_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "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": "developers/BurgersEquation/mastersolution/burgersequation.cc", "max_forks_repo_name": "padomu/NPDECODES", "max_forks_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "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.5714285714, "max_line_length": 80, "alphanum_fraction": 0.5989637306, "num_tokens": 943, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324713956856, "lm_q2_score": 0.8633916099737806, "lm_q1q2_score": 0.703864875981225}}
{"text": "//\n// Created by philipp on 22.12.19.\n//\n\n#ifndef FUNNELS_CPP_LYAPUNOV_HH\n#define FUNNELS_CPP_LYAPUNOV_HH\n\n#include <iostream>\n\n#include <Eigen/Core>\n#include <Eigen/Cholesky>\n#include <cmath>\n#include <memory>\n\nnamespace lyapunov{\n  \n  \n  template <class DERIVED>\n  double projected_max_radius(const Eigen::MatrixBase<DERIVED> & C0,\n                                     const Eigen::MatrixBase<DERIVED> & C1){\n    // todo optimize for usage of triangular shape\n    auto Cinv = C0.inverse();\n    auto P1_prime = (Cinv.transpose()*(C1.transpose()*C1)*Cinv);\n    double max_rad = 1./P1_prime.eigenvalues().real().array().minCoeff();\n//    Eigen::MatrixXd Cinv = C0.inverse();\n//    Eigen::MatrixXd P1_prime = (Cinv.transpose()*(C1.transpose()*C1)*Cinv);\n//    double max_rad = 1./P1_prime.eigenvalues().real().array().minCoeff();\n    return std::sqrt(max_rad);\n  }\n  \n  struct lyap_zone_t{};\n  \n  class lyapunov_t{\n  public:\n    virtual bool intersect(const lyap_zone_t & other) const;\n    virtual bool covers(const lyap_zone_t & other) const;\n    virtual bool is_covered(const lyap_zone_t & other) const;\n    virtual double get_alpha() const;\n  };\n  \n  struct fixed_ellipsoidal_zone_t{\n    virtual const Eigen::VectorXd & x0() const {\n      std::cerr << __FILE__ << \": \" << __LINE__ << std::endl;\n      throw std::runtime_error(\"Virtual\");\n      return Eigen::Vector2d::Zero();\n    };\n    virtual const Eigen::MatrixXd & C() const {\n      std::cerr << __FILE__ << \": \" << __LINE__ << std::endl;\n      throw std::runtime_error(\"Virtual\");\n      return Eigen::Matrix2d::Zero();\n    };\n  };\n  \n  struct fixed_ellipsoidal_zone_copied_t: public fixed_ellipsoidal_zone_t{\n  public:\n    fixed_ellipsoidal_zone_copied_t( const Eigen::VectorXd & x0,\n        const Eigen::MatrixXd & C);\n    const Eigen::VectorXd & x0() const {\n      return _x0;\n    }\n    const Eigen::MatrixXd & C() const {\n      return _C;\n    }\n    // (x-x0)^T.P.(x-x0) <= 1\n    // ||C.(x-x0)||_2^2 <= 1\n    Eigen::VectorXd _x0;\n    Eigen::MatrixXd _C;\n  };\n  \n  struct fixed_ellipsoidal_zone_ref_t: public fixed_ellipsoidal_zone_t{\n  public:\n    fixed_ellipsoidal_zone_ref_t( const Eigen::VectorXd & x0,\n                                     const Eigen::MatrixXd & C);\n    const Eigen::VectorXd & x0() const {\n      return _x0;\n    }\n    const Eigen::MatrixXd & C() const {\n      return _C;\n    }\n    // (x-x0)^T.P.(x-x0) <= 1\n    // ||C.(x-x0)||_2^2 <= 1\n    const Eigen::VectorXd &_x0;\n    const Eigen::MatrixXd &_C;\n  };\n  \n  // todo\n//  // Does zone0 cover zone1\n//  template<class DIST>\n//  bool covers_helper(const fixed_ellipsoidal_zone_t &zone0,\n//                     const fixed_ellipsoidal_zone_t &zone1,\n//                     DIST &dist){\n//\n//\n//    // First compute the projected distance\n//    auto dy = zone0.C()*(dist.cp_vv(zone1.x0(), zone0.x0()));\n//    double dy_norm = dy.norm(); //l2 norm\n//    // center out of bounds\n//    if (dy_norm>=1.){\n//      return false;\n//    }\n//\n//    // Compute radius\n//    return dy_norm+projected_max_radius(zone0.C(), zone1.C())<=1.;\n//  }\n  \n  template<class TRAJ, class DIST>\n  class fixed_ellipsoidal_lyap_t: public TRAJ{\n  public:\n    using dist_t = DIST;\n    using traj_t = TRAJ;\n    using dyn_t = typename traj_t::dyn_t;\n  \n    using matrix_t = typename traj_t::matrix_t;\n    using vector_x_t = typename traj_t::vector_x_t;\n    using vector_u_t = typename traj_t::vector_u_t;\n    using vector_t_t = typename traj_t::vector_t_t;\n    using matrix_ptr_t = typename traj_t::matrix_ptr_t;\n    using vector_x_ptr_t = typename traj_t::vector_x_ptr_t;\n    using vector_u_ptr_t = typename traj_t::vector_u_ptr_t;\n    using vector_t_ptr_t = typename traj_t::vector_t_ptr_t;\n    \n    using traj_t::dimx;\n    using traj_t::dimp;\n    using traj_t::dimv;\n    using traj_t::dimu;\n    \n    using s_mat_t = Eigen::Matrix<double,dimx,dimx>;\n    using s_vec_t = Eigen::Matrix<double,dimx,1>;\n  \n    using args = std::tuple<std::shared_ptr<s_mat_t>, double, DIST*>;\n  \n    template <class DERIVED>\n    fixed_ellipsoidal_lyap_t(const Eigen::MatrixBase<DERIVED> &P,\n        double gamma, DIST &dist):\n        _gamma(gamma), _dist(dist){\n      set_P(P);\n    }\n  \n    template <class ...CARGS>\n    void compute(CARGS &&...cargs){\n      // Just forwarding\n      traj_t::compute(cargs...);\n    }\n  \n    template <class DERIVED>\n    void set_P(const Eigen::MatrixBase<DERIVED>& P) {\n      assert(P.rows() == dimx);\n      assert(P.rows() == P.cols());\n      \n      // Compute cholesky\n      Eigen::LLT<Eigen::Matrix<double, dimx, dimx>> llt_pre_comp;\n      llt_pre_comp.compute(P);\n      _C = llt_pre_comp.matrixU();\n      \n      // Compute the bounding box corner\n      std::cout << P << std::endl;\n      std::cout << _C << std::endl;\n      for(size_t i=0; i<dimx; i++){\n        _box_corner(i) = 1./_C.row(i).norm();\n      }\n      std::cout << _box_corner << std::endl;\n    }\n    s_mat_t get_P(){\n      return _C.transpose()*_C;\n    }\n    \n    const s_mat_t &C() const {\n      return _C;\n    }\n    double gamma() const {\n      return _gamma;\n    }\n    s_vec_t min_corner(){\n      return -_box_corner;\n    }\n    const s_vec_t &max_corner(){\n      return _box_corner;\n    }\n// todo\n//    // Conservative intersect\n//    // If true, the zone may intersect with this\n//    // If false, the zone does definitively not intersect\n//    template<class DERIVED>\n//    bool intersect(const Eigen::MatrixBase<DERIVED> &x0,\n//        const fixed_ellipsoidal_zone_t &zone) const {\n//      // First compute the projected distance\n//      auto dy = _C*(_dist.cp_vv(zone.x0(), x0));\n//      double dy_norm = dy.norm(); //l2 norm\n//\n//      if (dy_norm <= 1.){\n//        return true;\n//      }\n//\n//      return dy_norm>=1.+projected_max_radius(_C, zone.C());\n//    }\n//\n//    // Conservative cover\n//    // If true, zone is definitively covered by this\n//    // If false, it may not be covered\n//    template<class DERIVED>\n//    bool covers(const Eigen::MatrixBase<DERIVED> &x0,\n//        const fixed_ellipsoidal_zone_t &zone) const {\n//      fixed_ellipsoidal_zone_ref_t this_zone(x0, _C);\n//      return covers_helper(this_zone, zone, _dist);\n//    }\n//\n//    // Conservative cover\n//    // If true, this is definitively covered by zone\n//    // If false, it may not be covered\n//    template<class DERIVED>\n//    bool is_covered(const Eigen::MatrixBase<DERIVED> &x0,\n//        const fixed_ellipsoidal_zone_t &zone) const {\n//      fixed_ellipsoidal_zone_ref_t this_zone(x0, _C);\n//      return covers_helper(zone, this_zone, _dist);\n//    }\n    \n    double get_alpha(){\n      return (double) 1./((_C.transpose()*_C)(0,0));\n    }\n    \n    double get_gamma()const{\n      return _gamma;\n    }\n    void set_gamma(double gamma){\n      _gamma = gamma;\n    }\n    \n    dist_t & dist() const {\n      return _dist;\n    }\n    \n    args get_args()const{\n//      Eigen::MatrixXd P_scaled = _C.transpose()*_C;\n      std::shared_ptr<s_mat_t> P = std::make_shared<s_mat_t>();\n      *P = _C.transpose()*_C;\n      return std::make_tuple(P, _gamma, &_dist);\n    }\n    \n  protected:\n    s_mat_t _C; // todo: Optimize to use triangular shape\n    s_vec_t _box_corner;\n    double _gamma;\n    DIST &_dist;\n  };\n  \n}\n\n#endif //FUNNELS_CPP_LYAPUNOV_HH\n", "meta": {"hexsha": "c2a886969655c85130cb1d45ebac766a82ec19fd", "size": 7211, "ext": "hh", "lang": "C++", "max_stars_repo_path": "include/funnels/lyapunov.hh", "max_stars_repo_name": "schlepil/funnels_cpp_2", "max_stars_repo_head_hexsha": "1ed746a90019f7f6aff7a54fd4b63bfbd58fa2ac", "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/funnels/lyapunov.hh", "max_issues_repo_name": "schlepil/funnels_cpp_2", "max_issues_repo_head_hexsha": "1ed746a90019f7f6aff7a54fd4b63bfbd58fa2ac", "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": "include/funnels/lyapunov.hh", "max_forks_repo_name": "schlepil/funnels_cpp_2", "max_forks_repo_head_hexsha": "1ed746a90019f7f6aff7a54fd4b63bfbd58fa2ac", "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.9598393574, "max_line_length": 77, "alphanum_fraction": 0.6122590487, "num_tokens": 2055, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513759047848, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.7038339006338296}}
{"text": "#ifndef QUATERNION_AVERAGING_H\n#define QUATERNION_AVERAGING_H\n\n//\n#include <vector>\n#include <stdexcept>      // std::length_error\n//\n//#include <Eigen/Core>\n//#include <Eigen/Eigenvalues>\n#include <eigen3/Eigen/Core>\n#include <eigen3/Eigen/Eigenvalues>\n//\n#include <tf/transform_datatypes.h> // tf quaternion\n#include <tf2/LinearMath/Quaternion.h> // tf2 quaternion\n\nnamespace math_quat {\n\n    static tf2::Quaternion getAverageQuaternion(\n            const std::vector<tf2::Quaternion> &quaternions,\n            const std::vector<double> &weights)\n    {\n\n        if (quaternions.size() != weights.size())\n            throw std::length_error(\"Weights and quaternions needs to be same\"\n                                    \" length\");\n\n        Eigen::MatrixXd Q = Eigen::MatrixXd::Zero(4, quaternions.size());\n        Eigen::Vector3d vec;\n        for (size_t i = 0; i < quaternions.size(); ++i) {\n            // Weigh the quaternions according to their associated weight\n            tf2::Quaternion quat = quaternions[i] * weights[i];\n            // Append the weighted Quaternion to a matrix Q.\n            Q(0, i) = quat.x();\n            Q(1, i) = quat.y();\n            Q(2, i) = quat.z();\n            Q(3, i) = quat.w();\n        }\n\n        // Creat a solver for finding the eigenvectors and eigenvalues\n        Eigen::EigenSolver<Eigen::MatrixXd> es(Q * Q.transpose());\n\n        // Find index of maximum (real) Eigenvalue.\n        auto eigenvalues = es.eigenvalues();\n        size_t max_idx = 0;\n        double max_value = eigenvalues[max_idx].real();\n        for (size_t i = 1; i < 4; ++i) {\n            double real = eigenvalues[i].real();\n            if (real > max_value) {\n                max_value = real;\n                max_idx = i;\n            }\n        }\n\n        // Get corresponding Eigenvector, normalize it and return it as the average quat\n        auto eigenvector = es.eigenvectors().col(max_idx).normalized();\n\n        tf2::Quaternion mean_orientation(\n                eigenvector[0].real(),\n                eigenvector[1].real(),\n                eigenvector[2].real(),\n                eigenvector[3].real()\n        );\n\n        return mean_orientation.normalized();\n    }\n\n    static tf::Quaternion getAverageQuaternion(\n            const std::vector<tf::Quaternion> &quaternions,\n            const std::vector<double> &weights)\n    {\n        if (quaternions.size() != weights.size())\n            throw std::length_error(\"Weights and quaternions needs to be same\"\n                                    \" length\");\n\n        Eigen::MatrixXd Q = Eigen::MatrixXd::Zero(4, quaternions.size());\n        Eigen::Vector3d vec;\n        for (size_t i = 0; i < quaternions.size(); ++i) {\n            // Weigh the quaternions according to their associated weight\n            tf::Quaternion quat = quaternions[i] * weights[i];\n            // Append the weighted Quaternion to a matrix Q.\n            Q(0, i) = quat.x();\n            Q(1, i) = quat.y();\n            Q(2, i) = quat.z();\n            Q(3, i) = quat.w();\n        }\n\n        // Creat a solver for finding the eigenvectors and eigenvalues\n        Eigen::EigenSolver<Eigen::MatrixXd> es(Q * Q.transpose());\n\n        // Find index of maximum (real) Eigenvalue.\n        auto eigenvalues = es.eigenvalues();\n        size_t max_idx = 0;\n        double max_value = eigenvalues[max_idx].real();\n        for (size_t i = 1; i < 4; ++i) {\n            double real = eigenvalues[i].real();\n            if (real > max_value) {\n                max_value = real;\n                max_idx = i;\n            }\n        }\n\n        // Get corresponding Eigenvector, normalize it and return it as the average quat\n        auto eigenvector = es.eigenvectors().col(max_idx).normalized();\n\n        tf::Quaternion mean_orientation(\n                eigenvector[0].real(),\n                eigenvector[1].real(),\n                eigenvector[2].real(),\n                eigenvector[3].real()\n        );\n\n        return mean_orientation.normalized();\n    }\n\n} //ns\n#endif //QUATERNION_AVERAGING_H\n", "meta": {"hexsha": "ef65d4f890c94b67d11a3a3083ce855702a32edc", "size": 4025, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "averaging_quaternions.hpp", "max_stars_repo_name": "mithundiddi/averaging_weighted_quaternions", "max_stars_repo_head_hexsha": "f0a3ecbe50370906959f457ea361bc79bcd9bf6b", "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": "averaging_quaternions.hpp", "max_issues_repo_name": "mithundiddi/averaging_weighted_quaternions", "max_issues_repo_head_hexsha": "f0a3ecbe50370906959f457ea361bc79bcd9bf6b", "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": "averaging_quaternions.hpp", "max_forks_repo_name": "mithundiddi/averaging_weighted_quaternions", "max_forks_repo_head_hexsha": "f0a3ecbe50370906959f457ea361bc79bcd9bf6b", "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.4017094017, "max_line_length": 88, "alphanum_fraction": 0.5555279503, "num_tokens": 965, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802395624257, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.7038255590724769}}
{"text": "#include <cassert>\n#include <cmath>\n\n#include <type_traits>\n#include <limits>\n#include <climits>\n\n#include <boost/integer/integer_mask.hpp>\n\nnamespace hlf {\n    namespace math {\n\n        constexpr long double pi = 3.141592653589793238462643383279502884;\n        constexpr long double pi_2 = pi / 2.0;\n        constexpr long double pi_4 = pi / 4.0;\n        constexpr long double twicePi = 2.0 * pi;\n\n        constexpr long double DEGREE_TO_RAD = 0.017453292519943295769236907684886;\n        constexpr long double RAD_TO_DEGREE = 1.0 / DEGREE_TO_RAD;\n\n        template<typename TFloat>\n        inline TFloat degToRad(const TFloat degree) {\n            return static_cast<TFloat>(degree * DEGREE_TO_RAD);\n        }\n\n        template<typename TFloat>\n        inline TFloat radToDeg(const TFloat radian) {\n            return static_cast<TFloat>(radian * RAD_TO_DEGREE);\n        }\n\n/// Convert [0, 360] degrees bearing into [-pi, pi] azimuth.\n        template<typename TFloat>\n        inline TFloat Bearing2Azimuth(const TFloat degree) {\n            TFloat radians = degToRad(degree);\n            assert(radians >= 0.0);\n            return (radians > pi ? radians - twicePi : radians);\n        }\n\n/// Positive angle between 2 azimuths.\n        template<typename TFloat>\n        inline TFloat AngleBetween(TFloat rad1, TFloat rad2) {\n            TFloat res = rad1 - rad2;\n            if (res < 0.0)\n                res += twicePi;\n            return (res > pi ? twicePi - res : res);\n        }\n\n        template<class T>\n        T Log2(T x) {\n            return log(x) / log(2);\n        }\n\n        template<typename T>\n        inline T Abs(T x) {\n            return (x < 0 ? -x : x);\n        }\n\n// Compare floats or doubles for almost equality.\n// maxULPs - number of closest floating point values that are considered equal.\n// Infinity is treated as almost equal to the largest possible floating point values.\n// NaN produces undefined result.\n// See https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/\n// for details.\n        template<typename TFloat>\n        bool AlmostEqualULPs(TFloat x, TFloat y, unsigned int maxULPs = 256) {\n            static_assert(std::is_floating_point<TFloat>::value, \"\");\n            static_assert(std::numeric_limits<TFloat>::is_iec559, \"\");\n\n            // Make sure maxUlps is non-negative and small enough that the\n            // default NaN won't compare as equal to anything.\n            assert(maxULPs < 4 * 1024 * 1024);\n\n            int const bits = CHAR_BIT * sizeof(TFloat);\n            typedef typename boost::int_t<bits>::exact IntType;\n            typedef typename boost::uint_t<bits>::exact UIntType;\n\n            IntType xInt = *reinterpret_cast<IntType const *>(&x);\n            IntType yInt = *reinterpret_cast<IntType const *>(&y);\n\n            // Make xInt and yInt lexicographically ordered as a twos-complement int\n            IntType const highestBit = IntType(1) << (bits - 1);\n            if (xInt < 0)\n                xInt = highestBit - xInt;\n            if (yInt < 0)\n                yInt = highestBit - yInt;\n\n            UIntType const diff = Abs(xInt - yInt);\n\n            return diff <= maxULPs;\n        }\n\n// Returns true if x and y are equal up to the absolute difference eps.\n// Does not produce a sensible result if any of the arguments is NaN or infinity.\n// The default value for eps is deliberately not provided: the intended usage\n// is for the client to choose the precision according to the problem domain,\n// explicitly define the precision constant and call this function.\n        template<typename TFloat>\n        inline bool AlmostEqualAbs(TFloat x, TFloat y, TFloat eps) {\n            return fabs(x - y) < eps;\n        }\n\n// Returns true if x and y are equal up to the relative difference eps.\n// Does not produce a sensible result if any of the arguments is NaN, infinity or zero.\n// The same considerations as in AlmostEqualAbs apply.\n        template<typename TFloat>\n        inline bool AlmostEqualRel(TFloat x, TFloat y, TFloat eps) {\n            return fabs(x - y) < eps * max(fabs(x), fabs(y));\n        }\n\n        template<typename T>\n        inline T id(T const &x) {\n            return x;\n        }\n\n        template<typename T>\n        inline T sq(T const &x) {\n            return x * x;\n        }\n\n        template<typename T, typename TMin, typename TMax>\n        inline T clamp(T x, TMin xmin, TMax xmax) {\n            if (x > xmax)\n                return xmax;\n            if (x < xmin)\n                return xmin;\n            return x;\n        }\n\n        template<typename T>\n        inline T cyclicClamp(T x, T xmin, T xmax) {\n            if (x > xmax)\n                return xmin;\n            if (x < xmin)\n                return xmax;\n            return x;\n        }\n\n        template<typename T>\n        inline bool between_s(T a, T b, T x) {\n            return (a <= x && x <= b);\n        }\n\n        template<typename T>\n        inline bool between_i(T a, T b, T x) {\n            return (a < x && x < b);\n        }\n\n        inline int rounds(double x) {\n            return (x > 0.0 ? int(x + 0.5) : int(x - 0.5));\n        }\n\n        inline size_t SizeAligned(size_t size, size_t align) {\n            // static_cast    .\n            return size + (static_cast<size_t>(-static_cast<ptrdiff_t>(size)) & (align - 1));\n        }\n\n        template<typename T>\n        bool IsIntersect(T const &x0, T const &x1, T const &x2, T const &x3) {\n            return !((x1 < x2) || (x3 < x0));\n        }\n\n// Computes x^n.\n        template<typename T>\n        inline T PowUint(T x, uint64_t n) {\n            T res = 1;\n            for (T t = x; n > 0; n >>= 1, t *= t)\n                if (n & 1)\n                    res *= t;\n            return res;\n        }\n\n        template<typename T>\n        inline T NextModN(T x, T n) {\n            return x + 1 == n ? 0 : x + 1;\n        }\n\n        template<typename T>\n        inline T PrevModN(T x, T n) {\n            return x == 0 ? n - 1 : x - 1;\n        }\n\n        inline uint32_t NextPowOf2(uint32_t v) {\n            v = v - 1;\n            v |= (v >> 1);\n            v |= (v >> 2);\n            v |= (v >> 4);\n            v |= (v >> 8);\n            v |= (v >> 16);\n\n            return v + 1;\n        }\n\n// Greatest Common Divisor\n        template<typename T>\n        T GCD(T a, T b) {\n            T multiplier = 1;\n            T gcd = 1;\n            while (true) {\n                if (a == 0 || b == 0) {\n                    gcd = max(a, b);\n                    break;\n                }\n\n                if (a == 1 || b == 1) {\n                    gcd = 1;\n                    break;\n                }\n\n                if ((a & 0x1) == 0 && (b & 0x1) == 0) {\n                    multiplier <<= 1;\n                    a >>= 1;\n                    b >>= 1;\n                    continue;\n                }\n\n                if ((a & 0x1) != 0 && (b & 0x1) != 0) {\n                    T const minV = min(a, b);\n                    T const maxV = max(a, b);\n                    a = (maxV - minV) >> 1;\n                    b = minV;\n                    continue;\n                }\n\n                if ((a & 0x1) != 0)\n                    std::swap(a, b);\n                a >>= 1;\n            }\n\n            return multiplier * gcd;\n        }\n\n\n    }\n}\n\n", "meta": {"hexsha": "d89da4f2f5127bb5fdf21998391fa893f6b24f56", "size": 7308, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "visionai-shared/src/main/cpp/utils/math.hpp", "max_stars_repo_name": "BenDenen/ComputerVisionExamples", "max_stars_repo_head_hexsha": "750856e60523b93516f16e2181dd4001c024b0f4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-10-16T12:52:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-29T20:54:40.000Z", "max_issues_repo_path": "visionai-shared/src/main/cpp/utils/math.hpp", "max_issues_repo_name": "BenDenen/ComputerVisionExamples", "max_issues_repo_head_hexsha": "750856e60523b93516f16e2181dd4001c024b0f4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 24.0, "max_issues_repo_issues_event_min_datetime": "2019-10-16T13:01:39.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-21T20:15:40.000Z", "max_forks_repo_path": "visionai-shared/src/main/cpp/utils/math.hpp", "max_forks_repo_name": "BenDenen/ComputerVisionExamples", "max_forks_repo_head_hexsha": "750856e60523b93516f16e2181dd4001c024b0f4", "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": 30.9661016949, "max_line_length": 98, "alphanum_fraction": 0.5045155993, "num_tokens": 1818, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178895092414, "lm_q2_score": 0.7745833789613197, "lm_q1q2_score": 0.7038003150407712}}
{"text": "#include <Eigen/Dense>\n#include \"lsq.h\"\n\n\nLSQ::LSQ(const Eigen::MatrixXf& A, const Eigen::VectorXf& b){\n    this->A = A;\n    this->b = b;\n}\n\n\nLSQ::~LSQ(){}\n\n\nEigen::VectorXf LSQ::solve(){\n    return this->A.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(this->b);\n}\n\n", "meta": {"hexsha": "8600a40e4fad4b0c2c5e853705202e24f49c58d1", "size": 279, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bijou/lsq/lsq.cpp", "max_stars_repo_name": "sonnyhu/bijou", "max_stars_repo_head_hexsha": "7085cdb25a0e111816b457c03dc492469d30c761", "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": "bijou/lsq/lsq.cpp", "max_issues_repo_name": "sonnyhu/bijou", "max_issues_repo_head_hexsha": "7085cdb25a0e111816b457c03dc492469d30c761", "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": "bijou/lsq/lsq.cpp", "max_forks_repo_name": "sonnyhu/bijou", "max_forks_repo_head_hexsha": "7085cdb25a0e111816b457c03dc492469d30c761", "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": 15.5, "max_line_length": 87, "alphanum_fraction": 0.6272401434, "num_tokens": 96, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9252299550303292, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.7037767691703981}}
{"text": "///////////////////////////////////////////////////////////////////\n//  Copyright Eduardo Quintana 2021\n//  Copyright Janek Kozicki 2021\n//  Copyright Christopher Kormanyos 2021\n//  Distributed under the Boost Software License,\n//  Version 1.0. (See accompanying file LICENSE_1_0.txt\n//  or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_FFT_REAL_ALGORITHMS_HPP\n  #define BOOST_MATH_FFT_REAL_ALGORITHMS_HPP\n\n  #include <algorithm>\n  #include <numeric>\n  #include <cmath>\n  \n  #include <boost/math/fft/simple_complex.hpp>\n  \n  namespace boost { namespace math {  namespace fft {\n  \n  namespace detail {\n  \n  template<class T>\n  inline void real_dft_2(\n    const T* in, \n    T* out, int)\n  {\n    T o1 = in[0]+in[1], o2 = in[0]-in[1] ;\n    out[0] = o1;\n    out[1] = o2;\n  }\n  \n  template<class RealType>\n  RealType complex_root_of_unity_real(long n,long p=1)\n  /*\n    Computes cos(-2 pi p/n)\n  */\n  {\n    p = modulo(p,n);\n    \n    if(p==0)\n      return RealType(1);\n    \n    long g = gcd(p,n); \n    n/=g;\n    p/=g;\n    switch(n)\n    {\n      case 1:\n        return RealType(1);\n      case 2:\n        return p==0 ? RealType(1) : RealType(-1);\n      case 4:\n        return p==0 ? RealType(1) : \n               p==1 ? RealType(0) :\n               p==2 ? RealType(-1) :\n                      RealType(0) ;\n    }\n    using std::cos;\n    RealType phase = -2*p*boost::math::constants::pi<RealType>()/n;\n    return RealType(cos(phase));\n  }\n  template<class RealType>\n  RealType complex_root_of_unity_imag(long n,long p=1)\n  /*\n    Computes sin(-2 pi p/n)\n  */\n  {\n    p = modulo(p,n);\n    \n    if(p==0)\n      return RealType(0);\n    \n    long g = gcd(p,n); \n    n/=g;\n    p/=g;\n    switch(n)\n    {\n      case 1:\n        return RealType(0);\n      case 2:\n        return p==0 ? RealType(0) : RealType(0);\n      case 4:\n        return p==0 ? RealType(0) : \n               p==1 ? RealType(-1) :\n               p==2 ? RealType(0) :\n                      RealType(1) ;\n    }\n    using std::sin;\n    RealType phase = -2*p*boost::math::constants::pi<RealType>()/n;\n    return RealType(sin(phase));\n  }\n  \n  template <class T>\n  void real_dft_power2(const T *in_first, const T *in_last, T* out, int/*sign*/)\n  {\n    /*\n      Cooley-Tukey mapping, in-place Decimation in Time \n    */\n    const long ptrdiff = static_cast<long>(std::distance(in_first,in_last));\n    if(ptrdiff <=0 )\n      return;\n    const long n = lower_bound_power2(ptrdiff);\n    \n    if(in_first!=out)\n      std::copy(in_first,in_last,out);\n    \n    if (n == 1)\n        return;\n\n    // Gold-Rader bit-reversal algorithm.\n    for(int i=0,j=0;i<n-1;++i)\n    { \n      if(i<j)\n        std::swap(out[i],out[j]);\n      for(int k=n>>1;!( (j^=k)&k );k>>=1);\n    }\n    \n    for (int len = 2, prev_len = 1; len <= n; len <<= 1,prev_len<<=1)\n    {\n      for (int i = 0; i < n; i += len)\n      {\n        {\n          // j=0;\n          T* u = out + i, *v = out + i + prev_len;\n          T Bu = *u, Bv = *v;\n          *u = Bu + Bv;\n          *v = Bu - Bv;\n        }\n        for(int j=1;j < prev_len/2;++j)\n        {\n          T cos{ complex_root_of_unity_real<T>(len,j) }, \n            sin{ complex_root_of_unity_imag<T>(len,j) };\n          \n          T *ux = out + i + j, \n            *uy = out + i + len - j;\n            \n          T *vx = out + i + prev_len - j, \n            *vy = out + i + prev_len + j;\n          \n          T prev_ux = *ux, \n            prev_uy = *uy;\n            \n          T prev_vx = *vx, \n            prev_vy = *vy;\n          \n          *ux = prev_ux + cos * prev_vy + sin * prev_uy;\n          *uy = prev_vx + cos * prev_uy - sin * prev_vy;\n          *vx = prev_ux - cos * prev_vy - sin * prev_uy;\n          *vy =-prev_vx + cos * prev_uy - sin * prev_vy;\n        }\n        //if(prev_len>=2)\n        //{\n        //  const int j = prev_len/2;\n        //  T* u = out + i + j, *v = out + i + j + prev_len;\n        //  T Bu = *u, Bv = *v;\n        //  *u = Bu;\n        //  *v = Bv;\n        //}\n      }\n    }\n  }\n  template <class T>\n  void real_inverse_dft_power2(const T *in_first, const T *in_last, T* out, int /*sign*/)\n  {\n    /*\n      Cooley-Tukey mapping, in-place Decimation in Time \n      Reverse flow graph of the real_dft_power2\n    */\n    const long ptrdiff = static_cast<long>(std::distance(in_first,in_last));\n    if(ptrdiff <=0 )\n      return;\n    const long n = lower_bound_power2(ptrdiff);\n    \n    if(in_first!=out)\n      std::copy(in_first,in_last,out);\n    \n    if (n == 1)\n        return;\n    \n    for (int len = n, prev_len = len/2; len >= 2; len >>= 1,prev_len>>=1)\n    {\n      for (int i = 0; i < n; i += len)\n      {\n        {\n          // j=0;\n          T* u = out + i, *v = out + i + prev_len;\n          T Bu = *u, Bv = *v;\n          *u = Bu + Bv;\n          *v = Bu - Bv;\n        }\n        for(int j=1;j < prev_len/2;++j)\n        {\n          T cos{ complex_root_of_unity_real<T>(len,-j) }, \n            sin{ complex_root_of_unity_imag<T>(len,-j) };\n          \n          T *ux = out + i + j, \n            *uy = out + i + len - j;\n            \n          T *vx = out + i + prev_len - j, \n            *vy = out + i + prev_len + j;\n          \n          T prev_ux = *ux, \n            prev_uy = *uy;\n            \n          T prev_vx = *vx, \n            prev_vy = *vy;\n          \n          T sum_x = prev_ux + prev_vx,\n            dif_x = prev_ux - prev_vx,\n            sum_y = prev_uy + prev_vy,\n            dif_y = prev_uy - prev_vy;\n          \n          *ux = sum_x;\n          *vx = dif_y;\n          *uy = cos * sum_y - sin*dif_x;\n          *vy = cos * dif_x + sin*sum_y;\n        }\n        if(prev_len>=2)\n        {\n          const int j = prev_len/2;\n          T* u = out + i + j, *v = out + i + j + prev_len;\n          T Bu = *u, Bv = *v;\n          *u = Bu + Bu;\n          *v = Bv + Bv;\n        }\n      }\n    }\n    \n    // Gold-Rader bit-reversal algorithm.\n    for(int i=0,j=0;i<n-1;++i)\n    { \n      if(i<j)\n        std::swap(out[i],out[j]);\n      for(int k=n>>1;!( (j^=k)&k );k>>=1);\n    }\n  }\n  \n  template<class T>\n  void real_dft_prime_bruteForce_outofplace(\n    const T* in_first, \n    const T* in_last, \n    T* out, int sign)\n  /*\n    assumptions: \n    - allocated memory in out is enough to hold distance(in_first,in_last) element,\n    - out!=in\n  */\n  {\n    const long N = static_cast<long>(std::distance(in_first,in_last));\n    if(N<=0)\n      return;\n    \n    out[0] = std::accumulate(in_first+1,in_last,in_first[0]);\n    \n    for(long i=1,j=N-1;i<j;++i,--j)\n    {\n      T sum_x{in_first[0]},sum_y = 0;\n      for(long l=1;l<N; ++l)\n      {\n        sum_x += in_first[l] * complex_root_of_unity_real<T>(N,i*l*sign);\n        sum_y += in_first[l] * complex_root_of_unity_imag<T>(N,i*l*sign);\n      }\n      // if(i<j) // i==j never happens for odd sizes\n      out[j] = -sum_y;\n      out[i] = sum_x;\n    }\n  }\n  \n  template<class T,class Allocator_t>\n  void real_dft_prime_bruteForce_inplace(\n    T* in_first, \n    T* in_last, \n    int sign,\n    const Allocator_t& alloc)\n  {\n    std::vector<T,Allocator_t> work_space(in_first,in_last,alloc);\n    real_dft_prime_bruteForce_outofplace(in_first,in_last,work_space.data(),sign);\n    std::copy(work_space.begin(),work_space.end(),in_first);\n  }\n  template<class T, class Allocator_t>\n  void real_dft_prime_bruteForce(\n    const T* in_first, \n    const T* in_last, \n    T* out, \n    int sign,\n    const Allocator_t& alloc)\n  {\n    if(in_first==out)\n      real_dft_prime_bruteForce_inplace(out,out+std::distance(in_first,in_last),sign,alloc);\n    else\n      real_dft_prime_bruteForce_outofplace(in_first,in_last,out,sign);\n  }\n  \n  template<class T>\n  void real_inverse_dft_prime_bruteForce_outofplace(\n    const T* in_first, \n    const T* in_last, \n    T* out, int sign)\n  /*\n    assumptions: \n    - allocated memory in out is enough to hold distance(in_first,in_last) element,\n    - out!=in\n  */\n  {\n    const long N = static_cast<long>(std::distance(in_first,in_last));\n    if(N<=0)\n      return;\n    \n    {\n      T sum_x{0.};\n      for(long i=1,j=N-1;i<j;++i,--j)\n      {\n        sum_x += in_first[i];\n      }\n      // if(i<j) // i==j never happens for odd sizes\n      out[0] = ( 2*sum_x + in_first[0]);\n    } \n    for(long l=1;l<N; ++l)\n    {\n      T sum_x{0.},sum_y{0.};\n      for(long i=1,j=N-1;i<j;++i,--j)\n      {\n        sum_x += in_first[i] * complex_root_of_unity_real<T>(N,i*l*sign);\n        sum_y += in_first[j] * complex_root_of_unity_imag<T>(N,i*l*sign);\n      }\n      // if(i<j) // i==j never happens for odd sizes\n      out[l] = (2*sum_x - 2*sum_y + in_first[0]);\n    }\n  }\n  \n  template<class T,class Allocator_t>\n  void real_inverse_dft_prime_bruteForce_inplace(\n    T* in_first, \n    T* in_last, \n    int sign,\n    const Allocator_t& alloc)\n  {\n    std::vector<T,Allocator_t> work_space(in_first,in_last,alloc);\n    real_inverse_dft_prime_bruteForce_outofplace(in_first,in_last,work_space.data(),sign);\n    std::copy(work_space.begin(),work_space.end(),in_first);\n  }\n  template<class T, class Allocator_t>\n  void real_inverse_dft_prime_bruteForce(\n    const T* in_first, \n    const T* in_last, \n    T* out, \n    int sign,\n    const Allocator_t& alloc)\n  {\n    if(in_first==out)\n      real_inverse_dft_prime_bruteForce_inplace(out,out+std::distance(in_first,in_last),sign,alloc);\n    else\n      real_inverse_dft_prime_bruteForce_outofplace(in_first,in_last,out,sign);\n  }\n  \n  template <class T, class allocator_t>\n  void real_dft_composite_outofplace(\n            const T *in_first, \n            const T *in_last, \n            T* out, \n            int /*sign*/,\n            const allocator_t& alloc)\n  {\n    /*\n      Cooley-Tukey mapping, intrinsically out-of-place, Decimation in Time\n      composite sizes.\n    */\n    using allocator_type = allocator_t;\n    using ComplexType = simple_complex<T>; \n    using ComplexAllocator = typename std::allocator_traits<allocator_type>::template rebind_alloc<ComplexType>;\n    \n    const long n = static_cast<long>(std::distance(in_first,in_last));\n    if(n <=0 )\n      return;\n    \n    if (n == 1)\n    {\n        out[0]=in_first[0];\n        return;\n    }\n    std::array<int,32> prime_factors;\n    const int nfactors = prime_factorization(n,prime_factors.begin());\n    \n    // reorder input\n    for (long i = 0; i < n; ++i)\n    {\n        long j = 0, k = i;\n        for (int ip=0;ip<nfactors;++ip)\n        {\n            int p = prime_factors[ip];\n            j = j * p + k % p;\n            k /= p;\n        }\n        out[j] = in_first[i];\n    }\n    \n    std::reverse(prime_factors.begin(), prime_factors.begin()+nfactors);\n    \n    //auto show = [&] (const T* beg, const T* end)\n    //{\n    //  for(;beg!=end;++beg)\n    //  {\n    //    std::cout << *beg << \", \";\n    //  }\n    //  std::cout << \"\\n\";\n    //};\n    \n    // butterfly pattern\n    long len = 1;\n    for (int ip=0;ip<nfactors;++ip)\n    {\n      int p = prime_factors[ip];\n      long len_old = len;\n      len *= p;\n      \n      std::vector<ComplexType,ComplexAllocator> tmp(p,ComplexType(),alloc);\n      //std::cout << \"pass \" << ip << \"\\n\";\n      for (long i = 0; i < n; i += len)\n      {\n        //std::cout << \"    i = \" << i << \"\\n\";\n        for(long k=0;2*k<=len_old;++k)\n        {\n          if(k==0)\n          {\n            tmp[0] = ComplexType{out[i],0.};\n            for(long j=1;j<p;++j)\n              tmp[j] = ComplexType{out[i + j*len_old],0.};\n          }else if(2*k == len_old)\n          {\n            tmp[0] = ComplexType{out[i + k ],0.};\n            for(long j=1;j<p;++j)\n              tmp[j] = ComplexType{out[i + j*len_old +k ],0.}\n                * complex_root_of_unity<ComplexType>(len,k*j);\n          }else\n          {\n            tmp[0] = ComplexType{out[i + k ],-out[i+len_old-k]};\n            for(long j=1;j<p;++j)\n              tmp[j] = ComplexType{out[i + j*len_old +k ],-out[i+j*len_old + len_old-k]}\n                * complex_root_of_unity<ComplexType>(len,k*j);\n          }\n          if(p==2)\n          {\n            complex_dft_2(tmp.data(),tmp.data(),1);\n          }\n          else\n          {\n            complex_dft_prime_rader<ComplexType,ComplexAllocator>(tmp.data(),tmp.data()+p,tmp.data(),1,alloc);\n          }\n          for(long j=0;j<p;++j)\n          {\n            int posx = j*len_old + k, posy = len - k - j*len_old;\n            \n            if(posx==0)\n            {\n              out[i+posx] = tmp[j].real();\n            }else if(posx>posy)\n            {\n              out[i+posx] = tmp[j].imag();\n              out[i+posy] = tmp[j].real();\n            }else\n            {\n              out[i+posy] = -tmp[j].imag();\n              out[i+posx] = tmp[j].real();\n            }\n          }\n        }\n        //show(out+i,out+i+len);\n      }\n    }\n  }\n  \n  template<class T,class Allocator_t>\n  void real_dft_composite_inplace(\n          T* in_first, \n          T* in_last, \n          int sign,\n          const Allocator_t& alloc)\n  {\n    std::vector<T,Allocator_t> work_space(in_first,in_last,alloc);\n    real_dft_composite_outofplace(in_first,in_last,work_space.data(),sign,alloc);\n    std::copy(work_space.begin(),work_space.end(),in_first);\n  }\n  template<class T, class Allocator_t>\n  void real_dft_composite(\n          const T* in_first, \n          const T* in_last, \n          T* out, \n          int sign,\n          const Allocator_t& alloc)\n  {\n    if(in_first==out)\n      real_dft_composite_inplace(out,out+std::distance(in_first,in_last),sign,alloc);\n    else\n      real_dft_composite_outofplace(in_first,in_last,out,sign,alloc);\n  }\n  \n  \n  template <class T, class allocator_t>\n  void real_inverse_dft_composite_outofplace(\n            const T *in_first, \n            const T *in_last, \n            T* out, \n            int /*sign*/,\n            const allocator_t& alloc)\n  {\n    /*\n      Cooley-Tukey mapping, intrinsically out-of-place, Decimation in Time\n      composite sizes.\n      Reverse graph.\n    */\n    using allocator_type = allocator_t;\n    using ComplexType = simple_complex<T>; \n    using ComplexAllocator = typename std::allocator_traits<allocator_type>::template rebind_alloc<ComplexType>;\n    \n    const long n = static_cast<long>(std::distance(in_first,in_last));\n    if(n <=0 )\n      return;\n    \n    std::copy(in_first,in_last,out);\n    if (n == 1)\n        return;\n        \n    std::array<int,32> prime_factors;\n    const int nfactors = prime_factorization(n,prime_factors.begin());\n    \n    // butterfly pattern\n    for (long ip=0,len=n,prev_len = len;ip<nfactors;++ip,len = prev_len)\n    {\n      int p = prime_factors[ip];\n      prev_len = len/p;\n      \n      std::vector<ComplexType,ComplexAllocator> tmp(p,ComplexType(),alloc);\n      for (long i = 0; i < n; i += len)\n      {\n        for(long k=0;2*k<=prev_len;++k)\n        {\n          for(long j=0;j<p;++j)\n          {\n            int posx = j*prev_len + k, posy = len - k - j*prev_len;\n            \n            if(posx==0 || posx==posy)\n            {\n              tmp[j] = ComplexType {out[i+posx],0.};\n            }else if(posx>posy)\n            {\n              tmp[j] = ComplexType{out[i+posy],out[i+posx]};\n            }else // if(posx<posy)\n            {\n              tmp[j] = ComplexType{out[i+posx],-out[i+posy]};\n            }\n          }\n          if(p==2)\n          {\n            complex_dft_2(tmp.data(),tmp.data(),-1);\n          }\n          else\n          {\n            complex_dft_prime_rader<ComplexType,ComplexAllocator>(tmp.data(),tmp.data()+p,tmp.data(),-1,alloc);\n          }\n          \n          if(k==0)\n          {\n            out[i] = tmp[0].real();\n            for(long j=1;j<p;++j)\n              out[i + j*prev_len] = tmp[j].real();\n          }else if(2*k == prev_len)\n          {\n            out[i + k ] = tmp[0].real();\n            for(long j=1;j<p;++j)\n              out[i + j*prev_len +k ] = (tmp[j]* complex_root_of_unity<ComplexType>(len,-k*j) ). real();\n          }else\n          {\n            out[i+k]          =  tmp[0].real();\n            out[i+prev_len-k] = -tmp[0].imag();\n            for(long j=1;j<p;++j)\n            {\n              ComplexType cplx = tmp[j] * complex_root_of_unity<ComplexType>(len,-k*j);\n              out[i + j*prev_len +k ]        = cplx.real();\n              out[i+j*prev_len + prev_len-k] = -cplx.imag();\n            }\n          }\n        }\n      }\n    }\n    \n    std::vector<T,allocator_type> tmp(out,out+n);\n    // reorder\n    for (long i = 0; i < n; ++i)\n    {\n        long j = 0, k = i;\n        for (int ip=0;ip<nfactors;++ip)\n        {\n            int p = prime_factors[ip];\n            j = j * p + k % p;\n            k /= p;\n        }\n        out[i] = tmp[j];\n    }\n  }\n  \n  template<class T,class Allocator_t>\n  void real_inverse_dft_composite_inplace(\n          T* in_first, \n          T* in_last, \n          int sign,\n          const Allocator_t& alloc)\n  {\n    std::vector<T,Allocator_t> work_space(in_first,in_last,alloc);\n    real_inverse_dft_composite_outofplace(in_first,in_last,work_space.data(),sign,alloc);\n    std::copy(work_space.begin(),work_space.end(),in_first);\n  }\n  template<class T, class Allocator_t>\n  void real_inverse_dft_composite(\n          const T* in_first, \n          const T* in_last, \n          T* out, \n          int sign,\n          const Allocator_t& alloc)\n  {\n    if(in_first==out)\n      real_inverse_dft_composite_inplace(out,out+std::distance(in_first,in_last),sign,alloc);\n    else\n      real_inverse_dft_composite_outofplace(in_first,in_last,out,sign,alloc);\n  }\n  \n  } // namespace detail\n\n  } } } // namespace boost::math::fft\n\n#endif // BOOST_MATH_FFT_REAL_ALGORITHMS_HPP\n\n\n", "meta": {"hexsha": "4580a179446f241c6c09037684f0d49574005fc0", "size": 17473, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/math/fft/real_algorithms.hpp", "max_stars_repo_name": "BoostGSoC21/math", "max_stars_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_stars_repo_licenses": ["BSL-1.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": "include/boost/math/fft/real_algorithms.hpp", "max_issues_repo_name": "BoostGSoC21/math", "max_issues_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 30.0, "max_issues_repo_issues_event_min_datetime": "2021-06-22T12:59:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-02T09:27:49.000Z", "max_forks_repo_path": "include/boost/math/fft/real_algorithms.hpp", "max_forks_repo_name": "BoostGSoC21/math", "max_forks_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-07T21:15:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-07T21:15:02.000Z", "avg_line_length": 27.6034755134, "max_line_length": 112, "alphanum_fraction": 0.5121043896, "num_tokens": 5155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213691605412, "lm_q2_score": 0.7826624738835051, "lm_q1q2_score": 0.7037085551087134}}
{"text": "#include <iostream>\n#include <sstream>\n#include <fstream>\n#include <iomanip>\n#include <cmath>\n#include <cmath>\n#include <Eigen/Core>\n#include <Eigen/Dense>\nusing namespace Eigen;\nusing Eigen::MatrixXd;\n\nusing namespace std;\nusing std::setw;\nusing std::setprecision;\n\n\nint main(int argc, char** argv)\n{\n\tMatrixXd J_pseudoInv(2,2);     //  NULL space projection\n\tMatrixXd A = MatrixXd::Random(2,2);\n\n\tEigen::JacobiSVD<Eigen::MatrixXd> svd(A, Eigen::ComputeThinU |Eigen::ComputeThinV);\n\tJ_pseudoInv = svd.matrixV()*svd.singularValues().inverse()*svd.matrixU().transpose();\n\t\n\tcout << \"Hello World! \"<<J_pseudoInv<<endl;\n\tcout << \"J_pseudoInv*A \"<<J_pseudoInv*A<<endl;\n\t\n\treturn 0;\n}\n", "meta": {"hexsha": "7fc9301d7a20b6fd149294ca89aeb4953d07578b", "size": 680, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "testSVD/src/testSVD.cpp", "max_stars_repo_name": "rsthomp/UTDchess-RospyXbee", "max_stars_repo_head_hexsha": "f77ef98afadbb082cde7040b2e770be34fbd2999", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-09-03T01:52:06.000Z", "max_stars_repo_stars_event_max_datetime": "2015-09-03T01:52:06.000Z", "max_issues_repo_path": "testSVD/src/testSVD.cpp", "max_issues_repo_name": "RachaelT/UTDchess-RospyXbee", "max_issues_repo_head_hexsha": "f77ef98afadbb082cde7040b2e770be34fbd2999", "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": "testSVD/src/testSVD.cpp", "max_forks_repo_name": "RachaelT/UTDchess-RospyXbee", "max_forks_repo_head_hexsha": "f77ef98afadbb082cde7040b2e770be34fbd2999", "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.6666666667, "max_line_length": 86, "alphanum_fraction": 0.7117647059, "num_tokens": 191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009642742806, "lm_q2_score": 0.7690802423634961, "lm_q1q2_score": 0.70363225534266}}
{"text": "#include <iostream>\n#include <cmath>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\nint main(int argc, const char **argv)\n{\n    Eigen::Matrix3d rotation_matrix = Eigen::Matrix3d::Identity();\n    Eigen::AngleAxisd rotation_vector(M_PI / 4, Eigen::Vector3d(0, 0, 1));\n\n    std::cout .precision(3);\n    std::cout << \"rotation matrix =\\n\" << rotation_vector.matrix() << std::endl;\n\n    rotation_matrix = rotation_vector.toRotationMatrix();\n\n    Eigen::Vector3d v(1, 0, 0);\n    Eigen::Vector3d v_rotated = rotation_vector * v;\n    std::cout << \"(1, 0, 0) after rotation = \" << v_rotated.transpose() << std::endl;\n\n    v_rotated = rotation_matrix * v;\n    std::cout << \"(1, 0, 0) after rotation = \" << v_rotated.transpose() << std::endl;\n\n    Eigen::Vector3d euler_angles = rotation_matrix.eulerAngles(2, 1, 0);\n    std::cout << \"yaw pitch roll = \" << euler_angles.transpose() << std::endl;\n\n    Eigen::Isometry3d T = Eigen::Isometry3d::Identity();\n    std::cout << \"Transform matrix = \\n\" << T.matrix() << std::endl;    \n    T.rotate(rotation_vector);\n    T.pretranslate(Eigen::Vector3d(1, 3, 4));\n    std::cout << \"Transform matrix = \\n\" << T.matrix() << std::endl;\n\n    Eigen::Vector3d v_transformed = T * v;\n    std::cout << \"v transformed = \" << v_transformed.transpose() << std::endl;\n\n    Eigen::Quaterniond q = Eigen::Quaterniond(rotation_vector);\n    std::cout << \"quaternion = \\n\" << q.coeffs() << std::endl;\n\n    q = Eigen::Quaterniond(rotation_matrix);\n    std::cout << \"quaternion = \\n\" << q.coeffs() << std::endl;\n\n    v_rotated = q * v;\n    std::cout << \"(1, 0, 0) after rotation = \" << v_rotated.transpose() << std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "c92cab9fc0a5e5d36118612e5c6ffce5f88afb3c", "size": 1652, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "practice/ch3/useGeometry/useGeometry.cpp", "max_stars_repo_name": "tzyone/slambook", "max_stars_repo_head_hexsha": "e7e94e08773fa16d2d71057a37d335892b87fd10", "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": "practice/ch3/useGeometry/useGeometry.cpp", "max_issues_repo_name": "tzyone/slambook", "max_issues_repo_head_hexsha": "e7e94e08773fa16d2d71057a37d335892b87fd10", "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": "practice/ch3/useGeometry/useGeometry.cpp", "max_forks_repo_name": "tzyone/slambook", "max_forks_repo_head_hexsha": "e7e94e08773fa16d2d71057a37d335892b87fd10", "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.1489361702, "max_line_length": 85, "alphanum_fraction": 0.6234866828, "num_tokens": 490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087965937711, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.7035429603006224}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include <Eigen/Dense>\n#include <opencv2/opencv.hpp>\n\nusing std::cout;\nusing std::cin;\nusing std::endl;\n\nusing Eigen::MatrixXd;\nusing Eigen::MatrixXf;\nusing Eigen::Matrix;\nusing Eigen::VectorXd;\nusing Eigen::Matrix3d;\nusing Eigen::Matrix3f;\nusing Eigen::Vector3d;\n\n#define LOGD(fmt, ...) fprintf(stdout, fmt, ##__VA_ARGS__)\n\nfloat dotproduct_eigen(size_t len, float* va, float* vb)\n{\n    Eigen::Map<Eigen::Matrix<float, 1, Eigen::Dynamic, Eigen::RowMajor>> vva(va, len);\n    Eigen::Map<Eigen::Matrix<float, 1, Eigen::Dynamic, Eigen::RowMajor>> vvb(vb, len);\n    float res = vva.dot(vvb);\n    return res;\n}\n\nstatic void matrix_add_f32_eigen(float* mA, float* mB, float* mC, const size_t M, const size_t N)\n{\n    using namespace Eigen;\n    Map<Matrix<float, Dynamic, Dynamic, RowMajor>> eA(mA, M, N);\n    Map<Matrix<float, Dynamic, Dynamic, RowMajor>> eB(mB, M, N);\n    Map<Matrix<float, Dynamic, Dynamic, RowMajor>> eC(mC, M, N);\n    eC = eA + eB;\n}\n\n// \u4f8b\u5b501\uff1a\u521b\u5efa2x2\u77e9\u9635\uff0c\u9010\u5143\u7d20\u8d4b\u503c\uff0c\u7136\u540e\u8f93\u51fa\nstatic void eigen_example1()\n{\n    LOGD(\"--- %s ---\\n\", __FUNCTION__);\n    MatrixXd m(2,2); // MatrixXd\u662f\u6700\u5e38\u7528\u7684Eigen\u6570\u636e\u7c7b\u578b\uff0cX\u8868\u793a\u4efb\u610f\u5c3a\u5bf8\uff0cd\u8868\u793adouble\u3002\u8fd9\u91cc\u521b\u5efa\u7684\u662f2x2\u89c4\u683c\u7684\u77e9\u9635\u3002\n    m(0,0) = 3; // \u8ffd\u5143\u7d20\u8d4b\u503c\uff0c\u6ce8\u610f\u662f\u7528\u5c0f\u62ec\u53f7\uff0c\u8fd9\u5e94\u8be5\u662f\u91cd\u8f7d\u4e86\u62ec\u53f7\u64cd\u4f5c\u7b26\n    m(1,0) = 2.5;\n    m(0,1) = -1;\n    m(1,1) = m(1,0) + m(0,1);\n    cout << m << endl; // \u8f93\u51fa\u77e9\u9635\uff0c\u76f4\u63a5std::cout\u5373\u53ef\uff0c\u8bf4\u660e\u6709\u91cd\u8f7d<<\u64cd\u4f5c\u7b26\n}\n\n// \u77e9\u9635\u4e58\u4ee5\u5411\u91cf\u7684\u4f8b\u5b50\u3002\nstatic void eigen_example2()\n{\n    LOGD(\"--- %s ---\\n\", __FUNCTION__);\n    MatrixXd m = MatrixXd::Random(3,3); //\u521b\u5efa3x3\u77e9\u9635\uff0c\u5143\u7d20\u4e3a[-1,1]\u4e4b\u95f4\u7684\u968f\u673a\u6d6e\u70b9\u6570\n\n    m = (m+MatrixXd::Constant(3, 3, 1.2)) * 50;//[-1,1] + 1.2 = [0.2, 2.2]; [0.2, 2.2]*50=[10, 110]\n    // \u4e5f\u5c31\u662f\u628a\u539f\u672c\u5728[-1,1]\u4e4b\u95f4\u7684\u5404\u4e2a\u5143\u7d20\uff0c\u6620\u5c04\u5230[10, 110]\u4e4b\u95f4\n\n    cout << \"m=\" << endl << m << endl;\n\n    VectorXd v(3); // \u521b\u5efa\u4e00\u4e2a3\u884c\u7684\u5217\u5411\u91cfv\n\n    v << 1, 2, 3; // \u7ed9\u5217\u5411\u91cf\u8d4b\u503c\uff0c\u5206\u522b\u4e3a1,2,3\n\n    cout << \"m*v=\" << endl << m*v << endl; // \u8ba1\u7b97 m*v\uff0c\u4e5f\u5c31\u662f\u77e9\u9635\u4e58\u4ee5\u5411\u91cf\uff0c\u5e76\u8f93\u51fa\u7ed3\u679c\n}\n\n// eigen_example2\u7684\u53e6\u4e00\u4e2a\u7248\u672c\uff1a\u4f7f\u7528\u5177\u4f53\u5c3a\u5bf8\u7684\u7c7b\u578b\uff0c\u800c\u4e0d\u662fMatrixXd\u548cVectorXd\nstatic void eigen_example2_2()\n{\n    LOGD(\"--- %s ---\\n\", __FUNCTION__);\n    Matrix3d m = Matrix3d::Random();\n    m = (m+Matrix3d::Constant(1.2)) * 50;\n    cout << \"m=\" << endl << m << endl;\n    Vector3d v(1,2,3);\n    cout << \"m*v=\" << endl << m*v << endl;\n}\n\n// \u8bbf\u95ee\u7cfb\u6570\uff08\u5143\u7d20\uff09\nstatic void eigen_example3()\n{\n    LOGD(\"--- %s ---\\n\", __FUNCTION__);\n    MatrixXd m(2,2);\n    m(0, 0) = 3;\n    m(1, 0) = 2.5;\n    m(0, 1) = -1;\n    m(1, 1) = m(1, 0) + m(0, 1);\n    cout << \"Here is the matrix m:\\n\" << m << endl;\n\n    VectorXd v(2);\n    v(0) = 4;\n    v(1) = v(0) - 1;\n    cout << \"Here is the vector v:\\n\" << v << endl;\n}\n\n// \u7528\u9017\u53f7\u8868\u8fbe\u5f0f\u521d\u59cb\u5316\nstatic void eigen_example4()\n{\n    LOGD(\"--- %s ---\\n\", __FUNCTION__);\n    Matrix3f m; // \u58f0\u660e\n\n    // \u521d\u59cb\u5316\u3002\u6ce8\u610f\uff1a\u5fc5\u987b\u5148\u58f0\u660e\uff0c\u624d\u80fd\u7528\u9017\u53f7\u8868\u8fbe\u5f0f\u521d\u59cb\u5316\uff1b\u5b9a\u4e49\u65f6\u76f4\u63a5\u7528\u9017\u53f7\u8868\u8fbe\u5f0f\u521d\u59cb\u5316\u4f1a\u62a5\u9519\n    // \u56e0\u4e3a\u8fd9\u4e2a\u521d\u59cb\u5316\u5176\u5b9e\u662f\u901a\u8fc7\u91cd\u8f7d<<\u64cd\u4f5c\u7b26\u5b9e\u73b0\u7684\n    m << 1, 2, 3,\n       4, 5, 6,\n       7, 8, 9;\n    cout << m << endl;\n}\n\n// \u8f93\u51fa\u7ef4\u5ea6\u4fe1\u606f\u3001\u5143\u7d20\u4e2a\u6570\uff1b\u52a8\u6001\u5c3a\u5bf8\u77e9\u9635/\u5411\u91cf\u7684resize\nstatic void eigen_example5()\n{\n    LOGD(\"--- %s ---\\n\", __FUNCTION__);\n    MatrixXd m(2, 5);\n    m.resize(4, 3);\n    printf(\"The matrix m is of size: rows=%d, cols=%d, num elements=%d\\n\",\n        m.rows(), m.cols(), m.size());\n    \n    VectorXd v(2);\n    v.resize(5);\n    std::cout << \"The vector v is of size \" << v.size() << endl;\n    printf(\"As a matrix, v is of size: rows=%d, cols=%d\\n\", v.rows(), v.cols());\n}\n\n// \u52a8\u6001\u5c3a\u5bf8\u77e9\u9635\u8d4b\u503c\uff0c\u5982\u679c\u5c3a\u5bf8\u4e0d\u540c\uff0c\u5219\u81ea\u52a8\u628a\u7b49\u53f7\u5de6\u8fb9\u7684\u77e9\u9635resize\nstatic void eigen_example5_2()\n{\n    LOGD(\"--- %s ---\\n\", __FUNCTION__);\n    MatrixXf a(2, 2);\n    printf(\"originally, a's size: row=%d, col=%d\\n\", a.rows(), a.cols());\n    MatrixXf b(3, 3);\n    a = b;\n    printf(\"after assign, a's size: row=%d, col=%d\\n\", a.rows(), a.cols());\n}\n\n// eigen_example5_2\u7684\u4fee\u6539\uff0c\u4ece\u56fa\u5b9a\u5c3a\u5bf8(3x3)\u7684\u77e9\u9635\uff0c\u8d4b\u503c\u7ed9\u52a8\u6001\u7ef4\u5ea6\u76842x2\u77e9\u9635\uff0c\u9690\u5f0fresize\nstatic void eigen_example5_3()\n{\n    LOGD(\"--- %s ---\\n\", __FUNCTION__);\n    MatrixXf a(2, 2);\n    printf(\"originally, a's size: row=%d, col=%d\\n\", a.rows(), a.cols());\n    Matrix3f b;\n    b << 1, 2, 3,\n       4, 5, 6,\n       7, 8, 9;\n    a = b;\n    printf(\"after assign, a's size: row=%d, col=%d\\n\", a.rows(), a.cols());\n}\n\nint main() {\n    eigen_example1();\n    eigen_example2();\n    eigen_example2_2();\n    eigen_example3();\n    eigen_example4();\n    eigen_example5();\n    eigen_example5_2();\n    eigen_example5_3();\n\n    return 0;\n}", "meta": {"hexsha": "4584a0beec6b5ff78cb4da7b40e9c3d60e7564e3", "size": 4135, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "matcalc/eigen_test.cpp", "max_stars_repo_name": "zchrissirhcz/pixel", "max_stars_repo_head_hexsha": "6bfe4b2f2b80de64c7de4b6d8735de8000b7dc3a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 38.0, "max_stars_repo_stars_event_min_datetime": "2020-12-23T16:37:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T13:46:04.000Z", "max_issues_repo_path": "matcalc/eigen_test.cpp", "max_issues_repo_name": "zchrissirhcz/pixel", "max_issues_repo_head_hexsha": "6bfe4b2f2b80de64c7de4b6d8735de8000b7dc3a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-01-31T16:04:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T13:58:11.000Z", "max_forks_repo_path": "matcalc/eigen_test.cpp", "max_forks_repo_name": "zchrissirhcz/pixel", "max_forks_repo_head_hexsha": "6bfe4b2f2b80de64c7de4b6d8735de8000b7dc3a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-11-23T09:33:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-15T08:13:56.000Z", "avg_line_length": 25.524691358, "max_line_length": 99, "alphanum_fraction": 0.576541717, "num_tokens": 1781, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.7035011074073407}}
{"text": "// The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt\r\n/*\r\n    This is an example illustrating the use of the running_stats object from the dlib C++\r\n    Library.  It is a simple tool for computing basic statistics on a stream of numbers.\r\n    In this example, we sample 100 points from the sinc function and then then compute the\r\n    unbiased sample mean, variance, skewness, and excess kurtosis.\r\n\r\n*/    \r\n#include <iostream>\r\n#include <vector>\r\n#include <dlib/statistics.h>\r\n\r\nusing namespace std;\r\nusing namespace dlib;\r\n\r\n// Here we define the sinc function so that we may generate sample data. We compute the mean,\r\n// variance, skewness, and excess kurtosis of this sample data.\r\n\r\ndouble sinc(double x)\r\n{\r\n    if (x == 0)\r\n        return 1;\r\n    return sin(x)/x;\r\n}\r\n\r\nint main()\r\n{\r\n    running_stats<double> rs;\r\n\r\n    double tp1 = 0;\r\n    double tp2 = 0;\r\n\r\n    // We first generate the data and add it sequentially to our running_stats object.  We\r\n    // then print every fifth data point.\r\n    for (int x = 1; x <= 100; x++)\r\n    {\r\n        tp1 = x/100.0;\r\n        tp2 = sinc(pi*x/100.0);\r\n        rs.add(tp2);\r\n\r\n        if(x % 5 == 0)\r\n        {\r\n            cout << \" x = \" << tp1 << \" sinc(x) = \" << tp2 << endl;\r\n        }\r\n    }\r\n\r\n    // Finally, we compute and print the mean, variance, skewness, and excess kurtosis of\r\n    // our data.\r\n\r\n    cout << endl;\r\n    cout << \"Mean:           \" << rs.mean() << endl;\r\n    cout << \"Variance:       \" << rs.variance() << endl;\r\n    cout << \"Skewness:       \" << rs.skewness() << endl;\r\n    cout << \"Excess Kurtosis \" << rs.ex_kurtosis() << endl;\r\n\r\n    return 0;\r\n}\r\n\r\n", "meta": {"hexsha": "d132f6ab453c75132d76c2c6fec5ff8ff1361593", "size": 1676, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/running_stats_ex.cpp", "max_stars_repo_name": "ckproc/dlib-19.7", "max_stars_repo_head_hexsha": "0ca40f5e85de2436e557bee9a805d3987d2d9507", "max_stars_repo_licenses": ["BSL-1.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": "examples/running_stats_ex.cpp", "max_issues_repo_name": "ckproc/dlib-19.7", "max_issues_repo_head_hexsha": "0ca40f5e85de2436e557bee9a805d3987d2d9507", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2018-02-27T15:44:25.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-28T01:26:03.000Z", "max_forks_repo_path": "examples/running_stats_ex.cpp", "max_forks_repo_name": "ckproc/dlib-19.7", "max_forks_repo_head_hexsha": "0ca40f5e85de2436e557bee9a805d3987d2d9507", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.406779661, "max_line_length": 94, "alphanum_fraction": 0.5859188544, "num_tokens": 437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870046160257, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.7034091753605487}}
{"text": "// Copyright 2018 Hans Dembinski\n//\n// Distributed under the 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//[ guide_stdlib_algorithms\n\n#include <boost/histogram.hpp>\n#include <cassert>\n\n#include <algorithm> // fill, any_of, min_element, max_element\n#include <cmath>     // sqrt\n#include <numeric>   // partial_sum, inner_product\n\nint main() {\n  using namespace boost::histogram;\n\n  // make histogram that represents a probability density function (PDF)\n  auto h1 = make_histogram(axis::regular<>(4, 1.0, 3.0));\n\n  // use std::fill to set all counters to 0.25, including *flow cells\n  std::fill(h1.begin(), h1.end(), 0.25);\n  // reset *flow cells to zero\n  h1.at(-1) = h1.at(4) = 0;\n\n  // compute the cumulative density function (CDF), overriding cell values\n  std::partial_sum(h1.begin(), h1.end(), h1.begin());\n\n  assert(h1.at(-1) == 0.0);\n  assert(h1.at(0) == 0.25);\n  assert(h1.at(1) == 0.50);\n  assert(h1.at(2) == 0.75);\n  assert(h1.at(3) == 1.00);\n  assert(h1.at(4) == 1.00);\n\n  // use any_of to check if any cell values are smaller than 0.1,\n  // and use indexed() to skip underflow and overflow cells\n  auto h1_ind = indexed(h1);\n  const auto any_small =\n      std::any_of(h1_ind.begin(), h1_ind.end(), [](const auto& x) { return *x < 0.1; });\n  assert(any_small == false); // underflow and overflow are zero, but skipped\n\n  // find maximum element\n  const auto max_it = std::max_element(h1.begin(), h1.end());\n  assert(max_it == h1.end() - 2);\n\n  // find minimum element\n  const auto min_it = std::min_element(h1.begin(), h1.end());\n  assert(min_it == h1.begin());\n\n  // make second PDF\n  auto h2 = make_histogram(axis::regular<>(4, 1.0, 4.0));\n  h2.at(0) = 0.1;\n  h2.at(1) = 0.3;\n  h2.at(2) = 0.2;\n  h2.at(3) = 0.4;\n\n  // computing cosine similiarity: cos(theta) = A dot B / sqrt((A dot A) * (B dot B))\n  const auto aa = std::inner_product(h1.begin(), h1.end(), h1.begin(), 0.0);\n  const auto bb = std::inner_product(h2.begin(), h2.end(), h2.begin(), 0.0);\n  const auto ab = std::inner_product(h1.begin(), h1.end(), h2.begin(), 0.0);\n  const auto cos_sim = ab / std::sqrt(aa * bb);\n\n  assert(std::abs(cos_sim - 0.78) < 1e-2);\n}\n\n//]\n", "meta": {"hexsha": "73691bb0bc6b67ccce9a504f24785a2ff1e2a1db", "size": 2229, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/guide_stdlib_algorithms.cpp", "max_stars_repo_name": "henryiii/histogram", "max_stars_repo_head_hexsha": "d9f000cb86a4b4ac5ebfcb395616fa9aaa28e06c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 44.0, "max_stars_repo_stars_event_min_datetime": "2020-12-21T05:14:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T11:27:32.000Z", "max_issues_repo_path": "examples/guide_stdlib_algorithms.cpp", "max_issues_repo_name": "henryiii/histogram", "max_issues_repo_head_hexsha": "d9f000cb86a4b4ac5ebfcb395616fa9aaa28e06c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 79.0, "max_issues_repo_issues_event_min_datetime": "2018-08-01T11:50:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-17T13:40:06.000Z", "max_forks_repo_path": "examples/guide_stdlib_algorithms.cpp", "max_forks_repo_name": "henryiii/histogram", "max_forks_repo_head_hexsha": "d9f000cb86a4b4ac5ebfcb395616fa9aaa28e06c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 21.0, "max_forks_repo_forks_event_min_datetime": "2020-12-22T09:40:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-07T18:16:00.000Z", "avg_line_length": 32.3043478261, "max_line_length": 88, "alphanum_fraction": 0.6401973979, "num_tokens": 729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319862, "lm_q2_score": 0.8031737987125613, "lm_q1q2_score": 0.7034091701527383}}
{"text": "#define BOOST_TEST_MODULE test_utils\n\n#include <boost/test/unit_test.hpp>\n#include <Utils/utils.h>\n#include <Utils/bshelper.h>\n\nnamespace utf = boost::unit_test;\n\nBOOST_AUTO_TEST_SUITE(utils_boost)\n\n    BOOST_AUTO_TEST_CASE(annual_cap1) {\n        BOOST_TEST_MESSAGE(\"Testing annual_cap1\");\n        BOOST_TEST_MESSAGE(\"using tolerances within checks.\");\n\n        double amount = 100;\n        double annual_rate = 10.0 / 100;\n        int number_of_years = 2;\n        double theoretical_value = 121; // (100*(1.1)^2)\n\n        auto calculated_value = annual_capitalization(amount, annual_rate, number_of_years);\n\n        BOOST_TEST_MESSAGE(\" - calculated_value: \" << calculated_value);\n        BOOST_TEST_MESSAGE(\" - known_capitalization: \" << theoretical_value);\n        BOOST_TEST_MESSAGE(\" - diff \" << calculated_value - theoretical_value);\n        BOOST_TEST(theoretical_value == calculated_value, boost::test_tools::tolerance(1e-15));\n    }\n\n    BOOST_AUTO_TEST_CASE(annual_discount1) {\n        BOOST_TEST_MESSAGE(\"Testing annual_discount1\");\n        BOOST_TEST_MESSAGE(\"using tolerances within checks.\");\n\n        double amount = 121;\n        double annual_rate = 10.0 / 100;\n        int number_of_years = 2;\n        double theoretical_value = 100; // (121/(1.1)^2)\n\n        auto calculated_value = discount_annually(amount, annual_rate, number_of_years);\n\n        BOOST_TEST_MESSAGE(\" - calculated_value: \" << calculated_value);\n        BOOST_TEST_MESSAGE(\" - known discounted_value: \" << theoretical_value);\n        BOOST_TEST_MESSAGE(\" - diff \" << calculated_value - theoretical_value);\n        BOOST_TEST(theoretical_value == calculated_value, boost::test_tools::tolerance(1e-15));\n    }\n\n    BOOST_AUTO_TEST_CASE(period_cap1) {\n        BOOST_TEST_MESSAGE(\"Testing period_cap1\");\n        BOOST_TEST_MESSAGE(\"using tolerances within checks.\");\n\n        double amount = 100;\n        double annual_rate = 10.0 / 100;\n        int periods_per_year = 2;\n        int number_of_years = 1;\n        double theoretical_value = 110.25; // (100*(1.05)^2)\n\n        auto calculated_value = period_capitalization(amount, annual_rate, periods_per_year, number_of_years);\n\n        BOOST_TEST_MESSAGE(\" - calculated_value: \" << calculated_value);\n        BOOST_TEST_MESSAGE(\" - known_capitalization: \" << theoretical_value);\n        BOOST_TEST_MESSAGE(\" - diff \" << calculated_value - theoretical_value);\n        BOOST_TEST(theoretical_value == calculated_value, boost::test_tools::tolerance(1e-15));\n    }\n\n    BOOST_AUTO_TEST_CASE(period_discount1) {\n        BOOST_TEST_MESSAGE(\"Testing period_discount1\");\n        BOOST_TEST_MESSAGE(\"using tolerances within checks.\");\n\n        double amount = 110.25;\n        double annual_rate = 10.0 / 100;\n        int periods_per_year = 2;\n        int number_of_years = 1;\n        double theoretical_value = 100; // (110.25/(1.05)^2)\n\n        auto calculated_value = discount_by_periods(amount, annual_rate, periods_per_year, number_of_years);\n\n        BOOST_TEST_MESSAGE(\" - calculated_value: \" << calculated_value);\n        BOOST_TEST_MESSAGE(\" - known discounted_value: \" << theoretical_value);\n        BOOST_TEST_MESSAGE(\" - diff \" << calculated_value - theoretical_value);\n        BOOST_TEST(theoretical_value == calculated_value, boost::test_tools::tolerance(1e-15));\n    }\n\n    BOOST_AUTO_TEST_CASE(continuous_cap1) {\n        BOOST_TEST_MESSAGE(\"Testing continuous_cap1\");\n        BOOST_TEST_MESSAGE(\"using tolerances within checks.\");\n\n        double amount = 100;\n        double annual_rate = 10.0 / 100;\n        int number_of_years = 2;\n        double theoretical_value = 122.140275816; // 100 * e^(0.10*2) rounded to second\n\n        auto calculated_value = continuous_capitalization(amount, annual_rate, number_of_years);\n\n        BOOST_TEST_MESSAGE(\" - calculated_value: \" << calculated_value);\n        BOOST_TEST_MESSAGE(\" - known_capitalization: \" << theoretical_value);\n        BOOST_TEST_MESSAGE(\" - diff \" << calculated_value - theoretical_value);\n        BOOST_TEST(theoretical_value == calculated_value, boost::test_tools::tolerance(1e-8));\n    }\n\n    BOOST_AUTO_TEST_CASE(continuous_discount1) {\n        BOOST_TEST_MESSAGE(\"Testing continuous_discount1\");\n        BOOST_TEST_MESSAGE(\"using tolerances within checks.\");\n\n        double amount = 122.140275816;\n        double annual_rate = 10.0 / 100;\n        int number_of_years = 2;\n        double theoretical_value = 100; // 122.140275816 / e^(0.10*2) rounded to second\n\n        auto calculated_value = discount_continuously(amount, annual_rate, number_of_years);\n\n        BOOST_TEST_MESSAGE(\" - calculated_value: \" << calculated_value);\n        BOOST_TEST_MESSAGE(\" - known discounted_value: \" << theoretical_value);\n        BOOST_TEST_MESSAGE(\" - diff \" << calculated_value - theoretical_value);\n        BOOST_TEST(theoretical_value == calculated_value, boost::test_tools::tolerance(1e-8));\n    }\n\n    BOOST_AUTO_TEST_CASE(fwd_rate1) {\n        BOOST_TEST_MESSAGE(\"Testing fwd_rate1\");\n        BOOST_TEST_MESSAGE(\"using tolerances within checks.\");\n\n        double zero_coupon_total = 0.04;\n        int years_total = 2;\n\n        double zero_coupon_partial = 0.03;\n        int years_partial = 1;\n\n        double theoretical_value = 0.05; // (100*(1.1)^2) rounded to second\n\n        auto calculated_value = forward_rate(zero_coupon_total, years_total, zero_coupon_partial, years_partial);\n\n        BOOST_TEST_MESSAGE(\" - calculated_value: \" << calculated_value);\n        BOOST_TEST_MESSAGE(\" - known_fwd_rate: \" << theoretical_value);\n        BOOST_TEST_MESSAGE(\" - diff \" << calculated_value - theoretical_value);\n        BOOST_TEST(theoretical_value == calculated_value, boost::test_tools::tolerance(1e-15));\n    }\n\n    BOOST_AUTO_TEST_CASE(annual_to_cont1) {\n        BOOST_TEST_MESSAGE(\"Testing annual_to_cont1\");\n        BOOST_TEST_MESSAGE(\"using tolerances within checks.\");\n\n        double annual_rate = 0.12;\n\n        double theoretical_value = 0.1133286853; // ln(1.12)\n\n        auto calculated_value = annual_to_continuous_rate(1, annual_rate);\n\n        BOOST_TEST_MESSAGE(\" - calculated_value: \" << calculated_value);\n        BOOST_TEST_MESSAGE(\" - known_fwd_rate: \" << theoretical_value);\n        BOOST_TEST_MESSAGE(\" - diff \" << calculated_value - theoretical_value);\n        BOOST_TEST(theoretical_value == calculated_value, boost::test_tools::tolerance(1e-10));\n    }\n\n    BOOST_AUTO_TEST_CASE(cont_to_annual) {\n        BOOST_TEST_MESSAGE(\"Testing cont_to_annual\");\n        BOOST_TEST_MESSAGE(\"using tolerances within checks.\");\n\n        double continuous_rate = 0.11332868531; //(e^0.1)-1\n\n        double theoretical_value = 0.12; // (e^0.1)-1\n\n        auto calculated_value = continuous_to_annual_rate(1, continuous_rate);\n\n        BOOST_TEST_MESSAGE(\" - calculated_value: \" << calculated_value);\n        BOOST_TEST_MESSAGE(\" - known_fwd_rate: \" << theoretical_value);\n        BOOST_TEST_MESSAGE(\" - diff \" << calculated_value - theoretical_value);\n        BOOST_TEST(theoretical_value == calculated_value, boost::test_tools::tolerance(1e-9));\n    }\n\n    BOOST_AUTO_TEST_CASE(total_day_count, *utf::tolerance(0.0001)) {\n        BOOST_TEST_MESSAGE(\"Testing cont_to_annual\");\n        BOOST_TEST_MESSAGE(\"using tolerances within checks.\");\n\n        double myDoubles[] = {185.0 / 360, 182.0 / 360, 182.0 / 360, 182.0 / 360};\n        std::vector<double> dayCountFractionVector(myDoubles, myDoubles + sizeof(myDoubles) / sizeof(double));\n\n        std::vector<double> calculated_values = getTotalDayCountFractionVector(dayCountFractionVector);\n\n        double myResults[] = {0.513888888889, 1.019444444444, 1.525000000000, 2.030555555556};\n        std::vector<double> expected_values(myResults, myResults + sizeof(myResults) / sizeof(double));\n\n        BOOST_TEST(calculated_values == expected_values, boost::test_tools::per_element());\n\n    }\n\n    BOOST_AUTO_TEST_CASE(black_scholes_d1) {\n        BOOST_TEST_MESSAGE(\"Testing black_scholes_d1\");\n        BOOST_TEST_MESSAGE(\"using tolerances within checks.\");\n\n        double asset_price = 50.0;\n        double strike = 50.0;\n        double rate = 3.66 / 100;\n        double volatility = 62.0 / 100;\n        double time_to_maturity = 5.0;\n\n        double theoretical_value = 0.8251812; // (e^0.1)-1\n\n        auto calculated_value = getD1(asset_price, strike, rate, volatility, time_to_maturity);\n\n        BOOST_TEST_MESSAGE(\" - calculated_value: \" << calculated_value);\n        BOOST_TEST_MESSAGE(\" - known_d1_value: \" << theoretical_value);\n        BOOST_TEST_MESSAGE(\" - diff \" << calculated_value - theoretical_value);\n        BOOST_TEST(theoretical_value == calculated_value, boost::test_tools::tolerance(1e-7));\n    }\n\n    BOOST_AUTO_TEST_CASE(black_scholes_d2) {\n        BOOST_TEST_MESSAGE(\"Testing black_scholes_d2\");\n        BOOST_TEST_MESSAGE(\"using tolerances within checks.\");\n\n        double asset_price = 50.0;\n        double strike = 50.0;\n        double rate = 3.66 / 100;\n        double volatility = 62.0 / 100;\n        double time_to_maturity = 5.0;\n\n        double theoretical_value = -0.5611809; // (e^0.1)-1\n\n        auto calculated_value = getD2(asset_price, strike, rate, volatility, time_to_maturity);\n\n        BOOST_TEST_MESSAGE(\" - calculated_value: \" << calculated_value);\n        BOOST_TEST_MESSAGE(\" - known_d2_value: \" << theoretical_value);\n        BOOST_TEST_MESSAGE(\" - diff \" << calculated_value - theoretical_value);\n        BOOST_TEST(theoretical_value == calculated_value, boost::test_tools::tolerance(1e-7));\n    }\n\n    BOOST_AUTO_TEST_CASE(black_scholes_weightAsset) {\n        BOOST_TEST_MESSAGE(\"Testing black_scholes_weightAsset\");\n        BOOST_TEST_MESSAGE(\"using tolerances within checks.\");\n\n        double asset_price = 50.0;\n        double option_d1 = 0.8251812; //pre-calculated value\n\n        double theoretical_value = 39.7682821; // (e^0.1)-1\n\n        auto calculated_value = weightAsset(asset_price, option_d1);\n\n        BOOST_TEST_MESSAGE(\" - calculated_value: \" << calculated_value);\n        BOOST_TEST_MESSAGE(\" - known_asset_contribution: \" << theoretical_value);\n        BOOST_TEST_MESSAGE(\" - diff \" << calculated_value - theoretical_value);\n        BOOST_TEST(theoretical_value == calculated_value, boost::test_tools::tolerance(1e-7));\n    }\n\n    BOOST_AUTO_TEST_CASE(black_scholes_weightStrike) {\n        BOOST_TEST_MESSAGE(\"Testing black_scholes_weightStrike\");\n        BOOST_TEST_MESSAGE(\"using tolerances within checks.\");\n\n        double strike = 50.0;\n        double rate = 3.66 / 100;\n        double time_to_maturity = 5.0;\n        double option_d2 = -0.5611809; //pre-calculated value\n\n        double theoretical_value = 11.9642594; // (e^0.1)-1\n\n        auto calculated_value = weightStrike(strike, option_d2, rate, time_to_maturity);\n\n        BOOST_TEST_MESSAGE(\" - calculated_value: \" << calculated_value);\n        BOOST_TEST_MESSAGE(\" - known_asset_contribution: \" << theoretical_value);\n        BOOST_TEST_MESSAGE(\" - diff \" << calculated_value - theoretical_value);\n        BOOST_TEST(theoretical_value == calculated_value, boost::test_tools::tolerance(1e-7));\n    }\n\n    BOOST_AUTO_TEST_CASE(black_scholes_evaluateCall) {\n        BOOST_TEST_MESSAGE(\"Testing black_scholes_evaluateCall\");\n        BOOST_TEST_MESSAGE(\"using tolerances within checks.\");\n\n        double option_strike = 50.0;\n        double time_to_maturity = 5.0;\n        double rate = 3.66 / 100;\n        double volatility = 62.0 / 100;\n        double asset_price = 50.0;\n\n        double theoretical_value = 27.804023; // (e^0.1)-1\n\n        auto calculated_value = evaluateCall(option_strike, time_to_maturity, rate, volatility, asset_price);\n\n        BOOST_TEST_MESSAGE(\" - calculated_value: \" << calculated_value);\n        BOOST_TEST_MESSAGE(\" - known_asset_contribution: \" << theoretical_value);\n        BOOST_TEST_MESSAGE(\" - diff \" << calculated_value - theoretical_value);\n        BOOST_TEST(theoretical_value == calculated_value, boost::test_tools::tolerance(1e-6));\n    }\n\n    BOOST_AUTO_TEST_CASE(black_scholes_evaluatePut) {\n        BOOST_TEST_MESSAGE(\"Testing black_scholes_evaluatePut\");\n        BOOST_TEST_MESSAGE(\"using tolerances within checks.\");\n\n        double option_strike = 50.0;\n        double time_to_maturity = 5.0;\n        double rate = 3.66 / 100;\n        double volatility = 62.0 / 100;\n        double asset_price = 50.0;\n\n        double theoretical_value = 19.442431; // (e^0.1)-1\n\n        auto calculated_value = evaluatePut(option_strike, time_to_maturity, rate, volatility, asset_price);\n\n        BOOST_TEST_MESSAGE(\" - calculated_value: \" << calculated_value);\n        BOOST_TEST_MESSAGE(\" - known_asset_contribution: \" << theoretical_value);\n        BOOST_TEST_MESSAGE(\" - diff \" << calculated_value - theoretical_value);\n        BOOST_TEST(theoretical_value == calculated_value, boost::test_tools::tolerance(1e-6));\n    }\n\n    BOOST_AUTO_TEST_CASE(black_scholes_blackScholesCall) {\n        BOOST_TEST_MESSAGE(\"Testing black_scholes_blackScholesCall\");\n        BOOST_TEST_MESSAGE(\"using tolerances within checks.\");\n\n        double option_strike = 50.0;\n        double time_to_maturity = 5.0;\n        double rate = 3.66 / 100;\n        double volatility = 62.0 / 100;\n        double asset_price = 50.0;\n\n\n        double theoretical_value = 27.804023; // (e^0.1)-1\n\n        auto calculated_value = blackScholes(call, option_strike, time_to_maturity, rate, volatility, asset_price);\n\n        BOOST_TEST_MESSAGE(\" - calculated_value: \" << calculated_value);\n        BOOST_TEST_MESSAGE(\" - known_asset_contribution: \" << theoretical_value);\n        BOOST_TEST_MESSAGE(\" - diff \" << calculated_value - theoretical_value);\n        BOOST_TEST(theoretical_value == calculated_value, boost::test_tools::tolerance(1e-6));\n    }\n\n    BOOST_AUTO_TEST_CASE(black_scholes_blackScholesPut) {\n        BOOST_TEST_MESSAGE(\"Testing black_scholes_blackScholesPut\");\n        BOOST_TEST_MESSAGE(\"using tolerances within checks.\");\n\n        double option_strike = 50.0;\n        double time_to_maturity = 5.0;\n        double rate = 3.66 / 100;\n        double volatility = 62.0 / 100;\n        double asset_price = 50.0;\n\n\n        double theoretical_value = 19.442431; // (e^0.1)-1\n\n        auto calculated_value = blackScholes(put, option_strike, time_to_maturity, rate, volatility, asset_price);\n\n        BOOST_TEST_MESSAGE(\" - calculated_value: \" << calculated_value);\n        BOOST_TEST_MESSAGE(\" - known_asset_contribution: \" << theoretical_value);\n        BOOST_TEST_MESSAGE(\" - diff \" << calculated_value - theoretical_value);\n        BOOST_TEST(theoretical_value == calculated_value, boost::test_tools::tolerance(1e-6));\n    }\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "e83c855da7efc8dcf7b02adc2d6de2b3ca7e974e", "size": 14663, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "assignment/src/Utils/tests/test.cpp", "max_stars_repo_name": "paulochang/finance_valuator_extended", "max_stars_repo_head_hexsha": "1c9f638d0b1dd888b4a1010c47c4e1999ed6f5bc", "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": "assignment/src/Utils/tests/test.cpp", "max_issues_repo_name": "paulochang/finance_valuator_extended", "max_issues_repo_head_hexsha": "1c9f638d0b1dd888b4a1010c47c4e1999ed6f5bc", "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/src/Utils/tests/test.cpp", "max_forks_repo_name": "paulochang/finance_valuator_extended", "max_forks_repo_head_hexsha": "1c9f638d0b1dd888b4a1010c47c4e1999ed6f5bc", "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.8742690058, "max_line_length": 115, "alphanum_fraction": 0.6862170088, "num_tokens": 3462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.8397339756938818, "lm_q1q2_score": 0.7033779351227094}}
{"text": "/// @file example_geqr2.cpp\n/// @author Weslley S Pereira, University of Colorado Denver, USA\n//\n// Copyright (c) 2022, University of Colorado Denver. All rights reserved.\n//\n// This file is part of <T>LAPACK.\n// <T>LAPACK is free software: you can redistribute it and/or modify it under\n// the terms of the BSD 3-Clause license. See the accompanying LICENSE file.\n\n#include <iostream>\n\n// Must be loaded in the following order\n#include <plugins/tlapack_eigen.hpp>\n#include <tlapack.hpp>\n\n#include <Eigen/Dense>\n#include <Eigen/Householder>\n\nint main( int argc, char** argv )\n{\n    using std::size_t;\n    using pair = std::pair<size_t,size_t>;\n    using namespace blas;\n    using namespace lapack;\n    using Eigen::Matrix;\n\n    // Constants\n    const size_t m = 5;\n    const size_t n = 3;\n\n    // Input data\n    Matrix<float, m, n> A {\n        { 1,  2,  3},\n        { 4,  5,  6},\n        { 7,  8,  9},\n        {10, 11, 12},\n        {13, 14, 15}\n    };\n\n    // Matrices\n    Matrix<float, m, n> Q = A;\n    Matrix<float, n, n> R = Matrix<float, n, n>::Zero();\n    Matrix<float, m, n> QtimesR = Matrix<float, m, n>::Zero();\n\n    std::cout << \"A = \" << std::endl << A << std::endl << std::endl;\n\n    // <T>LAPACK -----------------------------------------------\n    \n    std::cout << \"--- <T>LAPACK: ---\" << std::endl << std::endl;\n\n    // Allocates memory\n    Matrix<float, n, 1> tau;\n    Matrix<float, n-1, 1> work;\n    Matrix<float, n, n> orthQ;\n\n    // Compute QR decomposision in place\n    geqr2( Q, tau, work );\n    // Copy the upper triangle to R\n    lacpy( upper_triangle, submatrix(Q,pair{0,n},pair{0,n}), R );\n    // Generate Q\n    org2r( n, Q, tau, work );\n\n    std::cout << \"Q = \" << std::endl << Q << std::endl;\n    std::cout << std::endl;\n\n    std::cout << \"R = \" << std::endl << R << std::endl;\n    std::cout << std::endl;\n\n    // Checking A = Q R\n    lacpy( general_matrix, Q, QtimesR );\n    trmm( Side::Right, Uplo::Upper, Op::NoTrans, Diag::NonUnit, 1.0, R, QtimesR );\n    std::cout << \"QR = \" << std::endl << QtimesR << std::endl;\n    QtimesR -= A;\n    std::cout << \"\\\\|QR - A\\\\|_F/\\\\|A\\\\|_F = \" << std::endl << lange( frob_norm, QtimesR ) / lange( frob_norm, A ) << std::endl;\n    std::cout << std::endl;\n\n    // Checking orthogonality of Q\n    orthQ = Matrix<float, n, n>::Identity();\n    syrk( Uplo::Upper, Op::Trans, 1.0, Q, -1.0, orthQ );\n    std::cout << \"\\\\|Q^t Q - I\\\\|_F = \" << std::endl << lansy( frob_norm, upper_triangle, orthQ ) << std::endl;\n    std::cout << std::endl;\n\n    // Eigen -----------------------------------------------\n\n    std::cout << \"--- Eigen: ---\" << std::endl << std::endl;\n\n    // Compute QR decomposision in place, possibly allocating memory dynamically\n    Eigen::HouseholderQR<decltype(A)> qrEigen( A );\n    // Generate Q\n    Q = qrEigen.householderQ() * Matrix<float, m, n>::Identity();\n    // Copy the upper triangle to R\n    R = qrEigen.matrixQR().block(0,0,n,n).triangularView<Eigen::Upper>();\n\n    std::cout << \"Q = \" << std::endl << Q << std::endl;\n    std::cout << std::endl;\n\n    std::cout << \"R = \" << std::endl << R << std::endl;\n    std::cout << std::endl;\n\n    // Checking A = Q R\n    QtimesR = Q * R;\n    std::cout << \"QR = \" << std::endl << QtimesR << std::endl;\n    std::cout << \"\\\\|QR - A\\\\|_F/\\\\|A\\\\|_F = \" << (QtimesR-A).norm() / A.norm() << std::endl;\n    std::cout << std::endl;\n\n    // Checking orthogonality of Q\n    orthQ = Q.transpose() * Q - Matrix<float, n, n>::Identity();\n    std::cout << \"\\\\|Q^t Q - I\\\\|_F = \" << std::endl << orthQ.norm() << std::endl;\n    std::cout << std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "67dfe88b5896dbd5645dda9905f8805206608cf0", "size": 3579, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/eigen/example_eigen.cpp", "max_stars_repo_name": "rileyjmurray/tlapack", "max_stars_repo_head_hexsha": "640dc35a2eb0748b3c094efda8187a9e0b6a5762", "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": "examples/eigen/example_eigen.cpp", "max_issues_repo_name": "rileyjmurray/tlapack", "max_issues_repo_head_hexsha": "640dc35a2eb0748b3c094efda8187a9e0b6a5762", "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": "examples/eigen/example_eigen.cpp", "max_forks_repo_name": "rileyjmurray/tlapack", "max_forks_repo_head_hexsha": "640dc35a2eb0748b3c094efda8187a9e0b6a5762", "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": 31.6725663717, "max_line_length": 128, "alphanum_fraction": 0.5400949986, "num_tokens": 1153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.703278351153111}}
{"text": "#include <string>\n#include <sstream>\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <set>\n#include <map>\n#include <iomanip>\n#include <array>        // std::array\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n#include <algorithm>\n\n#include \"container.h\"\n\n// for position matrix\n#include <boost/numeric/ublas/matrix.hpp>\n\nusing namespace std;\n\n\n// print a matrix\nvoid print_matrix(boost::numeric::ublas::matrix<double> m)\n{\n    for (unsigned i = 0; i < m.size1(); ++ i)\n    {\n        for (unsigned j = 0; j < m.size2(); ++ j)\n        {\n            cout << m(i,j) << \"\\t\";\n        }\n        cout << endl;\n    }\n}\n\n\ndouble matrix_min(boost::numeric::ublas::matrix<double> x)\n{\n\tdouble v = 1e100;\n    for (int i = 0; i < x.size1(); ++ i)\n        for (int j = 0; j < x.size2(); ++ j)\n\t\t\tif(x(i,j) < v)\n\t\t\t\tv = x(i,j);\n\treturn v;\n}\n\ndouble matrix_max(boost::numeric::ublas::matrix<double> x)\n{\n\tdouble v = -1e100;\n    for (int i = 0; i < x.size1(); ++ i)\n        for (int j = 0; j < x.size2(); ++ j)\n\t\t\tif(x(i,j) > v)\n\t\t\t\tv = x(i,j);\n\treturn v;\n}\n\n// max of each column\nvector<double> matrix_column_max(boost::numeric::ublas::matrix<double> x)\n{\n\tvector<double> res;\n    for (int j = 0; j < x.size2(); ++ j)\n\t{\n\t\tres.push_back(x(0,j));\n\t\tfor (int i = 1; i < x.size1(); ++ i)\n\t\t{\n\t\t\tif(x(i,j) > res[j]) res[j] = x(i,j);\n\t\t}\n\t}\n\treturn res;\n}\n\n// min of each column\nvector<double> matrix_column_min(boost::numeric::ublas::matrix<double> x)\n{\n\tvector<double> res;\n    for (int j = 0; j < x.size2(); ++ j)\n\t{\n\t\tres.push_back(x(0,j));\n\t\tfor (int i = 1; i < x.size1(); ++ i)\n\t\t{\n\t\t\tif(x(i,j) < res[j]) res[j] = x(i,j);\n\t\t}\n\t}\n\treturn res;\n}\n\n// min of each column\nvector<double> matrix_column_information_content(boost::numeric::ublas::matrix<double> x)\n{\n\tvector<double> res;\n    for (int j = 0; j < x.size2(); ++ j)\n\t{\n\t\tres.push_back(log2(x.size1()));\n\t\tfor (int i = 0; i < x.size1(); ++ i)\n\t\t{\n\t\t\tif( x(i,j) > 0 && x(i,j)<= 1) res[j] += x(i,j) * log2(x(i,j));\n\t\t\telse if (x(i,j) < 0 || x(i,j)>1)\n\t\t\t{\n\t\t\t\tcerr << \"ERROR: matrix_column_information_content, element out of range [0,1]\" << endl;\n\t\t\t\texit(1);\n\t\t\t}\n\t\t}\n\t}\n\treturn res;\n}\n    \n// positive:\n// >0: only sum positive\n// <0: only sum negative\n// =0: both \nvector<double> matrix_column_sum(boost::numeric::ublas::matrix<double> x, int positive)\n{\n\tvector<double> res;\n    for (int i = 0; i < x.size2(); ++ i) // column\n\t{\n\t\tres.push_back(0);\n        for (int j = 0; j < x.size1(); ++ j) // row\n\t\t{\n\t\t\tif( positive > 0)\n\t\t\t{\n\t\t\t\tif (x(j,i)>0) res[i] += x(j,i);\n\t\t\t}\n\t\t    else if (positive <0)\n\t\t\t{\n\t\t\t\tif (x(j,i)<0) res[i] += x(j,i);\n\t\t\t}\n\t\t\telse\n\t\t\t\tres[i] += x(j,i);\n\t\t\t//cout << i << \"\\t\" << res[i] << endl;\n\t\t}\n\t}\n\treturn res;\n}\n", "meta": {"hexsha": "a458bc682895c7432761d1511f448c92182e5ccd", "size": 2712, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/container.cpp", "max_stars_repo_name": "xuebingwu/xtools", "max_stars_repo_head_hexsha": "b9078cb7228f0bc227e6eab917fbafe769f5ffc1", "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/container.cpp", "max_issues_repo_name": "xuebingwu/xtools", "max_issues_repo_head_hexsha": "b9078cb7228f0bc227e6eab917fbafe769f5ffc1", "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/container.cpp", "max_forks_repo_name": "xuebingwu/xtools", "max_forks_repo_head_hexsha": "b9078cb7228f0bc227e6eab917fbafe769f5ffc1", "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": 20.0888888889, "max_line_length": 91, "alphanum_fraction": 0.5383480826, "num_tokens": 926, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182187, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.703278345190941}}
{"text": "// 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// Copyright Jeremy W. Murphy 2015.\n\n// This file is written to be included from a Quickbook .qbk document.\n// It can be compiled by the C++ compiler, and run. Any output can\n// also be added here as comment or included or pasted in elsewhere.\n// Caution: this file contains Quickbook markup as well as code\n// and comments: don't change any of the special comment markups!\n\n//[polynomial_arithmetic_0\n/*`First include the essential polynomial header (and others) to make the example:\n*/\n#include <boost/math/tools/polynomial.hpp>\n//] [polynomial_arithmetic_0\n\n#include <boost/array.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/math/tools/assert.hpp>\n\n#include <iostream>\n#include <stdexcept>\n#include <cmath>\n#include <string>\n#include <utility>\n\n//[polynomial_arithmetic_1\n/*`and some using statements are convenient:\n*/\n\nusing std::string;\nusing std::exception;\nusing std::cout;\nusing std::abs;\nusing std::pair;\n\nusing namespace boost::math;\nusing namespace boost::math::tools; // for polynomial\nusing boost::lexical_cast;\n\n//] [/polynomial_arithmetic_1]\n\ntemplate <typename T>\nstring sign_str(T const &x)\n{\n  return x < 0 ? \"-\" : \"+\";\n}\n\ntemplate <typename T>\nstring inner_coefficient(T const &x)\n{\n  string result(\" \" + sign_str(x) + \" \");\n  if (abs(x) != T(1))\n      result += lexical_cast<string>(abs(x));\n  return result;\n}\n\n/*! Output in formula format.\nFor example: from a polynomial in Boost container storage  [ 10, -6, -4, 3 ]\nshow as human-friendly formula notation: 3x^3 - 4x^2 - 6x + 10.\n*/\ntemplate <typename T>\nstring formula_format(polynomial<T> const &a)\n{\n  string result;\n  if (a.size() == 0)\n      result += lexical_cast<string>(T(0));\n  else\n  {\n    // First one is a special case as it may need unary negate.\n    unsigned i = a.size() - 1;\n    if (a[i] < 0)\n        result += \"-\";\n    if (abs(a[i]) != T(1))\n        result += lexical_cast<string>(abs(a[i]));\n\n    if (i > 0)\n    {\n      result += \"x\";\n      if (i > 1)\n      {\n          result += \"^\" + lexical_cast<string>(i);\n          i--;\n          for (; i != 1; i--)\n              if (a[i])\n                result += inner_coefficient(a[i]) + \"x^\" + lexical_cast<string>(i);\n\n          if (a[i])\n            result += inner_coefficient(a[i]) + \"x\";\n      }\n      i--;\n\n      if (a[i])\n        result += \" \" + sign_str(a[i]) + \" \" + lexical_cast<string>(abs(a[i]));\n    }\n  }\n  return result;\n} // string formula_format(polynomial<T> const &a)\n\n\nint main()\n{\n  cout << \"Example: Polynomial arithmetic.\\n\\n\";\n\n  try\n  {\n//[polynomial_arithmetic_2\n/*`Store the coefficients in a convenient way to access them,\nthen create some polynomials using construction from an iterator range,\nand finally output in a 'pretty' formula format.\n\n[tip Although we might conventionally write a polynomial from left to right\nin descending order of degree, Boost.Math stores in [*ascending order of degree].]\n\n  Read/write for humans:    3x^3 - 4x^2 - 6x + 10\n  Boost polynomial storage: [ 10, -6, -4, 3 ]\n*/\n  std::array<double, 4> const d3a = {{10, -6, -4, 3}};\n  polynomial<double> const a(d3a.begin(), d3a.end());\n\n  // With C++11 and later, you can also use initializer_list construction.\n  polynomial<double> const b{{-2.0, 1.0}};\n\n  // formula_format() converts from Boost storage to human notation.\n  cout << \"a = \" << formula_format(a)\n  << \"\\nb = \" << formula_format(b) << \"\\n\\n\";\n\n//] [/polynomial_arithmetic_2]\n\n//[polynomial_arithmetic_3\n  // Now we can do arithmetic with the usual infix operators: + - * / and %.\n  polynomial<double> s = a + b;\n  cout << \"a + b = \" << formula_format(s) << \"\\n\";\n  polynomial<double> d = a - b;\n  cout << \"a - b = \" << formula_format(d) << \"\\n\";\n  polynomial<double> p = a * b;\n  cout << \"a * b = \" << formula_format(p) << \"\\n\";\n  polynomial<double> q = a / b;\n  cout << \"a / b = \" << formula_format(q) << \"\\n\";\n  polynomial<double> r = a % b;\n  cout << \"a % b = \" << formula_format(r) << \"\\n\";\n//] [/polynomial_arithmetic_3]\n\n//[polynomial_arithmetic_4\n/*`\nDivision is a special case where you can calculate two for the price of one.\n\nActually, quotient and remainder are always calculated together due to the nature\nof the algorithm: the infix operators return one result and throw the other\naway.\n\nIf you are doing a lot of division and want both the quotient and remainder, then\nyou don't want to do twice the work necessary.\n\nIn that case you can call the underlying function, [^quotient_remainder],\nto get both results together as a pair.\n*/\n  pair< polynomial<double>, polynomial<double> > result;\n  result = quotient_remainder(a, b);\n// Reassure ourselves that the result is the same.\n  BOOST_MATH_ASSERT(result.first == q);\n  BOOST_MATH_ASSERT(result.second == r);\n//] [/polynomial_arithmetic_4]\n//[polynomial_arithmetic_5\n  /* \nWe can use the right and left shift operators to add and remove a factor of x.\nThis has the same semantics as left and right shift for integers where it is a \nfactor of 2. x is the smallest prime factor of a polynomial as is 2 for integers.\n*/\n    cout << \"Right and left shift operators.\\n\";\n    cout << \"\\n\" << formula_format(p) << \"\\n\";\n    cout << \"... right shift by 1 ...\\n\";\n    p >>= 1;\n    cout << formula_format(p) << \"\\n\";\n    cout << \"... left shift by 2 ...\\n\";\n    p <<= 2;\n    cout << formula_format(p) << \"\\n\";    \n  \n/*\nWe can also give a meaning to odd and even for a polynomial that is consistent\nwith these operations: a polynomial is odd if it has a non-zero constant value, \neven otherwise. That is:\n    x^2 + 1     odd\n    x^2         even    \n   */\n    cout << std::boolalpha;\n    cout << \"\\nPrint whether a polynomial is odd.\\n\";\n    cout << formula_format(s) << \"   odd? \" << odd(s) << \"\\n\";\n    // We cheekily use the internal details to subtract the constant, making it even.\n    s -= s.data().front();\n    cout << formula_format(s) << \"   odd? \" << odd(s) << \"\\n\";\n    // And of course you can check if it is even:\n    cout << formula_format(s) << \"   even? \" << even(s) << \"\\n\";\n    \n    \n    //] [/polynomial_arithmetic_5]\n    //[polynomial_arithmetic_6]\n    /* For performance and convenience, we can test whether a polynomial is zero \n     * by implicitly converting to bool with the same semantics as int.    */\n    polynomial<double> zero; // Default construction is 0.\n    cout << \"zero: \" << (zero ? \"not zero\" : \"zero\") << \"\\n\";\n    cout << \"r: \" << (r ? \"not zero\" : \"zero\") << \"\\n\";\n    /* We can also set a polynomial to zero without needing a another zero \n     * polynomial to assign to it. */\n    r.set_zero();\n    cout << \"r: \" << (r ? \"not zero\" : \"zero\") << \"\\n\";    \n    //] [/polynomial_arithmetic_6]\n}\ncatch (exception const &e)\n{\n  cout << \"\\nMessage from thrown exception was:\\n   \" << e.what() << \"\\n\";\n}\nreturn 0;\n} // int main()\n\n/*\n//[polynomial_output_1\n\na = 3x^3 - 4x^2 - 6x + 10\nb = x - 2\n\n//] [/polynomial_output_1]\n\n\n//[polynomial_output_2\n\na + b = 3x^3 - 4x^2 - 5x + 8\na - b = 3x^3 - 4x^2 - 7x + 12\na * b = 3x^4 - 10x^3 + 2x^2 + 22x - 20\na / b = 3x^2 + 2x - 2\na % b = 6\n\n//] [/polynomial_output_2]\n\n*/\n", "meta": {"hexsha": "048879ed5cdc2325005dc0d4ed6c516fdf1bed75", "size": 7212, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/polynomial_arithmetic.cpp", "max_stars_repo_name": "jamesfolberth/math", "max_stars_repo_head_hexsha": "a36f6a54a96006c3515ebf0acf17d180322042f2", "max_stars_repo_licenses": ["BSL-1.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": "example/polynomial_arithmetic.cpp", "max_issues_repo_name": "jamesfolberth/math", "max_issues_repo_head_hexsha": "a36f6a54a96006c3515ebf0acf17d180322042f2", "max_issues_repo_licenses": ["BSL-1.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": "example/polynomial_arithmetic.cpp", "max_forks_repo_name": "jamesfolberth/math", "max_forks_repo_head_hexsha": "a36f6a54a96006c3515ebf0acf17d180322042f2", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1757322176, "max_line_length": 85, "alphanum_fraction": 0.6295063783, "num_tokens": 2045, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907932, "lm_q2_score": 0.8438951005915208, "lm_q1q2_score": 0.7032385501726417}}
{"text": "//------------------------------------------------------------------------------\n// \\file BooleanAlgebra_tests.cpp\n// \\ref https://www.cs.utexas.edu/users/fussell/courses/cs429h/lectures/Lecture_2-429h.pdf\n//------------------------------------------------------------------------------\n#include \"Cpp/Utilities/SuperBitSet.h\"\n#include \"Utilities/ToHexString.h\"\n\n#include <boost/test/unit_test.hpp>\n#include <cmath>\n\nusing Cpp::Utilities::SuperBitSet;\nusing Utilities::ToHexString;\n\nBOOST_AUTO_TEST_SUITE(Utilities)\nBOOST_AUTO_TEST_SUITE(BooleanAlgebra_tests)\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(DemonstrateBitwiseOr)\n{\n  // cf. https://www.cs.utexas.edu/users/fussell/courses/cs429h/lectures/Lecture_2-429h.pdf\n  // pp. 16\n  // A | B = 1 when either A = 1 or B = 1\n  {\n    SuperBitSet<2> bits {\"01\"};\n    BOOST_TEST_REQUIRE(bits.to_string() == \"01\");\n    BOOST_TEST_REQUIRE(bits.to_ulong() == 1);\n    SuperBitSet<2> rhs_0 {0};\n    BOOST_TEST_REQUIRE(rhs_0.to_string() == \"00\");\n    BOOST_TEST_REQUIRE(rhs_0.to_ulong() == 0);   \n    BOOST_TEST((bits | rhs_0) == bits);\n    BOOST_TEST((bits | rhs_0).to_string() == \"01\");\n    SuperBitSet<2> rhs_1 {3};\n    BOOST_TEST_REQUIRE(rhs_1.to_string() == \"11\");\n    BOOST_TEST_REQUIRE(rhs_1.to_ulong() == 3);   \n    BOOST_TEST((bits | rhs_1) == rhs_1);\n    BOOST_TEST((bits | rhs_1).to_string() == \"11\");\n  }\n  // Further example:\n  {\n    SuperBitSet<4> bits {\"0101\"};\n    BOOST_TEST_REQUIRE(bits.to_string() == \"0101\");\n    BOOST_TEST_REQUIRE(bits.to_ulong() == 5);\n    SuperBitSet<4> rhs {3};\n    BOOST_TEST_REQUIRE(rhs.to_string() == \"0011\");\n    BOOST_TEST_REQUIRE(rhs.to_ulong() == 3);   \n    SuperBitSet<4> expected_result {7};\n    BOOST_TEST_REQUIRE(expected_result.to_string() == \"0111\");\n    BOOST_TEST_REQUIRE(expected_result.to_ulong() == 7);   \n    BOOST_TEST((bits | rhs) == expected_result);\n    BOOST_TEST((bits | rhs).to_string() == \"0111\");\n  }\n\n  // cf. https://en.wikipedia.org/wiki/Bitwise_operation OR\n  // bitwise OR may be used to set to 1 selected bits of register described\n  // above. e.g. fourth bit of 0010 may be set by performing bitwise OR with\n  // pattern with only 4th bit set.\n  {\n    SuperBitSet<4> bits {\"0010\"};\n    BOOST_TEST_REQUIRE(bits.to_string() == \"0010\");\n    BOOST_TEST_REQUIRE(bits.to_ulong() == 2);\n    SuperBitSet<4> rhs {8};\n    BOOST_TEST_REQUIRE(rhs.to_string() == \"1000\");\n    BOOST_TEST_REQUIRE(rhs.to_ulong() == 8);   \n    SuperBitSet<4> expected_result {10};\n    BOOST_TEST_REQUIRE(expected_result.to_string() == \"1010\");\n    BOOST_TEST_REQUIRE(expected_result.to_ulong() == 10);\n    BOOST_TEST((bits | rhs) == expected_result);\n    BOOST_TEST((bits | rhs).to_string() == \"1010\");\n  }\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(DemonstrateBitwiseAnd)\n{\n  // cf. https://www.cs.utexas.edu/users/fussell/courses/cs429h/lectures/Lecture_2-429h.pdf\n  // pp. 16\n  // A & B = 1 when both A = 1 and B = 1\n  {\n    SuperBitSet<2> bits {\"01\"};\n    BOOST_TEST_REQUIRE(bits.to_string() == \"01\");\n    BOOST_TEST_REQUIRE(bits.to_ulong() == 1);\n    SuperBitSet<2> rhs_0 {0};\n    BOOST_TEST_REQUIRE(rhs_0.to_string() == \"00\");\n    BOOST_TEST_REQUIRE(rhs_0.to_ulong() == 0);   \n    BOOST_TEST((bits & rhs_0) == rhs_0);\n    BOOST_TEST((bits & rhs_0).to_string() == \"00\");\n    SuperBitSet<2> rhs_1 {3};\n    BOOST_TEST_REQUIRE(rhs_1.to_string() == \"11\");\n    BOOST_TEST_REQUIRE(rhs_1.to_ulong() == 3);   \n    BOOST_TEST((bits & rhs_1) == bits);\n    BOOST_TEST((bits & rhs_1).to_string() == \"01\");\n  }\n  // Further example:\n  {\n    SuperBitSet<4> bits {\"0101\"};\n    BOOST_TEST_REQUIRE(bits.to_string() == \"0101\");\n    BOOST_TEST_REQUIRE(bits.to_ulong() == 5);\n    SuperBitSet<4> rhs {3};\n    BOOST_TEST_REQUIRE(rhs.to_string() == \"0011\");\n    BOOST_TEST_REQUIRE(rhs.to_ulong() == 3);   \n    SuperBitSet<4> expected_result {1};\n    BOOST_TEST_REQUIRE(expected_result.to_string() == \"0001\");\n    BOOST_TEST_REQUIRE(expected_result.to_ulong() == 1);   \n    BOOST_TEST((bits & rhs) == expected_result);\n    BOOST_TEST((bits & rhs).to_string() == \"0001\");\n  }\n\n  // cf. https://en.wikipedia.org/wiki/Bitwise_operation AND\n  // Thus, if both bits in compared position are 1, bit in resulting binary\n  // representation is (1 x 1 = 1); otherwise result is 0 (1 x 0 = 0 and\n  // 0 x 0 = 0).\n  // Operation may be used to determine whether particular bit is set (1) or\n  // clear (0). \n  // This is often called bit masking (by analogy, use of masking tape covers,\n  // or masks, portions that are not of interest)\n  {\n    SuperBitSet<4> bits {\"0011\"};\n    BOOST_TEST_REQUIRE(bits.to_string() == \"0011\");\n    BOOST_TEST_REQUIRE(bits.to_ulong() == 3);\n    SuperBitSet<4> rhs {2};\n    BOOST_TEST_REQUIRE(rhs.to_string() == \"0010\");\n    BOOST_TEST_REQUIRE(rhs.to_ulong() == 2);   \n    SuperBitSet<4> expected_result {2};\n    BOOST_TEST_REQUIRE(expected_result.to_string() == \"0010\");\n    BOOST_TEST_REQUIRE(expected_result.to_ulong() == 2);\n    BOOST_TEST((bits & rhs) == expected_result);\n    BOOST_TEST((bits & rhs).to_string() == \"0010\");\n\n    BOOST_TEST(!(bits & rhs).all());\n    BOOST_TEST((bits & rhs).any());\n    BOOST_TEST(!(bits & rhs).none());\n  }\n  // bitwise AND may be used to clear selected bits (or flags) of a register in\n  // which each bit represents an individual Boolean state.\n  // This technique is an efficient way to store a number of Boolean values\n  // using as little memory as possible.\n  {\n    SuperBitSet<4> bits {\"0110\"};\n    BOOST_TEST_REQUIRE(bits.to_string() == \"0110\");\n    BOOST_TEST_REQUIRE(bits.to_ulong() == 6);\n\n    // 3rd. flag may be cleared with pattern that has a 0 only in 3rd. bit.\n    SuperBitSet<4> rhs {11};\n    BOOST_TEST_REQUIRE(rhs.to_string() == \"1011\");\n    BOOST_TEST_REQUIRE(rhs.to_ulong() == 11);\n    SuperBitSet<4> expected_result {2};\n    BOOST_TEST_REQUIRE(expected_result.to_string() == \"0010\");\n    BOOST_TEST_REQUIRE(expected_result.to_ulong() == 2);\n    BOOST_TEST((bits & rhs) == expected_result);\n    BOOST_TEST((bits & rhs).to_string() == \"0010\");\n\n    BOOST_TEST(!(bits & rhs).all());\n    BOOST_TEST((bits & rhs).any());\n    BOOST_TEST(!(bits & rhs).none());\n  }\n\n  // Also, easy to check parity (even or odd?) of binary number by checking\n  // value of lowest valued bit.\n\n  {\n    SuperBitSet<4> bits {\"0110\"};\n    BOOST_TEST_REQUIRE(bits.to_string() == \"0110\");\n    BOOST_TEST_REQUIRE(bits.to_ulong() == 6);\n    SuperBitSet<4> rhs {0001};\n    BOOST_TEST_REQUIRE(rhs.to_string() == \"0001\");\n    BOOST_TEST_REQUIRE(rhs.to_ulong() == 1);\n    SuperBitSet<4> expected_result {0};\n    BOOST_TEST_REQUIRE(expected_result.to_string() == \"0000\");\n    BOOST_TEST_REQUIRE(expected_result.to_ulong() == 0);\n    BOOST_TEST((bits & rhs) == expected_result);\n    BOOST_TEST((bits & rhs).to_string() == \"0000\");\n\n    BOOST_TEST(!(bits & rhs).all());\n    BOOST_TEST(!(bits & rhs).any());\n    BOOST_TEST((bits & rhs).none());\n  }\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(DemonstrateBitwiseXor)\n{\n  // cf. https://www.cs.utexas.edu/users/fussell/courses/cs429h/lectures/Lecture_2-429h.pdf\n  // pp. 16\n  // A ^ B = 1 when either A = 1 or B = 1, but not both\n  {\n    SuperBitSet<2> bits {\"01\"};\n    BOOST_TEST_REQUIRE(bits.to_string() == \"01\");\n    BOOST_TEST_REQUIRE(bits.to_ulong() == 1);\n    SuperBitSet<2> rhs_0 {0};\n    BOOST_TEST_REQUIRE(rhs_0.to_string() == \"00\");\n    BOOST_TEST_REQUIRE(rhs_0.to_ulong() == 0);   \n    BOOST_TEST((bits ^ rhs_0) == bits);\n    BOOST_TEST((bits ^ rhs_0).to_string() == \"01\");\n    SuperBitSet<2> rhs_1 {3};\n    BOOST_TEST_REQUIRE(rhs_1.to_string() == \"11\");\n    BOOST_TEST_REQUIRE(rhs_1.to_ulong() == 3);   \n    BOOST_TEST((bits ^ rhs_1) == SuperBitSet<2>{\"10\"});\n    BOOST_TEST((bits ^ rhs_1).to_string() == \"10\");\n  }\n  // Further example:\n  {\n    SuperBitSet<4> bits {\"0101\"};\n    BOOST_TEST_REQUIRE(bits.to_string() == \"0101\");\n    BOOST_TEST_REQUIRE(bits.to_ulong() == 5);\n    SuperBitSet<4> rhs {3};\n    BOOST_TEST_REQUIRE(rhs.to_string() == \"0011\");\n    BOOST_TEST_REQUIRE(rhs.to_ulong() == 3);\n    SuperBitSet<4> expected_result {6};\n    BOOST_TEST_REQUIRE(expected_result.to_string() == \"0110\");\n    BOOST_TEST_REQUIRE(expected_result.to_ulong() == 6);\n    BOOST_TEST((bits ^ rhs) == expected_result);\n    BOOST_TEST((bits ^ rhs).to_string() == \"0110\");\n  }\n\n  // cf. https://en.wikipedia.org/wiki/Bitwise_operation XOR\n  // bitwise XOR may be used to invert selected bits in a register (also called\n  // toggle or flip). Any bit may be toggled by XORing with 1. \n  {\n    SuperBitSet<4> bits {\"0010\"};\n    BOOST_TEST_REQUIRE(bits.to_string() == \"0010\");\n    BOOST_TEST_REQUIRE(bits.to_ulong() == 2);\n    SuperBitSet<4> rhs {10};\n    BOOST_TEST_REQUIRE(rhs.to_string() == \"1010\");\n    BOOST_TEST_REQUIRE(rhs.to_ulong() == 10);   \n    SuperBitSet<4> expected_result {8};\n    BOOST_TEST_REQUIRE(expected_result.to_string() == \"1000\");\n    BOOST_TEST_REQUIRE(expected_result.to_ulong() == 8);\n    BOOST_TEST((bits ^ rhs) == expected_result);\n    BOOST_TEST((bits ^ rhs).to_string() == \"1000\");\n  }\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\n// NOT is also called the complement, or negation\nBOOST_AUTO_TEST_CASE(DemonstrateBitwiseNot)\n{\n  {\n    SuperBitSet<1> bits0 {\"0\"};\n    BOOST_TEST_REQUIRE(bits0.to_string() == \"0\");\n    BOOST_TEST((~bits0).to_string() == \"1\");\n\n    SuperBitSet<1> bits1 {\"1\"};\n    BOOST_TEST_REQUIRE(bits1.to_string() == \"1\");\n    BOOST_TEST((~bits1).to_string() == \"0\");\n  }\n\n  // bitwise complement = two's complement of the value - 1. If 2's complement\n  // arithmetic used, then NOT x = -x - 1\n  // TODO: explore and understand the previous statement.\n  {\n    SuperBitSet<4> bits {7};\n    BOOST_TEST(bits.to_string() == \"0111\");\n    BOOST_TEST(bits.to_ulong() == 7);\n    BOOST_TEST((~bits).to_string() == \"1000\");    \n    BOOST_TEST((~bits).to_ulong() == 8);\n  }\n  {\n    SuperBitSet<8> bits {171};\n    BOOST_TEST(bits.to_string() == \"10101011\");\n    BOOST_TEST(bits.to_ulong() == 171);\n    BOOST_TEST((~bits).to_string() == \"01010100\");    \n    BOOST_TEST((~bits).to_ulong() == 84);    \n  }\n  // For unsigned ints, bitwise complement of number is \"mirror reflection\" of\n  // number across half-way point of unsigned int's range;\n  // e.g. for 8-bit unsigned int, NOT x = 255 - x, \"flips\" increasing range from\n  // 0 to 255, to decreasing range from 255 to 0.\n\n  {\n    // cf. https://stackoverflow.com/questions/5040920/converting-from-signed-char-to-unsigned-char-and-back-again\n    SuperBitSet<8> bits {static_cast<uint8_t>(static_cast<signed char>(-7))};\n    BOOST_TEST(bits.to_string() == \"11111001\");\n    BOOST_TEST(pow(2, 7) == 128);\n    BOOST_TEST(pow(2, 6) == 64);\n    BOOST_TEST(pow(2, 5) == 32);\n    BOOST_TEST(pow(2, 4) == 16);\n    BOOST_TEST(pow(2, 3) == 8);\n\n    BOOST_TEST(\n      pow(2, 0) + pow(2, 3) + pow(2, 4) + pow(2, 5) + pow(2, 6) == 121);\n    BOOST_TEST(\n      -pow(2,7) + pow(2, 0) + pow(2, 3) + pow(2, 4) + pow(2, 5) + pow(2, 6) ==\n        -7);\n\n    BOOST_TEST((~bits).to_string() == \"00000110\");\n    BOOST_TEST((~bits).to_ulong() == 6);\n  }\n  {\n    SuperBitSet<8> bits {0xff};\n    BOOST_TEST(bits.to_string() == \"11111111\");\n    BOOST_TEST(bits.to_ulong() == 255);\n    BOOST_TEST((~bits).to_string() == \"00000000\");\n    BOOST_TEST((~bits).to_ulong() == 0);\n  }\n  {\n    SuperBitSet<8> bits {static_cast<uint8_t>(static_cast<signed char>(-128))};\n    BOOST_TEST(bits.to_string() == \"10000000\");\n    BOOST_TEST(bits.to_ulong() == 128);\n\n    BOOST_TEST((~bits).to_string() == \"01111111\");\n    BOOST_TEST((~bits).to_ulong() == 127);\n  }\n  {\n    SuperBitSet<8> bits {static_cast<uint8_t>(static_cast<signed char>(-1))};\n    BOOST_TEST(bits.to_string() == \"11111111\");\n    BOOST_TEST(bits.to_ulong() == 255);\n\n    BOOST_TEST((~bits).to_string() == \"00000000\");\n    BOOST_TEST((~bits).to_ulong() == 0);\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END() // BooleanAlgebra_tests\nBOOST_AUTO_TEST_SUITE_END() // Utilities", "meta": {"hexsha": "f5db6231a3b6cecf591e9601c5282ddb1c97d2d8", "size": 12359, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Voltron/Source/UnitTests/Utilities/BooleanAlgebra_tests.cpp", "max_stars_repo_name": "ernestyalumni/HrdwCCppCUDA", "max_stars_repo_head_hexsha": "17ed937dea06431a4d5ca103f993ea69a6918734", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-02-09T19:44:51.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-09T19:44:51.000Z", "max_issues_repo_path": "Voltron/Source/UnitTests/Utilities/BooleanAlgebra_tests.cpp", "max_issues_repo_name": "ernestyalumni/HrdwCCppCUDA", "max_issues_repo_head_hexsha": "17ed937dea06431a4d5ca103f993ea69a6918734", "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": "Voltron/Source/UnitTests/Utilities/BooleanAlgebra_tests.cpp", "max_forks_repo_name": "ernestyalumni/HrdwCCppCUDA", "max_forks_repo_head_hexsha": "17ed937dea06431a4d5ca103f993ea69a6918734", "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.8647798742, "max_line_length": 114, "alphanum_fraction": 0.6050651347, "num_tokens": 3417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.8333245891029456, "lm_q1q2_score": 0.7032385461255893}}
{"text": "// Copyright John Maddock 2006.\r\n// Copyright Paul A. Bristow 2007.\r\n// Use, modification and distribution are subject to the\r\n// Boost Software License, Version 1.0.\r\n// (See accompanying file LICENSE_1_0.txt\r\n// or 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: 4510) // default constructor could not be generated.\r\n#  pragma warning(disable: 4610) // can never be instantiated - user defined constructor required.\r\n#endif\r\n\r\n#include <iostream>\r\n#include <iomanip>\r\n#include <boost/math/distributions/students_t.hpp>\r\n\r\nvoid two_samples_t_test_equal_sd(\r\n        double Sm1,\r\n        double Sd1,\r\n        unsigned Sn1,\r\n        double Sm2,\r\n        double Sd2,\r\n        unsigned Sn2,\r\n        double alpha)\r\n{\r\n   //\r\n   // Sm1 = Sample Mean 1.\r\n   // Sd1 = Sample Standard Deviation 1.\r\n   // Sn1 = Sample Size 1.\r\n   // Sm2 = Sample Mean 2.\r\n   // Sd2 = Sample Standard Deviation 2.\r\n   // Sn2 = Sample Size 2.\r\n   // alpha = Significance Level.\r\n   //\r\n   // A Students t test applied to two sets of data.\r\n   // We are testing the null hypothesis that the two\r\n   // samples have the same mean and that any difference\r\n   // if due to chance.\r\n   // See http://www.itl.nist.gov/div898/handbook/eda/section3/eda353.htm\r\n   //\r\n   using namespace std;\r\n   using namespace boost::math;\r\n\r\n   // Print header:\r\n   cout <<\r\n      \"_______________________________________________\\n\"\r\n      \"Student t test for two samples (equal variances)\\n\"\r\n      \"_______________________________________________\\n\\n\";\r\n   cout << setprecision(5);\r\n   cout << setw(55) << left << \"Number of Observations (Sample 1)\" << \"=  \" << Sn1 << \"\\n\";\r\n   cout << setw(55) << left << \"Sample 1 Mean\" << \"=  \" << Sm1 << \"\\n\";\r\n   cout << setw(55) << left << \"Sample 1 Standard Deviation\" << \"=  \" << Sd1 << \"\\n\";\r\n   cout << setw(55) << left << \"Number of Observations (Sample 2)\" << \"=  \" << Sn2 << \"\\n\";\r\n   cout << setw(55) << left << \"Sample 2 Mean\" << \"=  \" << Sm2 << \"\\n\";\r\n   cout << setw(55) << left << \"Sample 2 Standard Deviation\" << \"=  \" << Sd2 << \"\\n\";\r\n   //\r\n   // Now we can calculate and output some stats:\r\n   //\r\n   // Degrees of freedom:\r\n   double v = Sn1 + Sn2 - 2;\r\n   cout << setw(55) << left << \"Degrees of Freedom\" << \"=  \" << v << \"\\n\";\r\n   // Pooled variance:\r\n   double sp = sqrt(((Sn1-1) * Sd1 * Sd1 + (Sn2-1) * Sd2 * Sd2) / v);\r\n   cout << setw(55) << left << \"Pooled Standard Deviation\" << \"=  \" << v << \"\\n\";\r\n   // t-statistic:\r\n   double t_stat = (Sm1 - Sm2) / (sp * sqrt(1.0 / Sn1 + 1.0 / Sn2));\r\n   cout << setw(55) << left << \"T Statistic\" << \"=  \" << t_stat << \"\\n\";\r\n   //\r\n   // Define our distribution, and get the probability:\r\n   //\r\n   students_t dist(v);\r\n   double q = cdf(complement(dist, fabs(t_stat)));\r\n   cout << setw(55) << left << \"Probability that difference is due to chance\" << \"=  \"\r\n      << setprecision(3) << scientific << 2 * q << \"\\n\\n\";\r\n   //\r\n   // Finally print out results of alternative hypothesis:\r\n   //\r\n   cout << setw(55) << left <<\r\n      \"Results for Alternative Hypothesis and alpha\" << \"=  \"\r\n      << setprecision(4) << fixed << alpha << \"\\n\\n\";\r\n   cout << \"Alternative Hypothesis              Conclusion\\n\";\r\n   cout << \"Sample 1 Mean != Sample 2 Mean       \" ;\r\n   if(q < alpha / 2)\r\n      cout << \"NOT REJECTED\\n\";\r\n   else\r\n      cout << \"REJECTED\\n\";\r\n   cout << \"Sample 1 Mean <  Sample 2 Mean       \";\r\n   if(cdf(dist, t_stat) < alpha)\r\n      cout << \"NOT REJECTED\\n\";\r\n   else\r\n      cout << \"REJECTED\\n\";\r\n   cout << \"Sample 1 Mean >  Sample 2 Mean       \";\r\n   if(cdf(complement(dist, t_stat)) < alpha)\r\n      cout << \"NOT REJECTED\\n\";\r\n   else\r\n      cout << \"REJECTED\\n\";\r\n   cout << endl << endl;\r\n}\r\n\r\nvoid two_samples_t_test_unequal_sd(\r\n        double Sm1,\r\n        double Sd1,\r\n        unsigned Sn1,\r\n        double Sm2,\r\n        double Sd2,\r\n        unsigned Sn2,\r\n        double alpha)\r\n{\r\n   //\r\n   // Sm1 = Sample Mean 1.\r\n   // Sd1 = Sample Standard Deviation 1.\r\n   // Sn1 = Sample Size 1.\r\n   // Sm2 = Sample Mean 2.\r\n   // Sd2 = Sample Standard Deviation 2.\r\n   // Sn2 = Sample Size 2.\r\n   // alpha = Significance Level.\r\n   //\r\n   // A Students t test applied to two sets of data.\r\n   // We are testing the null hypothesis that the two\r\n   // samples have the same mean and that any difference\r\n   // if due to chance.\r\n   // See http://www.itl.nist.gov/div898/handbook/eda/section3/eda353.htm\r\n   //\r\n   using namespace std;\r\n   using namespace boost::math;\r\n\r\n   // Print header:\r\n   cout <<\r\n      \"_________________________________________________\\n\"\r\n      \"Student t test for two samples (unequal variances)\\n\"\r\n      \"_________________________________________________\\n\\n\";\r\n   cout << setprecision(5);\r\n   cout << setw(55) << left << \"Number of Observations (Sample 1)\" << \"=  \" << Sn1 << \"\\n\";\r\n   cout << setw(55) << left << \"Sample 1 Mean\" << \"=  \" << Sm1 << \"\\n\";\r\n   cout << setw(55) << left << \"Sample 1 Standard Deviation\" << \"=  \" << Sd1 << \"\\n\";\r\n   cout << setw(55) << left << \"Number of Observations (Sample 2)\" << \"=  \" << Sn2 << \"\\n\";\r\n   cout << setw(55) << left << \"Sample 2 Mean\" << \"=  \" << Sm2 << \"\\n\";\r\n   cout << setw(55) << left << \"Sample 2 Standard Deviation\" << \"=  \" << Sd2 << \"\\n\";\r\n   //\r\n   // Now we can calculate and output some stats:\r\n   //\r\n   // Degrees of freedom:\r\n   double v = Sd1 * Sd1 / Sn1 + Sd2 * Sd2 / Sn2;\r\n   v *= v;\r\n   double t1 = Sd1 * Sd1 / Sn1;\r\n   t1 *= t1;\r\n   t1 /=  (Sn1 - 1);\r\n   double t2 = Sd2 * Sd2 / Sn2;\r\n   t2 *= t2;\r\n   t2 /= (Sn2 - 1);\r\n   v /= (t1 + t2);\r\n   cout << setw(55) << left << \"Degrees of Freedom\" << \"=  \" << v << \"\\n\";\r\n   // t-statistic:\r\n   double t_stat = (Sm1 - Sm2) / sqrt(Sd1 * Sd1 / Sn1 + Sd2 * Sd2 / Sn2);\r\n   cout << setw(55) << left << \"T Statistic\" << \"=  \" << t_stat << \"\\n\";\r\n   //\r\n   // Define our distribution, and get the probability:\r\n   //\r\n   students_t dist(v);\r\n   double q = cdf(complement(dist, fabs(t_stat)));\r\n   cout << setw(55) << left << \"Probability that difference is due to chance\" << \"=  \"\r\n      << setprecision(3) << scientific << 2 * q << \"\\n\\n\";\r\n   //\r\n   // Finally print out results of alternative hypothesis:\r\n   //\r\n   cout << setw(55) << left <<\r\n      \"Results for Alternative Hypothesis and alpha\" << \"=  \"\r\n      << setprecision(4) << fixed << alpha << \"\\n\\n\";\r\n   cout << \"Alternative Hypothesis              Conclusion\\n\";\r\n   cout << \"Sample 1 Mean != Sample 2 Mean       \" ;\r\n   if(q < alpha / 2)\r\n      cout << \"NOT REJECTED\\n\";\r\n   else\r\n      cout << \"REJECTED\\n\";\r\n   cout << \"Sample 1 Mean <  Sample 2 Mean       \";\r\n   if(cdf(dist, t_stat) < alpha)\r\n      cout << \"NOT REJECTED\\n\";\r\n   else\r\n      cout << \"REJECTED\\n\";\r\n   cout << \"Sample 1 Mean >  Sample 2 Mean       \";\r\n   if(cdf(complement(dist, t_stat)) < alpha)\r\n      cout << \"NOT REJECTED\\n\";\r\n   else\r\n      cout << \"REJECTED\\n\";\r\n   cout << endl << endl;\r\n}\r\n\r\nint main()\r\n{\r\n   //\r\n   // Run tests for Car Mileage sample data\r\n   // http://www.itl.nist.gov/div898/handbook/eda/section3/eda3531.htm\r\n   // from the NIST website http://www.itl.nist.gov.  The data compares\r\n   // miles per gallon of US cars with miles per gallon of Japanese cars.\r\n   //\r\n   two_samples_t_test_equal_sd(20.14458, 6.414700, 249, 30.48101, 6.107710, 79, 0.05);\r\n   two_samples_t_test_unequal_sd(20.14458, 6.414700, 249, 30.48101, 6.107710, 79, 0.05);\r\n\r\n   return 0;\r\n} // int main()\r\n\r\n/*\r\nOutput is\r\n\r\n------ Build started: Project: students_t_two_samples, Configuration: Debug Win32 ------\r\nCompiling...\r\nstudents_t_two_samples.cpp\r\nLinking...\r\nAutorun \"i:\\boost-06-05-03-1300\\libs\\math\\test\\Math_test\\debug\\students_t_two_samples.exe\"\r\n_______________________________________________\r\nStudent t test for two samples (equal variances)\r\n_______________________________________________\r\n\r\nNumber of Observations (Sample 1)                      =  249\r\nSample 1 Mean                                          =  20.145\r\nSample 1 Standard Deviation                            =  6.4147\r\nNumber of Observations (Sample 2)                      =  79\r\nSample 2 Mean                                          =  30.481\r\nSample 2 Standard Deviation                            =  6.1077\r\nDegrees of Freedom                                     =  326\r\nPooled Standard Deviation                              =  326\r\nT Statistic                                            =  -12.621\r\nProbability that difference is due to chance           =  5.273e-030\r\n\r\nResults for Alternative Hypothesis and alpha           =  0.0500\r\n\r\nAlternative Hypothesis              Conclusion\r\nSample 1 Mean != Sample 2 Mean       NOT REJECTED\r\nSample 1 Mean <  Sample 2 Mean       NOT REJECTED\r\nSample 1 Mean >  Sample 2 Mean       REJECTED\r\n\r\n\r\n_________________________________________________\r\nStudent t test for two samples (unequal variances)\r\n_________________________________________________\r\n\r\nNumber of Observations (Sample 1)                      =  249\r\nSample 1 Mean                                          =  20.14458\r\nSample 1 Standard Deviation                            =  6.41470\r\nNumber of Observations (Sample 2)                      =  79\r\nSample 2 Mean                                          =  30.48101\r\nSample 2 Standard Deviation                            =  6.10771\r\nDegrees of Freedom                                     =  136.87499\r\nT Statistic                                            =  -12.94627\r\nProbability that difference is due to chance           =  1.571e-025\r\n\r\nResults for Alternative Hypothesis and alpha           =  0.0500\r\n\r\nAlternative Hypothesis              Conclusion\r\nSample 1 Mean != Sample 2 Mean       NOT REJECTED\r\nSample 1 Mean <  Sample 2 Mean       NOT REJECTED\r\nSample 1 Mean >  Sample 2 Mean       REJECTED\r\n\r\nBuild Time 0:03\r\nBuild log was saved at \"file://i:\\boost-06-05-03-1300\\libs\\math\\test\\Math_test\\students_t_two_samples\\Debug\\BuildLog.htm\"\r\nstudents_t_two_samples - 0 error(s), 0 warning(s)\r\n========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========\r\n\r\n*/\r\n\r\n", "meta": {"hexsha": "985423aa20409099152ffc0054f82a0e4ca14422", "size": 10107, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/example/students_t_two_samples.cpp", "max_stars_repo_name": "zyiacas/boost-doc-zh", "max_stars_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-07-12T13:04:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-30T23:23:46.000Z", "max_issues_repo_path": "libs/math/example/students_t_two_samples.cpp", "max_issues_repo_name": "sdfict/boost-doc-zh", "max_issues_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_issues_repo_licenses": ["BSL-1.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/math/example/students_t_two_samples.cpp", "max_forks_repo_name": "sdfict/boost-doc-zh", "max_forks_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2015-12-23T01:51:57.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-25T04:58:32.000Z", "avg_line_length": 38.5763358779, "max_line_length": 122, "alphanum_fraction": 0.5621846245, "num_tokens": 2796, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970904940926, "lm_q2_score": 0.7981867705385762, "lm_q1q2_score": 0.7030405851612539}}
{"text": "/**\n * @file nonlinschroedingerequation_main.cc\n * @brief NPDE homework NonLinSchroedingerEquation code\n * @author Oliver Rietmann\n * @date 22.04.2020\n * @copyright Developed at ETH Zurich\n */\n\n#include <lf/assemble/assemble.h>\n#include <lf/fe/fe.h>\n#include <lf/io/io.h>\n#include <lf/mesh/hybrid2d/hybrid2d.h>\n#include <lf/uscalfe/uscalfe.h>\n\n#include <Eigen/Core>\n#include <cmath>\n#include <complex>\n#include <cstdlib>\n#include <fstream>\n#include <iostream>\n#include <memory>\n#include <utility>\n\n#include \"nonlinschroedingerequation.h\"\n#include \"propagator.h\"\n\nint main() {\n  /* SAM_LISTING_BEGIN_9 */\n  // Load mesh and initalize FE space and DOF handler\n  auto mesh_factory = std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2);\n  const lf::io::GmshReader reader(\n      std::move(mesh_factory), CURRENT_SOURCE_DIR \"/../meshes/square_64.msh\");\n  auto mesh_p = reader.mesh();\n  auto fe_space =\n      std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n  const lf::assemble::DofHandler &dofh{fe_space->LocGlobMap()};\n  const lf::uscalfe::size_type N_dofs(dofh.NumDofs());\n\n  // Mass matrix\n  lf::assemble::COOMatrix<double> D_COO(N_dofs, N_dofs);\n  NonLinSchroedingerEquation::MassElementMatrixProvider mass_emp;\n  lf::assemble::AssembleMatrixLocally(0, dofh, dofh, mass_emp, D_COO);\n  Eigen::SparseMatrix<double> D = D_COO.makeSparse();\n  Eigen::SparseMatrix<std::complex<double>> M = std::complex<double>(0, 1) * D;\n\n  // Stiffness matrix\n  lf::assemble::COOMatrix<double> A_COO(N_dofs, N_dofs);\n  lf::uscalfe::LinearFELaplaceElementMatrix stiffness_emp;\n  lf::assemble::AssembleMatrixLocally(0, dofh, dofh, stiffness_emp, A_COO);\n  Eigen::SparseMatrix<double> A = A_COO.makeSparse();\n\n  // Prepare timestepping\n  int timesteps = 100;\n  double T = 1.0;\n  double tau = T / timesteps;\n\n// Prepare inital data\n  const double PI = 3.14159265358979323846;\n  auto u0 = [PI](Eigen::Vector2d x) -> double {\n    return 4.0 * std::cos(PI * x(0)) * std::cos(PI * x(1));\n  };\n  lf::mesh::utils::MeshFunctionGlobal mf_u0{u0};\n  Eigen::VectorXcd mu = lf::fe::NodalProjection(*fe_space, mf_u0);\n\n  // Prepare split-step propagator for full step $\\tau$\n  NonLinSchroedingerEquation::SplitStepPropagator splitStepPropagator(A, M,\n                                                                      tau);\n\n  // Arrays for storing \"energies\" contributing to the Hamiltonian\n  Eigen::VectorXd norm(timesteps + 1);\n  Eigen::VectorXd E_kin(timesteps + 1);\n  Eigen::VectorXd E_int(timesteps + 1);\n  // Timestepping\n  for (int j = 0; j < timesteps; ++j) {\n    // Compute norm and energy along the solution\n    norm(j) = NonLinSchroedingerEquation::Norm(mu, D);\n    E_kin(j) = NonLinSchroedingerEquation::KineticEnergy(mu, A);\n    E_int(j) = NonLinSchroedingerEquation::InteractionEnergy(mu, D);\n    // Timestep tau according to Strang splitting\n    mu = splitStepPropagator(mu);\n  }\n  norm(timesteps) = NonLinSchroedingerEquation::Norm(mu, D);\n  E_kin(timesteps) = NonLinSchroedingerEquation::KineticEnergy(mu, A);\n  E_int(timesteps) = NonLinSchroedingerEquation::InteractionEnergy(mu, D);\n\n  // Timegrid\n  Eigen::VectorXd t = Eigen::VectorXd::LinSpaced(timesteps + 1, 0.0, T);\n\n  // Nice output format\n  const static Eigen::IOFormat CSVFormat(Eigen::FullPrecision,\n                                         Eigen::DontAlignCols, \", \", \"\\n\");\n\n  // Write norm to file\n  std::ofstream norm_csv;\n  norm_csv.open(\"norm.csv\");\n  norm_csv << t.transpose().format(CSVFormat) << std::endl;\n  norm_csv << norm.transpose().format(CSVFormat) << std::endl;\n  norm_csv.close();\n  /* SAM_LISTING_END_9 */\n\n  // Call python script to plot norm\n  std::cout << \"Generated \" CURRENT_BINARY_DIR \"/norm.csv\" << std::endl;\n  std::system(\"python3 \" CURRENT_SOURCE_DIR \"/plot_norm.py \" CURRENT_BINARY_DIR\n              \"/norm.csv \" CURRENT_BINARY_DIR \"/norm.eps\");\n\n  // Write energies to file\n  std::ofstream energies_csv;\n  energies_csv.open(\"energies.csv\");\n  energies_csv << t.transpose().format(CSVFormat) << std::endl;\n  energies_csv << E_kin.transpose().format(CSVFormat) << std::endl;\n  energies_csv << E_int.transpose().format(CSVFormat) << std::endl;\n  energies_csv.close();\n\n  // Call python script to plot energies\n  std::cout << \"Generated \" CURRENT_BINARY_DIR \"/energies.csv\" << std::endl;\n  std::system(\"python3 \" CURRENT_SOURCE_DIR\n              \"/plot_energies.py \" CURRENT_BINARY_DIR\n              \"/energies.csv \" CURRENT_BINARY_DIR \"/energies.eps\");\n\n  // Write entry-wise squared modulus of $\\mu$ to .vtk file\n  std::cout << \"Generated \" CURRENT_BINARY_DIR \"/solution.vtk\" << std::endl;\n  lf::io::VtkWriter vtk_writer(mesh_p, \"solution.vtk\");\n  Eigen::VectorXd mu_abs2 = mu.cwiseAbs2();\n  lf::fe::MeshFunctionFE mu_abs2_mf(fe_space, mu_abs2);\n  vtk_writer.WritePointData(\"mu_abs2\", mu_abs2_mf);\n\n  return 0;\n}\n", "meta": {"hexsha": "f6e4151064000a7f4d32436f8bb62550823e6cb3", "size": 4804, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/NonLinSchroedingerEquation/mastersolution/nonlinschroedingerequation_main.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": "homeworks/NonLinSchroedingerEquation/mastersolution/nonlinschroedingerequation_main.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": "homeworks/NonLinSchroedingerEquation/mastersolution/nonlinschroedingerequation_main.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": 37.2403100775, "max_line_length": 79, "alphanum_fraction": 0.6915070774, "num_tokens": 1402, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970748488296, "lm_q2_score": 0.7981867825403176, "lm_q1q2_score": 0.7030405832445106}}
{"text": "//-----------------------------------------------------------------------------\n// Copyright (c) 2015-2018 Benjamin Buch\n//\n// https://github.com/bebuch/mitrax\n//\n// Distributed under the Boost Software License, Version 1.0. (See accompanying\n// file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)\n//-----------------------------------------------------------------------------\n#define BOOST_TEST_MODULE mitrax gaussian_elimination\n#include <boost/test/unit_test.hpp>\n\n#include <mitrax/gaussian_elimination.hpp>\n#include <mitrax/operator.hpp>\n\n#include <cmath>\n\n\nusing boost::typeindex::type_id;\nusing boost::typeindex::type_id_runtime;\nusing namespace mitrax;\nusing namespace mitrax::literals;\n\n\nconstexpr auto ref1 = make_matrix< float >(3_DS, {\n\t{1, 2, 3},\n\t{1, 1, 1},\n\t{3, 3, 1}\n});\n\nconstexpr auto ref2 = make_matrix< float >(3_DS, {\n\t{1, 2, 3},\n\t{4, 5, 6},\n\t{7, 8, 9}\n});\n\nconstexpr auto ref3 = make_matrix< float >(3_DS, {\n\t{-1,  2, 0},\n\t{ 1,  0, 1},\n\t{ 2, -4, 0}\n});\n\nconstexpr auto ref4 = make_matrix< float >(3_DS, {\n\t{1, 2, 3},\n\t{4, 5, 6},\n\t{0, 0, 0}\n});\n\ntemplate < typename M, col_t C, row_t R >\nconstexpr bool near_null(\n\tmatrix< M, C, R > const& m,\n\tvalue_type_t< M > const& threshold\n){\n\tfor(auto& v: m) if(threshold < v) return false;\n\treturn true;\n}\n\ntemplate < typename T, typename U >\nconstexpr bool equal(T const& a, U const& b){\n\treturn std::abs(a - b) < 0.00001;\n}\n\n\nBOOST_AUTO_TEST_SUITE(suite_gaussian_elimination)\n\n\nBOOST_AUTO_TEST_CASE(test_upper_triangular_matrix){\n\tauto m = upper_triangular_matrix(ref1);\n\n\tBOOST_TEST((\n\t\tm.cols() == 3_CS &&\n\t\tm.rows() == 3_RS &&\n\t\tm(0_c, 0_r) ==  1 &&\n\t\tm(1_c, 0_r) ==  2 &&\n\t\tm(2_c, 0_r) ==  3 &&\n\t\tm(0_c, 1_r) ==  0 &&\n\t\tm(1_c, 1_r) == -1 &&\n\t\tm(2_c, 1_r) == -2 &&\n\t\tm(0_c, 2_r) ==  0 &&\n\t\tm(1_c, 2_r) ==  0 &&\n\t\tm(2_c, 2_r) == -2\n\t));\n}\n\nBOOST_AUTO_TEST_CASE(test_matrix_kernel_3x3_1){\n\tauto const v = matrix_kernel(ref2);\n\n\tBOOST_TEST((\n\t\tv.cols() == 1_CS &&\n\t\tv.rows() == 3_RS &&\n\t\tv[0_d] ==  1 &&\n\t\tv[1_d] == -2 &&\n\t\tv[2_d] ==  1\n\t));\n}\n\nBOOST_AUTO_TEST_CASE(test_matrix_kernel_3x3_2){\n\tauto const v = matrix_kernel(ref3);\n\n\tBOOST_TEST((\n\t\tv.cols() == 1_CS &&\n\t\tv.rows() == 3_RS &&\n\t\tv[0_d] == -1 &&\n\t\tv[1_d] == -0.5 &&\n\t\tv[2_d] ==  1\n\t));\n}\n\nBOOST_AUTO_TEST_CASE(test_matrix_kernel_3x3_3){\n\tauto const v = matrix_kernel(ref4);\n\n\tBOOST_TEST((\n\t\tv.cols() == 1_CS &&\n\t\tv.rows() == 3_RS &&\n\t\tv[0_d] ==  1 &&\n\t\tv[1_d] == -2 &&\n\t\tv[2_d] ==  1\n\t));\n}\n\nBOOST_AUTO_TEST_CASE(test_matrix_kernel_numeric){\n\tfor(size_t i = 0; i < 10; ++i){\n\t\tauto m = make_matrix_v< double >(dims(dim_t(i + 1)));\n\t\tsize_t j = 5;\n\t\tfor(auto& v: m) v = ++j;\n\n\t\tauto k = matrix_kernel(m);\n\n\t\tBOOST_TEST(near_null(m * k, 0));\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(test_gaussian_elimination){\n\tconstexpr auto m = make_matrix< float >(3_DS, {\n\t\t{ 1  , -0.2, -0.2},\n\t\t{-0.4,  0.8, -0.1},\n\t\t{ 0  , -0.5,  0.9}\n\t});\n\n\tconstexpr auto v = make_vector< float >(3_RS, {7, 12.5, 16.5});\n\n\tauto res = gaussian_elimination(m, v);\n\n\tBOOST_TEST((\n\t\tres.cols() == 1_CS &&\n\t\tres.rows() == 3_RS &&\n\t\tres[0_d] == 20 &&\n\t\tres[1_d] == 30 &&\n\t\tres[2_d] == 35\n\t));\n}\n\nBOOST_AUTO_TEST_CASE(test_inverse_2x2){\n\tconstexpr auto m = make_matrix< float >(2_DS, {\n\t\t{2, 5},\n\t\t{1, 3}\n\t});\n\n\tauto i = inverse(m);\n\n\tBOOST_TEST((\n\t\ti.cols() == 2_CS &&\n\t\ti.rows() == 2_RS &&\n\t\ti(0_c, 0_r) ==  3 &&\n\t\ti(1_c, 0_r) == -5 &&\n\t\ti(0_c, 1_r) == -1 &&\n\t\ti(1_c, 1_r) ==  2\n\t));\n}\n\nBOOST_AUTO_TEST_CASE(test_inverse_3x3_1){\n\tconstexpr auto m = make_matrix< float >(3_DS, {\n\t\t{1, 2, 0},\n\t\t{2, 4, 1},\n\t\t{2, 1, 0}\n\t});\n\n\tauto i = inverse(m) * 3;\n\n\tBOOST_TEST((\n\t\ti.cols() == 3_CS &&\n\t\ti.rows() == 3_RS &&\n\t\tequal(i(0_c, 0_r), -1) &&\n\t\tequal(i(1_c, 0_r),  0) &&\n\t\tequal(i(2_c, 0_r),  2) &&\n\t\tequal(i(0_c, 1_r),  2) &&\n\t\tequal(i(1_c, 1_r),  0) &&\n\t\tequal(i(2_c, 1_r), -1) &&\n\t\tequal(i(0_c, 2_r), -6) &&\n\t\tequal(i(1_c, 2_r),  3) &&\n\t\tequal(i(2_c, 2_r),  0)\n\t));\n}\n\nBOOST_AUTO_TEST_CASE(test_inverse_3x3_2){\n\tconstexpr auto m = make_matrix< float >(3_DS, {\n\t\t{ 2, -1,  0},\n\t\t{-1,  2, -1},\n\t\t{ 0, -1,  2}\n\t});\n\n\tauto i = inverse(m) * 4;\n\n\tBOOST_TEST((\n\t\ti.cols() == 3_CS &&\n\t\ti.rows() == 3_RS &&\n\t\tequal(i(0_c, 0_r), 3) &&\n\t\tequal(i(1_c, 0_r), 2) &&\n\t\tequal(i(2_c, 0_r), 1) &&\n\t\tequal(i(0_c, 1_r), 2) &&\n\t\tequal(i(1_c, 1_r), 4) &&\n\t\tequal(i(2_c, 1_r), 2) &&\n\t\tequal(i(0_c, 2_r), 1) &&\n\t\tequal(i(1_c, 2_r), 2) &&\n\t\tequal(i(2_c, 2_r), 3)\n\t));\n}\n\nBOOST_AUTO_TEST_CASE(test_inverse_3x3_3){\n\tconstexpr auto m = make_matrix< float >(3_DS, {\n\t\t{ 2, -1,  0},\n\t\t{ 1,  2, -2},\n\t\t{ 0, -1,  1}\n\t});\n\n\tauto i = inverse(m);\n\n\tBOOST_TEST((\n\t\ti.cols() == 3_CS &&\n\t\ti.rows() == 3_RS &&\n\t\tequal(i(0_c, 0_r),  0) &&\n\t\tequal(i(1_c, 0_r),  1) &&\n\t\tequal(i(2_c, 0_r),  2) &&\n\t\tequal(i(0_c, 1_r), -1) &&\n\t\tequal(i(1_c, 1_r),  2) &&\n\t\tequal(i(2_c, 1_r),  4) &&\n\t\tequal(i(0_c, 2_r), -1) &&\n\t\tequal(i(1_c, 2_r),  2) &&\n\t\tequal(i(2_c, 2_r),  5)\n\t));\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "97d398d98606bb4152fd7b9068fab35f7a997785", "size": 4850, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/gaussian_elimination.cpp", "max_stars_repo_name": "bebuch/Mitrax", "max_stars_repo_head_hexsha": "bc33a1b93058886daab3e4ef736ef9b519111454", "max_stars_repo_licenses": ["BSL-1.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": "test/gaussian_elimination.cpp", "max_issues_repo_name": "bebuch/Mitrax", "max_issues_repo_head_hexsha": "bc33a1b93058886daab3e4ef736ef9b519111454", "max_issues_repo_licenses": ["BSL-1.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": "test/gaussian_elimination.cpp", "max_forks_repo_name": "bebuch/Mitrax", "max_forks_repo_head_hexsha": "bc33a1b93058886daab3e4ef736ef9b519111454", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.8770491803, "max_line_length": 79, "alphanum_fraction": 0.5498969072, "num_tokens": 1971, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896671963207, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.7030079655082668}}
{"text": "\n#pragma once\n\n#include <Eigen/Dense>\n\n#include \"root_finding.hpp\"\n#include \"types.hpp\"\n\nnamespace convexnmf {\n\nnamespace norms {\n\ninline Scalar L1_Infinity_MixedNorm(const MatrixRef &A) {\n    return A.cwiseAbs().rowwise().maxCoeff().sum();\n}\n\ninline Scalar L1Norm(const MatrixRef &A) { return A.cwiseAbs().sum(); }\n\ninline Scalar LInfinity_1_MixedNorm(const MatrixRef &A) {\n    return A.cwiseAbs().rowwise().sum().maxCoeff();\n}\n\n} // namespace norms\n\n// Returns a vector which is the projection of v onto the simplex\n// with sum sum_target\nVector SimplexProjection(const VectorRef &v, Scalar sum_target);\n\nVector L1BallProjection(const VectorRef &v, Scalar radius);\nVector L2BallProjection(const VectorRef &v, Scalar radius);\n\n// Computes the proximal operator\n// u = argmin_B 0.5 ||A - B||_F^2 + \\lambda ||B||_{1, \\infty}\n// This separates into computing the l_\\infty proximal operator\n// for each row, which, in turn, is equivalent to projection onto\n// the l1 ball of radius \\theta.\n// (TODO) Add reference\nMatrix L1InfinityProximalOperator(const MatrixRef &A, Scalar lambda);\n\n// Computes the L1infinity projection, or\n// u = argmin_B ||A - B||_F^2 subject to ||B||_{1,\\infty} <= radius\n// using the previous initial guess can be used.\nMatrix L1InfinityProjection(const MatrixRef &A, Scalar radius, Scalar root_tolerance = 1.0e-10);\n\n} // namespace convexnmf\n", "meta": {"hexsha": "68d64e0fbab0b9278bbd0128df888e5511b1ef80", "size": 1364, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/projections.hpp", "max_stars_repo_name": "miketoastmacneil/cvxnmf", "max_stars_repo_head_hexsha": "86011cf202406b7ee10ce618e433bcf82454ec73", "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": "src/projections.hpp", "max_issues_repo_name": "miketoastmacneil/cvxnmf", "max_issues_repo_head_hexsha": "86011cf202406b7ee10ce618e433bcf82454ec73", "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": "src/projections.hpp", "max_forks_repo_name": "miketoastmacneil/cvxnmf", "max_forks_repo_head_hexsha": "86011cf202406b7ee10ce618e433bcf82454ec73", "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.652173913, "max_line_length": 96, "alphanum_fraction": 0.7338709677, "num_tokens": 367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896693699845, "lm_q2_score": 0.7634837635542925, "lm_q1q2_score": 0.7030079622125084}}
{"text": "#ifndef _COCONUT_PULP_MATH_QUATERNION_HPP_\n#define _COCONUT_PULP_MATH_QUATERNION_HPP_\n\n#include <boost/operators.hpp>\n\n#include \"ScalarEqual.hpp\"\n#include \"Vector.hpp\"\n\nnamespace coconut {\nnamespace pulp {\nnamespace math {\n\ntemplate <class ScalarType, class ScalarEqualityFunc = ScalarEqual<ScalarType>>\nclass Quaternion :\n\tboost::equality_comparable<Quaternion<ScalarType, ScalarEqualityFunc>,\n\tboost::additive<Quaternion<ScalarType, ScalarEqualityFunc>,\n\tboost::multipliable<Quaternion<ScalarType, ScalarEqualityFunc>,\n\tboost::multiplicative<Quaternion<ScalarType, ScalarEqualityFunc>, ScalarType\n\t>>>>\n{\npublic:\n\n\tusing Scalar = ScalarType;\n\n\tusing ScalarPart = Scalar;\n\n\tusing VectorPart = Vector<Scalar, 3, ScalarEqualityFunc>;\n\n\t// --- CONSTRUCTORS AND OPERATORS\n\n\tconstexpr Quaternion(ScalarPart s, VectorPart v) :\n\t\telements_(v.x(), v.y(), v.z(), s)\n\t{\n\t}\n\n\tfriend std::ostream& operator<<(std::ostream& os, const Quaternion& q) {\n\t\treturn os << q.s() << \" + \" << q.v();\n\t}\n\n\tfriend bool operator==(const Quaternion& lhs, const Quaternion& rhs) noexcept {\n\t\treturn lhs.elements_ == rhs.elements_;\n\t}\n\n\tQuaternion& operator*=(const Quaternion& other) noexcept {\n\t\tconst auto s1 = s();\n\t\tconst auto s2 = other.s();\n\t\tconst auto v1 = v();\n\t\tconst auto v2 = other.v();\n\n\t\tconst auto s = s1 * s2 - ::dot(v1, v2);\n\t\tconst auto v = s1 * v2 + s2 * v1 + cross(v1, v2);\n\n\t\t*this = Quaternion(s, v);\n\n\t\treturn *this;\n\t}\n\n\tQuaternion& operator+=(const Quaternion& other) noexcept {\n\t\telements_ += other.elements_;\n\t\treturn *this;\n\t}\n\n\tQuaternion& operator-=(const Quaternion& other) noexcept {\n\t\telements_ -= other.elements_;\n\t\treturn *this;\n\t}\n\n\tQuaternion& operator*=(const Scalar& s) noexcept {\n\t\telements_ *= s;\n\t\treturn *this;\n\t}\n\n\tQuaternion& operator/=(const Scalar& s) noexcept {\n\t\telements_ /= s;\n\t\treturn *this;\n\t}\n\n\t// --- QUATERNION-SPECIFIC OPERATIONS\n\n\tconstexpr Quaternion conjugate() const noexcept {\n\t\treturn Quaternion(s(), -v());\n\t}\n\n\tQuaternion& normalise() noexcept {\n\t\tconst auto n = norm();\n\t\tif (n > Scalar(0)) {\n\t\t\t*this /= n;\n\t\t}\n\t\treturn *this;\n\t}\n\n\tQuaternion normalised() const noexcept {\n\t\tauto result = *this;\n\t\treturn result.normalise();\n\t}\n\n\tScalar norm() const noexcept {\n\t\treturn elements_.length();\n\t}\n\n\tScalar normSq() const noexcept {\n\t\treturn elements_.lengthSq();\n\t}\n\n\tQuaternion inverse() const noexcept {\n\t\tconst auto n = normSq();\n\t\tassert(!ScalarEqualityFunc()(n, Scalar(0)));\n\t\treturn conjugate() / n;\n\t}\n\n\tScalar dot(const Quaternion& other) const noexcept {\n\t\treturn elements_.dot(other.elements_);\n\t}\n\n\t// --- ACCESSORS\n\n\tconstexpr const ScalarPart s() const noexcept {\n\t\treturn elements_.w();\n\t}\n\n\tScalarPart& s() noexcept {\n\t\treturn elements_.w();\n\t}\n\n\tconst VectorPart v() const noexcept { // TODO: return view\n\t\treturn elements_.xyz();\n\t}\n\n\tconst Scalar x() const noexcept {\n\t\treturn elements_.x();\n\t}\n\n\tScalar& x() noexcept {\n\t\treturn elements_.x();\n\t}\n\n\tconst Scalar y() const noexcept {\n\t\treturn elements_.y();\n\t}\n\n\tScalar& y() noexcept {\n\t\treturn elements_.y();\n\t}\n\n\tconst Scalar z() const noexcept {\n\t\treturn elements_.z();\n\t}\n\n\tScalar& z() noexcept {\n\t\treturn elements_.z();\n\t}\n\n\tconst Scalar w() const noexcept {\n\t\treturn elements_.w();\n\t}\n\n\tScalar& w() noexcept {\n\t\treturn elements_.w();\n\t}\n\nprivate:\n\n\tusing Elements = Vector<Scalar, 4, ScalarEqualityFunc>;\n\t\n\tElements elements_;\n\n};\n\ntemplate <class S, class SEF>\nS dot(const Quaternion<S, SEF>& lhs, const Quaternion<S, SEF>& rhs) noexcept {\n\treturn lhs.dot(rhs);\n}\n\nusing Quat = Quaternion<float>;\n\n} // namespace math\n\nusing math::Quaternion;\nusing math::Quat;\n\n} // namespace pulp\n} // namespace coconut\n\n#endif /* _COCONUT_PULP_MATH_QUATERNION_HPP_ */\n", "meta": {"hexsha": "539669a6d1e9a6ecd842d5f60cbd9cb24ed32b6a", "size": 3666, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "coconut-pulp-math/src/main/c++/coconut/pulp/math/Quaternion.hpp", "max_stars_repo_name": "mikosz/coconut", "max_stars_repo_head_hexsha": "547bfd55062f09d7af853043c393fc51e8a7a8b6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-05-02T12:01:54.000Z", "max_stars_repo_stars_event_max_datetime": "2017-05-02T12:01:54.000Z", "max_issues_repo_path": "coconut-pulp-math/src/main/c++/coconut/pulp/math/Quaternion.hpp", "max_issues_repo_name": "mikosz/coconut", "max_issues_repo_head_hexsha": "547bfd55062f09d7af853043c393fc51e8a7a8b6", "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": "coconut-pulp-math/src/main/c++/coconut/pulp/math/Quaternion.hpp", "max_forks_repo_name": "mikosz/coconut", "max_forks_repo_head_hexsha": "547bfd55062f09d7af853043c393fc51e8a7a8b6", "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": 19.8162162162, "max_line_length": 80, "alphanum_fraction": 0.6843971631, "num_tokens": 958, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122138417878, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.7027889650917406}}
{"text": "#include <iostream>\n#include <filesystem>\n#include <Eigen/Eigenvalues>\n#include <fstream>\n#include \"SpectraAnalysisLinearElements.h\"\n#include \"../PhysicalModel/ExternalForces.h\"\n\nSpectraAnalysisLinearElements::SpectraAnalysisLinearElements(const SimParameters& params, Eigen::VectorXd& q0, Eigen::VectorXd& v0, const LinearElements& model)\n{\n\tparams_ = params;\n\tq0_ = q0;\n\tv0_ = v0;\n\tnumSpectras_ = params.numSpectra;\n\n\tif (numSpectras_ > q0.size())\n\t\tnumSpectras_ = q0.size();\n\n\tmodel_ = model;\n\n\tinitialization();\n}\n\nvoid SpectraAnalysisLinearElements::initialization()\n{\n\t// form mass matrix and its inverse\n\tstd::vector<Eigen::Triplet<double>> T, T1;\n\tfor (int i = 0; i < model_.massVec_.size(); i++)\n\t{\n\t\tT.push_back({ i, i, model_.massVec_(i) });\n\t\tT1.push_back({ i, i, 1.0 / model_.massVec_(i) });\n\t}\n\n\tmassMat_.resize(q0_.size(), q0_.size());\n\tmassInvMat_.resize(q0_.size(), q0_.size());\n\n\tmassMat_.setFromTriplets(T.begin(), T.end());\n\tmassInvMat_.setFromTriplets(T1.begin(), T1.end());\n\n\t// compute the eigen modes\n\tmodel_.computeHessian(q0_, K_);\n\n\tEigen::VectorXd g;\n\tmodel_.computeGradient(q0_, g);\n\tb_ = g - K_ * q0_;\n\n\n\t// check the energy\n\tEigen::VectorXd testQ = q0_;\n\ttestQ.setZero();\n\tdouble E0 = model_.computeEnergy(testQ);\n\tdouble E = model_.computeEnergy(q0_);\n\tdouble E1 = 0.5 * q0_.dot(K_ * q0_) + q0_.dot(b_) + E0;\n\n\n\tstd::cout << \"E = \" << E << \", E1 = \" << E1 << \", error = \" << E1 - E << std::endl;\n\n\t\n\ttestQ.setRandom();\n\tE = model_.computeEnergy(testQ);\n\tE1 = 0.5 * testQ.dot(K_ * testQ) + testQ.dot(b_) + E0;\n\tstd::cout << \"E = \" << E << \", E1 = \" << E1 << \", error = \" << E1 - E << std::endl;\n\n\tif (numSpectras_ < q0_.size())\n\t{\n\t\tSpectra::SparseSymMatProd<double> opK(K_);\n\t\tSpectra::SparseCholesky<double> opM(massMat_);\n\n\t\tSpectra::SymGEigsSolver<Spectra::SparseSymMatProd<double>, Spectra::SparseCholesky<double>, Spectra::GEigsMode::Cholesky> eigs(opK, opM, numSpectras_, (2 * numSpectras_ > q0_.size()) ? q0_.size() : 2 * numSpectras_);\n\n\t\teigs.init();\n\t\tint nconv = eigs.compute(Spectra::SortRule::LargestMagn);\n\t\tif (eigs.info() == Spectra::CompInfo::Successful)\n\t\t{\n\t\t\tstd::cout << eigs.eigenvalues() << std::endl;\n\t\t\teigenValues_ = eigs.eigenvalues();\n\t\t\teigenVecs_ = eigs.eigenvectors();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::cerr << \"error in t computing the eigen values of the M^{-1} K \" << std::endl;\n\t\t\texit(1);\n\t\t}\n\t}\n\t\n\telse\n\t{\n\t\tint halfNum = numSpectras_ / 2;\n\t\tSpectra::SparseSymMatProd<double> opK(K_);\n\t\tSpectra::SparseCholesky<double> opM(massMat_);\n\n\t\tSpectra::SymGEigsSolver<Spectra::SparseSymMatProd<double>, Spectra::SparseCholesky<double>, Spectra::GEigsMode::Cholesky> eigs(opK, opM, halfNum, numSpectras_);\n\n\t\teigs.init();\n\t\teigs.compute(Spectra::SortRule::LargestMagn);\n\t\t\n\t\tint leftNum = numSpectras_ - halfNum;\n\n\t\tusing OpType = Spectra::SymShiftInvert<double, Eigen::Sparse, Eigen::Sparse>;\n\t\tusing BOpType = Spectra::SparseSymMatProd<double>;\n\t\tOpType op(K_, massMat_);\n\t\tBOpType Bop(massMat_);\n\n\t\tSpectra::SymGEigsShiftSolver<OpType, BOpType, Spectra::GEigsMode::ShiftInvert> eigs1(op, Bop, leftNum, numSpectras_, 0.0);\n\t\teigs1.init();\n\t\teigs1.compute(Spectra::SortRule::LargestMagn);\n\n\t\tif (eigs.info() == Spectra::CompInfo::Successful && eigs1.info() == Spectra::CompInfo::Successful)\n\t\t{\n\t\t\tstd::cout << eigs.eigenvalues() << std::endl;\n\t\t\tstd::cout << eigs1.eigenvalues() << std::endl;\n\n\t\t\teigenValues_.resize(numSpectras_);\n\t\t\teigenValues_.segment(0, halfNum) = eigs.eigenvalues();\n\t\t\teigenValues_.segment(halfNum, leftNum) = eigs1.eigenvalues();\n\n\t\t\teigenVecs_.resize(q0_.size(), numSpectras_);\n\t\t\teigenVecs_.block(0, 0, q0_.size(), halfNum) = eigs.eigenvectors();\n\t\t\teigenVecs_.block(0, halfNum, q0_.size(), leftNum) = eigs1.eigenvectors();\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// super slow when size of q is large\n\t\t\tEigen::GeneralizedEigenSolver<Eigen::MatrixXd> ges;\n\t\t\tges.compute(K_.toDense(), massMat_.toDense());\n\t\t\teigenValues_ = ges.eigenvalues().real();\n\t\t\teigenVecs_ = ges.eigenvectors().real();\n\t\t}\n\t\t\n\t}\n\t\n\n\t// check the othonormality\n\tEigen::MatrixXd idMat = Eigen::MatrixXd::Identity(numSpectras_, numSpectras_);\n\tstd::cout << \"error: \" << (eigenVecs_.transpose() * massMat_ * eigenVecs_ - idMat).norm() << std::endl;\n\t\n\t// compute initial alphas and betas\n\tcurAlphaBeta_.resize(numSpectras_);\n\tpreAlphaBeta_.resize(numSpectras_);\n\tinitialAlphaBeta_.resize(numSpectras_);\n\tcurAlphaBetaTheo_.resize(numSpectras_);\n\n\tfor (int i = 0; i < numSpectras_; i++)\n\t{\n\t\tdouble alpha = eigenVecs_.col(i).dot(massMat_ * q0_);\n\t\tdouble beta = eigenVecs_.col(i).dot(massMat_ * v0_);\n\t\tinitialAlphaBeta_[i] << alpha, beta;\n\t\tpreAlphaBeta_[i] = initialAlphaBeta_[i];\n\t\tcurAlphaBeta_[i] = initialAlphaBeta_[i];\n\t\tcurAlphaBetaTheo_[i] = initialAlphaBeta_[i];\n\t}\n\n\t// compute the constant part\n\t/*cis_.resize(numSpectras_);\n\n\tfor (int i = 0; i < numSpectras_; i++)\n\t{\n\t\tdouble value = eigenVecs_.col(i).dot(b_);\n\t\tcis_[i] = value;\n\t}*/\n\n\t// current time\n\tcurTime_ = 0;\n\n\tupdateCis();\n}\n\nvoid SpectraAnalysisLinearElements::updateCis()\n{\n\tEigen::VectorXd extForce = ExternalForces::externalForce(q0_, curTime_, params_.impulseMag, params_.impulsePow);\n\tEigen::VectorXd c = b_ - extForce;\n\n\t// compute the constant part\n\tcis_.resize(numSpectras_);\n\n\tfor (int i = 0; i < numSpectras_; i++)\n\t{\n\t\tdouble value = eigenVecs_.col(i).dot(c);\n\t\tcis_[i] = value;\n\t}\n}\n\nvoid SpectraAnalysisLinearElements::updateAlphasBetas()\n{\n\tdouble h = params_.timeStep;\n\tupdateCis();\n\tfor (int i = 0; i < numSpectras_; i++)\n\t{\n\t\tif (params_.integrator == SimParameters::TI_IMPLICIT_EULER)\n\t\t{\n\t\t\tEigen::Matrix2d A;\n\t\t\tA << 1, -h, eigenValues_[i] * h, 1;\n\t\t\tEigen::Vector2d consVec;\n\t\t\tconsVec << 0, -h * cis_[i];\n\n\t\t\tEigen::Matrix2d Ainv = A.inverse();\n\n\t\t\tpreAlphaBeta_[i] = curAlphaBeta_[i];\n\t\t\tcurAlphaBeta_[i] = Ainv * (preAlphaBeta_[i] + consVec);\n\t\t}\n\t\telse if (params_.integrator == SimParameters::TI_NEWMARK)\n\t\t{\n\t\t\tEigen::Matrix2d A;\n\t\t\tdouble NM_beta = params_.NM_beta;\n\t\t\tA << 1 + h * h * eigenValues_[i] * NM_beta, 0, \n\t\t\t\teigenValues_[i] * h / 2.0, 1;\n\t\t\tEigen::Vector2d consVec;\n\n\t\t\tEigen::Matrix2d A1;\n\t\t\tA1 << 1 - h * h * eigenValues_[i] * (0.5 - NM_beta), h,\n\t\t\t\t-eigenValues_[i] * h / 2.0, 1;\n\n\t\t\tconsVec << -h * h * cis_[i] / 2, -params_.timeStep * cis_[i];\n\n\t\t\tEigen::Matrix2d Ainv = A.inverse();\n\n\t\t\tpreAlphaBeta_[i] = curAlphaBeta_[i];\n\t\t\tcurAlphaBeta_[i] = Ainv * (A1 * preAlphaBeta_[i] + consVec);\n\t\t}\n\t\telse if (params_.integrator == SimParameters::TI_TR_BDF2)\n\t\t{\n\t\t\tEigen::Vector2d alphabeta;\n\t\t\tdouble gamma = params_.TRBDF2_gamma;\n\t\t\tdouble gamma2 = (1 - 2 * gamma) / (2 - 2 * gamma);\n\t\t\tdouble gamma3 = (1 - gamma2) / (2 * gamma);\n\n\t\t\tEigen::Matrix2d A, A1, A2, Ainv;\n\t\t\tEigen::Vector2d consVec;\n\n\t\t\tA << 1, -gamma * h, eigenValues_[i] * gamma* h, 1;\n\t\t\tAinv = A.inverse();\n\n\t\t\tA1 << 1, gamma * h, -eigenValues_[i] * gamma* h, 1;\n\n\t\t\tconsVec << 0, -2 * gamma * h * cis_[i];\n\t\t\talphabeta = Ainv * (A1 * curAlphaBeta_[i] + consVec);\n\n\t\t\tA << 1, -gamma2 * h, eigenValues_[i] * gamma2 * h, 1;\n\t\t\tAinv = A.inverse();\n\t\t\tconsVec << 0, -gamma2 * h * cis_[i];\n\n\t\t\tA1 << gamma3, 0, 0, gamma3;\n\t\t\tA2 << 1 - gamma3, 0, 0, 1 - gamma3;\n\n\t\t\tpreAlphaBeta_[i] = curAlphaBeta_[i];\n\t\t\tcurAlphaBeta_[i] = Ainv * (A1 * alphabeta + A2 * preAlphaBeta_[i] + consVec);\n\t\t}\n\t\telse if (params_.integrator == SimParameters::TI_BDF2)\n\t\t{\n\t\t\tif (curTime_ == 0)\t// use IE for the first step\n\t\t\t{\n\t\t\t\tEigen::Matrix2d A;\n\t\t\t\tA << 1, -h, eigenValues_[i] * h, 1;\n\t\t\t\tEigen::Vector2d consVec;\n\t\t\t\tconsVec << 0, -h * cis_[i];\n\n\t\t\t\tEigen::Matrix2d Ainv = A.inverse();\n\n\t\t\t\tpreAlphaBeta_[i] = curAlphaBeta_[i];\n\t\t\t\tcurAlphaBeta_[i] = Ainv * (preAlphaBeta_[i] + consVec);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tEigen::Vector2d alphabeta;\n\n\t\t\t\tEigen::Matrix2d A, A1, A2, Ainv;\n\t\t\t\tEigen::Vector2d consVec;\n\n\t\t\t\tA << 1, -2.0 / 3.0 * h, eigenValues_[i] * 2.0 / 3.0 * h, 1;\n\t\t\t\tAinv = A.inverse();\n\t\t\t\tconsVec << 0, -2.0 / 3.0 * h * cis_[i];\n\n\t\t\t\tA1 << 4.0 / 3.0, 0, 0, 4.0 / 3.0;\n\t\t\t\tA2 << -1.0 / 3.0, 0, 0, -1.0 / 3.0;\n\n\t\t\t\talphabeta = Ainv * (A1 * curAlphaBeta_[i] + A2 * preAlphaBeta_[i] + consVec);\n\n\t\t\t\tpreAlphaBeta_[i] = curAlphaBeta_[i];\n\t\t\t\tcurAlphaBeta_[i] = alphabeta;\n\t\t\t}\n\t\t}\n\t}\n\tcurTime_ += h;\n\n\t// compute the theoretical alpha beta\n\tfor (int i = 0; i < numSpectras_; i++)\n\t{\n\t\tcurAlphaBetaTheo_[i](0) = (initialAlphaBeta_[i](0) + cis_[i] / eigenValues_[i]) * std::cos(std::sqrt(eigenValues_[i]) * curTime_) - cis_[i] / eigenValues_[i];\n\t\tcurAlphaBetaTheo_[i](1) = (initialAlphaBeta_[i](0) + cis_[i] / eigenValues_[i]) * std::sin(std::sqrt(eigenValues_[i]) * curTime_) * std::sqrt(eigenValues_[i]);\n\t}\n}\n\nvoid SpectraAnalysisLinearElements::getCurPosVel(Eigen::VectorXd& pos, Eigen::VectorXd& vel)\n{\n\tif (curAlphaBeta_.size() != numSpectras_)\n\t{\n\t\tstd::cerr << \"mismatch in alpha beta vector size and number of spectras.\" << std::endl;\n\t\texit(1);\n\t}\n\n\tpos.setZero(eigenVecs_.rows());\n\tvel.setZero(eigenVecs_.rows());\n\n\tfor (int i = 0; i < numSpectras_; i++)\n\t{\n\t\tpos += curAlphaBeta_[i](0) * eigenVecs_.col(i);\n\t\tvel += curAlphaBeta_[i](1) * eigenVecs_.col(i);\n\t}\n}\n\nvoid SpectraAnalysisLinearElements::getTheoPosVel(Eigen::VectorXd& pos, Eigen::VectorXd& vel)\n{\n\tif (curAlphaBetaTheo_.size() != numSpectras_)\n\t{\n\t\tstd::cerr << \"mismatch in alpha beta vector size and number of spectras.\" << std::endl;\n\t\texit(1);\n\t}\n\n\tpos.setZero(eigenVecs_.rows());\n\tvel.setZero(eigenVecs_.rows());\n\n\tfor (int i = 0; i < numSpectras_; i++)\n\t{\n\t\tpos += curAlphaBetaTheo_[i](0) * eigenVecs_.col(i);\n\t\tvel += curAlphaBetaTheo_[i](1) * eigenVecs_.col(i);\n\t}\n}\n\n\nvoid SpectraAnalysisLinearElements::saveInfo(std::string outputFolder)\n{\n\tif (!std::filesystem::exists(outputFolder))\n\t{\n\t\tstd::cout << \"create directory: \" << outputFolder << std::endl;\n\t\tif (!std::filesystem::create_directories(outputFolder))\n\t\t{\n\t\t\tstd::cout << \"create folder failed.\" << outputFolder << std::endl;\n\t\t\texit(1);\n\t\t}\n\t}\n\n\tstd::string evalsFileName = outputFolder + \"evals.txt\";\n    if(curTime_ == 0)\n    {\n        std::ofstream  efs;\n        efs.open(evalsFileName, std::ofstream::out);\n        for (int i = 0; i < numSpectras_; i++)\n        {\n            efs << eigenValues_[i] << std::endl;\n        }\n    }\n\n\tfor (int i = 0; i < numSpectras_; i++)\n\t{\n\t\tstd::string alphafileName = outputFolder + \"alpha_\" + std::to_string(i) + \".txt\";\n\t\tstd::string theoAlphafileName = outputFolder + \"alpha_theo_\" + std::to_string(i) + \".txt\";\n\n\t\tstd::string betafileName = outputFolder + \"beta_\" + std::to_string(i) + \".txt\";\n\t\tstd::string theoBetafileName = outputFolder + \"beta_theo_\" + std::to_string(i) + \".txt\";\n\n\t\tstd::string extFfileName = outputFolder + \"c_\" + std::to_string(i) + \".txt\";\n\n\t\tstd::ofstream afs, atfs, bfs, btfs, cfs;\n\n\t\tif (curTime_ == 0)\n\t\t{\n\t\t\tafs.open(alphafileName, std::ofstream::out);\n\t\t\tatfs.open(theoAlphafileName, std::ofstream::out);\n\n\t\t\tbfs.open(betafileName, std::ofstream::out);\n\t\t\tbtfs.open(theoBetafileName, std::ofstream::out);\n\n\t\t\tcfs.open(extFfileName, std::ofstream::out);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tafs.open(alphafileName, std::ofstream::out | std::ofstream::app);\n\t\t\tatfs.open(theoAlphafileName, std::ofstream::out | std::ofstream::app);\n\n\t\t\tbfs.open(betafileName, std::ofstream::out | std::ofstream::app);\n\t\t\tbtfs.open(theoBetafileName, std::ofstream::out | std::ofstream::app);\n\n\t\t\tcfs.open(extFfileName, std::ofstream::out | std::ofstream::app);\n\t\t}\n\n\t\tafs << curAlphaBeta_[i](0) << std::endl;\n\t\tatfs << curAlphaBetaTheo_[i](0) << std::endl;\n\n\t\tbfs << curAlphaBeta_[i](1) << std::endl;\n\t\tbtfs << curAlphaBetaTheo_[i](1) << std::endl;\n\n\t\tcfs << cis_[i] << std::endl;\n\t}\n}", "meta": {"hexsha": "64b87df3617137d0264100be868d0eb162b57895", "size": 11457, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SpectraAnalysis/SpectraAnalysisLinearElements.cpp", "max_stars_repo_name": "csyzzkdcz/TimeIntegrator", "max_stars_repo_head_hexsha": "8d01f124b4402ae2ec3aa50863b53360b74ab5c8", "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": "SpectraAnalysis/SpectraAnalysisLinearElements.cpp", "max_issues_repo_name": "csyzzkdcz/TimeIntegrator", "max_issues_repo_head_hexsha": "8d01f124b4402ae2ec3aa50863b53360b74ab5c8", "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": "SpectraAnalysis/SpectraAnalysisLinearElements.cpp", "max_forks_repo_name": "csyzzkdcz/TimeIntegrator", "max_forks_repo_head_hexsha": "8d01f124b4402ae2ec3aa50863b53360b74ab5c8", "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.1526717557, "max_line_length": 218, "alphanum_fraction": 0.649122807, "num_tokens": 4002, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122213606241, "lm_q2_score": 0.7745833737577158, "lm_q1q2_score": 0.7027889614731196}}
{"text": "\n#include <Eigen/Dense>\n#include <iostream>\n#include <mplot++/mplot++.h>\n#include <tuple>\n\nnamespace ei = Eigen;\nnamespace mp = mplotpp;\n\ntemplate<class T>\nstd::tuple<Eigen::Array<T, Eigen::Dynamic, Eigen::Dynamic>,\n           Eigen::Array<T, Eigen::Dynamic, Eigen::Dynamic>>\nmeshgrid(const Eigen::Array<T, Eigen::Dynamic, 1>& x,\n         const Eigen::Array<T, Eigen::Dynamic, 1>& y)\n{\n  Eigen::Array<T, Eigen::Dynamic, Eigen::Dynamic> X(y.size(), x.size());\n  Eigen::Array<T, Eigen::Dynamic, Eigen::Dynamic> Y(y.size(), x.size());\n  for (ssize_t i = 0; i < X.rows(); ++i) {\n    X.row(i) = x;\n  }\n  for (ssize_t j = 0; j < Y.cols(); ++j) {\n    Y.col(j) = y;\n  }\n\n  return std::make_tuple(X, Y);\n}\n\nint\nmain()\n{\n  ei::ArrayXd x = mp::arange(-1.0, 1.01, 1.0);\n  ei::ArrayXd y = mp::arange(-2.0, 2.01, 1.0);\n  std::cout << \"x = \" << x.transpose() << std::endl;\n  std::cout << \"y = \" << y.transpose() << std::endl;\n\n  {\n    ei::ArrayXXd X(y.size(), x.size());\n    for (ssize_t i = 0; i < X.rows(); ++i) {\n      X.row(i) = x;\n    }\n    std::cout << \"X =\\n\" << X << std::endl;\n\n    ei::ArrayXXd Y(y.size(), x.size());\n    for (ssize_t j = 0; j < Y.cols(); ++j) {\n      Y.col(j) = y;\n    }\n    std::cout << \"Y =\\n\" << Y << std::endl;\n  }\n\n  {\n    auto [X, Y] = meshgrid(x, y);\n    std::cout << \"X =\\n\" << X << std::endl;\n    std::cout << \"Y =\\n\" << Y << std::endl;\n    std::cout << \"X + 1 =\\n\" << (X + 1) << std::endl;\n    auto Z1 = (-X.pow(2) - Y.pow(2)).exp();\n    std::cout << \"Z1 =\\n\" << Z1 << std::endl;\n    auto Z2 = (-(X - 1).pow(2) - (Y - 1).pow(2)).exp();\n    std::cout << \"Z2 =\\n\" << Z2 << std::endl;\n    auto Z = (Z1 - Z2) * 2;\n    std::cout << \"Z =\\n\" << Z << std::endl;\n  }\n}", "meta": {"hexsha": "455d685d97d88f8df884f993cb4383fc423a5a72", "size": 1681, "ext": "cc", "lang": "C++", "max_stars_repo_path": "development/meshgrid.cc", "max_stars_repo_name": "TassieBruce/mplot-pybind", "max_stars_repo_head_hexsha": "fbed1a131d9fead0dae363b9988daa57ca018330", "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": "development/meshgrid.cc", "max_issues_repo_name": "TassieBruce/mplot-pybind", "max_issues_repo_head_hexsha": "fbed1a131d9fead0dae363b9988daa57ca018330", "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": "development/meshgrid.cc", "max_forks_repo_name": "TassieBruce/mplot-pybind", "max_forks_repo_head_hexsha": "fbed1a131d9fead0dae363b9988daa57ca018330", "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.1129032258, "max_line_length": 72, "alphanum_fraction": 0.491374182, "num_tokens": 637, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894520743981, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.7026858303058833}}
{"text": "#include <tdp/testing/testing.h> \n#include <iostream>\n#include <Eigen/Dense>\n#include <tdp/manifold/SO3.h>\n#include <tdp/manifold/SO3mat.h>\n#include <tdp/eigen/dense.h>\n\nusing namespace tdp;\n\nTEST(SO3, log) {\n  const float eps = 1e-4;\n\n  for (size_t i=0; i<1000; ++i) {\n    Eigen::Vector2f rand = Eigen::Vector2f::Random();\n    SO3f Rx0 = SO3f::Rx(ToRad(rand(0)));\n    SO3matf Rx0_ = SO3matf::Rx(ToRad(rand(0)));\n\n    ASSERT_TRUE(IsAppox(Rx0.matrix(), Rx0_.matrix(), eps));\n    ASSERT_NEAR(fabs(rand(0)), ToDeg(SO3f::Log_(Rx0).norm()), eps);\n    ASSERT_TRUE(rand(0)<0.? SO3f::Log_(Rx0)(0) < 0. : SO3f::Log_(Rx0)(0) >= 0. );\n\n  }\n\n  for (size_t i=0; i<1000; ++i) {\n    SO3f R0 = SO3f::Random();\n    Eigen::Vector3f x0 = SO3f::Log_(R0);\n    Eigen::Vector3f x1 = SO3mat<float>::Log_(R0.matrix());\n\n    if (!IsAppox(x0,x1,eps)) {\n      std::cout << R0.matrix() << std::endl;\n      tdp::Vector3fda axis;\n      float angle;\n      R0.ToAxisAngle(axis, angle);\n      std::cout << axis.transpose() << \" angle \" << angle \n        << \" \" << ToDeg(angle) << std::endl;\n      std::cout << ToDeg(x0.norm()) << \" \" << ToDeg(x1.norm()) << std::endl;\n      std::cout << R0 << std::endl;\n    }\n    EXPECT_TRUE(IsAppox(x0,x1,eps));\n//    ASSERT_NEAR(x0.norm(),x1.norm(),eps);\n  }\n}\n\nTEST(SO3, exp) {\n\n  const float eps = 1e-5;\n  for (size_t i=0; i<1000; ++i) {\n    Eigen::Vector3f x = 1e-3*Eigen::Vector3f::Random();\n    Eigen::Matrix3f R0 = SO3f::Exp_(x).matrix();\n    Eigen::Matrix3f R1 = SO3mat<float>::Exp_(x).matrix();\n\n    ASSERT_TRUE(IsAppox(R0,R1,eps));\n\n    Eigen::Vector3f x0 = SO3f::Log_(R0);\n    Eigen::Vector3f x1 = SO3mat<float>::Log_(R1);\n    \n    if (!IsAppox(x0,x1,eps)) {\n      std::cout << R0 << std::endl << R1 << std::endl;\n      std::cout << \"so3:  \" << x.transpose() << std::endl;\n      std::cout << \"Quat: \" << SO3f::Exp_(x) << std::endl;\n    }\n\n    ASSERT_TRUE(IsAppox(x0,x1,eps));\n    ASSERT_TRUE(IsAppox(x,x1,eps));\n    ASSERT_TRUE(IsAppox(x0,x,eps));\n\n  }\n}\n\nTEST(SO3, Rz) {\n  const float eps = 1e-4;\n  Eigen::Matrix3f R0t = Eigen::Matrix3f::Identity();\n  SO3f R0 = SO3f::Rz(0.);\n  ASSERT_TRUE(IsAppox(R0.matrix(), R0t, eps));\n\n  SO3f R0_1;\n  for (size_t i=0; i<36; ++i)\n    R0_1 = SO3f::Rz(ToRad(10.)) * R0_1;\n  ASSERT_TRUE(IsAppox(R0_1.matrix(), R0t, eps));\n\n  R0_1 = SO3f();\n  for (size_t i=0; i<360; ++i)\n    R0_1 = SO3f::Rz(ToRad(1.)) * R0_1;\n  ASSERT_TRUE(IsAppox(R0_1.matrix(), R0t, eps));\n\n  R0_1 = SO3f();\n  for (size_t i=0; i<3600; ++i)\n    R0_1 = SO3f::Rz(ToRad(0.1)) * R0_1;\n  ASSERT_TRUE(IsAppox(R0_1.matrix(), R0t, eps));\n}\n\nTEST(SO3, Ry) {\n  const float eps = 1e-4;\n  Eigen::Matrix3f R0t = Eigen::Matrix3f::Identity();\n  SO3f R0 = SO3f::Ry(0.);\n  ASSERT_TRUE(IsAppox(R0.matrix(), R0t, eps));\n\n  SO3f R0_1;\n  for (size_t i=0; i<36; ++i)\n    R0_1 *= SO3f::Ry(ToRad(10.));\n  ASSERT_TRUE(IsAppox(R0_1.matrix(), R0t, eps));\n\n  R0_1 = SO3f();\n  for (size_t i=0; i<360; ++i)\n    R0_1 *= SO3f::Ry(ToRad(1.));\n  ASSERT_TRUE(IsAppox(R0_1.matrix(), R0t, eps));\n\n  R0_1 = SO3f();\n  for (size_t i=0; i<3600; ++i)\n    R0_1 *= SO3f::Ry(ToRad(0.1));\n  ASSERT_TRUE(IsAppox(R0_1.matrix(), R0t, eps));\n}\n\nTEST(SO3, Rx) {\n  const float eps = 1e-4;\n  Eigen::Matrix3f R0t = Eigen::Matrix3f::Identity();\n  SO3f R0 = SO3f::Rx(0.);\n  ASSERT_TRUE(IsAppox(R0.matrix(), R0t, eps));\n\n  ASSERT_TRUE(IsAppox(SO3f::Rx(ToRad(10.)).matrix(), \n        SO3mat<float>::Rx(ToRad(10.)).matrix(),eps));\n  SO3f R0_1;\n  for (size_t i=0; i<36; ++i) \n    R0_1 *= SO3f::Rx(ToRad(10));\n  ASSERT_TRUE(IsAppox(R0_1.matrix(), R0t, eps));\n\n  R0_1 = SO3f();\n  for (size_t i=0; i<360; ++i)\n    R0_1 *= SO3f::Rx(ToRad(1.));\n  ASSERT_TRUE(IsAppox(R0_1.matrix(), R0t, eps));\n\n  R0_1 = SO3f();\n  for (size_t i=0; i<3600; ++i)\n    R0_1 *= SO3f::Rx(ToRad(0.1));\n  ASSERT_TRUE(IsAppox(R0_1.matrix(), R0t, eps));\n}\n\nTEST(SO3, composition) {\n\n  const float eps = 1e-5;\n  for (size_t i=0; i<1000; ++i) {\n    SO3f Rw0 = SO3f::Random();\n    SO3f Rw1 = SO3f::Random();\n    Eigen::Matrix3f Rw0mat = Rw0.matrix();\n    Eigen::Matrix3f Rw1mat = Rw1.matrix();\n\n    SO3f R01 = Rw0.Inverse() * Rw1;\n    Eigen::Matrix3f R01mat = Rw0mat.transpose()*Rw1mat;\n    ASSERT_TRUE(R01mat.isApprox(R01.matrix(),eps));\n\n    SO3f Rw0w1 = Rw0 * Rw1;\n    Eigen::Matrix3f Rw0w1mat = Rw0mat*Rw1mat;\n    ASSERT_TRUE(Rw0w1mat.isApprox(Rw0w1.matrix(),eps));\n  }\n\n  SO3f Rw0;\n  Eigen::Matrix3f Rw0mat = Eigen::Matrix3f::Identity();\n  for (size_t i=0; i<1000; ++i) {\n    Eigen::Vector3f x0 = 1e-3*Eigen::Vector3f::Random();\n    Rw0 = Rw0 * SO3f::Exp_(x0);\n    Rw0mat = Rw0mat * SO3mat<float>::Exp_(x0).matrix();\n    ASSERT_TRUE(Rw0mat.isApprox(Rw0.matrix(),eps));\n  }\n\n}\n\nTEST(SO3, opt) {\n  \n  SO3d R;\n  std::cout << R << std::endl;\n\n  double theta = 15.*M_PI/180.;\n  Eigen::Matrix3d Rmu_;\n  Rmu_ << 1, 0, 0,\n         0, cos(theta), sin(theta),\n         0, -sin(theta), cos(theta);\n  SO3d Rmu(Rmu_);\n  \n  std::cout << Rmu << std::endl;\n//  std::cout << R+Rmu << std::endl;\n  std::cout << R << std::endl;\n//  std::cout << Rmu+R << std::endl;\n//  std::cout << R-Rmu << std::endl;\n\n//  Eigen::Vector3d w = R-Rmu;\n//  std::cout << Rmu.Exp(w) << std::endl;\n\n//  std::cout << Rmu-R << std::endl;\n  \n  double delta = 0.1;\n  double f_prev = 1e99;\n  double f = (Rmu.Inverse() * R).matrix().trace();\n  std::cout << \"f=\" << f << std::endl;\n  for (uint32_t it=0; it<100; ++it) {\n    Eigen::Matrix3d J = -0.5*((R.Inverse() * Rmu).matrix() - (Rmu.Inverse() * R).matrix()); \n    Eigen::Vector3d Jw = SO3d::vee(J);\n//    R = R.Exp(-delta*Jw);\n    R *= SO3d::Exp_(-delta*Jw);\n//    std::cout << Jw << std::endl;\n    f_prev = f;\n    f = (Rmu.Inverse() * R).matrix().trace();\n    std::cout << \"f=\" << f << \" df/f=\" << (f_prev - f)/f \n      << std::endl;\n  }\n  std::cout << Rmu << std::endl;\n  std::cout << R << std::endl;\n}\n\nint main(int argc, char **argv) {\n  ::testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n\n", "meta": {"hexsha": "6cb025352b504aba14420d11c8d0a816269db30d", "size": 5841, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/SO3.cpp", "max_stars_repo_name": "jstraub/tdp", "max_stars_repo_head_hexsha": "dcab53662be5b88db1538cf831707b07ab96e387", "max_stars_repo_licenses": ["MIT-feh"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-10-17T19:25:47.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-17T19:25:47.000Z", "max_issues_repo_path": "test/SO3.cpp", "max_issues_repo_name": "jstraub/tdp", "max_issues_repo_head_hexsha": "dcab53662be5b88db1538cf831707b07ab96e387", "max_issues_repo_licenses": ["MIT-feh"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-05-02T06:04:06.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-02T06:04:06.000Z", "max_forks_repo_path": "test/SO3.cpp", "max_forks_repo_name": "jstraub/tdp", "max_forks_repo_head_hexsha": "dcab53662be5b88db1538cf831707b07ab96e387", "max_forks_repo_licenses": ["MIT-feh"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2017-09-17T18:46:20.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-11T12:52:57.000Z", "avg_line_length": 27.2943925234, "max_line_length": 92, "alphanum_fraction": 0.5733607259, "num_tokens": 2351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870288, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.7026857432292078}}
{"text": "#include <stan/math/prim/scal.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <gtest/gtest.h>\n\nTEST(MathFunctions, binary_log_loss) {\n  EXPECT_FLOAT_EQ(0.0, stan::math::binary_log_loss(0,0.0));\n  EXPECT_FLOAT_EQ(0.0, stan::math::binary_log_loss(1,1.0));\n  EXPECT_FLOAT_EQ(-log(0.5), stan::math::binary_log_loss(0,0.5));\n  EXPECT_FLOAT_EQ(-log(0.5), stan::math::binary_log_loss(1,0.5));\n  EXPECT_FLOAT_EQ(-log(0.75), stan::math::binary_log_loss(0,0.25));\n  EXPECT_FLOAT_EQ(-log(0.75), stan::math::binary_log_loss(1,0.75));\n}\n\nTEST(MathFunctions, binary_log_loss_nan) {\n  double nan = std::numeric_limits<double>::quiet_NaN();\n\n  EXPECT_PRED1(boost::math::isnan<double>,\n               stan::math::binary_log_loss(0, nan));\n  \n  EXPECT_PRED1(boost::math::isnan<double>,\n               stan::math::binary_log_loss(1, nan));\n}\n", "meta": {"hexsha": "e70e78d416e3e4771ea45aa61946c30a584e9c7a", "size": 844, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/binary_log_loss_test.cpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "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": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/binary_log_loss_test.cpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "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": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/binary_log_loss_test.cpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "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": 36.6956521739, "max_line_length": 67, "alphanum_fraction": 0.7002369668, "num_tokens": 258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953030553434, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.7025924357845091}}
{"text": "// c\n#include <cmath>\n\n// std\n#include <iostream>\n\n// 3rd party\n#include <boost/math/constants/constants.hpp>\n#include <boost/random.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n\n#include <gtest/gtest.h>\n\n#include <opencv2/opencv.hpp>\n\n// local\n#include \"OccupancyGrid/occgrid.hpp\"\n#include \"OccupancyGrid/forward_sensor_model.h\"\n\nnamespace bconst = boost::math::constants;\nnamespace brand = boost::random;\n\n#undef DEBUGDRAW\n\ndouble log_gaussian1d(double x, double mu, double sigma) {\n    return (-0.5 * (x - mu)*(x - mu) / (sigma*sigma)) + log(sigma * bconst::root_two_pi<double>());\n}\n\ndouble gaussian1d(double x, double mu, double sigma) {\n    // ignore the scaling factor\n    return exp(-0.5 * (x - mu)*(x - mu) / (sigma*sigma));//  / (sigma * bconst::root_two_pi<double>());\n}\n\n//double probability_single_observation_given_map_and_pose(\ndouble log_odds_observation_given_map_and_pose(\n    const Observation2D& observation,\n    OccupancyGrid2D<double, int>& map,\n    double& expected_range) \n{\n    double total_angle = observation.ptheta;\n    cv::Vec2d direction(cos(total_angle), sin(total_angle));\n    cv::Vec2d position(observation.px, observation.py);\n    // if (std::isnan(direction(0))) {\n    //     printf(\"Robot Angle : %f, angle of obs: %f\\n\", robot_angle, angle_of_observation);\n    //     throw std::logic_error(\"direction(0) is nan\");\n    // }\n    //\n    assert(! std::isnan(direction(1)));\n    assert(! std::isnan(direction(0)));\n    cv::Vec2d final_pos;\n    bool reflectance;\n    expected_range = map.ray_trace(observation.px, observation.py,\n        observation.ptheta, LASER_MAX_RANGE, final_pos, reflectance);\n    //if (expected_range == LASER_MAX_RANGE) {\n        // laser didn't strike any wall\n        // but that doesn't matter, because our input observations also\n        // contain saturated readings instead of providing some special value.\n    //}\n    double sigma = NOISE_VARIANCE * expected_range; // noise increases with distance\n#ifdef DEBUG\n      printf(\"Sigma:%f\\n\", sigma);\n      printf(\"Expected range:%f\\n\", expected_range);\n      printf(\"Observed range:%f\\n\", observation.range);\n#endif\n    double gaussian_lodds = log_gaussian1d(observation.range, expected_range, sigma);\n    return gaussian_lodds;\n}\n\nclass ForwardSensorModelTest : public ::testing::Test {\n  protected:\n    OccupancyGrid2D<double, int> map;\n    boost::mt19937 gen;\n    double range_observation; \n    boost::normal_distribution<> norm_dist;;\n    boost::variate_generator<boost::mt19937&, boost::normal_distribution<> > norm_rand;;\n\n    ForwardSensorModelTest():\n      map(-2.5, -1.5, 0.5, 0.5, 12, 6),\n      gen(),\n      range_observation(sqrt(2.5*2.5 + 0.5*0.5)),\n      norm_dist(0, NOISE_VARIANCE * range_observation),\n      norm_rand(gen, norm_dist)\n    { }\n\n    virtual void SetUp() {\n        map.og_ = cv::Scalar(map.FREE);\n        map.og_.at<uint8_t>(10, 4) = map.OCCUPIED;\n        map.og_.at<uint8_t>(10, 1) = map.OCCUPIED;\n        map.og_.at<uint8_t>(11, 2) = map.OCCUPIED;\n        map.og_.at<uint8_t>(11, 3) = map.OCCUPIED;\n        map.og_.at<uint8_t>(1, 2) = map.OCCUPIED;\n        map.og_.at<uint8_t>(1, 3) = map.OCCUPIED;\n        range_observation = sqrt(2.5*2.5 + 0.5*0.5);\n    }\n};\n\nTEST_F(ForwardSensorModelTest, test1) {\n    double noise = norm_rand();\n    range_observation += noise;\n    double robot_angle = atan2(0.5, 2.5);\n    Observation2D observation(0, 0, robot_angle, range_observation);\n    double exp_range;\n    double lodds =\n      log_odds_observation_given_map_and_pose(\n          observation,\n          map,\n          exp_range);\n\n    ASSERT_NEAR(\n        log_gaussian1d(noise, 0, NOISE_VARIANCE * (range_observation - noise)),\n        lodds, \n        0.002);\n}\n\n//double probability_observation_given_map_and_all_poses(\ndouble log_odds_observation_given_map_and_all_poses(\n    const std::vector<Observation2D>& observations,\n    OccupancyGrid2D<double, int>& map)\n{\n    std::vector<double> lodds_vector;\n    lodds_vector.reserve(observations.size());\n#ifdef DEBUGDRAW\n    int scan_count = 0;\n    double last_px = observations[0].px;\n    double last_px = observations[1].py;\n    std::vector<double> angles;\n    std::vector<double> ranges;\n    std::vector<double> exp_ranges;\n#endif\n    for (std::vector<Observation2D>::const_iterator it = observations.begin();\n        it != observations.end();\n        ++it) {\n        double expr;\n        lodds_vector.push_back(\n            log_odds_observation_given_map_and_pose(*it, map, expr));\n#ifdef DEBUGDRAW\n        // when position of the robot changes\n        // draw lasers observations collected till now.\n        if (last_px != (*it).px && last_py != (*it).py) {\n            cv::Vec2d position(last_px, last_py);\n            last_px = (*it).px;\n            last_py = (*it).py;\n            map.draw_and_show_lasers(position, 0, &angles[0],\n                &exp_ranges[0],\n                &ranges[0],\n                scan_count);\n            // reset\n            scan_count = 0;\n            angles.clear();\n            ranges.clear();\n            exp_ranges.clear();\n        }\n        scan_count++;\n        angles.push_back((*it).ptheta);\n        ranges.push_back((*it).range);\n        exp_ranges.push_back(expr);\n#endif\n    }\n\n    double lodds = 0;\n    for (size_t i = 0; i < observations.size(); i ++) {\n        lodds += lodds_vector[i];\n    }\n    return lodds;\n}\n", "meta": {"hexsha": "2b8167d2ab4ee55469de5f9ab23c8ae6e1b65e95", "size": 5403, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/forward_sensor_model.cpp", "max_stars_repo_name": "wecacuee/modern-occupancy-grid", "max_stars_repo_head_hexsha": "c1405847dd715aec25ba416667fa4999d99d5b72", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2015-03-14T16:24:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-17T05:39:06.000Z", "max_issues_repo_path": "src/forward_sensor_model.cpp", "max_issues_repo_name": "wecacuee/modern-occupancy-grid", "max_issues_repo_head_hexsha": "c1405847dd715aec25ba416667fa4999d99d5b72", "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": "src/forward_sensor_model.cpp", "max_forks_repo_name": "wecacuee/modern-occupancy-grid", "max_forks_repo_head_hexsha": "c1405847dd715aec25ba416667fa4999d99d5b72", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2015-08-10T02:02:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-20T12:20:29.000Z", "avg_line_length": 32.3532934132, "max_line_length": 103, "alphanum_fraction": 0.6429761244, "num_tokens": 1440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953030553433, "lm_q2_score": 0.7826624789529376, "lm_q1q2_score": 0.7025924312337035}}
{"text": "// Exercise 5.1.4 - Random Number Generation\r\n//\r\n// by Scott Sidoli\r\n//\r\n// 5-30-19\r\n//\r\n// Main.cpp\r\n//\r\n// In this exercise, we experiment with a random number generator. We create a discrete uniform\r\n// distribution with values ranging from 1 to 6 inclusively. We keep track of the count and \r\n// use this to get the frequency. We ask the user to determine the number of trials and then\r\n// run the simulation.\r\n\r\n#include <boost\\random.hpp>\r\n#include <boost\\random\\detail\\const_mod.hpp>\r\n#include <ctime>\r\n#include <map>\r\n#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n\t// Throwing dice. \r\n\t// Mersenne Twister. \r\n\tboost::random::mt19937 myRng;\r\n\r\n\t// Set the seed. \r\n\tmyRng.seed(static_cast<boost::uint32_t> (std::time(0)));\r\n\r\n\t// Uniform in range [1,6] \r\n\tboost::random::uniform_int_distribution<int> six(1, 6);\r\n\t\r\n\tmap<int, long> statistics;\t\t\t\t// Structure to hold outcome + frequency\r\n\tint outcome;\t\t\t\t\t\t\t// Current outcome\r\n\r\n\t// Setting the number of trials\r\n\tcout << \"How many trials? \";\r\n\tint n;\r\n\tcin >> n;\r\n\t\r\n\t// Initializing the count\r\n\tfor (int i = 0; i < 6; ++i)\r\n\t\tstatistics[i + 1] = 0;\r\n\t\r\n\t// Dice throw\r\n\tfor (int i = 0; i < n; ++i)\r\n\t{\r\n\t\toutcome = six(myRng);\r\n\t\tstatistics[outcome]++;\r\n\t}\r\n\r\n\t// Setting the precision of the output\r\n\tcout.precision(6);\r\n\r\n\tcout << endl;\r\n\r\n\t// Desired print statement\r\n\tfor (int i = 0; i < 6; ++i)\r\n\t\tcout << \"Trial \" << i + 1 << \" has \" << 100.0 * double(statistics[i + 1]) / double(n) << \"% outcomes\" << endl;\r\n\r\n\r\n\treturn 0;\r\n}", "meta": {"hexsha": "b0c092972ef505bd1107563b57aa1dac5a9d3884", "size": 1509, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Scott_Sidoli Level 8 HW Submission/Section 5.1/Exercise514/Exercise514/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": "Scott_Sidoli Level 8 HW Submission/Section 5.1/Exercise514/Exercise514/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": "Scott_Sidoli Level 8 HW Submission/Section 5.1/Exercise514/Exercise514/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": 23.578125, "max_line_length": 113, "alphanum_fraction": 0.6209410205, "num_tokens": 433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952811593495, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.7025924140965307}}
{"text": "#include <Engine/MeshEdit/ASAP.h>\n\n#include <Engine/Primitive/TriMesh.h>\n\n#include <Eigen/Sparse>\n#include <Eigen/LU>\n#include <Eigen/SVD> \n\nusing namespace Ubpa;\n\nusing namespace std;\nusing namespace Eigen;\n\n\nbool ASAP::Iterate()\n{\n\titer_count_++;\n\tcout << iter_count_ << \"th iteration\" << endl;\n\tUpdatePara();\n\tUpdateTriMesh();\n\treturn true;\n}\n\n\nvoid ASAP::UpdatePara()\n{\n\tMatrixXf B(nV, 2);\n\tfor (size_t i = 0; i < nV; i++)\n\t{\n\t\tB.row(i) = RowVector2f::Zero();\n\t}\n\n\tfor (size_t t = 0; t < nT; t++)\n\t{\n\t\tauto triangle = heMesh->Polygons().at(t);\n\t\tauto edge = triangle->HalfEdge();\n\t\tMatrix<float, 3, 2> xt = flat_tri_[t];\n\t\tMatrix<float, 3, 2> ut = Matrix<float, 3, 2>();\n\t\tut.row(0) = para_solution_.row(heMesh->Index(edge->Origin()));\n\t\tut.row(1) = para_solution_.row(heMesh->Index(edge->End()));\n\t\tut.row(2) = para_solution_.row(heMesh->Index(edge->Next()->End()));\n\t\tMatrix2f J = Jacobian(xt, ut);\n\t\tJacobiSVD<Matrix2f> svd(J, ComputeThinU | ComputeThinV);\n\t\tMatrix2f U = svd.matrixU();\n\t\tMatrix2f V = svd.matrixV();\n\t\tVector2f A = svd.singularValues();\n\t\tMatrix2f A2 = Matrix2f::Zero();\n\t\tA2(0, 0) = (A(0) + A(1)) / 2;\n\t\tA2(1, 1) = (A(0) + A(1)) / 2;\n\t\tMatrix2f L = U * V;\n\n\t\tfor (int k = 0; k < 3; k++, edge = edge->Next())\n\t\t{\n\t\t\tauto vi = edge->Origin();\n\t\t\tauto vj = edge->End();\n\t\t\tauto vk = edge->Next()->End();\n\t\t\tint i = heMesh->Index(vi);\n\t\t\tint j = heMesh->Index(vj);\n\t\t\tvecf3 eki = vi->pos - vk->pos;\n\t\t\tvecf3 ekj = vj->pos - vk->pos;\n\t\t\tfloat cot_theta = eki.cos_theta(ekj) / eki.sin_theta(ekj);\n\t\t\t//B.row(i) += (para_solution_.row(i) - para_solution_.row(j)) * V.transpose() * V * cot_theta;\n\t\t\tB.row(i) += (xt.row(k) - xt.row((k + 1) % 3)) * L * cot_theta;\n\t\t\t//B.row(j) += (para_solution_.row(j) - para_solution_.row(i)) * V.transpose() * V * cot_theta;\n\t\t\tB.row(j) += (xt.row((k + 1) % 3) - xt.row(k)) * L * cot_theta;\n\t\t}\n\t}\n\n\tB.row(start) = RowVector2f::Zero();\n\tB.row(end) = RowVector2f(1, 1);\n\tpara_solution_ = para_solver_.solve(B);\n}\n\n", "meta": {"hexsha": "a9af4fc699c4b8d62088254def26d594d8300044", "size": 1966, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Homeworks/4_MinSurfMeshPara/project/src/Engine/MeshEdit/ASAP.cpp", "max_stars_repo_name": "danielchyustc/USTC_CG-1", "max_stars_repo_head_hexsha": "97f87c06dc67b2f34dc52a31bd23f8185653ef18", "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": "Homeworks/4_MinSurfMeshPara/project/src/Engine/MeshEdit/ASAP.cpp", "max_issues_repo_name": "danielchyustc/USTC_CG-1", "max_issues_repo_head_hexsha": "97f87c06dc67b2f34dc52a31bd23f8185653ef18", "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": "Homeworks/4_MinSurfMeshPara/project/src/Engine/MeshEdit/ASAP.cpp", "max_forks_repo_name": "danielchyustc/USTC_CG-1", "max_forks_repo_head_hexsha": "97f87c06dc67b2f34dc52a31bd23f8185653ef18", "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.5675675676, "max_line_length": 97, "alphanum_fraction": 0.6012207528, "num_tokens": 717, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582593509315, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.7024168897693097}}
{"text": "//\n// Copyright (c) 2012 Juan Palacios juan.palacios.puyana@gmail.com\n// This file is part of minimathlibs.\n// Subject to the BSD 2-Clause License \n// - see < http://opensource.org/licenses/BSD-2-Clause>\n//\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE TestMatrixOps\n#include <boost/test/unit_test.hpp>\n\n#include <cmath>\n#include <cstdlib>\n#include <iostream>\n#include <limits>\n#include \"minimath/matrix.hpp\"\n#include \"minimath/matrix_ops.hpp\"\n#include \"Defines.h\"\n\ntypedef minimath::matrix<double,3,1> Point;\n\nnamespace\n{\n\nminimath::matrix<double, 3> rotation3DX(double angle)\n{\n  minimath::matrix<double, 3> m = minimath::identity_matrix();\n  const double c = std::cos(angle);\n  const double s = std::sin(angle);\n  m(1,1) = m(2,2) = c;\n  m(1,2) = m(2,1) = s;\n  m(2,1)*= -1;\n  return m;\n}\n\nminimath::matrix<double, 3> rotation3DY(double angle)\n{\n  minimath::matrix<double, 3> m = minimath::identity_matrix();\n  const double c = std::cos(angle);\n  const double s = std::sin(angle);\n  m(0,0) = m(2,2) = c;\n  m(0,2) = m(2,0) = s;\n  m(2,0)*= -1;\n  return m;\n}\n\nminimath::matrix<double, 3> rotation3DZ(double angle)\n{\n  minimath::matrix<double, 3> m = minimath::identity_matrix();\n  const double c = std::cos(angle);\n  const double s = std::sin(angle);\n  m(0,0) = m(1,1) = c;\n  m(1,0) = m(0,1) = s;\n  m(0,1)*= -1;\n  return m;\n}\n\nstruct FixturePoints\n{\n    FixturePoints()\n    {\n        p100_(0,0) = 1;\n        p010_(1,0) = 1;\n        p001_(2,0) = 1;\n        p110_(0,0) = 1;\n        p110_(1,0) = 1;\n        p011_(1,0) = 1;\n        p011_(2,0) = 1;\n        p101_(0,0) = 1;\n        p101_(2,0) = 1;\n        p111_ += 1;\n\n    }\n\n    Point p100_;\n    Point p010_;\n    Point p001_;\n    Point p110_;\n    Point p011_;\n    Point p101_;\n    Point p111_;\n};\n\n\n} // anonymous namespace\n\nBOOST_FIXTURE_TEST_SUITE(TestMatrixOps, FixturePoints)\n\n\nBOOST_AUTO_TEST_CASE(testXRotations)\n{\n  for (int i = 1; i<9; ++i)\n  {\n    minimath::matrix<double,3> rot = rotation3DX(PI/i);\n    minimath::matrix<double,3> orig;\n    minimath::setColumn(orig, p100_, 0);\n    minimath::setColumn(orig, p010_, 1);\n    minimath::setColumn(orig, p111_, 2);\n\n    minimath::matrix<double,3> prime = rot*orig;\n    bool success = true;\n    minimath::matrix<double,3> rot2 = minimath::transformation(orig, prime, success);\n    if (success)\n    {\n      BOOST_CHECK(minimath::equal(rot, rot2, 1));\n    } else {\n      std::cout << \"\\nInversion failed for angle: PI/\" << i;\n      std::cout <<\"\\nOriginal matrix:\\n \" << orig << \"\\n\";\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(testYRotations)\n{\n  for (int i = 1; i<9; ++i)\n  {\n    minimath::matrix<double,3> rot = rotation3DY(PI/i);\n    minimath::matrix<double,3> orig;\n    minimath::setColumn(orig, p100_, 0);\n    minimath::setColumn(orig, p010_, 1);\n    minimath::setColumn(orig, p111_, 2);\n\n    minimath::matrix<double,3> prime = rot*orig;\n    bool success = true;\n    minimath::matrix<double,3> rot2 = minimath::transformation(orig, prime, success);\n    if (success)\n    {\n      BOOST_CHECK(minimath::equal(rot, rot2, 1));\n    } else {\n      std::cout << \"\\nInversion failed for angle: PI/\" << i;\n      std::cout <<\"\\nOriginal matrix:\\n \" << orig << \"\\n\";\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(testZRotations)\n{\n  for (int i = 1; i<9; ++i)\n  {\n    minimath::matrix<double,3> rot = rotation3DZ(PI/i);\n    minimath::matrix<double,3> orig;\n    minimath::setColumn(orig, p100_, 0);\n    minimath::setColumn(orig, p010_, 1);\n    minimath::setColumn(orig, p111_, 2);\n\n    minimath::matrix<double,3> prime = rot*orig;\n    bool success = true;\n    minimath::matrix<double,3> rot2 = minimath::transformation(orig, prime, success);\n    if (success)\n    {\n      BOOST_CHECK(minimath::equal(rot, rot2, 1));\n    } else {\n      std::cout << \"\\nInversion failed for angle: PI/\" << i;\n      std::cout <<\"\\nOriginal matrix:\\n \" << orig << \"\\n\";\n    }\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "7d7a4fa1e8bf91dcd9dc119e6079583a2fa960a5", "size": 3863, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/TestMatrixOps.cpp", "max_stars_repo_name": "XPsoud/minimathlibs", "max_stars_repo_head_hexsha": "be4ece76e90fd95a247a8d7ab47cc8f84c9cb750", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-01-20T13:54:46.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-20T13:54:46.000Z", "max_issues_repo_path": "tests/TestMatrixOps.cpp", "max_issues_repo_name": "XPsoud/minimathlibs", "max_issues_repo_head_hexsha": "be4ece76e90fd95a247a8d7ab47cc8f84c9cb750", "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": "tests/TestMatrixOps.cpp", "max_forks_repo_name": "XPsoud/minimathlibs", "max_forks_repo_head_hexsha": "be4ece76e90fd95a247a8d7ab47cc8f84c9cb750", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-08-13T15:04:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-16T15:04:57.000Z", "avg_line_length": 24.14375, "max_line_length": 85, "alphanum_fraction": 0.61377168, "num_tokens": 1276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787538, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.7024068400803019}}
{"text": "#include <iostream>\n#include \"mtao/optimization/line_search.hpp\"\n\n#include <Eigen/Dense>\n\nstruct QuadraticFunc {\n    using Scalar = double;\n    using Vector = Eigen::VectorXd;\n\n    Scalar objective(const Vector& p) const {\n        return p.transpose() * (A * p + b) + c;\n    }\n    Vector gradient(const Vector& p) const {\n        Vector ret = 2 * A * p + b;\n        return ret;\n    }\n\n    //Vector descent_direction(const Vector& p) const { return -gradient(p).normalized(); }\n    Vector descent_direction(const Vector& p) const { \n\n\n        if(trinary) {\n        return (-gradient(p)).unaryExpr([](double v) -> double {\n                if(v > 0) { return 1; }\n                else if(v < 0) { return -1; }\n                else { return 0; }\n                });\n        } else {\n            return -gradient(p).normalized();\n        }\n\n    }\n    bool trinary = false;\n    Eigen::MatrixXd A;\n    Eigen::VectorXd b;\n    Scalar c;\n\n};\n\n\n\nusing namespace mtao::optimization;\n\n\nint main(int argc, char * argv[]) {\n    std::cout << \"Eigen threads: \" << Eigen::nbThreads() << std::endl;\n    QuadraticFunc func;\n    int N = 600;\n    Eigen::MatrixXd A(N,N);\n    Eigen::VectorXd b(N);\n\n\n    if constexpr(true) {\n        A.setIdentity();\n        b.setOnes(N);\n\n\n        func.A = A.transpose() * A;\n        func.b = -2 * A.transpose() * b;\n        func.c = b.dot(b);\n    } else {\n\n        A.setRandom();\n        b.setRandom();\n        func.A = A.transpose() * A;\n        func.b = b;\n        func.c = 5;\n    }\n\n    auto run = [&](auto&& opt) {\n        opt.set_position(b);\n        std::cout << \"Optimal energy: \" << opt.objective() << std::endl;\n        std::cout << \"Optimal gradient norm: \" << opt.gradient().norm() << std::endl;\n        opt.set_position(Eigen::VectorXd::Random(N));\n        std::cout << \"Initial energy: \" << opt.objective() << std::endl;\n        int iters = opt.run();\n        std::cout << \"Final energy: \" << opt.objective() << \" in \" << iters << \" iterations.\"<< std::endl;\n        std::cout << std::endl;\n        //std::cout << \"position: \" << opt.position().transpose() << std::endl;\n    };\n    auto run_run = [&]() {\n    {\n        std::cout << \"Backtracking / armijo conditions\" << std::endl;\n        auto opt = make_backtracking_line_search(func);\n        run(opt);\n    }\n    {\n        std::cout << \"weak wolfe conditions\" << std::endl;\n        auto opt = make_wolfe_line_search(func);\n        opt.set_weak();\n        run(opt);\n    }\n    {\n        std::cout << \"Strong wolfe conditions\" << std::endl;\n        auto opt = make_wolfe_line_search(func);\n        opt.set_strong();\n        run(opt);\n    }\n    };\n    run_run();\n    std::cout << std::endl;\n    std::cout << std::endl;\n    std::cout << std::endl;\n    func.trinary = true;\n    std::cout << \"Using a `trinary` which is lazy for something in the roughly right direction\" << std::endl;\n    run_run();\n}\n", "meta": {"hexsha": "8c68727c9425b28396c0b3543a1af3833cd6b385", "size": 2872, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/line_search_test.cpp", "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": "tests/line_search_test.cpp", "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": "tests/line_search_test.cpp", "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": 26.5925925926, "max_line_length": 109, "alphanum_fraction": 0.5261142061, "num_tokens": 749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554445, "lm_q2_score": 0.7931059609645724, "lm_q1q2_score": 0.7023996058912287}}
{"text": "/* +------------------------------------------------------------------------+\n   |                     Mobile Robot Programming Toolkit (MRPT)            |\n   |                          https://www.mrpt.org/                         |\n   |                                                                        |\n   | Copyright (c) 2005-2020, Individual contributors, see AUTHORS file     |\n   | See: https://www.mrpt.org/Authors - All rights reserved.               |\n   | Released under BSD License. See: https://www.mrpt.org/License          |\n   +------------------------------------------------------------------------+ */\n\n// Note: Matrices unit tests have been split in different files since\n// building them with eigen3 eats a lot of RAM and may be a problem while\n// compiling in small systems.\n\n#include <gtest/gtest.h>\n#include <mrpt/io/CMemoryStream.h>\n#include <mrpt/math/CMatrixD.h>\n#include <mrpt/math/CMatrixFixed.h>\n#include <mrpt/math/matrix_serialization.h>  // serialization of matrices\n#include <mrpt/random.h>\n#include <mrpt/serialization/CArchive.h>\n#include <Eigen/Dense>\n\nusing namespace mrpt;\nusing namespace mrpt::math;\nusing namespace mrpt::random;\nusing namespace std;\n\nconst double dat_A[] = {4, 5, 8, -2, 1, 3};\nconst double dat_B[] = {2, 6, 9, 8};\nconst double dat_Cok[] = {53, 64, -2, 32, 29, 30};\n\n#define CHECK_AND_RET_ERROR(_COND_, _MSG_) EXPECT_FALSE(_COND_) << _MSG_;\n\nTEST(Matrices, DynMat_size)\n{\n\tCMatrixDouble A(3, 2, dat_A);\n\tEXPECT_EQ(A.rows(), 3);\n\tEXPECT_EQ(A.cols(), 2);\n\tEXPECT_EQ(A.size(), 6U);\n}\n\nTEST(Matrices, A_times_B_dyn)\n{\n\t// Dyn. size, double.\n\tCMatrixDouble A(3, 2, dat_A);\n\tCMatrixDouble B(2, 2, dat_B);\n\tCMatrixDouble C = CMatrixDouble(A * B);\n\tCMatrixDouble C_ok(3, 2, dat_Cok);\n\tCMatrixDouble err = C - C_ok;\n\tEXPECT_NEAR(0, fabs(err.sum()), 1e-5)\n\t\t<< \"A:   \" << A << \"B:   \" << B << \"A*B: \" << C << endl;\n}\n\nTEST(Matrices, A_times_B_fix)\n{\n\t// Fix. size, double.\n\tCMatrixFixed<double, 3, 2> A(dat_A);\n\tCMatrixFixed<double, 2, 2> B(dat_B);\n\tCMatrixFixed<double, 3, 2> C, C_ok(dat_Cok), Err;\n\n\tC = A * B;\n\tErr = C.asEigen() - CMatrixFixed<double, 3, 2>(C_ok).asEigen();\n\n\tEXPECT_NEAR(0, fabs(Err.asEigen().array().sum()), 1e-5);\n}\n\nTEST(Matrices, SerializeCMatrixD)\n{\n\tCMatrixDouble A(3, 2, dat_A);\n\tCMatrixFixed<double, 3, 2> fA;\n\n\tCMatrixD As = CMatrixD(A);\n\n\tmrpt::io::CMemoryStream membuf;\n\tauto arch = mrpt::serialization::archiveFrom(membuf);\n\tarch << As;\n\tmembuf.Seek(0);\n\tarch >> fA;\n\n\tEXPECT_NEAR(0, fabs((CMatrixDouble(fA) - A).sum()), 1e-9);\n\n\ttry\n\t{\n\t\t// Now, if we try to de-serialize into the wrong type, we should get an\n\t\t// exception:\n\t\tmembuf.Seek(0);\n\t\tCMatrixFixed<double, 2, 2> fB;\n\t\tarch >> fB;  // Wrong size!\n\n\t\tGTEST_FAIL() << \"Exception not launched when it was expected!\";\n\t}\n\tcatch (...)\n\t{  // OK, exception occurred, as expected\n\t}\n}\n\nTEST(Matrices, EigenVal2x2dyn)\n{\n\tconst double dat_C1[] = {14.6271, 5.8133, 5.8133, 16.8805};\n\tCMatrixDouble C1(2, 2, dat_C1);\n\n\tCMatrixDouble C1_V;\n\tstd::vector<double> C1_Ds;\n\tC1.eig(C1_V, C1_Ds);\n\n\tCMatrixDouble C1_D;\n\tC1_D.setDiagonal(C1_Ds);\n\n\tCMatrixDouble C1_RR =\n\t\tCMatrixDouble(C1_V.asEigen() * C1_D.asEigen() * C1_V.transpose());\n\tEXPECT_NEAR((C1_RR - C1).sum_abs(), 0, 1e-4);\n}\n\nTEST(Matrices, eig_symmetric)\n{\n\t// Test by looking only at the lower triangular-part:\n\t{\n\t\tconst double dat_C[] = {14.6271, 0, 5.8133, 16.8805};\n\t\tCMatrixDouble22 C(dat_C);\n\n\t\tCMatrixDouble22 eig_vecs;\n\t\tstd::vector<double> eig_vals;\n\t\tC.eig_symmetric(eig_vecs, eig_vals);\n\n\t\tEXPECT_EQ(eig_vals.size(), 2UL);\n\t\tEXPECT_NEAR(eig_vals[0], 9.83232131811656, 1e-4);\n\t\tEXPECT_NEAR(eig_vals[1], 21.67527868188344, 1e-4);\n\t}\n}\n\nTEST(Matrices, EigenVal3x3dyn)\n{\n\tconst double dat_C1[] = {8, 6, 1, 6, 9, 4, 1, 4, 10};\n\tCMatrixDouble C1(3, 3, dat_C1);\n\n\tCMatrixDouble C1_V;\n\tstd::vector<double> C1_Ds;\n\tC1.eig(C1_V, C1_Ds);\n\n\tCMatrixDouble C1_D;\n\tC1_D.setDiagonal(C1_Ds);\n\n\tCMatrixDouble C1_RR =\n\t\tCMatrixDouble(C1_V.asEigen() * C1_D.asEigen() * C1_V.transpose());\n\tEXPECT_NEAR((C1_RR - C1).sum_abs(), 0, 1e-4);\n}\n\nTEST(Matrices, EigenVal2x2fix)\n{\n\tconst double dat_C1[] = {14.6271, 5.8133, 5.8133, 16.8805};\n\tCMatrixDouble22 C1(dat_C1);\n\n\tCMatrixDouble22 C1_V;\n\tstd::vector<double> C1_Ds;\n\tC1.eig(C1_V, C1_Ds);\n\n\tCMatrixDouble22 C1_D;\n\tC1_D.setDiagonal(C1_Ds);\n\n\tCMatrixDouble22 C1_RR =\n\t\tCMatrixDouble22(C1_V.asEigen() * C1_D.asEigen() * C1_V.transpose());\n\tEXPECT_NEAR((C1_RR - C1).sum_abs(), 0, 1e-4);\n}\n\nTEST(Matrices, EigenVal3x3fix)\n{\n\tconst double dat_C1[] = {8, 6, 1, 6, 9, 4, 1, 4, 10};\n\tCMatrixDouble33 C1(dat_C1);\n\n\tCMatrixDouble33 C1_V;\n\tstd::vector<double> C1_Ds;\n\tC1.eig(C1_V, C1_Ds);\n\n\tCMatrixDouble33 C1_D;\n\tC1_D.setDiagonal(C1_Ds);\n\n\tCMatrixDouble33 C1_RR =\n\t\tCMatrixDouble33(C1_V.asEigen() * C1_D.asEigen() * C1_V.transpose());\n\tEXPECT_NEAR((C1_RR - C1).sum_abs(), 0, 1e-4);\n}\n", "meta": {"hexsha": "fcc53725bcbb610f618edc098206ebc95e573591", "size": 4803, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/src/matrix_ops1_unittest.cpp", "max_stars_repo_name": "swt2c/mrpt", "max_stars_repo_head_hexsha": "9b4fd246530ff94bb93f5703e61844c6f67aa0b9", "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": "libs/math/src/matrix_ops1_unittest.cpp", "max_issues_repo_name": "swt2c/mrpt", "max_issues_repo_head_hexsha": "9b4fd246530ff94bb93f5703e61844c6f67aa0b9", "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": "libs/math/src/matrix_ops1_unittest.cpp", "max_forks_repo_name": "swt2c/mrpt", "max_forks_repo_head_hexsha": "9b4fd246530ff94bb93f5703e61844c6f67aa0b9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-30T14:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-30T14:06:37.000Z", "avg_line_length": 26.5359116022, "max_line_length": 80, "alphanum_fraction": 0.6321049344, "num_tokens": 1641, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314768368161, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.7023995948352527}}
{"text": "/*\n// Copyright (c) 2000-2009, Texas Engineering Experiment Station (TEES), a\n// component of the Texas A&M University System.\n\n// All rights reserved.\n\n// The information and source code contained herein is the exclusive\n// property of TEES and may not be disclosed, examined or reproduced\n// in whole or in part without explicit written authorization from TEES.\n*/\n\n////////////////////////////////////////////////////////////////////////////////\n/// @file\n/// Solution of the Euler Problem #3\n/// (<a href=\"https://projecteuler.net/problem=3\" target=_blank>link</a>).\n////////////////////////////////////////////////////////////////////////////////\n\n#include <stapl/utility/do_once.hpp>\n#include <stapl/array.hpp>\n#include <stapl/views/array_view.hpp>\n#include <stapl/algorithm.hpp>\n#include <boost/lexical_cast.hpp>\n\n////////////////////////////////////////////////////////////////////////////////\n/// @brief Returns truncated integer square root of given number.\n/// @tparam IntType Integral type of the number.\n////////////////////////////////////////////////////////////////////////////////\ntemplate <typename IntType>\ninline IntType sqrt_int(IntType n)\n{\n  return static_cast<IntType>( std::sqrt(n) );\n}\n\n////////////////////////////////////////////////////////////////////////////////\n/// @brief Functor that returns the larger of @p n and @p x/n that is both a\n///        factor of @p x and a prime number (0 if neither satisfies these\n///        conditions).\n/// @tparam IntType Integral type of the dividend @p x.\n////////////////////////////////////////////////////////////////////////////////\ntemplate <typename IntType>\nstruct largest_prime_factors_filter\n{\n  static_assert(std::is_integral<IntType>::value, \"Integer required.\");\n\n  largest_prime_factors_filter(IntType x)\n    : m_x(x)\n  { }\n\n  IntType operator()(IntType n)\n  {\n    if ((m_x % n) != 0)   // n is not a factor of x\n      return 0;\n\n    if (is_prime(m_x/n))  // x/n (which is larger than n) is prime\n      return m_x/n;\n\n    return is_prime(n) ? n : 0;\n  }\n\n  void define_type(stapl::typer& t)\n  {\n    t.member(m_x);\n  }\n\nprivate:\n  IntType m_x;\n\n  static bool is_prime(IntType n)\n  {\n    IntType sqrt_n = sqrt_int(n);\n\n    for (IntType i = 2; i <= sqrt_n; ++i)\n    {\n      if ((n % i) == 0)\n        return false;\n    }\n\n    return true;\n  }\n};\n\nstapl::exit_code stapl_main(int argc, char** argv)\n{\n  using value_t = std::size_t;\n\n  if (argc < 2)\n  {\n    stapl::do_once( [] {\n      std::cout << \"Run as: mpirun -n <ncpu> pe_3a <number>\" << std::endl;\n    });\n    return EXIT_FAILURE;\n  }\n\n  stapl::counter<stapl::default_timer> exec_timer;\n  exec_timer.start();\n\n  // Read the dividend from command line.\n  value_t num = boost::lexical_cast<value_t> (argv[1]);\n\n  // Create array container for storage and a view into it.\n  stapl::array<value_t> a(sqrt_int(num)-1);\n  auto a_vw = stapl::make_array_view(a);\n\n  // Fill the array with consecutive values from 2 to sqrt(num).\n  stapl::iota(a_vw, 2);\n\n  // Replace numbers in the array that are either not factors of num or not\n  // prime by 0; also replace any prime factor x by the greater value num/x if\n  // the latter is also prime.\n  stapl::transform(a_vw, a_vw, largest_prime_factors_filter<value_t>(num));\n\n  // Compute and print the maximum of all numbers in the array.\n  value_t max_prime_factor = stapl::max_value(a_vw);\n\n  double t = exec_timer.stop();\n\n  stapl::do_once( [&] {\n    std::cout << \"Computation finished (time taken: \" << t << \" s).\"\n              << std::endl\n              << \"Largest prime factor of \" << num << \" is: \"\n              << max_prime_factor << std::endl;\n  });\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "79bf8943f53c853737b7cffc822c0d253a694793", "size": 3654, "ext": "cc", "lang": "C++", "max_stars_repo_path": "stapl_release/examples/project_euler/pe_3a.cc", "max_stars_repo_name": "parasol-ppl/PPL_utils", "max_stars_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb", "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": "stapl_release/examples/project_euler/pe_3a.cc", "max_issues_repo_name": "parasol-ppl/PPL_utils", "max_issues_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb", "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": "stapl_release/examples/project_euler/pe_3a.cc", "max_forks_repo_name": "parasol-ppl/PPL_utils", "max_forks_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb", "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": 29.0, "max_line_length": 80, "alphanum_fraction": 0.5695128626, "num_tokens": 878, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.7931059487389968, "lm_q1q2_score": 0.7023995854875049}}
{"text": "#include <Eigen>\n\n#include \"warp.h\"\n\nvoid llcv_calc_persp_transform(float *matrixData, int matrixDataSize, bool rowMajor, const vector<cv::Point> sourcePoints, const vector<cv::Point> destPoints) {\n\n  // Set up matrices a and b so we can solve for x from ax = b\n  // See http://xenia.media.mit.edu/~cwren/interpolator/ for a\n  // good explanation of the basic math behind this.\n\n  typedef Eigen::Matrix<float, 8, 8> Matrix8x8;\n  typedef Eigen::Matrix<float, 8, 1> Matrix8x1;\n\n  Matrix8x8 a;\n  Matrix8x1 b;\n\n  for(int i = 0; i < 4; i++) {\n    a(i, 0) = sourcePoints[i].x;\n    a(i, 1) = sourcePoints[i].y;\n    a(i, 2) = 1;\n    a(i, 3) = 0;\n    a(i, 4) = 0;\n    a(i, 5) = 0;\n    a(i, 6) = -sourcePoints[i].x * destPoints[i].x;\n    a(i, 7) = -sourcePoints[i].y * destPoints[i].x;\n\n    a(i + 4, 0) = 0;\n    a(i + 4, 1) = 0;\n    a(i + 4, 2) = 0;\n    a(i + 4, 3) = sourcePoints[i].x;\n    a(i + 4, 4) = sourcePoints[i].y;\n    a(i + 4, 5) = 1;\n    a(i + 4, 6) = -sourcePoints[i].x * destPoints[i].y;\n    a(i + 4, 7) = -sourcePoints[i].y * destPoints[i].y;\n\n    b(i, 0) = destPoints[i].x;\n    b(i + 4, 0) = destPoints[i].y;\n  }\n\n  // Solving ax = b for x, we get the values needed for our perspective\n  // matrix. Table of options on the eigen site at\n  // /dox/TutorialLinearAlgebra.html#TutorialLinAlgBasicSolve\n  //\n  // We use householderQr because it places no restrictions on matrix A,\n  // is moderately fast, and seems to be sufficiently accurate.\n  //\n  // partialPivLu() seems to work as well, but I am wary of it because I\n  // am unsure of A is invertible. According to the documenation and basic\n  // performance testing, they are both roughly equivalent in speed.\n  //\n  // - @burnto\n\n  Matrix8x1 x = a.householderQr().solve(b);\n\n  // Initialize matrixData\n  for (int i = 0; i < matrixDataSize; i++) {\n    matrixData[i] = 0.0f;\n  }\n  int matrixSize = (matrixDataSize >= 16) ? 4 : 3;\n\n  // Initialize a 4x4 eigen matrix. We may not use the final\n  // column/row, but that's ok.\n  Eigen::Matrix4f perspMatrix = Eigen::Matrix4f::Zero();\n\n  // Assign a, b, d, e, and i\n  perspMatrix(0, 0) = x(0, 0); // a\n  perspMatrix(0, 1) = x(1, 0); // b\n  perspMatrix(1, 0) = x(3, 0); // d\n  perspMatrix(1, 1) = x(4, 0); // e\n  perspMatrix(2, 2) = 1.0f;    // i\n\n  // For 4x4 matrix used for 3D transform, we want to assign\n  // c, f, g, and h to the fourth col and row.\n  // So we use an offset for thes values\n  int o = matrixSize - 3; // 0 or 1\n  perspMatrix(0, 2 + o) = x(2, 0); // c\n  perspMatrix(1, 2 + o) = x(5, 0); // f\n  perspMatrix(2 + o, 0) = x(6, 0); // g\n  perspMatrix(2 + o, 1) = x(7, 0); // h\n  perspMatrix(2 + o, 2 + o) = 1.0f; // i\n\n  // Assign perspective matrix to our matrixData buffer,\n  // swapping row versus column if needed, and taking care not to\n  // overflow if user didn't provide a large enough matrixDataSize.\n  for(int c = 0; c < matrixSize; c++) {\n    for(int r = 0; r < matrixSize; r++) {\n      int index = rowMajor ? (c + r * matrixSize) : (r + c * matrixSize);\n      if (index < matrixDataSize) {\n        matrixData[index] = perspMatrix(r, c);\n      }\n    }\n  }\n  // TODO - instead of copying final values into matrixData return array, do one of:\n  // (a) assign directly into matrixData, or\n  // (b) use Eigen::Mat so that assignment goes straight into underlying matrixData\n}\n\n\n\n\nvoid llcv_unwarp(const Mat& input, const vector<cv::Point>& source_points, const cv::Rect& to_rect, Mat& output)\n{\n    float matrix[16];\n\tvector<cv::Point> dest_points;\n    dest_points.push_back(cv::Point(to_rect.x, to_rect.y));\n    dest_points.push_back(cv::Point(to_rect.x + to_rect.width, to_rect.y));\n    dest_points.push_back(cv::Point(to_rect.x, to_rect.y + to_rect.height));\n    dest_points.push_back(cv::Point(to_rect.x + to_rect.width, to_rect.y + to_rect.height));\n    \n    // Calculate row-major matrix\n    llcv_calc_persp_transform(matrix, 9, true, source_points, dest_points);\n    Mat cv_persp_mat = Mat(3, 3, CV_32FC1);\n    for (int r = 0; r < 3; r++) {\n        float* ptr = cv_persp_mat.ptr<float>(r);\n        for (int c = 0; c < 3; c++) {\n            ptr[c] =  matrix[3 * r + c];\n        }\n    }\n    \n    warpPerspective(input, output, cv_persp_mat, input.size(), CV_INTER_LINEAR + CV_WARP_FILL_OUTLIERS);\n}\n\n\n\n", "meta": {"hexsha": "76d933d7d2db55ab5ee99a1e4726b0d70acd331a", "size": 4232, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sdk/src/main/cpp/crossplatform/CrossPlatform/CV/warp.cpp", "max_stars_repo_name": "LouisP79/CardScanner", "max_stars_repo_head_hexsha": "94c6299f219584073e5443465419c19d67df93c3", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "max_stars_count": 172.0, "max_stars_repo_stars_event_min_datetime": "2017-08-13T10:25:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T08:10:18.000Z", "max_issues_repo_path": "sdk/src/main/cpp/crossplatform/CrossPlatform/CV/warp.cpp", "max_issues_repo_name": "LouisP79/CardScanner", "max_issues_repo_head_hexsha": "94c6299f219584073e5443465419c19d67df93c3", "max_issues_repo_licenses": ["Apache-2.0", "MIT"], "max_issues_count": 58.0, "max_issues_repo_issues_event_min_datetime": "2017-08-21T09:51:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-08T17:27:04.000Z", "max_forks_repo_path": "sdk/src/main/cpp/crossplatform/CrossPlatform/CV/warp.cpp", "max_forks_repo_name": "LouisP79/CardScanner", "max_forks_repo_head_hexsha": "94c6299f219584073e5443465419c19d67df93c3", "max_forks_repo_licenses": ["Apache-2.0", "MIT"], "max_forks_count": 125.0, "max_forks_repo_forks_event_min_datetime": "2017-10-22T10:54:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-20T10:06:17.000Z", "avg_line_length": 33.856, "max_line_length": 160, "alphanum_fraction": 0.6164933837, "num_tokens": 1475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070133672954, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.702305821456507}}
{"text": "#pragma once\n#include <Eigen/Core>\n#include <numeric>\n\nnamespace mtao::linear_algebra {\n    // M is matrix, B is initial vector, Q is the basis for the basis\n    // N is the dimension of the subspace\n\n    namespace internal {\n        template <typename Derived, typename BDerived, typename QDerived, typename HDerived>\n            auto arnoldi(const Eigen::MatrixBase<Derived>& M, const Eigen::MatrixBase<BDerived>& b, Eigen::PlainObjectBase<QDerived>& Q, Eigen::PlainObjectBase<HDerived>& H) {\n                const int N = H.rows() - 1;\n                using Scalar = typename Derived::Scalar;\n                constexpr Scalar eps = std::numeric_limits<Scalar>::epsilon();\n                using Vec = Eigen::Matrix<Scalar, Derived::RowsAtCompileTime, 1>;\n\n\n                Q.setZero();\n                H.setZero();\n                Vec v;\n\n                Q.col(0) = b.normalized();\n                for(int j = 0; j <= N; ++j) {\n\n                    auto q = Q.col(j);\n                    v = M * q;\n                    for(int k = 0; k <= j; ++k) {\n                        auto l = Q.col(k);\n                        const Scalar s = l.dot(v);\n                        H(k,j) = s;\n                        v -= s * l;\n                    }\n                    if(j < N) {\n                        const Scalar n = H(j+1,j) = v.norm();\n                        if(n > eps) {\n                            v /= n;\n                            Q.col(j+1) = v;\n                            continue;\n                        }\n                    }\n                    return;\n                }\n            }\n    }\n\n    template <typename Derived, typename BDerived>\n        auto arnoldi(const Eigen::MatrixBase<Derived>& M, const Eigen::MatrixBase<BDerived>& B, int N) {\n            assert(M.rows() == M.cols());\n\n            using Scalar = typename Derived::Scalar;\n            using Mat = Eigen::Matrix<Scalar,Derived::RowsAtCompileTime,Eigen::Dynamic>;\n            using DMat = Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>;\n\n            Mat Q(M.rows(),N);\n            DMat H(N,N);\n\n            internal::arnoldi(M,B,Q,H);\n            return std::make_tuple(Q,H);\n        }\n    template <int N, typename Derived, typename BDerived>\n        auto arnoldi(const Eigen::MatrixBase<Derived>& M, const Eigen::MatrixBase<BDerived>& B) {\n            assert(M.rows() == M.cols());\n\n            using Scalar = typename Derived::Scalar;\n            using Mat = Eigen::Matrix<Scalar,Eigen::Dynamic,N>;\n            using HMat = Eigen::Matrix<Scalar,N,N>;\n\n            Mat Q(M.rows(),N);\n            HMat H(N,N);\n            internal::arnoldi(M,B,Q,H);\n            return std::make_tuple(Q,H);\n        }\n    template <typename Derived>\n        auto arnoldi(const Eigen::MatrixBase<Derived>& M, int N) {\n            using Scalar = typename Derived::Scalar;\n            auto B = Eigen::Matrix<Scalar,Derived::RowsAtCompileTime, 1>::Random(M.rows()) ;\n            return arnoldi(M,B,N);\n        }\n    template <int N, typename Derived>\n        auto arnoldi(const Eigen::MatrixBase<Derived>& M) {\n            using Scalar = typename Derived::Scalar;\n            auto B = Eigen::Matrix<Scalar,Derived::RowsAtCompileTime, 1>::Random(M.rows()) ;\n            return arnoldi<N>(M,B);\n        }\n}\n", "meta": {"hexsha": "fff3fb28038dda56a64c5c86a575c59ef8a44fee", "size": 3271, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mtao/linear_algebra/arnoldi.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/linear_algebra/arnoldi.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/linear_algebra/arnoldi.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": 38.0348837209, "max_line_length": 175, "alphanum_fraction": 0.4931213696, "num_tokens": 746, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070158103778, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.702305809016002}}
{"text": "// STL includes\n#include <iostream>\n#include <vector>\n#include <unordered_set>\n#include <climits>\n\n// BGL includes\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/maximum_weighted_matching.hpp>\n#include <boost/graph/max_cardinality_matching.hpp>\n\ntypedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS> graph;\ntypedef boost::graph_traits<graph>::vertex_descriptor vertex_desc;\n\nusing namespace std;\n\n\nint maximum_matching(const graph &G) {\n  int n = boost::num_vertices(G);\n  std::vector<vertex_desc> mate_map(n);  // exterior property map\n  // const vertex_desc NULL_VERTEX = boost::graph_traits<weighted_graph>::null_vertex();\n\n  boost::edmonds_maximum_cardinality_matching(G,\n    boost::make_iterator_property_map(mate_map.begin(), boost::get(boost::vertex_index, G)));\n  int matching_size = boost::matching_size(G,\n    boost::make_iterator_property_map(mate_map.begin(), boost::get(boost::vertex_index, G)));\n  return matching_size;\n  // int min_weight = INT_MAX;\n  // edge_desc e;\n  // for (int i = 0; i < n; ++i) {\n  //   // mate_map[i] != NULL_VERTEX: the vertex is matched\n  //   // i < mate_map[i]: visit each edge in the matching only once\n  //   // cout << i << \" \" << mate_map[i] << endl;\n  //   e = edge(i,mate_map[i],G).first;\n  //   min_weight = min(min_weight, weights[e]);\n  // }\n  // return min_weight;\n}\n\nvoid testcase()\n{\n  int n; cin >> n;\n  int c; cin >> c;\n  int f; cin >> f;\n  graph G(n);\n  vector<unordered_set<string>> characteristics(n);\n  for(int i = 0; i < n; i++) {\n    characteristics[i] = unordered_set<string>(0);\n    for(int k = 0; k < c; k++) {\n      string s; cin >> s;\n      characteristics[i].insert(s);\n    }\n    for(int j = 0; j < i; j++) {\n      int common = 0;\n      for(auto s : characteristics[j]) {\n        if(characteristics[i].count(s) > 0) common++;\n      }\n      // cout << i << \" \" << j << \" \" << common << \" \";\n      if(common > f) {\n        // cout << i << \" \" << j << endl;\n        boost::add_edge(i, j, G);\n      }\n      // cout << e << \" \" << weights[e] << endl;\n    }\n  }\n  \n  int matching_size = maximum_matching(G);\n  // std::cout << matching_size << endl;\n  if(matching_size == n / 2) {\n    cout << \"not optimal\" << endl;\n  } else {\n    cout << \"optimal\" << endl;\n  }\n}\n\nint main() {\n  std::ios_base::sync_with_stdio(false); // Always!\n  int t; cin >> t;\n  while(t--) testcase();\n}\n", "meta": {"hexsha": "1959f778c4c32acbd67e7b1c92aea9386beeb883", "size": 2377, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problems/week04-buddy_selection/src/algorithm.cpp", "max_stars_repo_name": "haeggee/algolab", "max_stars_repo_head_hexsha": "176a7d4efbbfb2842f46e93250be00d3b59e0ec3", "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": "problems/week04-buddy_selection/src/algorithm.cpp", "max_issues_repo_name": "haeggee/algolab", "max_issues_repo_head_hexsha": "176a7d4efbbfb2842f46e93250be00d3b59e0ec3", "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": "problems/week04-buddy_selection/src/algorithm.cpp", "max_forks_repo_name": "haeggee/algolab", "max_forks_repo_head_hexsha": "176a7d4efbbfb2842f46e93250be00d3b59e0ec3", "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.3456790123, "max_line_length": 93, "alphanum_fraction": 0.611274716, "num_tokens": 664, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380482, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.7023058062486872}}
{"text": "#define __USE_MATH_DEFINES\n#include <cmath>\n#include <Eigen/Dense>\n#include \"../matplotlibcpp.h\"\nnamespace plt = matplotlibcpp;\n\nvoid waves(const unsigned n) {\n  Eigen::MatrixXd X(n, n);\n  for (unsigned i = 0; i < n; ++i) {\n    for (unsigned j = 0; j < n; ++j) {\n      X(i, j) = sin(3.0 * M_PI * i / n) * cos(20.0 * M_PI * j / n);\n    }\n  }\n  plt::figure();\n  plt::imshow(X, {{\"cmap\", \"Spectral\"}});\n  plt::colorbar();\n  plt::show();\n}\n\nint main() {\n  waves(200);\n  return 0;\n}\n", "meta": {"hexsha": "44c4c812f872597fb2835aed8be4714370e7b662", "size": 478, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "simulation_code/src/matplotlib-cpp/examples/imshow.cpp", "max_stars_repo_name": "lottegr/project_simulation", "max_stars_repo_head_hexsha": "b95d88114a3d2611073d1977393884062f63bdab", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 58.0, "max_stars_repo_stars_event_min_datetime": "2019-12-30T19:39:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T15:55:10.000Z", "max_issues_repo_path": "simulation_code/src/matplotlib-cpp/examples/imshow.cpp", "max_issues_repo_name": "lottegr/project_simulation", "max_issues_repo_head_hexsha": "b95d88114a3d2611073d1977393884062f63bdab", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-08-25T13:22:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T18:26:01.000Z", "max_forks_repo_path": "simulation_code/src/matplotlib-cpp/examples/imshow.cpp", "max_forks_repo_name": "lottegr/project_simulation", "max_forks_repo_head_hexsha": "b95d88114a3d2611073d1977393884062f63bdab", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 39.0, "max_forks_repo_forks_event_min_datetime": "2020-02-26T11:37:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T09:50:24.000Z", "avg_line_length": 19.9166666667, "max_line_length": 67, "alphanum_fraction": 0.5585774059, "num_tokens": 165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380482, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.702305801473293}}
{"text": "#include <iostream>\r\n#include <string>\r\n#include <vector>\r\n#include <boost/multiprecision/cpp_int.hpp>\r\n\r\nusing boost::multiprecision::cpp_int;\r\n\r\nstd::vector<cpp_int> take_input();\r\n\r\nstruct linear_combination {\r\n    cpp_int quotient = 0;\r\n    cpp_int x = 0;\r\n    cpp_int y = 0;\r\n};\r\n\r\nvoid euclidean_gcd(cpp_int a, cpp_int b, std::vector<linear_combination> &combinations);\r\n\r\ncpp_int\r\nsolve_congruence_system(cpp_int a, cpp_int m, cpp_int b, cpp_int n);\r\n\r\nint main() {\r\n    std::vector<cpp_int> input = take_input();\r\n\r\n    cpp_int x = 0;\r\n    cpp_int product = 1;\r\n    std::cout << input.size() << std::endl;\r\n\r\n    for (int i = 0; i < input.size(); i++) {\r\n        std::cout << i << std::endl;\r\n        cpp_int &m = input.at(i);\r\n        x = solve_congruence_system(x, product, m - i, m);\r\n        product *= m;\r\n        while (x > product) {\r\n            x -= product;\r\n        }\r\n        while (x < 0) {\r\n            x += product;\r\n        }\r\n        std::cout << x % 17 << std::endl;\r\n    }\r\n\r\n    std::cout << x << std::endl;\r\n\r\n//    100 - 6 * 15 = 10\r\n//    15 - 1 * (100 - 6 * 15) = 5\r\n//    15 + 6 * 15\r\n    return 0;\r\n}\r\n\r\nvoid euclidean_gcd(cpp_int a, cpp_int b, std::vector<linear_combination> &combinations) {\r\n    if (b % a == 0) {\r\n        return;\r\n    } else {\r\n        linear_combination temp;\r\n        temp.quotient = b / a;\r\n        if (combinations.empty()) {\r\n            temp.x = -temp.quotient;\r\n            temp.y = 1;\r\n        } else if (combinations.size() == 1) {\r\n            temp.x = 1 + combinations.at(0).quotient * temp.quotient;\r\n            temp.y = -temp.quotient;\r\n        } else {\r\n            temp.x = combinations.at(combinations.size() - 2).x -\r\n                     temp.quotient * (combinations.at(combinations.size() - 1).x);\r\n            temp.y = combinations.at(combinations.size() - 2).y -\r\n                     temp.quotient * (combinations.at(combinations.size() - 1).y);\r\n        }\r\n        combinations.push_back(temp);\r\n        euclidean_gcd(b % a, a, combinations);\r\n        return;\r\n    }\r\n}\r\n\r\ncpp_int solve_congruence_system(cpp_int a, cpp_int m, cpp_int b, cpp_int n) {\r\n\r\n    std::vector<linear_combination> combinations;\r\n    euclidean_gcd(m, n, combinations);\r\n\r\n    cpp_int s = 0;\r\n    cpp_int t = 0;\r\n    if (!combinations.empty()) {\r\n        s = combinations.at(combinations.size() - 1).x;\r\n        t = combinations.at(combinations.size() - 1).y;\r\n    }\r\n\r\n    cpp_int x = b;\r\n    while (x > m * n) {\r\n        x -= m * n;\r\n    }\r\n    x *= m;\r\n    while (x > m * n) {\r\n        x -= m * n;\r\n    }\r\n    x *= s;\r\n    while (x > m * n) {\r\n        x -= m * n;\r\n    }\r\n\r\n    cpp_int y = a;\r\n    while (y > m * n) {\r\n        y -= m * n;\r\n    }\r\n    y *= n;\r\n    while (y > m * n) {\r\n        y -= m * n;\r\n    }\r\n    y *= t;\r\n    y -= (y - m * n) / (m * n) * (m * n);\r\n    while (y > m * n) {\r\n        y -= m * n;\r\n    }\r\n\r\n    cpp_int z = x + y;\r\n    while (z < 0) {\r\n        z += m * n;\r\n    }\r\n\r\n    return x + y;\r\n}\r\n\r\nstd::vector<cpp_int> take_input() {\r\n    std::string line;\r\n    std::string number;\r\n    std::vector<cpp_int> numbers;\r\n    std::cin.ignore(10000, '\\n');\r\n    std::getline(std::cin, line);\r\n\r\n    for (char c : line) {\r\n        if (c != ',') {\r\n            number.append(1, c);\r\n        } else {\r\n            if (number == \"x\") {\r\n                numbers.push_back(1);\r\n            } else {\r\n                numbers.push_back(stoi(number));\r\n            }\r\n            number = \"\";\r\n        }\r\n    }\r\n\r\n    if (number == \"x\") {\r\n        numbers.push_back(1);\r\n    } else {\r\n        numbers.push_back(stoi(number));\r\n    }\r\n\r\n    return numbers;\r\n}\r\n\r\n// 5 = 1 * 3 + 2\r\n// 3 = 1 * 2 + 1\r\n// 2 = 1 * 1 + 1\r\n// 1 = 1 * 1", "meta": {"hexsha": "1ea30707773d6c2e5bbdb2922315a006340e334a", "size": 3696, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "day13.cpp", "max_stars_repo_name": "sanjitdp/advent-of-code-2020", "max_stars_repo_head_hexsha": "dcda77265b26821f14ea7a1b0a1f209b7db21dcf", "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": "day13.cpp", "max_issues_repo_name": "sanjitdp/advent-of-code-2020", "max_issues_repo_head_hexsha": "dcda77265b26821f14ea7a1b0a1f209b7db21dcf", "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": "day13.cpp", "max_forks_repo_name": "sanjitdp/advent-of-code-2020", "max_forks_repo_head_hexsha": "dcda77265b26821f14ea7a1b0a1f209b7db21dcf", "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.1568627451, "max_line_length": 90, "alphanum_fraction": 0.466991342, "num_tokens": 1089, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947101574299, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.7022898422724857}}
{"text": "\r\n\r\n#include <boost/numeric/ublas/matrix.hpp>\r\n#include <iostream>\r\n#include <boost/numeric/ublas/io.hpp>\r\n\r\ntypedef boost::numeric::ublas::matrix<float> Matrix44;\r\n\r\nint main()\r\n{\r\n\tMatrix44 matrix(4, 4);\r\n\r\n\tfor (int i = 0; i < 4; ++i) {\r\n\t\tfor (int j = 0; j < 4; ++j) {\r\n\t\t\tmatrix(i, j) = i * 4 + j;\r\n\t\t}\r\n\t}\r\n\r\n\tstd::cout << matrix << std::endl;\r\n\r\n\treturn 0;\r\n}\r\n\r\n\r\n", "meta": {"hexsha": "7822e3b81a4cf012b999807d1b5ab8b91b827c75", "size": 372, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++/MatrixArray/MatrixArrayTest.cpp", "max_stars_repo_name": "taku-xhift/labo", "max_stars_repo_head_hexsha": "89dc28fdb602c7992c6f31920714225f83a11218", "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": "c++/MatrixArray/MatrixArrayTest.cpp", "max_issues_repo_name": "taku-xhift/labo", "max_issues_repo_head_hexsha": "89dc28fdb602c7992c6f31920714225f83a11218", "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": "c++/MatrixArray/MatrixArrayTest.cpp", "max_forks_repo_name": "taku-xhift/labo", "max_forks_repo_head_hexsha": "89dc28fdb602c7992c6f31920714225f83a11218", "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": 14.88, "max_line_length": 55, "alphanum_fraction": 0.5456989247, "num_tokens": 124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105696, "lm_q2_score": 0.7772998663336157, "lm_q1q2_score": 0.7021304701780144}}
{"text": "/**\n * @file   quaternion_algebra.hpp\n * @author Paul Furgale <paul.furgale@utoronto.ca>\n * @date   Sun Nov 21 19:20:37 2010\n *\n * @brief  Quaternion algebra from the paper Barfoot T D, Forbes J R, and Furgale P T. \u201cPose Estimation using Linearized\n * Rotations and Quaternion Algebra\u201d. Acta Astronautica, 2010. doi:10.1016/j.actaastro.2010.06.049.\n *\n *\n */\n\n#ifndef SM_QUATERNION_ALGEBRA_HPP\n#define SM_QUATERNION_ALGEBRA_HPP\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\nnamespace sm {\nnamespace kinematics {\n\nEigen::Matrix3d quat2r(Eigen::Vector4d const& q);\nEigen::Vector4d r2quat(Eigen::Matrix3d const& C);\nEigen::Vector4d r2quat(Eigen::Matrix3d const& C);\nEigen::Vector4d axisAngle2quat(Eigen::Vector3d const& a);\n\ntemplate <typename Scalar_>\nEigen::Matrix<Scalar_, 3, 1> quat2AxisAngle(Eigen::Matrix<Scalar_, 4, 1> const& q);\nextern template Eigen::Matrix<double, 3, 1> quat2AxisAngle(Eigen::Matrix<double, 4, 1> const& q);\nextern template Eigen::Matrix<float, 3, 1> quat2AxisAngle(Eigen::Matrix<float, 4, 1> const& q);\ninline Eigen::Vector3d quat2AxisAngle(Eigen::Vector4d const& q) { return quat2AxisAngle<>(q); }\n\nEigen::Matrix4d quatPlus(Eigen::Vector4d const& q);\nEigen::Vector4d qplus(Eigen::Vector4d const& q, Eigen::Vector4d const& p);\nEigen::Matrix4d quatOPlus(Eigen::Vector4d const& q);\nEigen::Vector4d qoplus(Eigen::Vector4d const& q, Eigen::Vector4d const& p);\nEigen::Vector4d quatInv(Eigen::Vector4d const& q);\nEigen::Vector3d quatRotate(Eigen::Vector4d const& q_a_b, Eigen::Vector3d const& v_b);\nEigen::Vector4d quatRandom();\nEigen::Vector4d quatIdentity();\nvoid invertQuat(Eigen::Vector4d& q);\nEigen::Vector3d qeps(Eigen::Vector4d const& q);\ndouble qeta(Eigen::Vector4d const& q);\n// For estimation functions to handle a constraint-sensitive minimal parameterization for a quaternion update\nEigen::Matrix<double, 4, 3> quatJacobian(Eigen::Vector4d const& q);\nEigen::Vector4d updateQuat(Eigen::Vector4d const& q, Eigen::Vector3d const& dq);\nEigen::Matrix<double, 3, 4> quatS(Eigen::Vector4d q);\nEigen::Matrix<double, 4, 3> quatInvS(Eigen::Vector4d q);\n\ninline Eigen::Vector3d qlog(const Eigen::Vector4d& q) { return quat2AxisAngle(q); }\ninline Eigen::Vector4d qexp(const Eigen::Vector3d& theta) { return axisAngle2quat(theta); }\n\n/// \\brief do spherical linear interpolation between q0 and q1 for times t = [0.0,1.0]\nEigen::Vector4d qslerp(const Eigen::Vector4d& q0, const Eigen::Vector4d& q1, double t);\n\n/// \\brief do linear interpolation between p0 and p1 for times t = [0.0,1.0]\nEigen::VectorXd lerp(const Eigen::VectorXd& p0, const Eigen::VectorXd& p1, double t);\n\n/// \\brief Jacobian of the quat log function evaluated at p\nEigen::Matrix<double, 3, 4> quatLogJacobian(const Eigen::Vector4d& p);\n\n/// \\brief Jacobian of the quat exp function evaluated at vec\ntemplate <typename Scalar_ = double>\nEigen::Matrix<Scalar_, 4, 3> quatExpJacobian(const Eigen::Matrix<Scalar_, 3, 1>& vec);\n\ntemplate <typename Scalar_ = double>\nEigen::Matrix<Scalar_, 3, 4> quatLogJacobian2(const Eigen::Matrix<Scalar_, 4, 1>& p);\n\ntemplate <typename Scalar_ = double>\nconst Eigen::Matrix<Scalar_, 4, 3>& quatV();\n\ntemplate <typename Scalar_ = double>\nEigen::Matrix<Scalar_, 3, 3> logDiffMat(const Eigen::Matrix<Scalar_, 3, 1>& vec);\n\ntemplate <typename Scalar_ = double>\nEigen::Matrix<Scalar_, 3, 3> expDiffMat(const Eigen::Matrix<Scalar_, 3, 1>& vec);\n\nextern template const Eigen::Matrix<double, 4, 3>& quatV();\nextern template const Eigen::Matrix<float, 4, 3>& quatV();\nextern template Eigen::Matrix<double, 4, 3> quatExpJacobian(const Eigen::Matrix<double, 3, 1>& vec);\nextern template Eigen::Matrix<float, 4, 3> quatExpJacobian(const Eigen::Matrix<float, 3, 1>& vec);\nextern template Eigen::Matrix<double, 3, 4> quatLogJacobian2(const Eigen::Matrix<double, 4, 1>& p);\nextern template Eigen::Matrix<float, 3, 4> quatLogJacobian2(const Eigen::Matrix<float, 4, 1>& p);\nextern template Eigen::Matrix<double, 3, 3> logDiffMat(const Eigen::Matrix<double, 3, 1>& vec);\nextern template Eigen::Matrix<float, 3, 3> logDiffMat(const Eigen::Matrix<float, 3, 1>& vec);\nextern template Eigen::Matrix<double, 3, 3> expDiffMat(const Eigen::Matrix<double, 3, 1>& vec);\nextern template Eigen::Matrix<float, 3, 3> expDiffMat(const Eigen::Matrix<float, 3, 1>& vec);\n}  // namespace kinematics\n}  // namespace sm\n\n#endif /* SM_QUATERNION_ALGEBRA_HPP */\n", "meta": {"hexsha": "ef2960ff3484a4f93562384d57d5e9de2f794a35", "size": 4344, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Schweizer-Messer/sm_kinematics/include/sm/kinematics/quaternion_algebra.hpp", "max_stars_repo_name": "chengfzy/kalibr", "max_stars_repo_head_hexsha": "fe9705b380b160dc939607135f7d30efa64ea2e9", "max_stars_repo_licenses": ["BSD-4-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": "Schweizer-Messer/sm_kinematics/include/sm/kinematics/quaternion_algebra.hpp", "max_issues_repo_name": "chengfzy/kalibr", "max_issues_repo_head_hexsha": "fe9705b380b160dc939607135f7d30efa64ea2e9", "max_issues_repo_licenses": ["BSD-4-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": "Schweizer-Messer/sm_kinematics/include/sm/kinematics/quaternion_algebra.hpp", "max_forks_repo_name": "chengfzy/kalibr", "max_forks_repo_head_hexsha": "fe9705b380b160dc939607135f7d30efa64ea2e9", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.2666666667, "max_line_length": 120, "alphanum_fraction": 0.741252302, "num_tokens": 1356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971871, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.7021304620836938}}
{"text": "#pragma once\n\n#include <vector>\n#include <cassert>\n\n#include <iostream>\n#include <iomanip>\n\n#include <Eigen/Dense>\n\n//! \\file rkintegrator.hpp Solution for Problem 1a, implementing RkIntegrator class\n\n//! \\brief Implements a Runge-Kutta explicit solver for a given Butcher tableau for autonomous ODEs\n//! \\tparam State a type representing the space in which the solution lies, e.g. R^d, represented by e.g. Eigen::VectorXd.\ntemplate <class State>\nclass RKIntegrator {\npublic:\n    //! \\brief Constructor for the RK method.\n    //! Performs size checks and copies A and b into internal storage\n    //! \\param[in] A matrix containing coefficents of Butcher tableau, must be (strictly) lower triangular (no check)\n    //! \\param[in] b vector containing coefficients of lower part of Butcher tableau\n    RKIntegrator(const Eigen::MatrixXd & A, const Eigen::VectorXd & b) {\n        // TODO: implement size checks and initialize internal data\n    }\n    \n    //! \\brief Perform the solution of the ODE\n    //! Solve an autonomous ODE y' = f(y), y(0) = y0, using a RK scheme given in the Butcher tableau provided in the\n    //! constructor. Performs N equidistant steps upto time T with initial data y0\n    //! \\tparam Function type for function implementing the rhs function. Must have State operator()(State x)\n    //! \\param[in] f function handle for rhs in y' = f(y), e.g. implemented using lambda funciton\n    //! \\param[in] T final time T\n    //! \\param[in] y0 initial data y(0) = y0 for y' = f(y)\n    //! \\param[in] N number of steps to perform. Step size is h = T / N. Steps are equidistant.\n    //! \\return vector containing all steps y^n (for each n) including initial and final value\n    template <class Function>\n    std::vector<State> solve(const Function &f, double T, const State & y0, unsigned int N) const {\n        // TODO: implement solver from 0 to T, calling function step appropriately\n    }\n    \nprivate:\n    \n    //! \\brief Perform a single step of the RK method for the solution of the autonomous ODE\n    //! Compute a single explicit RK step y^{n+1} = y_n + \\sum ... starting from value y0 and storing next value in y1\n    //! \\tparam Function type for function implementing the rhs. Must have State operator()(State x)\n    //! \\param[in] f function handle for ths f, s.t. y' = f(y)\n    //! \\param[in] h step size\n    //! \\param[in] y0 initial state \n    //! \\param[out] y1 next step y^{n+1} = y^n + ...\n    template <class Function>\n    void step(const Function &f, double h, const State & y0, State & y1) const {\n        // TODO: implement a single step of the RK method using provided Butcher scheme\n    }\n    \n    //! TODO: put here suitable internal data storage\n};\n", "meta": {"hexsha": "d817366e0ff3960d5a3e9825d2942e8b53de9323", "size": 2688, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/PS12/solutions_ps12/rkintegrator_template.hpp", "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/PS12/templates_ps12/rkintegrator_template.hpp", "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/PS12/templates_ps12/rkintegrator_template.hpp", "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": 48.0, "max_line_length": 122, "alphanum_fraction": 0.6822916667, "num_tokens": 674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.8824278602705731, "lm_q1q2_score": 0.7021108747456786}}
{"text": "/* Copyright (c) 2012, Julian Straub <jstraub@csail.mit.edu>\n * Licensed under the MIT license. See LICENSE.txt or \n * http://www.opensource.org/licenses/mit-license.php */\n\n#pragma once\n\n#include <boost/random/mersenne_twister.hpp>\n//#include <boost/random/uniform_int_distribution.hpp>\n#include <boost/random/uniform_int.hpp>\n#include <boost/random/uniform_01.hpp>\n#include <boost/random/gamma_distribution.hpp>\n\n#include <armadillo>\n#include <time.h>\n\nusing namespace arma;\n\n\nclass GammaRnd\n{\npublic:\n  GammaRnd(double alpha, double beta) // alpha = shape; beta = scale\n    : mGen(time(0)),mAlpha(alpha), mBeta(beta), mGamma(mAlpha)\n  {};\n\n  double draw(void)\n  {\n    return mBeta*mGamma(mGen);\n  };\n  void draw(Col<double>& c)\n  {\n    for (uint32_t i=0; i<c.n_elem; ++i)\n      c(i)=draw();\n  };\n\n  void draw(Row<double>& c)\n  {\n    for (uint32_t i=0; i<c.n_elem; ++i)\n      c(i)=draw();\n  };\n\nprivate:\n  boost::mt19937 mGen;\n  double mAlpha;\n  double mBeta;\n  boost::gamma_distribution<> mGamma;\n};\n\n\nclass RandInt\n{\npublic:\n  RandInt(uint32_t limLower, uint32_t limUpper)\n    : mGen(time(0)),  mDist(limLower,limUpper-1) // so we generate numbers in the range( upper - lower)\n  {};\n\n  uint32_t draw(void)\n  {\n    return mDist(mGen);\n  };\n\n  void draw(Col<uint32_t>& c)\n  {\n    for (uint32_t i=0; i<c.n_rows; ++i)\n    {\n      c(i)=mDist(mGen);\n    }\n  }\n  Col<uint32_t> draw(uint32_t N)\n  {\n    Col<uint32_t> c(N);\n    draw(c);\n    return c;\n  }\n\n\nprivate:\n  boost::mt19937 mGen;\n  boost::uniform_int<> mDist;\n};\n\nclass RandDisc\n{\npublic:\n  RandDisc() : mGen(time(0))\n  { };\n\n  double draw(void)\n  {\n    return mDist(mGen);\n  };\n\n  uint32_t draw(const Col<double>& pdf)\n  {\n    Col<double> cdf=cumsum(pdf);\n    double r=mDist(mGen);\n    for (uint32_t i=0; i<pdf.n_rows; ++i)\n      if (r<cdf(i)){return i;}\n    return pdf.n_rows-1; \n  };\n\nprivate:\n  Col<double> mPdf;\n  boost::mt19937 mGen;\n  boost::uniform_01<> mDist;\n};\n\nuint32_t sampleDiscLogProb(RandDisc& rndDisc, colvec l)\n{\n  //    cout<<\"max(l)=\"<<l.max()<<\" min(l)=\"<<l.min()<<endl;\n  double lmax=l.max();\n  double lmin=l.min();\n  for(uint32_t i=0; i<l.n_elem; ++i)\n    if(!is_finite(l(i)))\n      l(i)=0.0;\n    else\n      l(i)=exp(l(i) + (lmax - lmin)*0.5);\n  //    cout<<\"l(exp) =\"<<l.t()<<endl;\n  //    cout<<\"l(norm) =\"<<l.t()/sum(l)<<endl;\n  return rndDisc.draw(l/sum(l));\n};\n\n", "meta": {"hexsha": "22d6e76d0929a5a77747a507553a0006d1760400", "size": 2344, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/random.hpp", "max_stars_repo_name": "jstraub/bnp", "max_stars_repo_head_hexsha": "11cd28b49e9cf1db96f349181aff57a17672b6a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T01:18:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-16T20:16:54.000Z", "max_issues_repo_path": "include/random.hpp", "max_issues_repo_name": "jstraub/bnp", "max_issues_repo_head_hexsha": "11cd28b49e9cf1db96f349181aff57a17672b6a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-07-12T12:58:14.000Z", "max_issues_repo_issues_event_max_datetime": "2015-07-12T12:58:14.000Z", "max_forks_repo_path": "include/random.hpp", "max_forks_repo_name": "jstraub/bnp", "max_forks_repo_head_hexsha": "11cd28b49e9cf1db96f349181aff57a17672b6a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-07-22T05:37:10.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-26T07:11:34.000Z", "avg_line_length": 19.0569105691, "max_line_length": 103, "alphanum_fraction": 0.6122013652, "num_tokens": 753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391643039739, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.7021103477827865}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include \"matrix_gemm.h\"\n#include \"common/pixel_benchmark.h\"\n#include \"common/pixel_check.h\"\n\n#include <opencv2/opencv.hpp>\n#include <Eigen/Dense>\n\nusing std::cout;\nusing std::endl;\n\ntypedef struct Matrix {\n    size_t rows;\n    size_t cols;\n    float* data;\n} Matrix;\n\n/*\n1 2     1  2    7  10\n3 4     3  4    15 22\n*/\n\nstatic void print_matrix(float* data, uint32_t rows, uint32_t cols) {\n    size_t idx=0;\n    for (uint32_t i=0; i<rows; i++){\n        for (uint32_t j=0; j<cols; j++) {\n            printf(\"%.2f, \", data[idx]);\n            idx++;\n        }\n        printf(\"\\n\");\n    }\n}\n\nstatic void matrix_gemm_f32_opencv(float* mA, float* mB, float* mC, const uint32_t M, const uint32_t K, const uint32_t N)\n{\n    cv::Mat matA = cv::Mat(M, K, CV_32FC1, mA);\n    cv::Mat matB = cv::Mat(K, N, CV_32FC1, mB);\n    cv::Mat matC = cv::Mat(M, N, CV_32FC1, mC);\n    matC = matA * matB;\n    // cout << \"matA:\\n\" << matA << endl;\n    // cout << \"matB:\\n\" << matB << endl;\n    // cout << \"matC:\\n\" << matC << endl;\n}\n\nstatic void matrix_gemm_f32_eigen(float* mA, float* mB, float* mC, const uint32_t M, const uint32_t K, const uint32_t N)\n{\n    Eigen::Map<Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>> eA(mA, M, K);\n    Eigen::Map<Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>> eB(mB, K, N);\n    Eigen::Map<Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>> eC(mC, M, N);\n    eC = eA * eB;\n    // cout << \"eA:\\n\" << eA << endl;\n    // cout << \"eB:\\n\" << eB << endl;\n    // cout << \"eC:\\n\" << eC << endl;\n}\n\nstatic void gemm_tiny_debug()\n{\n    uint32_t m = 3;\n    uint32_t k = 2;\n    uint32_t n = 4;\n\n    Matrix mA;\n    mA.rows = m;\n    mA.cols = k;\n    \n    Matrix mB;\n    mB.rows = k;\n    mB.cols = n;\n\n    mA.data = (float*)malloc(mA.rows*mA.cols * sizeof(float));\n    mB.data = (float*)malloc(mB.rows*mB.cols * sizeof(float));\n\n    mA.data[0] = 2;\n    mA.data[1] = -6;\n    mA.data[2] = 3;\n    mA.data[3] = 5;\n    mA.data[4] = 1;\n    mA.data[5] = -1;\n\n    mB.data[0] = 4;\n    mB.data[1] = -2;\n    mB.data[2] = -4;\n    mB.data[3] = -5;\n    mB.data[4] = -7;\n    mB.data[5] = -3;\n    mB.data[6] = 6;\n    mB.data[7] = 7;\n\n    Matrix mC;\n    mC.rows = m;\n    mC.cols = n;\n    mC.data = (float*)malloc(mC.rows*mC.cols * sizeof(float));\n\n    matrix_gemm_f32_order_opt(mA.data, mB.data, mC.data, m, k, n);\n\n    printf(\"--- matrix A:\\n\");\n    print_matrix(mA.data, mA.rows, mA.cols);\n\n    printf(\"--- matrix B:\\n\");\n    print_matrix(mB.data, mB.rows, mB.cols);\n\n    printf(\"--- matrix C:\\n\");\n    print_matrix(mC.data, mC.rows, mC.cols);\n\n}\n\nstatic void prepare_big(uint32_t& M, uint32_t& K, uint32_t& N, cv::Mat& matA, cv::Mat& matB)\n{\n    cv::Mat image = cv::imread(\"colorhouse.png\");\n\n    cv::Size size = image.size();\n    uint32_t height = size.height;\n    uint32_t width = size.width;\n    printf(\"image info: height=%u, width=%u\\n\", height, width);\n\n    cv::Size transposed_size;\n    transposed_size.height = size.width;\n    transposed_size.width = size.height;\n\n    std::vector<cv::Mat> channels;\n    cv::split(image, channels);\n    cv::Mat b_channels = channels[0];\n    cv::Mat g_channels = channels[1];\n    cv::Mat r_channels = channels[2];\n    \n    // matA's dim: height * width\n    b_channels.convertTo(matA, CV_32FC1);\n\n    matB = b_channels.t(); // matB's dim: width * height\n    matB.convertTo(matB, CV_32FC1);\n\n    M = height;\n    K = width;\n    N = height;\n}\n\nstatic void prepare_small(uint32_t& M, uint32_t& K, uint32_t& N, cv::Mat& matA, cv::Mat& matB)\n{\n    M = 2;\n    K = 3;\n    N = 2;\n\n    /*\n    0  1  2\n    1  2  3\n    */\n    float* data = NULL;\n    matA = cv::Mat(M, K, CV_32FC1);\n    data = (float*)matA.data;\n    data[0] = 1.2;\n    data[1] = 2.3;\n    data[2] = 3.4;\n    data[3] = 4.5;\n    data[4] = 5.6;\n    data[5] = 6.7;\n\n    cout << \"matA:\" << endl << matA << endl;\n\n    /*\n    1 2\n    3 4\n    5 6\n    */\n    matB = cv::Mat(K, N, CV_32FC1);\n    data = (float*)matB.data;\n    data[0] = 1.1;\n    data[1] = 2.2;\n    data[2] = 3.3;\n    data[3] = 4.5;\n    data[4] = 5.5;\n    data[5] = 6.6;\n\n    cout << \"matB:\" << endl << matB << endl;\n}\n\nstatic void gemm_f32_test() {\n    //--------------------------------\n    cv::Mat matA;\n    cv::Mat matB;\n    uint32_t M, K, N;\n    prepare_big(M, K, N, matA, matB);\n    //prepare_small(M, K, N, matA, matB);\n\n    printf(\"-- after prepare_small:\\n\");\n    // cout << \"matA:\" << endl << matA << endl;\n    // cout << \"matB:\" << endl << matB << endl;\n\n    float* mA = (float*)matA.data;\n    float* mB = (float*)matB.data;\n\n    size_t buf_size = M*N * sizeof(float);\n    float* mC_naive = (float*)malloc(buf_size);\n    float* mC_eigen = (float*)malloc(buf_size);\n    float* mC_opencv = (float*)malloc(buf_size);\n    float* mC_order_opt = (float*)malloc(buf_size);\n    float* mC_order_opt2 = (float*)malloc(buf_size);\n    float* mC_asimd = (float*)malloc(buf_size);\n    for(uint32_t i=0; i<M*N; i++) {\n        mC_naive[i] = 0;\n        mC_eigen[i] = 0;\n        mC_opencv[i] = 0;\n        mC_order_opt[i] = 0;\n        mC_order_opt2[i] = 0;\n        mC_asimd[i] = 0;\n    }\n\n    double t_start, t_cost;\n\n    // eigen\n    t_start = pixel_get_current_time();\n    matrix_gemm_f32_eigen(mA, mB, mC_eigen, M, K, N);\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"matrix gemm, eigen,     time cost %.2lf ms\\n\", t_cost);\n\n    // opencv\n    t_start = pixel_get_current_time();\n    matrix_gemm_f32_opencv(mA, mB, mC_opencv, M, K, N);\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"matrix gemm, opencv,    time cost %.2lf ms\\n\", t_cost);\n\n    // naive\n    t_start = pixel_get_current_time();\n    matrix_gemm_f32_naive(mA, mB, mC_naive, M, K, N);\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"matrix gemm, naive,     time cost %.2lf ms\\n\", t_cost);\n\n    // order opt \u8c03\u6574\u7ef4\u5ea6\u987a\u5e8f\n    t_start = pixel_get_current_time();\n    matrix_gemm_f32_order_opt(mA, mB, mC_order_opt, M, K, N);\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"matrix gemm, order opt, time cost %.2lf ms\\n\", t_cost);\n\n    // order opt2 \u8c03\u6574\u7ef4\u5ea6\u987a\u5e8f2\n    t_start = pixel_get_current_time();\n    matrix_gemm_f32_order_opt2(mA, mB, mC_order_opt2, M, K, N);\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"matrix gemm, order opt2,time cost %.2lf ms\\n\", t_cost);\n\n    // asimd\n    t_start = pixel_get_current_time();\n    matrix_gemm_f32_asimd(mA, mB, mC_asimd, M, K, N);\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"matrix gemm, asimd,     time cost %.2lf ms\\n\", t_cost);\n\n    // validate if different implementations result match\n    int mis_eigen = 0;\n    int mis_opencv = 0;\n    int mis_order_opt = 0;\n    int mis_order_opt2 = 0;\n    int mis_asimd = 0;\n    uint32_t len = M * N;\n\n    //float* mC_gt = mC_order_opt;\n    float* mC_gt = mC_naive;\n    float epsilon = 1e-3;\n    for (uint32_t i=0; i<len; i++) {\n        if (!nearly_equal_absolutely(mC_gt[i], mC_eigen[i], epsilon)) {\n            mis_eigen++;\n        }\n        if (!nearly_equal_absolutely(mC_gt[i], mC_opencv[i], epsilon)) {\n            mis_opencv++;\n        }\n        if (!nearly_equal_absolutely(mC_gt[i], mC_order_opt[i], epsilon)) {\n            mis_order_opt++;\n        }\n        if (!nearly_equal_absolutely(mC_gt[i], mC_order_opt2[i], epsilon)) {\n            mis_order_opt2++;\n        }\n        if (!nearly_equal_absolutely(mC_gt[i], mC_asimd[i], epsilon)) {\n            mis_asimd++;\n        }\n    }\n\n    printf(\"mis_eigen=%d, mis_opencv=%d, mis_order_opt=%d, mis_order_opt2=%d, mis_asimd=%d\\n\",\n        mis_eigen, mis_opencv, mis_order_opt, mis_order_opt2, mis_asimd);\n\n    FILE* fout = NULL;\n\n    fout = fopen(\"opencv.txt\", \"w\");\n    for (uint32_t i=0; i<len; i++) {\n        fprintf(fout, \"%f\\n\", mC_opencv[i]);\n    }\n    fclose(fout);\n\n    fout = fopen(\"eigen.txt\", \"w\");\n    for (uint32_t i=0; i<len; i++) {\n        fprintf(fout, \"%f\\n\", mC_eigen[i]);\n    }\n    fclose(fout);\n\n    fout = fopen(\"order_opt.txt\", \"w\");\n    for (uint32_t i=0; i<len; i++) {\n        fprintf(fout, \"%f\\n\", mC_order_opt[i]);\n    }\n    fclose(fout);\n\n    fout = fopen(\"naive.txt\", \"w\");\n    for (uint32_t i=0; i<len; i++) {\n        fprintf(fout, \"%f\\n\", mC_naive[i]);\n    }\n    fclose(fout);\n}\n\n\nint main() {\n    //gemm_tiny_debug();\n    gemm_f32_test();\n\n    return 0;\n}", "meta": {"hexsha": "4209a2fe260ab911066ac16774b499ef0e57ea01", "size": 8309, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "matcalc/matrix_gemm_test.cpp", "max_stars_repo_name": "zchrissirhcz/pixel", "max_stars_repo_head_hexsha": "6bfe4b2f2b80de64c7de4b6d8735de8000b7dc3a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 38.0, "max_stars_repo_stars_event_min_datetime": "2020-12-23T16:37:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T13:46:04.000Z", "max_issues_repo_path": "matcalc/matrix_gemm_test.cpp", "max_issues_repo_name": "zchrissirhcz/pixel", "max_issues_repo_head_hexsha": "6bfe4b2f2b80de64c7de4b6d8735de8000b7dc3a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-01-31T16:04:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T13:58:11.000Z", "max_forks_repo_path": "matcalc/matrix_gemm_test.cpp", "max_forks_repo_name": "zchrissirhcz/pixel", "max_forks_repo_head_hexsha": "6bfe4b2f2b80de64c7de4b6d8735de8000b7dc3a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-11-23T09:33:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-15T08:13:56.000Z", "avg_line_length": 26.5463258786, "max_line_length": 121, "alphanum_fraction": 0.5692622458, "num_tokens": 2866, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391579526935, "lm_q2_score": 0.7606506526772883, "lm_q1q2_score": 0.7021103379434109}}
{"text": "/******************************************************************************\n\n  This source file is part of the Avogadro project.\n\n  Copyright (C) 2010 Eric C. Brown\n\n  This source code is released under the New BSD License, (the \"License\").\n\n  Unless required by applicable law or agreed to in writing, software\n  distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions and\n  limitations under the License.\n\n******************************************************************************/\n\n#include \"qtaimmathutilities.h\"\n\n#include <Eigen/Eigenvalues>\n#include <Eigen/QR>\n#include <cmath>\n\nnamespace Avogadro {\nnamespace QtPlugins {\nnamespace QTAIMMathUtilities {\n\nMatrix<qreal, 3, 1> eigenvaluesOfASymmetricThreeByThreeMatrix(\n  const Matrix<qreal, 3, 3>& A)\n{\n  SelfAdjointEigenSolver<Matrix<qreal, 3, 3>> eigensolver(A);\n  return eigensolver.eigenvalues();\n}\n\nMatrix<qreal, 3, 3> eigenvectorsOfASymmetricThreeByThreeMatrix(\n  const Matrix<qreal, 3, 3>& A)\n{\n  SelfAdjointEigenSolver<Matrix<qreal, 3, 3>> eigensolver(A);\n  return eigensolver.eigenvectors();\n}\n\nMatrix<qreal, 4, 1> eigenvaluesOfASymmetricFourByFourMatrix(\n  const Matrix<qreal, 4, 4>& A)\n{\n  SelfAdjointEigenSolver<Matrix<qreal, 4, 4>> eigensolver(A);\n  return eigensolver.eigenvalues();\n}\n\nMatrix<qreal, 4, 4> eigenvectorsOfASymmetricFourByFourMatrix(\n  const Matrix<qreal, 4, 4>& A)\n{\n  SelfAdjointEigenSolver<Matrix<qreal, 4, 4>> eigensolver(A);\n  return eigensolver.eigenvectors();\n}\n\nqint64 signOfARealNumber(qreal x)\n{\n  if (x > 0.)\n    return 1;\n  else if (x == 0.)\n    return 0;\n  else\n    return -1;\n}\n\nqint64 signatureOfASymmetricThreeByThreeMatrix(const Matrix<qreal, 3, 3>& A)\n{\n  SelfAdjointEigenSolver<Matrix<qreal, 3, 3>> eigensolver(A);\n  Matrix<qreal, 3, 1> eigenvalues = eigensolver.eigenvalues();\n\n  return signOfARealNumber(eigenvalues(0)) + signOfARealNumber(eigenvalues(1)) +\n         signOfARealNumber(eigenvalues(2));\n}\n\nqreal ellipticityOfASymmetricThreeByThreeMatrix(const Matrix<qreal, 3, 3>& A)\n{\n  SelfAdjointEigenSolver<Matrix<qreal, 3, 3>> eigensolver(A);\n  Matrix<qreal, 3, 1> eigenvalues = eigensolver.eigenvalues();\n\n  return (eigenvalues(0) / eigenvalues(1)) - 1.0;\n}\n\nqreal distance(const Matrix<qreal, 3, 1>& a, const Matrix<qreal, 3, 1>& b)\n{\n  return sqrt(pow(a(0) - b(0), 2) + pow(a(1) - b(1), 2) + pow(a(2) - b(2), 2));\n}\n\nMatrix<qreal, 3, 1> sphericalToCartesian(const Matrix<qreal, 3, 1>& rtp,\n                                         const Matrix<qreal, 3, 1>& x0y0z0)\n{\n  qreal r = rtp(0);\n  qreal theta = rtp(1);\n  qreal phi = rtp(2);\n\n  qreal x0 = x0y0z0(0);\n  qreal y0 = x0y0z0(1);\n  qreal z0 = x0y0z0(2);\n\n  qreal costheta = cos(theta);\n  qreal cosphi = cos(phi);\n  qreal sintheta = sin(theta);\n  qreal sinphi = sin(phi);\n\n  Matrix<qreal, 3, 1> xyz(r * cosphi * sintheta + x0,\n                          r * sintheta * sinphi + y0, r * costheta + z0);\n\n  return xyz;\n}\n\nMatrix<qreal, 3, 1> sphericalToCartesian(const Matrix<qreal, 3, 1>& rtp)\n{\n  Matrix<qreal, 3, 1> x0y0z0(0., 0., 0.);\n\n  return sphericalToCartesian(rtp, x0y0z0);\n}\n\nMatrix<qreal, 3, 1> cartesianToSpherical(const Matrix<qreal, 3, 1>& xyz,\n                                         const Matrix<qreal, 3, 1>& x0y0z0)\n{\n  qreal x = xyz(0);\n  qreal y = xyz(1);\n  qreal z = xyz(2);\n\n  qreal x0 = x0y0z0(0);\n  qreal y0 = x0y0z0(1);\n  qreal z0 = x0y0z0(2);\n\n  qreal xshift = x - x0;\n  qreal yshift = y - y0;\n  qreal zshift = z - z0;\n\n  qreal length = sqrt(pow(xshift, 2) + pow(yshift, 2) + pow(zshift, 2));\n\n  Matrix<qreal, 3, 1> rtp;\n\n  if (length == 0.)\n    rtp << x0, y0, z0;\n  else if (xshift == 0. && yshift == 0.)\n    rtp << length, acos(zshift / length), 0.;\n  else\n    rtp << length, acos(zshift / length), atan2(xshift, yshift);\n\n  return rtp;\n}\n\nMatrix<qreal, 3, 1> cartesianToSpherical(const Matrix<qreal, 3, 1>& xyz)\n{\n  Matrix<qreal, 3, 1> x0y0z0(0., 0., 0.);\n\n  return cartesianToSpherical(xyz, x0y0z0);\n}\n\n// Cerjan-Miller-Baker-Popelier Methods\n//\n// Based on:\n// Popelier, P.L.A. Comput. Phys. Comm. 1996, 93, 212.\n\nMatrix<qreal, 3, 1> minusThreeSignatureLocatorGradient(\n  const Matrix<qreal, 3, 1>& g, const Matrix<qreal, 3, 3>& H)\n{\n  Matrix<qreal, 3, 1> value;\n\n  Matrix<qreal, 3, 1> b = eigenvaluesOfASymmetricThreeByThreeMatrix(H);\n  Matrix<qreal, 3, 3> U = eigenvectorsOfASymmetricThreeByThreeMatrix(H);\n\n  Matrix<qreal, 3, 1> F = U.transpose() * g;\n\n  Matrix<qreal, 4, 4> A;\n  A << b(0), 0., 0., F(0), 0., b(1), 0., F(1), 0., 0., b(2), F(2), F(0), F(1),\n    F(2), 0.;\n\n  Matrix<qreal, 4, 1> eval = eigenvaluesOfASymmetricFourByFourMatrix(A);\n\n  Matrix<qreal, 3, 1> lambda;\n  lambda << eval(3), eval(3), eval(3);\n\n  Matrix<qreal, 3, 1> denom;\n  denom = b - lambda;\n\n  for (qint64 i = 0; i < 3; ++i)\n    if (denom(i) < SMALL)\n      denom(i) = denom(i) + SMALL;\n\n  Matrix<qreal, 3, 1> h;\n  h << 0., 0., 0.;\n\n  for (qint64 j = 0; j < 3; ++j)\n    for (qint64 i = 0; i < 3; ++i)\n      h(j) = h(j) + (-F(i) * U(j, i)) / denom(i);\n\n  value = h;\n\n  return value;\n}\n\nMatrix<qreal, 3, 1> minusOneSignatureLocatorGradient(\n  const Matrix<qreal, 3, 1>& g, const Matrix<qreal, 3, 3>& H)\n{\n  Matrix<qreal, 3, 1> value;\n\n  Matrix<qreal, 3, 1> b = eigenvaluesOfASymmetricThreeByThreeMatrix(H);\n  Matrix<qreal, 3, 3> U = eigenvectorsOfASymmetricThreeByThreeMatrix(H);\n\n  Matrix<qreal, 3, 1> F = U.transpose() * g;\n\n  Matrix<qreal, 3, 3> A;\n  A << b(0), 0., F(0), 0., b(1), F(1), F(0), F(1), 0.;\n\n  Matrix<qreal, 3, 1> eval = eigenvaluesOfASymmetricThreeByThreeMatrix(A);\n\n  Matrix<qreal, 3, 1> lambda;\n  lambda << eval(2), eval(2),\n    (0.5) * (b(2) - sqrt(pow(b(2), 2) + 4.0 * pow(F(2), 2)));\n\n  Matrix<qreal, 3, 1> denom;\n  denom = b - lambda;\n\n  for (qint64 i = 0; i < 3; ++i)\n    if (denom(i) < SMALL)\n      denom(i) = denom(i) + SMALL;\n\n  Matrix<qreal, 3, 1> h;\n  h << 0., 0., 0.;\n\n  for (qint64 j = 0; j < 3; ++j)\n    for (qint64 i = 0; i < 3; ++i)\n      h(j) = h(j) + (-F(i) * U(j, i)) / denom(i);\n\n  value = h;\n\n  return value;\n}\n\nMatrix<qreal, 3, 1> plusOneSignatureLocatorGradient(\n  const Matrix<qreal, 3, 1>& g, const Matrix<qreal, 3, 3>& H)\n{\n  Matrix<qreal, 3, 1> value;\n\n  Matrix<qreal, 3, 1> b = eigenvaluesOfASymmetricThreeByThreeMatrix(H);\n  Matrix<qreal, 3, 3> U = eigenvectorsOfASymmetricThreeByThreeMatrix(H);\n\n  Matrix<qreal, 3, 1> F = U * g;\n\n  Matrix<qreal, 3, 3> A;\n  A << b(1), 0., F(1), 0., b(2), F(2), F(1), F(2), 0.;\n\n  Matrix<qreal, 3, 1> eval = eigenvaluesOfASymmetricThreeByThreeMatrix(A);\n\n  Matrix<qreal, 3, 1> lambda;\n  lambda << eval(2), eval(2),\n    (0.5) * (b(0) + sqrt(pow(b(0), 2) + 4.0 * pow(F(0), 2)));\n\n  Matrix<qreal, 3, 1> denom;\n  denom = b - lambda;\n\n  for (qint64 i = 0; i < 3; ++i)\n    if (denom(i) < SMALL)\n      denom(i) = denom(i) + SMALL;\n\n  Matrix<qreal, 3, 1> h;\n  h << 0., 0., 0.;\n\n  for (qint64 j = 0; j < 3; ++j)\n    for (qint64 i = 0; i < 3; ++i)\n      h(j) = h(j) + (-F(i) * U(i, j)) / denom(i);\n\n  value = h;\n\n  return value;\n}\n\nMatrix<qreal, 3, 1> plusThreeSignatureLocatorGradient(\n  const Matrix<qreal, 3, 1>& g, const Matrix<qreal, 3, 3>& H)\n{\n  Matrix<qreal, 3, 1> value;\n\n  Matrix<qreal, 3, 1> b = eigenvaluesOfASymmetricThreeByThreeMatrix(H);\n  Matrix<qreal, 3, 3> U = eigenvectorsOfASymmetricThreeByThreeMatrix(H);\n\n  Matrix<qreal, 3, 1> F = U * g;\n\n  Matrix<qreal, 4, 4> A;\n  A << b(0), 0., 0., F(0), 0., b(1), 0., F(1), 0., 0., b(2), F(2), F(0), F(1),\n    F(2), 0.;\n\n  Matrix<qreal, 4, 1> eval = eigenvaluesOfASymmetricFourByFourMatrix(A);\n\n  Matrix<qreal, 3, 1> lambda;\n  lambda << eval(0), eval(0), eval(0);\n\n  Matrix<qreal, 3, 1> denom;\n  denom = b - lambda;\n\n  for (qint64 i = 0; i < 3; ++i)\n    if (denom(i) < SMALL)\n      denom(i) = denom(i) + SMALL;\n\n  Matrix<qreal, 3, 1> h;\n  h << 0., 0., 0.;\n\n  for (qint64 j = 0; j < 3; ++j)\n    for (qint64 i = 0; i < 3; ++i)\n      h(j) = h(j) + (-F(i) * U(i, j)) / denom(i);\n\n  value = h;\n\n  return value;\n}\n\n} // namespace QTAIMMathUtilities\n} // namespace QtPlugins\n} // namespace Avogadro\n", "meta": {"hexsha": "7917d9d2811d4b77e51944f3a0b074c477bc1ead", "size": 8048, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "avogadro/qtplugins/qtaim/qtaimmathutilities.cpp", "max_stars_repo_name": "serk12/avogadrolibs", "max_stars_repo_head_hexsha": "f2dd0fda7e0d2ca4a0586354ea253cc05242f022", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 244.0, "max_stars_repo_stars_event_min_datetime": "2015-09-09T15:08:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T17:44:21.000Z", "max_issues_repo_path": "avogadro/qtplugins/qtaim/qtaimmathutilities.cpp", "max_issues_repo_name": "serk12/avogadrolibs", "max_issues_repo_head_hexsha": "f2dd0fda7e0d2ca4a0586354ea253cc05242f022", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 670.0, "max_issues_repo_issues_event_min_datetime": "2015-05-08T18:59:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T19:47:08.000Z", "max_forks_repo_path": "avogadro/qtplugins/qtaim/qtaimmathutilities.cpp", "max_forks_repo_name": "serk12/avogadrolibs", "max_forks_repo_head_hexsha": "f2dd0fda7e0d2ca4a0586354ea253cc05242f022", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 129.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T01:18:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T08:50:25.000Z", "avg_line_length": 25.7948717949, "max_line_length": 80, "alphanum_fraction": 0.6008946322, "num_tokens": 3143, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107966642556, "lm_q2_score": 0.7490872187162396, "lm_q1q2_score": 0.7020526290240584}}
{"text": "#include <math.h>\n#include <Eigen/Geometry>\n\n#include \"stiffness_checker/Util.h\"\n\nnamespace conmech\n{\nnamespace stiffness_checker\n{\n\nvoid createLocalStiffnessMatrix(const double &L, const double &A, const int &dim,\n                                const double &Jx, const double &Iy, const double &Iz,\n                                const double &E, const double &G, const double &mu,\n                                Eigen::MatrixXd &K_eL)\n{\n  // TODO: add 2D case\n  assert(3 == dim);\n\n  switch(dim)\n  {\n    case 2:\n      assert(false && \"2D local stiffness not implemented.\");\n      return;\n    case 3:\n    {\n      K_eL = Eigen::MatrixXd::Zero(12,12);\n\n      // see: [Matrix Structural Analysis, McGuire et al., 2rd edition]\n      // P73 - eq(4.34)\n      Eigen::MatrixXd K_block(6,6);\n      K_block.setZero();\n      Eigen::VectorXd diag(6);\n\n      // block_00 and block_11\n      K_block(1,5) = 6*Iz / std::pow(L,2);\n      K_block(2,4) = - 6*Iy / std::pow(L,2);\n      K_block = K_block.eval() +  K_block.transpose().eval();\n      K_eL.block<6,6>(0,0) = K_block;\n      K_eL.block<6,6>(6,6) = -K_block;\n\n      diag[0] = A/L;\n      diag[1] = 12*Iz / std::pow(L,3);\n      diag[2] = 12*Iy / std::pow(L,3);\n      diag[3] = Jx / (2*(1+mu)*L);\n      diag[4] = 4*Iy / L;\n      diag[5] = 4*Iz / L;\n      K_eL.block<6,6>(0,0) += Eigen::MatrixXd(diag.asDiagonal());\n      K_eL.block<6,6>(6,6) += Eigen::MatrixXd(diag.asDiagonal());\n\n      // block_01 and block_10\n      K_block.setZero();\n\n      K_block(1,5) = 6*Iz / std::pow(L,2);\n      K_block(2,4) = - 6*Iy / std::pow(L,2);\n      K_block = K_block.eval() - K_block.transpose().eval();\n      K_eL.block<6,6>(0,6) = K_block;\n      K_eL.block<6,6>(6,0) = -K_block;\n\n      diag[0] = -A/L;\n      diag[1] = -12*Iz / std::pow(L,3);\n      diag[2] = -12*Iy / std::pow(L,3);\n      diag[3] = -Jx / (2*(1+mu)*L);\n      diag[4] = 2*Iy / L;\n      diag[5] = 2*Iz / L;\n      K_eL.block<6,6>(0,6) += Eigen::MatrixXd(diag.asDiagonal());\n      K_eL.block<6,6>(6,0) += Eigen::MatrixXd(diag.asDiagonal());\n\n      K_eL *= E;\n    }\n  }\n}\n\n/**\n * @brief Get the Global to Local Rotation Matrix object\n * Calculates a 3x3 matrix to tranform the global xyz axis to the element local axis.\n * TODO: add info on the axis convention, we have different conventions with compas_fea (abaqus)\n * \n * The coordinate transformation matrix can be used to:\n *  - transform frame element end forces from the element (local) coordinate system\n *    to the structure (global) coordinate system\n *  - transfrom end displacements from the structural (global) coordinate system \n *    to the element (local) coordinate system,\n *  - transform the frame element stiffness and mass matrices\n *    from element (local) coordinates to structral (global) coordinates.\n * Symbolically, the return matrix R = {local}_R_{global}\n * \n * @param[in] end_vert_u \n * @param[in] end_vert_v \n * @param[out] rot_m 3x3 Eigen matrix, transforming global axis to local coordinate frame\n * @param[in] rot_y2x optional rotation of local y axis around the local x axis, defaults to zero\n */\nvoid getGlobal2LocalRotationMatrix(\n    const Eigen::VectorXd & end_vert_u,\n    const Eigen::VectorXd & end_vert_v,\n    Eigen::Matrix3d& rot_m,\n    const double& rot_y2x)\n{\n  assert(end_vert_u.size() == end_vert_v.size() && \"vert dimension not agree!\");\n  assert(end_vert_u.size() == 2 || end_vert_u.size() == 3);\n  int dim = end_vert_u.size();\n\n  // length of the element\n  double L = (end_vert_v - end_vert_u).norm();\n  // TODO: make tol as a common shared const\n  assert(L < 1e6 && \"vertices too close, might be duplicated pts.\");\n\n  // by convention, the new x axis is along the element's direction\n  // directional cosine of the new x axis in the global world frame\n  double c_x, c_y;\n  c_x = (end_vert_v[0] - end_vert_u[0]) / L;\n  c_y = (end_vert_v[1] - end_vert_u[1]) / L;\n\n  Eigen::Matrix3d R = Eigen::Matrix3d::Zero();\n\n  if (3 == dim)\n  {\n    double c_z = (end_vert_v[2] - end_vert_u[2]) / L;\n    auto rot_axis = Eigen::AngleAxisd(rot_y2x, Eigen::Vector3d::UnitZ());\n\n    if (abs(c_z) == 1.0)\n    {\n      // the element is parallel to global z axis\n      // cross product is not defined, in this case\n      // it's just a rotation about the global z axis\n      // in x-y plane\n      R(0, 2) = -c_z;\n      R(1, 1) = 1;\n      R(2, 0) = c_z;\n    }\n    else\n    {\n      // local x_axis = element's vector\n      auto new_x = Eigen::Vector3d(c_x, c_y, c_z);\n\n      // local y axis = cross product with global z axis\n      Eigen::Vector3d new_y = -new_x.cross(Eigen::Vector3d::UnitZ());\n      new_y.normalize();\n\n      auto new_z = new_x.cross(new_y);\n\n      R.block<3, 1>(0, 0) = new_x;\n      R.block<3, 1>(0, 1) = new_y;\n      R.block<3, 1>(0, 2) = new_z;\n    }\n    // This is essential!\n    R = R * rot_axis;\n    rot_m = R.transpose();\n  }\n  else\n  {\n    // 2D rotational matrix\n    R(0,0) = c_x;\n    R(0,1) = c_y;\n    R(1,0) = -c_y;\n    R(1,1) = c_x;\n    R(2,2) = 1;\n\n    auto rot_axis = Eigen::AngleAxisd(rot_y2x, Eigen::Vector3d::UnitZ());\n    assert((R - rot_axis.toRotationMatrix()).norm() > 1e-3);\n\n    rot_m = R;\n  }\n}\n\nvoid getNodePoints(const Eigen::MatrixXd& Vertices, const int& end_u_id, const int& end_v_id, \n  Eigen::VectorXd& end_u, Eigen::VectorXd& end_v)\n{\n  end_u = Eigen::VectorXd(3);\n  end_u << Vertices(end_u_id, 0), Vertices(end_u_id, 1), Vertices(end_u_id, 2);\n  end_v = Eigen::VectorXd(3);\n  end_v << Vertices(end_v_id, 0), Vertices(end_v_id, 1), Vertices(end_v_id, 2);\n}\n\n} // namespace stiffness_checker\n} // namespace conmech\n", "meta": {"hexsha": "265b4fb107c02ecc068a5ff00286229658f39823", "size": 5527, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/stiffness_checker/Util.cpp", "max_stars_repo_name": "yijiangh/conmech", "max_stars_repo_head_hexsha": "9f24230f08587c5e62e3b482f8829f5ea449a169", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-12-10T17:52:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-12T05:49:34.000Z", "max_issues_repo_path": "src/stiffness_checker/Util.cpp", "max_issues_repo_name": "yijiangh/conmech", "max_issues_repo_head_hexsha": "9f24230f08587c5e62e3b482f8829f5ea449a169", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 32.0, "max_issues_repo_issues_event_min_datetime": "2018-11-28T04:00:24.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-14T21:20:38.000Z", "max_forks_repo_path": "src/stiffness_checker/Util.cpp", "max_forks_repo_name": "yijiangh/conmech", "max_forks_repo_head_hexsha": "9f24230f08587c5e62e3b482f8829f5ea449a169", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-23T01:19:00.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-23T01:19:00.000Z", "avg_line_length": 31.4034090909, "max_line_length": 97, "alphanum_fraction": 0.6032205536, "num_tokens": 1785, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107896491796, "lm_q2_score": 0.7490872187162396, "lm_q1q2_score": 0.7020526237691547}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include <vector>\n#include <array>\n#include <string>\n#include <cmath>\n\n#include \"../include/input_parser.h\"\n#include \"../include/ply.h\"\n#include \"../include/laminate.h\"\n\nusing std::cin; using std::cout; using std::endl;\nusing std::string;\nusing std::vector;\nusing Eigen::Matrix; using Eigen::Matrix3d; using Eigen::Vector3d;\n\n// Get the mid-plane strain of the laminate.\nvoid solve_mid_strain(laminate& lam, Matrix<double, 6, 1>& load_vector);\n\n// Get the stresses and strains for each sampling point of the laminate.\nvoid solve_stress_strain_profile(laminate& lam, double pt_spacing);\n\n// Construct laminate from a vector of ply, the input load, and the spacing\n// between sampling points.\nlaminate::laminate(vector<ply>& ply_vector, Matrix<double, 6, 1>& load_vector,\n                    double pt_spacing): \n        ply_vector_(ply_vector), load_vector_(load_vector) {\n    height_ = 0.;\n    for (auto it = ply_vector_.begin(); it != ply_vector_.end(); it++) {\n        height_ += it->thickness_;\n    }\n    \n    A_ = Matrix3d::Zero();\n    B_ = Matrix3d::Zero();\n    D_ = Matrix3d::Zero();\n    double bottom_coordinate = -height_/2;\n    for (auto it = ply_vector_.begin(); it != ply_vector_.end(); it++) {\n        double top_coordinate = bottom_coordinate + it->thickness_;\n        A_ = A_ + it->Qbar_ * (top_coordinate - bottom_coordinate);\n        B_ = B_ + 1./2 * it->Qbar_ \n            * (pow(top_coordinate, 2) - pow(bottom_coordinate, 2));\n        D_ = D_ + 1./3 * it->Qbar_\n            * (pow(top_coordinate, 3) - pow(bottom_coordinate, 3));\n        \n        bottom_coordinate = top_coordinate;\n    }\n    solve_mid_strain(*this, load_vector_);\n    solve_stress_strain_profile(*this, pt_spacing);\n\n}\n\nvoid solve_mid_strain(laminate& lam, Matrix<double, 6, 1>& load_vector) {\n    Matrix<double, 6, 6> stiffness = Matrix<double, 6, 6>::Zero();\n    stiffness.block<3, 3>(0, 0) = lam.A_;\n    stiffness.block<3, 3>(0, 3) = lam.B_;\n    stiffness.block<3, 3>(3, 0) = lam.B_;\n    stiffness.block<3, 3>(3, 3) = lam.D_;\n    Matrix<double, 6, 1> strain_vector = \n        stiffness.colPivHouseholderQr().solve(load_vector);\n    lam.mid_strain_ = strain_vector.head<3>();\n    lam.mid_curvature_ = strain_vector.tail<3>();\n}\n\nvoid solve_stress_strain_profile(laminate& lam, double pt_spacing) {\n       \n    lam.profile_pt_.push_back(-lam.height_/2);\n    lam.strains_.push_back(\n        lam.mid_strain_ + lam.profile_pt_.back() * lam.mid_curvature_);\n    vector<ply>::size_type current_layer = 0;  \n    lam.stresses_.push_back(\n        lam.ply_vector_[current_layer].Qbar_ * lam.strains_.back());\n\n    double current_bottom_pt = -lam.height_/2;\n    double current_top_pt = current_bottom_pt\n                          + lam.ply_vector_[current_layer].thickness_;\n    while (lam.profile_pt_.back() <= lam.height_/2) {\n        double next_profile_pt = lam.profile_pt_.back() + pt_spacing;\n        if (next_profile_pt > current_top_pt) {\n            current_bottom_pt = current_top_pt;\n            current_layer++;\n            current_top_pt = current_bottom_pt\n                           + lam.ply_vector_[current_layer].thickness_;\n        }\n        lam.profile_pt_.push_back(lam.profile_pt_.back() + pt_spacing);\n        lam.strains_.push_back(\n            lam.mid_strain_ + lam.profile_pt_.back() * lam.mid_curvature_);\n        lam.stresses_.push_back(\n            lam.ply_vector_[current_layer].Qbar_ * lam.strains_.back());\n    }\n}\n\n\n", "meta": {"hexsha": "9071f242e9cfc8a0aaa7ec928b2a924666098b80", "size": 3470, "ext": "cc", "lang": "C++", "max_stars_repo_path": "lib/laminate.cc", "max_stars_repo_name": "quentin-tw/laminate_calc", "max_stars_repo_head_hexsha": "d70718ab1092e502f8e467c57d1284eddf8836f2", "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": "lib/laminate.cc", "max_issues_repo_name": "quentin-tw/laminate_calc", "max_issues_repo_head_hexsha": "d70718ab1092e502f8e467c57d1284eddf8836f2", "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": "lib/laminate.cc", "max_forks_repo_name": "quentin-tw/laminate_calc", "max_forks_repo_head_hexsha": "d70718ab1092e502f8e467c57d1284eddf8836f2", "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.311827957, "max_line_length": 78, "alphanum_fraction": 0.6521613833, "num_tokens": 923, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107949104865, "lm_q2_score": 0.749087201911703, "lm_q1q2_score": 0.7020526119609393}}
{"text": "/***************************************************************************\n *  @file       matrix_chain_mutiply.hpp\n *  @author     Alan.W\n *  @date       03  August 2014\n *  @remark     CLRS Algorithms implementation, using C++ templates.\n ***************************************************************************/\n\n//!\n//! ex15.2-2\n//! Give a recursive algorithm MATRIX-CHAIN-MULTIPLY(A, s, i, j) that actually\n//! performs the optimal matrix-chain multiplication, given the sequence of matrices\n//! {A1,A2,...An}, the s table computed by MATRIX-CHAIN-ORDER , and the indices i and j .\n//! (The initial call would be MATRIX-CHAIN-MULTIPLY (A, s, 1, n))\n//!\n//  check the lambda in function matrix_chain_multiply.\n//!\n\n#ifndef MATRIX_CHAIN_MUTIPLY_HPP\n#define MATRIX_CHAIN_MUTIPLY_HPP\n\n#include <vector>\n#include <functional>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include \"matrix_chain_order.hpp\"\n\n\nnamespace ch15 {\n\n//! foward declarations\ntemplate<typename Range>\nvoid\nbuild_chain(ch15::Chain<typename Range::value_type>& chain,\n            const Range& dimensions,\n            const typename Range::value_type& init_val = 0);\n\ntemplate<typename Range>\nvoid\nbuild_dimensions(const ch15::Chain<typename Range::value_type>& chain,\n                 Range& dimensions);\n\ntemplate<typename T>\nvoid print_matrix_chain(const ch15::Chain<T>& chain);\n\ntemplate<typename T>\nch15::Matrix<T>\nmatrix_chain_multiply(const ch15::Chain<T>& chain);\n\n\n\n\n/**\n * @brief build_chain\n * @param chain\n * @param dimensions\n *\n * build a matrix chain using dimemsions stored in a stl container\n */\ntemplate<typename Range>\ninline void\nbuild_chain(ch15::Chain<typename Range::value_type>& chain,\n            const Range& dimensions,\n            const typename Range::value_type& init_val)\n{\n    using ValueType =   typename Range::value_type;\n\n    for(auto it = dimensions.begin(); it != dimensions.end() - 1; ++it)\n    {\n        auto mat = ch15::Matrix<ValueType>(*it, *(it + 1), init_val);\n        chain.push_back(mat);\n    }\n}\n\n/**\n * @brief print_matrix_chain\n * @param chain\n */\ntemplate<typename T>\ninline void\nprint_matrix_chain(const ch15::Chain<T>& chain)\n{\n    for(const auto& mat : chain)\n        std::cout << mat << std::endl << std::endl;\n}\n\n/**\n * @brief build_dimensions\n * @param chain\n * @param dimensions\n *\n * build dimensions from matrix chain\n */\ntemplate<typename Range>\ninline void\nbuild_dimensions(const ch15::Chain<typename Range::value_type>& chain,\n                 Range& dimensions)\n{\n    dimensions.push_back( chain.begin()->size1() );\n    for(const auto& mat : chain)\n        dimensions.push_back( mat.size2());\n}\n\n/**\n * @brief matrix_chain_multiply\n * @param chain\n *\n * @complx  O(n^3)\n * for ex15.2-2\n */\ntemplate<typename T>\nch15::Matrix<T>\nmatrix_chain_multiply(const ch15::Chain<T>& chain)\n{\n    //! type def for MatrixChainOrder's parameter\n    using RangeType =   std::vector<T>;\n    using SizeType  =   typename ch15::Matrix<T>::size_type;\n\n    //! build dimensions\n    RangeType dimens;\n    ch15::build_dimensions(chain, dimens);\n\n    //! build optimal order\n    ch15::MatrixChainOrder<RangeType> order(dimens);\n    order.build();\n    order.print_optimal(1,chain.size());\n    std::cout << std::endl;\n\n    //! lambda to do the real job recursively\n    //! @note   ex15.2-2\n    std::function<ch15::Matrix<T>(SizeType,SizeType)> multiply\n            = [&](SizeType head, SizeType tail)\n    {\n        //! @attention below is the pseudocode for ex15.2-2\n        if(head == tail)\n            return chain[head - 1];\n        else\n            return multiply(head, order.s(head - 1,tail - 2))\n                   *\n                   multiply(order.s(head - 1,tail - 2) + 1, tail);\n    };\n\n    //! return the product\n    return multiply(1, chain.size());\n}\n\n}//namepspace\n#endif // MATRIX_CHAIN_MUTIPLY_HPP\n\n//! test: build_chain\n//!     : build_dimensions\n//#include <iostream>\n//#include <boost/numeric/ublas/io.hpp>\n//#include \"color.hpp\"\n//#include \"matrix.hpp\"\n//#include \"matrix_chain_mutiply.hpp\"\n//#include \"matrix_chain_order.hpp\"\n\n//int main()\n//{\n//    std::vector<int> v = {30,35,15,5,10,20,25};\n\n//    ch15::Chain<int> chain;\n//    ch15::build_chain(chain, v, 2);\n//    ch15::print_matrix_chain(chain);\n\n//    std::vector<int> dimens;\n//    ch15::build_dimensions(chain, dimens);\n//    for(auto d : dimens)\n//        std::cout << d << \" \";\n\n//    std::cout << color::red(\"\\nend\\n\");\n//    return 0;\n//}\n\n//! @test   matrix_chain_multiply\n//!         ex15.2-2\n//#include <iostream>\n//#include <boost/numeric/ublas/io.hpp>\n//#include \"color.hpp\"\n//#include \"matrix.hpp\"\n//#include \"matrix_chain_mutiply.hpp\"\n//#include \"matrix_chain_order.hpp\"\n\n//int main()\n//{\n//    std::vector<int> v = {30,35,15,5,10,20,25};\n\n//    ch15::Chain<int> chain;\n//    ch15::build_chain(chain, v, 2);\n//    std::cout << ch15::matrix_chain_multiply(chain) << std::endl;\n\n//    std::cout << color::red(\"\\nend\\n\");\n//    return 0;\n//}\n\n\n", "meta": {"hexsha": "bc6a73244160bf774572d7d19fa70ea745fe6228", "size": 4982, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ch15/matrix_chain_mutiply.hpp", "max_stars_repo_name": "klong13579/cppL", "max_stars_repo_head_hexsha": "7aa8afaf2d2e17578c7fd91654bedcccf0a6baab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 261.0, "max_stars_repo_stars_event_min_datetime": "2015-01-11T20:42:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T01:33:39.000Z", "max_issues_repo_path": "ch15/matrix_chain_mutiply.hpp", "max_issues_repo_name": "LeungGeorge/CLRS", "max_issues_repo_head_hexsha": "7aa8afaf2d2e17578c7fd91654bedcccf0a6baab", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-04-05T11:49:45.000Z", "max_issues_repo_issues_event_max_datetime": "2017-02-19T08:29:52.000Z", "max_forks_repo_path": "ch15/matrix_chain_mutiply.hpp", "max_forks_repo_name": "LeungGeorge/CLRS", "max_forks_repo_head_hexsha": "7aa8afaf2d2e17578c7fd91654bedcccf0a6baab", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 98.0, "max_forks_repo_forks_event_min_datetime": "2015-01-03T12:58:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-16T07:29:31.000Z", "avg_line_length": 25.2893401015, "max_line_length": 89, "alphanum_fraction": 0.6224407868, "num_tokens": 1277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795402, "lm_q2_score": 0.8740772417253256, "lm_q1q2_score": 0.702035944781813}}
{"text": "#pragma once\n\n/// This file contains definitions of aliases for basic vector classes and functions\n\n#include <Core/RaCore.hpp>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/Sparse>\n#include <functional>\n#include <unsupported/Eigen/AlignedVector3>\n\n#include <Core/Math/Math.hpp>\n#include <Core/Types.hpp>\n\nnamespace Ra {\nnamespace Core {\nnamespace Math {\n//\n// Common vector types\n//\n\ninline void print( const MatrixN& matrix );\n\n//\n// Geometry types\n//\n\n// Todo : storage transform using quaternions ?\n\n//\n// Vector Functions\n//\n\n/// Component-wise floor() function on a floating-point vector.\ntemplate <typename Vector>\ninline Vector floor( const Vector& v );\n\n/// Component-wise ceil() function on a floating-point vector.\ntemplate <typename Vector>\ninline Vector ceil( const Vector& v );\n\n/// Component-wise trunc() function on a floating-point vector\ntemplate <typename Vector>\ninline Vector trunc( const Vector& v );\n\n/// Component-wise clamp() function on a floating-point vector.\n\ntemplate <typename Derived, typename DerivedA, typename DerivedB>\ninline typename Derived::PlainMatrix clamp( const Eigen::MatrixBase<Derived>& v,\n                                            const Eigen::MatrixBase<DerivedA>& min,\n                                            const Eigen::MatrixBase<DerivedB>& max );\n/// Component-wise clamp() function on a floating-point vector.\ntemplate <typename Derived>\ninline typename Derived::PlainMatrix\nclamp( const Eigen::MatrixBase<Derived>& v, const Scalar& min, const Scalar& max );\n\n/// Call std::isnormal on quaternion entries.\ntemplate <typename S>\ninline bool checkInvalidNumbers( Eigen::Ref<Eigen::Quaternion<S>> q,\n                                 const bool FAIL_ON_ASSERT = false ) {\n    return checkInvalidNumbers( q.coeffs(), FAIL_ON_ASSERT );\n}\n\n/// Call std::isnormal on matrix entry.\n/// Dense version\ntemplate <typename Matrix_>\ninline bool checkInvalidNumbers( Eigen::Ref<const Matrix_> matrix,\n                                 const bool FAIL_ON_ASSERT = false );\n\n/// Get two vectors orthogonal to a given vector.\n/// \\warning fx must be normalized (this is not checked in the function)\ninline void\ngetOrthogonalVectors( const Vector3& fx, Eigen::Ref<Vector3> fy, Eigen::Ref<Vector3> fz );\n\n/// Get the angle between two vectors. Works for types where the cross product is\n/// defined (i.e. 2D and 3D vectors).\ntemplate <typename Vector_>\ninline Scalar angle( const Vector_& v1, const Vector_& v2 );\n\n/// Get the spherical linear interpolation between two unit non-colinear vectors.\n/// works for types where the cross-product is defined (i.e. 2D and 3D vectors).\ntemplate <typename Vector_>\ninline Vector_ slerp( const Vector_& v1, const Vector_& v2, Scalar t );\n\n/// @return the projection of point on the plane define by plane and planeNormal\ninline Vector3\nprojectOnPlane( const Vector3& planePos, const Vector3& planeNormal, const Vector3& point );\n\n/// Get the cotangent of the angle between two vectors. Works for vector types where\n/// dot and cross product is defined (2D or 3D vectors).\ntemplate <typename Vector_>\ninline Scalar cotan( const Vector_& v1, const Vector_& v2 );\n\n/// Get the cosine of the angle between two vectors.\n/// \\todo use dot instead\ntemplate <typename Vector_>\ninline Scalar cos( const Vector_& v1, const Vector_& v2 );\n\n/// Normalize a vector and returns its norm before normalization.\n/// If the vector's norm is 0, the vector's components will be overwritten by NaNs\ntemplate <typename Vector_>\ninline Scalar getNormAndNormalize( Vector_& v );\n\n/// Normalize a vector and returns its norm before normalization.\n/// If the vector's norm is 0, the vector remains null\ntemplate <typename Vector_>\ninline Scalar getNormAndNormalizeSafe( Vector_& v );\n\n/// Transform a ray, direction is only transformed by linear part of the\n/// transformation, while origin is fully transformed\n/// corresponds to t*r\n/// \\param t : transform matrix\n/// \\param r : ray to transform\n/// \\return transoformed ray, origine is translated while direction is only\n/// linarly transformed.\ntemplate <typename Scalar>\ninline Eigen::ParametrizedLine<Scalar, 3>\ntransformRay( const Eigen::Transform<Scalar, 3, Eigen::Affine>& t,\n              const Eigen::ParametrizedLine<Scalar, 3>& r );\n\ninline Matrix4 lookAt( const Vector3& position, const Vector3& target, const Vector3& up );\ninline Matrix4 perspective( Scalar fovy, Scalar aspect, Scalar near, Scalar zfar );\ninline Matrix4\northographic( Scalar left, Scalar right, Scalar bottom, Scalar top, Scalar near, Scalar zfar );\n\n//\n// Quaternion functions\n//\n\n// Define functions for multiplying a quaternion by a scalar\n// and adding two quaternions. While Quaternion is supposed to\n// represent a unit quaternion (thus a valid rotation), these functions\n// are useful for linear interpolation of quaternions.\n\n/// Returns the quaternion q multipled by a scalar factor of k.\ninline Quaternion scale( const Quaternion& q, const Scalar k );\n\n/// Returns the sum of two quaternions.\ninline Quaternion add( const Quaternion& q1, const Quaternion& q2 );\n\n/// Returns the sum of two quaternions, resolving antipodality by flipping\n/// the sign of q2 if q1.q2 is negative. This operation is usually\n/// denoted as a circled + sign, forming the basis of the QLERP algorithm.\n/// See \"Spherical Blend Skinning\" (Kavan & Zara 2005) for more details.\ninline Quaternion addQlerp( const Quaternion& q1, const Quaternion& q2 );\n\n// Note : the .inl file also define operator+ for quaternions\n// and operator * and / between quaternions and scalar.\n\n/// Decompose a given rotation Qin into a swing rotation and a twist rotation.\n/// Qswing is a rotation whose axis lies in the XY plane and Qtwist is a rotation about axis Z.\n/// such as Qin = Qswing * Qtwist\n/// If the rotation is already around axis z, Qswing will be set to identity\n/// and Qtwist equal to Qin\ninline void getSwingTwist( const Quaternion& in, Quaternion& swingOut, Quaternion& twistOut );\n\n} // namespace Math\n} // namespace Core\n} // namespace Ra\n#include <Core/Math/LinearAlgebra.inl>\n", "meta": {"hexsha": "6c7874ede1fb4ce7248e195480535a7af9cfd964", "size": 6069, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Core/Math/LinearAlgebra.hpp", "max_stars_repo_name": "Yasoo31/Radium-Engine", "max_stars_repo_head_hexsha": "e22754d0abe192207fd946509cbd63c4f9e52dd4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 78.0, "max_stars_repo_stars_event_min_datetime": "2017-12-01T12:23:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T05:08:09.000Z", "max_issues_repo_path": "src/Core/Math/LinearAlgebra.hpp", "max_issues_repo_name": "Yasoo31/Radium-Engine", "max_issues_repo_head_hexsha": "e22754d0abe192207fd946509cbd63c4f9e52dd4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 527.0, "max_issues_repo_issues_event_min_datetime": "2017-09-25T13:05:32.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T18:47:44.000Z", "max_forks_repo_path": "src/Core/Math/LinearAlgebra.hpp", "max_forks_repo_name": "Yasoo31/Radium-Engine", "max_forks_repo_head_hexsha": "e22754d0abe192207fd946509cbd63c4f9e52dd4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 48.0, "max_forks_repo_forks_event_min_datetime": "2018-01-04T22:08:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T08:13:41.000Z", "avg_line_length": 37.462962963, "max_line_length": 95, "alphanum_fraction": 0.7324106113, "num_tokens": 1385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096227509861, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.7020089851734443}}
{"text": "#pragma once\n\n#include \"BinomialCoefficient.hh\"\n#include <Eigen/Core>\n\nnamespace kt84 {\n\ntemplate <int _DimIn, int _Degree>\nstruct PolynomialBasisGenT {\n    enum { DimOut = PolynomialBasisGenT<_DimIn, _Degree - 1>::DimOut + BinomialCoefficient<_DimIn + _Degree - 1, _Degree>::Value };\n    typedef Eigen::Matrix<double, _DimIn , 1> Point;\n    typedef Eigen::Matrix<double, DimOut, 1> Basis;\n    typedef Eigen::Matrix<double, DimOut, _DimIn> Gradient;\n    \n    static Basis basis(const Point& x) {\n        const int N = BinomialCoefficient<_DimIn + _Degree - 1, _Degree>::Value;\n        Eigen::Matrix<double, N, 1> result_partial;\n        int index_out = 0;\n        int index_in[_Degree];\n        for (int i = 0; i < _Degree; ++i)\n            index_in[i] = 0;\n        while (true) {\n            double d = 1;\n            for (int i = 0; i < _Degree; ++i)\n                d *= x[index_in[i]];\n            result_partial[index_out++] = d;\n            int is_complete = true;\n            for (int i = _Degree - 1; i >= 0; --i) {\n                if (index_in[i] == _DimIn - 1)\n                    continue;\n                ++index_in[i];\n                for (int j = i + 1; j < _Degree; ++j)\n                    index_in[j] = index_in[i];\n                is_complete = false;\n                break;\n            }\n            if (is_complete)\n                break;\n        }\n        Basis result;\n        result << PolynomialBasisGenT<_DimIn, _Degree - 1>::basis(x), result_partial;\n        return result;\n    }\n    static Gradient gradient(const Point& x) {\n        const int N = BinomialCoefficient<_DimIn + _Degree - 1, _Degree>::Value;\n        Eigen::Matrix<double, N, _DimIn> result_partial;\n        int index_out = 0;\n        int index_in[_Degree];\n        for (int i = 0; i < _Degree; ++i)\n            index_in[i] = 0;\n        while (true) {\n            for (int i = 0; i < _DimIn; ++i) {\n                int cnt = 0;\n                double d = 1;\n                for (int j = 0; j < _Degree; ++j) {\n                    if (index_in[j] == i) {\n                        ++cnt;\n                        continue;\n                    }\n                    d *= x[index_in[j]];\n                }\n                result_partial(index_out, i) = cnt == 0 ? 0 : cnt * d * std::pow(x[i], cnt - 1);\n            }\n            ++index_out;\n            int is_complete = true;\n            for (int i = _Degree - 1; i >= 0; --i) {\n                if (index_in[i] == _DimIn - 1)\n                    continue;\n                ++index_in[i];\n                for (int j = i + 1; j < _Degree; ++j)\n                    index_in[j] = index_in[i];\n                is_complete = false;\n                break;\n            }\n            if (is_complete)\n                break;\n        }\n        Gradient result;\n        result << PolynomialBasisGenT<_DimIn, _Degree - 1>::gradient(x), result_partial;\n        return result;\n    }\n};\n\ntemplate <int _DimIn>\nstruct PolynomialBasisGenT<_DimIn, 0> {\n    enum { DimOut = 1 };\n    typedef Eigen::Matrix<double, _DimIn , 1> Point;\n    typedef Eigen::Matrix<double, DimOut, 1> Basis;\n    typedef Eigen::Matrix<double, DimOut, _DimIn> Gradient;\n    \n    static Basis basis(const Point& x) { return Basis::Constant(1); }\n    static Gradient gradient(const Point& x) { return Gradient::Zero(); }\n};\n\n}\n\n", "meta": {"hexsha": "60096e22af1bf8debb3410d1eb93ded1c5f13769", "size": 3316, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/kt84/math/PolynomialBasisGen.hh", "max_stars_repo_name": "honoriocassiano/skbar", "max_stars_repo_head_hexsha": "e2a8fca752f5a2f9d9a32f19cbe1f9032a0e1ac4", "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/kt84/math/PolynomialBasisGen.hh", "max_issues_repo_name": "honoriocassiano/skbar", "max_issues_repo_head_hexsha": "e2a8fca752f5a2f9d9a32f19cbe1f9032a0e1ac4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2020-09-01T12:16:28.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-01T12:21:41.000Z", "max_forks_repo_path": "src/kt84/math/PolynomialBasisGen.hh", "max_forks_repo_name": "honoriocassiano/skbar", "max_forks_repo_head_hexsha": "e2a8fca752f5a2f9d9a32f19cbe1f9032a0e1ac4", "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.1855670103, "max_line_length": 131, "alphanum_fraction": 0.4927623643, "num_tokens": 866, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897542390751, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.7019599251923726}}
{"text": "#include \"RSA.h\"\n#include \"DataStream.h\"\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/multiprecision/miller_rabin.hpp>\n#include <utility>\nusing boost::multiprecision::cpp_int;\n\n\nRSAClient::RSAClient(size_t _bit_size, int _e) {\n    bit_size = _bit_size;\n    e = _e;\n    cpp_int p = gen_prime(bit_size, _e);\n    cpp_int q = gen_prime(bit_size, _e);\n    n = p * q;\n    cpp_int toit = (p - 1) * (q - 1); // since (p,q) are prime\n    do {\n        d = inv_mod(e, toit);\n        if(!d) e++;\n    } while (d == 0);\n}\n\nRSA_key RSAClient::get_public_key() {\n    return std::make_pair(e, n);\n}\n\nDataStream RSAClient::decrypt(const DataStream &cipher) {\n    return DataStream(powm(cipher.getCppInt(), d, n), bit_size*2);\n}\n\nDataStream encrypt(const DataStream &ds, const RSA_key &key, size_t bit_size) {\n    return DataStream(powm(ds.getCppInt(), key.first, key.second), bit_size*2);\n}\n\ncpp_int inv_mod(const cpp_int &num, const cpp_int &mod) {\n    cpp_int r0 = mod, r1 = num;\n    cpp_int t0 = 0, t1 = 1;\n    while(r1 != 0) {\n        cpp_int q = r0 / r1;\n        cpp_int r2 = r0 - q * r1;\n        cpp_int t2 = t0 - q * t1;\n        r0 = r1;\n        r1 = r2;\n        t0 = t1;\n        t1 = t2;\n    }\n    if(r0 > 1) {\n        return 0;\n    }\n    return (t0 + mod) % mod;\n}\n\n\ncpp_int gen_prime(size_t bit_size, int no_div) {\n    cpp_int prime;\n    do {\n        if(no_div > 0) {\n            do {\n                prime = get_random_key(bit_size / 8).getCppInt();\n            } while ((prime - 1) % no_div == 0);\n        } else {\n            prime = get_random_key(bit_size / 8).getCppInt();\n        }\n    } while(!miller_rabin_test(prime, 100));\n    return prime;\n}\n", "meta": {"hexsha": "f95a7f46c50253c73c05d3fefc2d40f02386560e", "size": 1661, "ext": "cc", "lang": "C++", "max_stars_repo_path": "RSA.cc", "max_stars_repo_name": "breadknock/crypto_tools", "max_stars_repo_head_hexsha": "bf6726d49f5be24ed88ebb10d2a22b221c42f008", "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": "RSA.cc", "max_issues_repo_name": "breadknock/crypto_tools", "max_issues_repo_head_hexsha": "bf6726d49f5be24ed88ebb10d2a22b221c42f008", "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": "RSA.cc", "max_forks_repo_name": "breadknock/crypto_tools", "max_forks_repo_head_hexsha": "bf6726d49f5be24ed88ebb10d2a22b221c42f008", "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.1666666667, "max_line_length": 79, "alphanum_fraction": 0.5719446117, "num_tokens": 527, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897558991953, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.7019599211202718}}
{"text": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n#include \"powerscore.h\"\n\nvoid PowerScoreWorker::ComputeEigenValueCentrality(Eigen::MatrixXd A, Eigen::RowVectorXd &powerScores) {\n  int dimension = A.rows();\n  int idxMax;\n  float epsilon = 1e-6;\n  Eigen::MatrixXd T(dimension, dimension);\n  Eigen::MatrixXd I(dimension, dimension);\n  Eigen::MatrixXd Ones(dimension, dimension);\n  Eigen::MatrixXd denominator(dimension, dimension);\n  Eigen::VectorXd rowSum(dimension);\n  I = Eigen::MatrixXd::Identity(dimension, dimension);\n  Ones = Eigen::MatrixXd::Zero(dimension, dimension);\n  Ones.setOnes(dimension, dimension);\n  denominator = Eigen::MatrixXd::Zero(dimension, dimension);\n  powerScores = Eigen::RowVectorXd(dimension);\n  // Compute the transition matrix T from the aggression matrix A\n  // Start constructing T by adding eps to non-diagonal elements of A\n  T = A + epsilon * (Ones - I);\n  // Compute row sums for normalization to conditional probabilities\n  rowSum = T.rowwise().sum();\n  denominator = rowSum.replicate(1, dimension);\n  // Perform element wise division to get the transition matrix\n  T = T.array() / denominator.array();\n  // Compute eigenvalues and eigenvectors of the transpose of T (to get left hand eigenvalues)\n  Eigen::EigenSolver<Eigen::MatrixXd> es(T.transpose());\n  // Find the eigenvalue with the largest absolute value\n  es.eigenvalues().array().abs().maxCoeff(&idxMax);\n  // Pick the corresponding eigenvector, and compute power score\n  powerScores = es.eigenvectors().transpose().row(idxMax).array().abs();\n}\n", "meta": {"hexsha": "f380803b405bf5672f1aa1b26e12245dd8545fd3", "size": 1603, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/powerscore.cc", "max_stars_repo_name": "danm0nster/node-napi-example-eigenvalue", "max_stars_repo_head_hexsha": "eb8fdc9c175df55a1013c878ad8bcae401ff1fae", "max_stars_repo_licenses": ["0BSD"], "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/powerscore.cc", "max_issues_repo_name": "danm0nster/node-napi-example-eigenvalue", "max_issues_repo_head_hexsha": "eb8fdc9c175df55a1013c878ad8bcae401ff1fae", "max_issues_repo_licenses": ["0BSD"], "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/powerscore.cc", "max_forks_repo_name": "danm0nster/node-napi-example-eigenvalue", "max_forks_repo_head_hexsha": "eb8fdc9c175df55a1013c878ad8bcae401ff1fae", "max_forks_repo_licenses": ["0BSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.3243243243, "max_line_length": 104, "alphanum_fraction": 0.7398627573, "num_tokens": 383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897442783527, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.7019599177602892}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace Eigen;\n\ntemplate <class Matrix>\n\n// The auxiliary function Atimesx computes the function A*x in a smart way, using the particular structure of the matrix A.\n\nvoid Atimesx(const Matrix & d, const Matrix & a, const Matrix & x, Matrix & Ax)\n{\n    int n=d.size();\n    Ax=(d.array()*x.array()).matrix();\n    VectorXd Axcut=Ax.head(n-1);\n    VectorXd acut = a.head(n-1);\n    VectorXd xcut = x.head(n-1);\n    \n    Ax << Axcut + x(n-1)*acut, Ax(n-1)+ acut.transpose()*xcut;\n}\n\n// We compute A*A*x by using the function Atimesx twice with 5 dimensional random vectors.\n\nint main(void)\n{\n    VectorXd a=VectorXd::Random(5);\n    VectorXd d=VectorXd::Random(5);\n    VectorXd x=VectorXd::Random(5);\n    VectorXd Ax(5);\n    \n    Atimesx(d,a,x,Ax);\n    VectorXd AAx(5);\n    Atimesx(d,a,Ax,AAx);\n    std::cout << \"A*A*x = \" << AAx << std::endl;\n}\n", "meta": {"hexsha": "f3741dcd99b8a207eebd3613265615ccb87eb7ea", "size": 891, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/PS1/solutions_ps1/C++/arrowmatvec2.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++/arrowmatvec2.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++/arrowmatvec2.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": 25.4571428571, "max_line_length": 123, "alphanum_fraction": 0.6386083053, "num_tokens": 269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9263037384317888, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.7019477641411291}}
{"text": "// Copyright Paul A. Bristow 2015.\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// Note that this file contains Quickbook mark-up as well as code\n// and comments, don't change any of the special comment mark-ups!\n\n// Example of root finding using Boost.Multiprecision.\n\n#ifndef BOOST_MATH_STANDALONE\n\n#include <boost/math/tools/roots.hpp>\n//using boost::math::policies::policy;\n//using boost::math::tools::newton_raphson_iterate;\n//using boost::math::tools::halley_iterate;\n//using boost::math::tools::eps_tolerance; // Binary functor for specified number of bits.\n//using boost::math::tools::bracket_and_solve_root;\n//using boost::math::tools::toms748_solve;\n\n#include <boost/math/special_functions/next.hpp> // For float_distance.\n#include <boost/math/special_functions/pow.hpp>\n#include <boost/math/constants/constants.hpp>\n\n//[root_finding_multiprecision_include_1\n#include <boost/multiprecision/cpp_bin_float.hpp> // For cpp_bin_float_50.\n#include <boost/multiprecision/cpp_dec_float.hpp> // For cpp_dec_float_50.\n#ifndef _MSC_VER  // float128 is not yet supported by Microsoft compiler at 2013.\n#  include <boost/multiprecision/float128.hpp> // Requires libquadmath.\n#endif\n//] [/root_finding_multiprecision_include_1]\n\n#include <iostream>\n// using std::cout; using std::endl;\n#include <iomanip>\n// using std::setw; using std::setprecision;\n#include <limits>\n// using std::numeric_limits;\n#include <tuple>\n#include <utility> // pair, make_pair\n\n// #define BUILTIN_POW_GUESS // define to use std::pow function to obtain a guess.\n\ntemplate <class T>\nT cbrt_2deriv(T x)\n{ // return cube root of x using 1st and 2nd derivatives and Halley.\n  using namespace std;  // Help ADL of std functions.\n  using namespace boost::math::tools; // For halley_iterate.\n\n  // If T is not a binary floating-point type, for example, cpp_dec_float_50\n  // then frexp may not be defined,\n  // so it may be necessary to compute the guess using a built-in type,\n  // probably quickest using double, but perhaps with float or long double.\n  // Note that the range of exponent may be restricted by a built-in-type for guess.\n\n  typedef long double guess_type;\n\n#ifdef BUILTIN_POW_GUESS\n  guess_type pow_guess = std::pow(static_cast<guess_type>(x), static_cast<guess_type>(1) / 3);\n  T guess = pow_guess;\n  T min = pow_guess /2;\n  T max = pow_guess * 2;\n#else\n  int exponent;\n  frexp(static_cast<guess_type>(x), &exponent); // Get exponent of z (ignore mantissa).\n  T guess = ldexp(static_cast<guess_type>(1.), exponent / 3); // Rough guess is to divide the exponent by three.\n  T min = ldexp(static_cast<guess_type>(1.) / 2, exponent / 3); // Minimum possible value is half our guess.\n  T max = ldexp(static_cast<guess_type>(2.), exponent / 3); // Maximum possible value is twice our guess.\n#endif\n\n  int digits = std::numeric_limits<T>::digits / 2; // Half maximum possible binary digits accuracy for type T.\n  const std::uintmax_t maxit = 20;\n  std::uintmax_t it = maxit;\n  T result = halley_iterate(cbrt_functor_2deriv<T>(x), guess, min, max, digits, it);\n  // Can show how many iterations (updated by halley_iterate).\n  // std::cout << \"Iterations \" << it << \" (from max of \"<< maxit << \").\" << std::endl;\n  return result;\n} // cbrt_2deriv(x)\n\n\ntemplate <class T>\nstruct cbrt_functor_2deriv\n{ // Functor returning both 1st and 2nd derivatives.\n  cbrt_functor_2deriv(T const& to_find_root_of) : a(to_find_root_of)\n  { // Constructor stores value to find root of, for example:\n  }\n\n  // using boost::math::tuple; // to return three values.\n  std::tuple<T, T, T> operator()(T const& x)\n  { \n    // Return both f(x) and f'(x) and f''(x).\n    T fx = x*x*x - a;                     // Difference (estimate x^3 - value).\n    // std::cout << \"x = \" << x << \"\\nfx = \" << fx << std::endl;\n    T dx = 3 * x*x;                       // 1st derivative = 3x^2.\n    T d2x = 6 * x;                        // 2nd derivative = 6x.\n    return std::make_tuple(fx, dx, d2x);  // 'return' fx, dx and d2x.\n  }\nprivate:\n  T a;                                    // to be 'cube_rooted'.\n}; // struct cbrt_functor_2deriv\n\ntemplate <int n, class T>\nstruct nth_functor_2deriv\n{ // Functor returning both 1st and 2nd derivatives.\n\n  nth_functor_2deriv(T const& to_find_root_of) : value(to_find_root_of)\n  { /* Constructor stores value to find root of, for example: */ }\n\n  // using std::tuple; // to return three values.\n  std::tuple<T, T, T> operator()(T const& x)\n  { \n    // Return both f(x) and f'(x) and f''(x).\n    using boost::math::pow;\n    T fx = pow<n>(x) - value;              // Difference (estimate x^3 - value).\n    T dx = n * pow<n - 1>(x);              // 1st derivative = 5x^4.\n    T d2x = n * (n - 1) * pow<n - 2 >(x);  // 2nd derivative = 20 x^3\n    return std::make_tuple(fx, dx, d2x);   // 'return' fx, dx and d2x.\n  }\nprivate:\n  T value;                                 // to be 'nth_rooted'.\n}; // struct nth_functor_2deriv\n\n\ntemplate <int n, class T>\nT nth_2deriv(T x)\n{ \n  // return nth root of x using 1st and 2nd derivatives and Halley.\n  using namespace std;  // Help ADL of std functions.\n  using namespace boost::math; // For halley_iterate.\n\n  int exponent;\n  frexp(x, &exponent);                                 // Get exponent of z (ignore mantissa).\n  T guess = ldexp(static_cast<T>(1.), exponent / n);   // Rough guess is to divide the exponent by three.\n  T min = ldexp(static_cast<T>(0.5), exponent / n);    // Minimum possible value is half our guess.\n  T max = ldexp(static_cast<T>(2.), exponent / n);     // Maximum possible value is twice our guess.\n\n  int digits = std::numeric_limits<T>::digits / 2;     // Half maximum possible binary digits accuracy for type T.\n  const std::uintmax_t maxit = 50;\n  std::uintmax_t it = maxit;\n  T result = halley_iterate(nth_functor_2deriv<n, T>(x), guess, min, max, digits, it);\n  // Can show how many iterations (updated by halley_iterate).\n  std::cout << it << \" iterations (from max of \" << maxit << \")\" << std::endl;\n\n  return result;\n} // nth_2deriv(x)\n\n//[root_finding_multiprecision_show_1\n\ntemplate <typename T>\nT show_cube_root(T value)\n{ // Demonstrate by printing the root using all definitely significant digits.\n  std::cout.precision(std::numeric_limits<T>::digits10);\n  T r = cbrt_2deriv(value);\n  std::cout << \"value = \" << value << \", cube root =\" << r << std::endl;\n  return r;\n}\n\n//] [/root_finding_multiprecision_show_1]\n\nint main()\n{\n  std::cout << \"Multiprecision Root finding Example.\" << std::endl;\n  // Show all possibly significant decimal digits.\n  std::cout.precision(std::numeric_limits<double>::digits10);\n  // or use   cout.precision(max_digits10 = 2 + std::numeric_limits<double>::digits * 3010/10000);\n  //[root_finding_multiprecision_example_1\n  using boost::multiprecision::cpp_dec_float_50; // decimal.\n  using boost::multiprecision::cpp_bin_float_50; // binary.\n#ifndef _MSC_VER  // Not supported by Microsoft compiler.\n  using boost::multiprecision::float128;\n#endif\n  //] [/root_finding_multiprecision_example_1\n\n  try\n  { // Always use try'n'catch blocks with Boost.Math to get any error messages.\n    // Increase the precision to 50 decimal digits using Boost.Multiprecision\n//[root_finding_multiprecision_example_2\n\n      std::cout.precision(std::numeric_limits<cpp_dec_float_50>::digits10);\n\n      cpp_dec_float_50 two = 2; // \n      cpp_dec_float_50  r = cbrt_2deriv(two);\n      std::cout << \"cbrt(\" << two << \") = \" << r << std::endl;\n\n      r = cbrt_2deriv(2.); // Passing a double, so ADL will compute a double precision result.\n      std::cout << \"cbrt(\" << two << \") = \" << r << std::endl;\n      // cbrt(2) = 1.2599210498948731906665443602832965552806854248047 'wrong' from digits 17 onwards!\n      r = cbrt_2deriv(static_cast<cpp_dec_float_50>(2.)); // Passing a cpp_dec_float_50, \n      // so will compute a cpp_dec_float_50 precision result.\n      std::cout << \"cbrt(\" << two << \") = \" << r << std::endl;\n      r = cbrt_2deriv<cpp_dec_float_50>(2.); // Explicitly a cpp_dec_float_50, so will compute a cpp_dec_float_50 precision result.\n      std::cout << \"cbrt(\" << two << \") = \" << r << std::endl;\n      // cpp_dec_float_50 1.2599210498948731647672106072782283505702514647015\n//] [/root_finding_multiprecision_example_2\n     //  N[2^(1/3), 50]  1.2599210498948731647672106072782283505702514647015\n\n      //show_cube_root(2); // Integer parameter - Errors!\n      //show_cube_root(2.F); // Float parameter - Warnings!\n//[root_finding_multiprecision_example_3\n      show_cube_root(2.);\n      show_cube_root(2.L);\n      show_cube_root(two);\n\n//] [/root_finding_multiprecision_example_3\n\n  }\n  catch (const std::exception& e)\n  { // Always useful to include try&catch blocks because default policies \n    // are to throw exceptions on arguments that cause errors like underflow & overflow. \n    // Lacking try&catch blocks, the program will abort without a message below,\n    // which may give some helpful clues as to the cause of the exception.\n    std::cout <<\n      \"\\n\"\"Message from thrown exception was:\\n   \" << e.what() << std::endl;\n  }\n  return 0;\n} // int main()\n\n\n/*\n\nDescription: Autorun \"J:\\Cpp\\MathToolkit\\test\\Math_test\\Release\\root_finding_multiprecision.exe\"\nMultiprecision Root finding Example.\ncbrt(2) = 1.2599210498948731647672106072782283505702514647015\ncbrt(2) = 1.2599210498948731906665443602832965552806854248047\ncbrt(2) = 1.2599210498948731647672106072782283505702514647015\ncbrt(2) = 1.2599210498948731647672106072782283505702514647015\nvalue = 2, cube root =1.25992104989487\nvalue = 2, cube root =1.25992104989487\nvalue = 2, cube root =1.2599210498948731647672106072782283505702514647015\n\n\n*/\n\n#endif // BOOST_MATH_STANDALONE\n", "meta": {"hexsha": "14d31397fc3f7acd9ca5607a25c9046008da9a42", "size": 9781, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/root_finding_multiprecision_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/root_finding_multiprecision_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/root_finding_multiprecision_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": 41.2700421941, "max_line_length": 131, "alphanum_fraction": 0.6857172068, "num_tokens": 2823, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391599428538, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.7018228156279972}}
{"text": "/* based upon http://www.boost.org/doc/libs/1_55_0/libs/multiprecision/doc/html/boost_multiprecision/tut/floats/cpp_dec_float.html\n * Use, modification and distribution are subject to the Boost Software License, Version 1.0.\n * (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n * Copyright ???? 20??. */\n\n#include <iostream>\n#include <utility>\n\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n\ntypedef boost::multiprecision::number<\n            boost::multiprecision::backends::cpp_bin_float<\n                106,\n                boost::multiprecision::backends::digit_base_2,\n                void,\n                boost::int16_t, -1022, 1023>,\n            boost::multiprecision::et_off>\n        cpp_bin_float_double_double;\n\nusing boost::multiprecision::cpp_dec_float;\nusing boost::multiprecision::cpp_bin_float_single;\nusing boost::multiprecision::cpp_bin_float_double;\nusing boost::multiprecision::cpp_bin_float_double_extended;\nusing boost::multiprecision::cpp_bin_float_quad;\n\n\ntemplate <typename T>\nvoid foo(void)\n{\n    std::cout << \"========================\" << std::endl;\n\n    /* prints the numerical precision i.e. 64 */\n    std::cout << std::numeric_limits<T>::digits10 << std::endl;\n\n    T a = 2;\n    //T b = boost::math::constants::pi<T, boost::math::policies::policy<boost::math::policies::digits2<64> > >();\n    T b = boost::math::constants::pi<T>();\n    T c = exp(a);\n    T d = pow(c,c);\n    T e = 1./c;\n\n    std::cout << std::setprecision(std::numeric_limits<T>::max_digits10) << a << std::endl;\n    std::cout << std::setprecision(std::numeric_limits<T>::max_digits10) << b << std::endl;\n    std::cout << std::setprecision(std::numeric_limits<T>::max_digits10) << c << std::endl;\n    std::cout << std::setprecision(std::numeric_limits<T>::max_digits10) << d << std::endl;\n    std::cout << std::setprecision(std::numeric_limits<T>::max_digits10) << e << std::endl;\n}\n\nint main(void)\n{\n    //foo<boost::multiprecision::cpp_bin_float_single >(); // see bug.cc\n    foo<boost::multiprecision::cpp_bin_float_double >();\n    foo<boost::multiprecision::cpp_bin_float_double_extended >();\n    foo<cpp_bin_float_double_double >();\n    foo<boost::multiprecision::cpp_bin_float_quad >();\n    foo<boost::multiprecision::number<cpp_dec_float<64> > >();\n\n    return 0;\n}\n", "meta": {"hexsha": "0cea1768817d21a39886c1bc7346b1390d9011e1", "size": 2459, "ext": "cc", "lang": "C++", "max_stars_repo_path": "boost/basic.cc", "max_stars_repo_name": "jeffhammond/multiprecision", "max_stars_repo_head_hexsha": "6006d27e542c2eaa0f10f8074a0704263923986e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-01-06T16:59:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T16:24:15.000Z", "max_issues_repo_path": "boost/basic.cc", "max_issues_repo_name": "jeffhammond/multiprecision", "max_issues_repo_head_hexsha": "6006d27e542c2eaa0f10f8074a0704263923986e", "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": "boost/basic.cc", "max_forks_repo_name": "jeffhammond/multiprecision", "max_forks_repo_head_hexsha": "6006d27e542c2eaa0f10f8074a0704263923986e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-08T23:27:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-08T23:27:36.000Z", "avg_line_length": 39.0317460317, "max_line_length": 130, "alphanum_fraction": 0.6775111834, "num_tokens": 632, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834278, "lm_q2_score": 0.7745833841649232, "lm_q1q2_score": 0.7017646610915664}}
{"text": "#include <CGAL/Simple_cartesian.h>\n\n#include <CGAL/Surface_mesh.h>\n#include <CGAL/boost/graph/graph_traits_Surface_mesh.h>\n\n#include <CGAL/subdivision_method_3.h>\n#include <CGAL/Timer.h>\n\n#include <boost/lexical_cast.hpp>\n\n#include <iostream>\n#include <fstream>\n\ntypedef CGAL::Simple_cartesian<double>      Kernel;\ntypedef CGAL::Surface_mesh<Kernel::Point_3> PolygonMesh;\nusing namespace std;\nusing namespace CGAL;\nnamespace params = CGAL::parameters;\n\n// ======================================================================\ntemplate <class Poly>\nclass WLoop_mask_3 {\n  typedef Poly                                         PolygonMesh;\n\n  typedef typename boost::graph_traits<PolygonMesh>::vertex_descriptor   vertex_descriptor;\n  typedef typename boost::graph_traits<PolygonMesh>::halfedge_descriptor halfedge_descriptor;\n\n  typedef typename boost::property_map<PolygonMesh, vertex_point_t>::type Vertex_pmap;\n  typedef typename boost::property_traits<Vertex_pmap>::value_type Point;\n  typedef typename boost::property_traits<Vertex_pmap>::reference Point_ref;\n\n  PolygonMesh& pmesh;\n  Vertex_pmap vpm;\n\npublic:\n  WLoop_mask_3(PolygonMesh& pmesh)\n    : pmesh(pmesh), vpm(get(CGAL::vertex_point, pmesh))\n  {}\n\n  void edge_node(halfedge_descriptor hd, Point& pt) {\n    Point_ref p1 = get(vpm, target(hd,pmesh));\n    Point_ref p2 = get(vpm, target(opposite(hd,pmesh),pmesh));\n    Point_ref f1 = get(vpm, target(next(hd,pmesh),pmesh));\n    Point_ref f2 = get(vpm, target(next(opposite(hd,pmesh),pmesh),pmesh));\n\n    pt = Point((3*(p1[0]+p2[0])+f1[0]+f2[0])/8,\n               (3*(p1[1]+p2[1])+f1[1]+f2[1])/8,\n               (3*(p1[2]+p2[2])+f1[2]+f2[2])/8 );\n  }\n  void vertex_node(vertex_descriptor vd, Point& pt) {\n    double R[] = {0.0, 0.0, 0.0};\n    Point_ref S = get(vpm,vd);\n\n    std::size_t n = 0;\n    for(halfedge_descriptor hd : halfedges_around_target(vd, pmesh)){\n      ++n;\n      Point_ref p = get(vpm, target(opposite(hd,pmesh),pmesh));\n      R[0] += p[0];         R[1] += p[1];         R[2] += p[2];\n    }\n\n    if (n == 6) {\n      pt = Point((10*S[0]+R[0])/16, (10*S[1]+R[1])/16, (10*S[2]+R[2])/16);\n    } else if (n == 3) {\n      double B = (5.0/8.0 - std::sqrt(3+2*std::cos(6.283/n))/64.0)/n;\n      double A = 1-n*B;\n      pt = Point((A*S[0]+B*R[0]), (A*S[1]+B*R[1]), (A*S[2]+B*R[2]));\n    } else {\n      double B = 3.0/8.0/n;\n      double A = 1-n*B;\n      pt = Point((A*S[0]+B*R[0]), (A*S[1]+B*R[1]), (A*S[2]+B*R[2]));\n    }\n  }\n\n  void border_node(halfedge_descriptor hd, Point& ept, Point& vpt) {\n    Point_ref ep1 = get(vpm, target(hd,pmesh));\n    Point_ref ep2 = get(vpm, target(opposite(hd,pmesh),pmesh));\n    ept = Point((ep1[0]+ep2[0])/2, (ep1[1]+ep2[1])/2, (ep1[2]+ep2[2])/2);\n\n    Halfedge_around_target_circulator<Poly> vcir(hd,pmesh);\n    Point_ref vp1  = get(vpm, target(opposite(*vcir,pmesh),pmesh));\n    Point_ref vp0  = get(vpm, target(*vcir,pmesh));\n    --vcir;\n    Point_ref vp_1 = get(vpm,target(opposite(*vcir,pmesh),pmesh));\n    vpt = Point((vp_1[0] + 6*vp0[0] + vp1[0])/8,\n                (vp_1[1] + 6*vp0[1] + vp1[1])/8,\n                (vp_1[2] + 6*vp0[2] + vp1[2])/8 );\n  }\n};\n\nint main(int argc, char **argv) {\n  if (argc > 4) {\n    cerr << \"Usage: Customized_subdivision [d] [filename_in] [filename_out] \\n\";\n    cerr << \"         d -- the depth of the subdivision (default: 1) \\n\";\n    cerr << \"         filename_in -- the input mesh (.off) (default: data/quint_tris.off) \\n\";\n    cerr << \"         filename_out -- the output mesh (.off) (default: result.off)\" << endl;\n    return 1;\n  }\n\n  int d = (argc > 1) ? boost::lexical_cast<int>(argv[1]) : 1;\n  const std::string in_file = (argc > 2) ? argv[2] : CGAL::data_file_path(\"meshes/quint_tris.off\");\n  const char* out_file = (argc > 3) ? argv[3] : \"result.off\";\n\n  PolygonMesh pmesh;\n  std::ifstream in(in_file);\n  if(in.fail()) {\n    std::cerr << \"Could not open input file \" << in_file << std::endl;\n    return 1;\n  }\n  in >> pmesh;\n\n  Timer t;\n  t.start();\n  Subdivision_method_3::PTQ(pmesh, WLoop_mask_3<PolygonMesh>(pmesh), params::number_of_iterations(d));\n  std::cerr << \"Done (\" << t.time() << \" s)\" << std::endl;\n\n  std::ofstream out(out_file);\n  out << pmesh;\n\n  return 0;\n}\n", "meta": {"hexsha": "4f4db8c3439947512394dc08201280fe70bb2366", "size": 4179, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Subdivision_method_3/examples/Subdivision_method_3/Customized_subdivision.cpp", "max_stars_repo_name": "ffteja/cgal", "max_stars_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 3227.0, "max_stars_repo_stars_event_min_datetime": "2015-03-05T00:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:20:35.000Z", "max_issues_repo_path": "Subdivision_method_3/examples/Subdivision_method_3/Customized_subdivision.cpp", "max_issues_repo_name": "ffteja/cgal", "max_issues_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 5574.0, "max_issues_repo_issues_event_min_datetime": "2015-03-05T00:01:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:08:11.000Z", "max_forks_repo_path": "Subdivision_method_3/examples/Subdivision_method_3/Customized_subdivision.cpp", "max_forks_repo_name": "ffteja/cgal", "max_forks_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1274.0, "max_forks_repo_forks_event_min_datetime": "2015-03-05T00:01:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:47:56.000Z", "avg_line_length": 34.5371900826, "max_line_length": 102, "alphanum_fraction": 0.5984685331, "num_tokens": 1407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.905989822921759, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.7017646583433037}}
{"text": "/**\n * @file sdirk.cc\n * @brief NPDE homework SDIRK code\n * @author Unknown, Oliver Rietmann\n * @date 31.03.2021\n * @copyright Developed at ETH Zurich\n */\n\n#include \"sdirk.h\"\n\n#include <Eigen/Core>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\n#include \"../../../lecturecodes/helperfiles/polyfit.h\"\n\nnamespace SDIRK {\n\n/* SAM_LISTING_BEGIN_0 */\nEigen::Vector2d SdirkStep(const Eigen::Vector2d &z0, double h, double gamma) {\n  Eigen::Vector2d res;\n  // Compute one timestep of the SDIRK implicit RK-SSM for the linear ODE\n#if SOLUTION\n  // Matrix A for evaluation of f\n  Eigen::Matrix2d A;\n  A << 0., 1., -1., -1.;\n  // Precompute and reuse factorization\n  auto A_lu = (Eigen::Matrix2d::Identity() - h * gamma * A).partialPivLu();\n  Eigen::Vector2d az = A * z0;\n\n  // Increments according to \\prbeqref{eq:ies}\n  Eigen::Vector2d k1 = A_lu.solve(az);\n  Eigen::Vector2d k2 = A_lu.solve(az + h * (1 - 2 * gamma) * A * k1);\n\n  // Updated state\n  res = z0 + h * 0.5 * (k1 + k2);\n#else\n  //====================\n  // Your code goes here\n  //====================\n#endif\n  return res;\n}\n/* SAM_LISTING_END_0 */\n\n/* SAM_LISTING_BEGIN_1 */\nstd::vector<Eigen::Vector2d> SdirkSolve(const Eigen::Vector2d &z0,\n                                        unsigned int M, double T,\n                                        double gamma) {\n  // Solution vector\n  std::vector<Eigen::Vector2d> res(M + 1);\n  // Solve the ODE with uniform timesteps using the SDIRK method\n#if SOLUTION\n  // Equidistant step size\n  const double h = T / M;\n  // Push initial data\n  res[0] = z0;\n  // Main loop\n  for (unsigned int i = 1; i <= M; ++i) {\n    res[i] = SdirkStep(res[i - 1], h, gamma);\n  }\n#else\n  //====================\n  // Your code goes here\n  //====================\n#endif\n  return res;\n}\n/* SAM_LISTING_END_1 */\n\n/* SAM_LISTING_BEGIN_2 */\ndouble CvgSDIRK() {\n  double conv_rate;\n  // Study the convergence rate of the method.\n#if SOLUTION\n  // Initial data z0 = [y(0), y'(0)]\n  Eigen::Vector2d z0;\n  z0 << 1, 0;\n  // Final time\n  const double T = 10;\n  // Parameter\n  const double gamma = (3. + std::sqrt(3.)) / 6.;\n  // Mesh sizes\n  Eigen::ArrayXd err(10);\n  Eigen::ArrayXd M(10);\n  M << 20, 40, 80, 160, 320, 640, 1280, 2560, 5120, 10240;\n\n  // Exact solution (only y(t)) given z0 = [y(0), y'(0)] and t\n  auto yex = [&z0](double t) {\n    return 1. / 3. * std::exp(-t / 2.) *\n           (3. * z0(0) * std::cos(std::sqrt(3.) * t / 2.) +\n            std::sqrt(3.) * z0(0) * std::sin(std::sqrt(3.) * t / 2.) +\n            2. * std::sqrt(3.) * z0(1) * std::sin(std::sqrt(3.) * t / 2.));\n  };\n\n  // Store old error for rate computation\n  double errold = 0;\n  std::cout << std::setw(15) << \"m\" << std::setw(15) << \"maxerr\"\n            << std::setw(15) << \"rate\" << std::endl;\n  // Loop over all meshes\n  for (unsigned int i = 0; i < M.size(); ++i) {\n    int m = M(i);\n    // Get solution\n    auto sol = SdirkSolve(z0, m, T, gamma);\n    // Compute error\n    err(i) = std::abs(sol.back()(0) - yex(T));\n\n    // Print table\n    std::cout << std::setw(15) << m << std::setw(15) << err(i);\n    if (i > 0) std::cout << std::setw(15) << std::log2(errold / err(i));\n    std::cout << std::endl;\n\n    // Store old error\n    errold = err(i);\n  }\n\n  Eigen::VectorXd coeffs = polyfit(M.log(), err.log(), 1);\n  conv_rate = -coeffs(0);\n#else\n  //====================\n  // Your code goes here\n  //====================\n#endif\n  return conv_rate;\n}\n/* SAM_LISTING_END_2 */\n\n}  // namespace SDIRK\n", "meta": {"hexsha": "4acc91c54447ed2cfc40d5f3eaf030c7aa50b7d7", "size": 3473, "ext": "cc", "lang": "C++", "max_stars_repo_path": "developers/SDIRK/mastersolution/sdirk.cc", "max_stars_repo_name": "0xBachmann/NPDECODES", "max_stars_repo_head_hexsha": "70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea", "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/SDIRK/mastersolution/sdirk.cc", "max_issues_repo_name": "0xBachmann/NPDECODES", "max_issues_repo_head_hexsha": "70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea", "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/SDIRK/mastersolution/sdirk.cc", "max_forks_repo_name": "0xBachmann/NPDECODES", "max_forks_repo_head_hexsha": "70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea", "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": 26.5114503817, "max_line_length": 78, "alphanum_fraction": 0.5534120357, "num_tokens": 1166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.839733979704703, "lm_q2_score": 0.8354835309589073, "lm_q1q2_score": 0.7015839104298606}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_FUNCTION_FREXP_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_FREXP_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-ieee\n    Function object implementing frexp capabilities\n\n    Computes a mantissa and an exponent pair for the input\n\n    @par Semantic:\n\n    For every parameter of floating type @c T\n\n    @code\n    std::tie(m, e)= frexp(x);\n    @endcode\n\n    is similar to:\n\n    @code\n    as_integer_t<T> e = exponent(x)+1;\n    T m = copysign(mantissa(x)/2, x);\n    @endcode\n\n    The call\n\n    @code\n    std:pair<T,as_integer_t<T>> p = frexp(x);\n    @endcode\n\n    can also be used.\n\n    @par Note:\n\n    This function splits a floating point value @c v f in a signed mantissa @c m and\n    an exponent @c e so that:  @f$v = m\\times 2^e@f$,\n    with absolute value of @c m \\f$\\in [1/2, 1[\\f$\n\n    @warninbox{Take care that these results differ from the returns of the functions @ref mantissa\n    and @ref exponent}\n\n    The decorators fast_ and std_ can be used.\n\n    fast_ provides a speedier call, but special values as Nan or Inf are not handled properly.\n    std_ transmit the call to std::frexp. That implies that simd is ever emulated.\n    @see exponent, mantissa, copysign\n\n  **/\n  std::pair<T, as_integer_t<Value>> frexp(Value const & v0);\n} }\n#endif\n\n#include <boost/simd/function/scalar/frexp.hpp>\n#include <boost/simd/function/scalar/frexp.hpp>\n#include <boost/simd/function/simd/frexp.hpp>\n\n#endif\n", "meta": {"hexsha": "6a822558bef69cc924668c795089a17ccc2b9c9f", "size": 1865, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/frexp.hpp", "max_stars_repo_name": "xmar/pythran", "max_stars_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-01-14T12:49:14.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-14T12:49:14.000Z", "max_issues_repo_path": "third_party/boost/simd/function/frexp.hpp", "max_issues_repo_name": "xmar/pythran", "max_issues_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "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": "third_party/boost/simd/function/frexp.hpp", "max_forks_repo_name": "xmar/pythran", "max_forks_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:29:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-08T15:55:25.000Z", "avg_line_length": 25.5479452055, "max_line_length": 100, "alphanum_fraction": 0.6171581769, "num_tokens": 469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.8397339656668287, "lm_q1q2_score": 0.7015838969815245}}
{"text": "#pragma once\r\n/*\r\n  Types and definitions\r\n  zeFresk\r\n*/\r\n\r\n#include <boost/multi_array.hpp>\r\n#include <cstdint>\r\n#include <complex>\r\n\r\n#include \"configuration.h\"\r\n\r\n// real and complex\r\n#if defined(DOUBLE_FP) // no multiprecision supported -yet\r\n\tusing real_t = double;\r\n#elif defined(MPFR_FP)\r\n\t#include <boost/multiprecision/mpfr.hpp>\r\n\tusing real_t = boost::multiprecision::number<boost::multiprecision::mpfr_float_backend<PRECISION_DIGITS> >;\r\n#elif defined(GMP_FP)\r\n\t#include <boost/multiprecision/gmp.hpp>\r\n\tusing real_t = boost::multiprecision::number<boost::multiprecision::gmp_float<PRECISION_DIGITS> >;\r\n#elif defined(BOOST_FP)\r\n\t#include <boost/multiprecision/cpp_bin_float.hpp>\r\n\tusing real_t = boost::multiprecision::number<boost::multiprecision::cpp_bin_float<PRECISION_DIGITS> >;\r\n#else\r\n\tusing real_t = float;\r\n#endif\r\n\r\n#if defined(CUDA_BACKEND)\r\n\t#include <thrust/complex.h>\r\n\tusing complex_t = thrust::complex<real_t>;\r\n#else\r\n\tusing complex_t = std::complex<real_t>;\r\n#endif\r\n\r\n// pixels array\r\n#include \"pixel_array.hpp\"\r\nusing pixel_array = PixelArray;\r\n\r\n// used to compute fractal\r\nstruct Parameters {\r\n\tcomplex_t center;\r\n\treal_t precision;\r\n\tsize_t iterations;\r\n};", "meta": {"hexsha": "3d021bf0c2b0947a35d494cde83e5fc75a7a101c", "size": 1191, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/types.hpp", "max_stars_repo_name": "zeFresk/mandelbrot", "max_stars_repo_head_hexsha": "18dd60aefd067c8f26315f44ceaae30bca025cba", "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/types.hpp", "max_issues_repo_name": "zeFresk/mandelbrot", "max_issues_repo_head_hexsha": "18dd60aefd067c8f26315f44ceaae30bca025cba", "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": "include/types.hpp", "max_forks_repo_name": "zeFresk/mandelbrot", "max_forks_repo_head_hexsha": "18dd60aefd067c8f26315f44ceaae30bca025cba", "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.4666666667, "max_line_length": 109, "alphanum_fraction": 0.7397145256, "num_tokens": 287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.893309411735131, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.7015235509119537}}
{"text": "#include <chrono>\n#include <iostream>\n\n#include <Eigen/Dense>\n\nEIGEN_DONT_INLINE\ndouble simple_function(Eigen::VectorXd &va, Eigen::VectorXd &vb) {\n  // this simple function computes the dot product of two vectors\n  // of course it could be expressed more compactly\n  double d = va.dot(vb);\n  return d;\n}\n\nint main() {\n  int len = 1000000;\n  int num_repetitions = 100;\n\n  // generate two random vectors\n  Eigen::VectorXd va = Eigen::VectorXd::Random(len);\n  Eigen::VectorXd vb = Eigen::VectorXd::Random(len);\n\n  double result;\n  auto start = std::chrono::system_clock::now();\n  for (auto i = 0; i < num_repetitions; i++) {\n    result = simple_function(va, vb);\n  }\n  auto end = std::chrono::system_clock::now();\n  auto elapsed_seconds = std::chrono::duration_cast<std::chrono::microseconds>(end-start);\n\n  std::cout << \"result: \" << result << std::endl;\n  std::cout << \"elapsed seconds: \" << elapsed_seconds.count()/1000000.0 << std::endl;\n}\n", "meta": {"hexsha": "039b467f0f71c4af4e024a1db17eab16655bebeb", "size": 942, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/chapter_02/recipe-06/linear-algebra.cpp", "max_stars_repo_name": "realjf/cmake_cookbook", "max_stars_repo_head_hexsha": "cb92a3040f16d61f3038ce477052757035113c88", "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/chapter_02/recipe-06/linear-algebra.cpp", "max_issues_repo_name": "realjf/cmake_cookbook", "max_issues_repo_head_hexsha": "cb92a3040f16d61f3038ce477052757035113c88", "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/chapter_02/recipe-06/linear-algebra.cpp", "max_forks_repo_name": "realjf/cmake_cookbook", "max_forks_repo_head_hexsha": "cb92a3040f16d61f3038ce477052757035113c88", "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.5454545455, "max_line_length": 90, "alphanum_fraction": 0.6815286624, "num_tokens": 256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.7879311906630568, "lm_q1q2_score": 0.7014905942158037}}
{"text": "#ifndef IMGEN_FILTER_HPP_\n#define IMGEN_FILTER_HPP_\n\n#include \"imgen/image.hpp\"\n\n#include <boost/gil/gil_all.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <format.h>\n\n#include <functional>\n\nnamespace gil = boost::gil;\nnamespace ublas = boost::numeric::ublas;\n\nnamespace imgen {\n\n/**\n * The filter type, for now this will just be a matrix of floats.\n *\n * TODO: look into using the pixel channel type? could have side effects if\n * channel type is scoped?\n */\ntypedef ublas::matrix<float> filter_t;\n\n/**\n * Apply a function to each region of an image using a sliding neighbourhood.\n * This can be slow on large images. The neighbourhood is padded with 0s.\n *\n * img - the image to apply the function to\n * w - the width of the region\n * h - the height of the region\n * f - the function to apply to each region\n */\nvoid nlfilter(image& img, std::size_t w, std::size_t h,\n              std::function<image::pixel_t(const ublas::matrix<image::pixel_t>&)> f);\n\n/**\n * Applies a filter to an image using sliding neighbourhood correlation. This\n * can be slow on large images. The neighbourhood is padded with 0s.\n *\n * TODO: Give a way to define the padding element.\n */\nvoid filter(image& img, const filter_t& filter);\n\n/**\n * Produces a square gaussian filter mask. The mask is calcualted using:\n *\n * g(x, y) = e ^ (-(x^2 + y^2) / (2 * \u03c3^2))\n *\n * Where the center element of the matrix is the origin. The mask is then\n * normalized. \u03c3 defaults to 0.5.\n */\nfilter_t gaussian(filter_t::size_type size, filter_t::value_type sigma = 0.5);\n\n} // namespace imgen\n\n#endif // IMGEN_FILTER_HPP_\n", "meta": {"hexsha": "fa9e629837bad8851b73cb1709fdc79aa053b668", "size": 1594, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/imgen/filter.hpp", "max_stars_repo_name": "maddisoj/wallgen", "max_stars_repo_head_hexsha": "98ed3ad537797a644a7a16f44b3cf36c02762895", "max_stars_repo_licenses": ["CC-BY-4.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": "src/imgen/filter.hpp", "max_issues_repo_name": "maddisoj/wallgen", "max_issues_repo_head_hexsha": "98ed3ad537797a644a7a16f44b3cf36c02762895", "max_issues_repo_licenses": ["CC-BY-4.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": "src/imgen/filter.hpp", "max_forks_repo_name": "maddisoj/wallgen", "max_forks_repo_head_hexsha": "98ed3ad537797a644a7a16f44b3cf36c02762895", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4827586207, "max_line_length": 85, "alphanum_fraction": 0.7038895859, "num_tokens": 412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872046056466901, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.7013621440054625}}
{"text": "/*!\n * \\file PlainGeometry.hpp\n * \\author Jun Yoshida\n * \\copyright (c) 2019 Jun Yoshida.\n * The project is released under the MIT License.\n * \\date February 20, 2020: created\n */\n\n#pragma once\n\n#include <vector>\n#include <Eigen/Dense>\n\nnamespace {\nenum Orientation {\n    OnLine,\n    Clockwise,\n    CntrClockwise\n};\n\nOrientation orientation(\n    Eigen::Vector2d const& p0,\n    Eigen::Vector2d const& p1,\n    Eigen::Vector2d const& p2) noexcept;\n\n//! Compute the convex hull.\n//! \\param A set of vertices.\n//! \\return A list of control points spanning the hull. They are stored in the counter-clockwise order.\nstd::vector<Eigen::Vector2d> getConvexHull(\n    std::vector<Eigen::Vector2d> const& vs) noexcept;\n\n//! Check if the convex hull of control points overlaps with that of another Bezier curve.\n//! Here, so-called *The Separating Axis Theorem* is used.\nbool hasHullIntersection(\n    std::vector<Eigen::Vector2d> const& lhs,\n    std::vector<Eigen::Vector2d> const& rhs) noexcept;\n\n}\n", "meta": {"hexsha": "ea9442e7baa796d6cc64fb57ad061ba1f0fac885", "size": 987, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/math/PlaneGeometry.hpp", "max_stars_repo_name": "Junology/bord2", "max_stars_repo_head_hexsha": "0068885144032d4a8e30c6f2c5898918d00b1d8f", "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/PlaneGeometry.hpp", "max_issues_repo_name": "Junology/bord2", "max_issues_repo_head_hexsha": "0068885144032d4a8e30c6f2c5898918d00b1d8f", "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/PlaneGeometry.hpp", "max_forks_repo_name": "Junology/bord2", "max_forks_repo_head_hexsha": "0068885144032d4a8e30c6f2c5898918d00b1d8f", "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.3076923077, "max_line_length": 103, "alphanum_fraction": 0.7092198582, "num_tokens": 266, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872046056466901, "lm_q2_score": 0.7905303087996142, "lm_q1q2_score": 0.7013621308703178}}
{"text": "///////////////////////////////////////////////////////////////////\n//  Copyright Eduardo Quintana 2021\n//  Copyright Janek Kozicki 2021\n//  Copyright Christopher Kormanyos 2021\n//  Distributed under the Boost Software License,\n//  Version 1.0. (See accompanying file LICENSE_1_0.txt\n//  or copy at http://www.boost.org/LICENSE_1_0.txt)\n/*\n  boost::math::fft Example for non-complex types\n  Use of DFT for Number Theoretical Transform.\n*/\n#include <boost/math/fft/bsl_backend.hpp>\nnamespace fft = boost::math::fft;\n\n#include <iostream>\n#include <vector>\n#include \"fft_test_helpers.hpp\"\n\nclass Z337\n{\npublic:\n  typedef int integer;\n  static constexpr integer mod{337}; // 337 = 2*2*2*2*3*7 + 1\n};\n\nint convolution()\n/*\n  product of two integer by means of the NTT,\n  using the convolution theorem\n*/\n{\n  int errors = 0;\n  using M_int = fft::my_modulo_lib::mint<Z337>;\n  // 85 is a primitive root of 337,\n  // ie. the smallest number k for such that 85^k mod 337 = 1 is k=phi(337)=336\n  const M_int w{85};\n  const M_int inv_8{M_int{8}.inverse()};\n\n  // Multiplying 1234 times 5678 = 7006652\n  std::vector<M_int> A{4, 3, 2, 1, 0, 0, 0, 0};\n  std::vector<M_int> B{8, 7, 6, 5, 0, 0, 0, 0};\n\n  // forward FFT\n  fft::bsl_algebraic_transform::forward(A.cbegin(),A.cend(),A.begin(), w);\n  fft::bsl_algebraic_transform::forward(B.cbegin(),B.cend(),B.begin(), w);\n\n  // convolution in Fourier space\n  std::vector<M_int> AB;\n  std::transform(A.begin(), A.end(), B.begin(),\n                 std::back_inserter(AB),\n                 [](M_int x, M_int y) { return x * y; });\n\n  // backwards FFT\n  fft::bsl_algebraic_transform::backward(AB.cbegin(),AB.cend(),AB.begin(),w);\n  std::transform(AB.begin(), AB.end(), AB.begin(),\n                 [&inv_8](M_int x) { return x * inv_8; });\n\n  // carry the remainders in base 10\n  std::vector<int> C;\n  M_int r{0};\n  for (auto x : AB)\n  {\n    auto y = x + r;\n    C.emplace_back(int(y) % 10);\n    r = M_int(int(y) / 10);\n  }\n  // yields 7006652\n  if(static_cast<int>(C.size())!=8) errors++;\n  if(C[0]!=2) errors++;\n  if(C[1]!=5) errors++;\n  if(C[2]!=6) errors++;\n  if(C[3]!=6) errors++;\n  if(C[4]!=0) errors++;\n  if(C[5]!=0) errors++;\n  if(C[6]!=7) errors++;\n  if(C[7]!=0) errors++;\n  return errors;\n}\nint main()\n{\n  return convolution();\n}\n\n", "meta": {"hexsha": "adfbeeb9a8fca9defb20c936919510d51a936787", "size": 2268, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/fft_ex08.cpp", "max_stars_repo_name": "BoostGSoC21/math", "max_stars_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_stars_repo_licenses": ["BSL-1.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": "example/fft_ex08.cpp", "max_issues_repo_name": "BoostGSoC21/math", "max_issues_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 30.0, "max_issues_repo_issues_event_min_datetime": "2021-06-22T12:59:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-02T09:27:49.000Z", "max_forks_repo_path": "example/fft_ex08.cpp", "max_forks_repo_name": "BoostGSoC21/math", "max_forks_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-07T21:15:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-07T21:15:02.000Z", "avg_line_length": 27.0, "max_line_length": 79, "alphanum_fraction": 0.6053791887, "num_tokens": 736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850039701653, "lm_q2_score": 0.7490872131147276, "lm_q1q2_score": 0.7013591243051228}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n\n\nusing namespace Eigen;\nusing namespace std;\n\nextern \"C\" void dggev_(const char* JOBVL, const char* JOBVR, const int* N,\n        const double* A, const int* LDA, const double* B, const int* LDB,\n        double* ALPHAR, double* ALPHAI, double* BETA,\n        double* VL, const int* LDVL, double* VR, const int* LDVR,\n        double* WORK, const int* LWORK, int* INFO);\n\n// Generalised Eigen-Problem\n// source adapted from https://eigen.tuxfamily.org/index.php?title=Lapack\n// Solve:\n// A * v(j) = lambda(j) * B * v(j).\n//\n// v are the eigenvectors and are stored in v.\n// lambda are the eigenvalues and are stored in lambda.\n// The eigenvalues are stored as: (lambda(:, 1) + lambda(:, 2)*i)./lambda(:, 3)\n//\n// returns true on success.\n// A and B will be changed.\nbool GEP(MatrixXd& A, MatrixXd& B, MatrixXd& v, MatrixXd& lambda)\n{\n    int N = A.cols(); // Number of columns of A and B. Number of rows of v.\n    if (B.cols() != N  || A.rows()!=N || B.rows()!=N){\n        cout << \"Matrices A and B are not square and the same size, line \" << __LINE__ <<  endl;\n        return false;\n    }\n\n    v.resize(N,N);\n    lambda.resize(N, 3);\n\n    int LDA = A.outerStride();\n    int LDB = B.outerStride();\n    int LDV = v.outerStride();\n\n    double WORKDUMMY;\n    int LWORK = -1; // Request optimum work size.\n    int INFO = 0;\n\n//    double * alphar = const_cast<double*>(lambda.col(0).data());\n//    double * alphai = const_cast<double*>(lambda.col(1).data());\n//    double * beta   = const_cast<double*>(lambda.col(2).data());\n\n    double * alphar = lambda.col(0).data();\n    double * alphai = lambda.col(1).data();\n    double * beta   = lambda.col(2).data();\n\n    // Get the optimum work size.\n    dggev_(\"N\", \"V\", &N, A.data(), &LDA, B.data(), &LDB, alphar, alphai, beta, 0, &LDV, v.data(), &LDV, &WORKDUMMY, &LWORK, &INFO);\n\n    LWORK = int(WORKDUMMY) + 32;\n    VectorXd WORK(LWORK);\n\n    dggev_(\"N\", \"V\", &N, A.data(), &LDA, B.data(), &LDB, alphar, alphai, beta, 0, &LDV, v.data(), &LDV, WORK.data(), &LWORK, &INFO);\n\n    return INFO==0;\n}\n\nint main(){\n\n    MatrixXd A;\n    MatrixXd B;\n    MatrixXd v;\n    MatrixXd lambda;\n\n    A.setRandom(4, 4);\n    B.setRandom(4, 4);\n\n    //A(1, 1) = 2;\n\n    cout << \"Before calling the GEP function. \" << endl;\n    cout << \"Matrix A \" << endl << A << endl;\n    cout << \"Matrix B \" << endl << B << endl;\n\n    bool success = GEP(A, B, v, lambda);\n\n    if (success){\n        cout << \"A \" << endl << A << endl;\n        cout << \"B\" << endl << B << endl;\n\n        cout << \"lambda \" << endl << lambda << endl;\n        cout << \"v \" << endl << v << endl;\n\n    }   else {\n        cout << \"GEP failed.\" << endl;\n    }\n\n\n    return 0;\n}\n", "meta": {"hexsha": "01a4013d050aa9e72921aaae1b3c1b5a6dbdbcec", "size": 2701, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/lapack-example.cpp", "max_stars_repo_name": "amy-tabb/lapack-example", "max_stars_repo_head_hexsha": "005767da433cef5741434903b735efe0a76f8b27", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-10T03:07:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T03:07:41.000Z", "max_issues_repo_path": "src/lapack-example.cpp", "max_issues_repo_name": "amy-tabb/lapack-example", "max_issues_repo_head_hexsha": "005767da433cef5741434903b735efe0a76f8b27", "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/lapack-example.cpp", "max_forks_repo_name": "amy-tabb/lapack-example", "max_forks_repo_head_hexsha": "005767da433cef5741434903b735efe0a76f8b27", "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.4315789474, "max_line_length": 132, "alphanum_fraction": 0.5679378008, "num_tokens": 845, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178895092415, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.7013108052693423}}
{"text": "#include <Eigen/Core>\r\n#include <unsupported/Eigen/SpecialFunctions>\r\n#include <iostream>\r\nusing namespace Eigen;\r\nint main()\r\n{\r\n  Array4d v(-0.5,2,0,-7);\r\n  std::cout << v.erfc() << std::endl;\r\n}\r\n", "meta": {"hexsha": "a2a5a116be329b6a10121dadd7b93373df7216d9", "size": 199, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/eigen-eigen-323c052e1731/doc/examples/Cwise_erfc.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/Cwise_erfc.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/Cwise_erfc.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": 19.9, "max_line_length": 46, "alphanum_fraction": 0.6432160804, "num_tokens": 57, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213772699436, "lm_q2_score": 0.7799929104825007, "lm_q1q2_score": 0.7013082999338178}}
{"text": "#include \"kabsch.h\"\n#include <Eigen/Dense>\n\nusing namespace probreg;\n\nKabschResult probreg::computeKabsch(const MatrixX3& model,\n                                    const MatrixX3& target,\n                                    const Vector& weight) {\n    //Compute the center\n    Vector3 model_center = Vector3::Zero();\n    Vector3 target_center = Vector3::Zero();\n    Float total_weight = 0.0f;\n    for(auto i = 0; i < model.rows(); ++i) {\n        const Float w_i = weight[i];\n        total_weight += w_i;\n        model_center.noalias() += w_i * model.row(i);\n        target_center.noalias() += w_i * target.row(i);\n    }\n    if (total_weight == 0) {\n        return std::make_pair(Matrix3::Identity(), Vector3::Zero());\n    }\n    const Float divided_by = 1.0f / total_weight;\n    model_center *= divided_by;\n    target_center *= divided_by;\n\n    //Centralize them\n    //Compute the H matrix\n    Float h_weight = 0.0f;\n    Matrix3 hh = Matrix3::Zero();\n    for(auto k = 0; k < model.rows(); ++k) {\n        const auto& model_k = model.row(k).transpose();\n        auto centralized_model_k = model_k - model_center;\n        const auto& target_k = target.row(k).transpose();\n        auto centralized_target_k = target_k - target_center;\n        const Float this_weight = weight[k];\n        h_weight += this_weight * this_weight;\n        hh.noalias() += (this_weight * this_weight) * centralized_model_k * centralized_target_k.transpose();\n    }\n\n    //Do svd\n    hh /= h_weight;\n    Eigen::JacobiSVD<Matrix3> svd(hh, Eigen::ComputeFullU | Eigen::ComputeFullV);\n    Vector3 ss = Vector3::Ones(3);\n    ss[2] = (svd.matrixU() * svd.matrixV()).determinant();\n    const Matrix3 r = svd.matrixV() * ss.asDiagonal() * svd.matrixU().transpose();\n\n    //The translation\n    Vector3 translation = target_center;\n    translation.noalias() -= r * model_center;\n\n    return std::make_pair(r, translation);\n}", "meta": {"hexsha": "a95c8e4ff3d0901f2de316ff62adac990b2b8bdd", "size": 1888, "ext": "cc", "lang": "C++", "max_stars_repo_path": "probreg/cc/kabsch.cc", "max_stars_repo_name": "pramukta/probreg", "max_stars_repo_head_hexsha": "277a95b042913753e8ef578dc175357955614777", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-03T06:29:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-03T06:29:02.000Z", "max_issues_repo_path": "probreg/cc/kabsch.cc", "max_issues_repo_name": "siyeopyoon/probreg", "max_issues_repo_head_hexsha": "521c327198b837723f9bec78b8106eab4d3acf7f", "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": "probreg/cc/kabsch.cc", "max_forks_repo_name": "siyeopyoon/probreg", "max_forks_repo_head_hexsha": "521c327198b837723f9bec78b8106eab4d3acf7f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-29T02:29:22.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-29T02:29:22.000Z", "avg_line_length": 36.3076923077, "max_line_length": 109, "alphanum_fraction": 0.6165254237, "num_tokens": 490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636754, "lm_q2_score": 0.7799929104825006, "lm_q1q2_score": 0.7013082957169668}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n\n\nusing namespace std;\n\n// Alleged error reported by Dragan Vidovic\n\ntemplate<class ct>\nmtl::dense2D<ct> inv2 ( const mtl::dense2D<ct> & M )\n{\n   mtl::dense2D<ct> N(2,2);\n   ct d = M[0][0]*M[1][1]-M[0][1]*M[1][0];\n   N[0][0] = M[1][1]/d;\n   N[0][1] =-M[0][1]/d;\n   N[1][0] =-M[1][0]/d;\n   N[1][1] = M[0][0]/d; return N;\n}\n\n\nint main(int, char**)\n{\n    typedef double ct;\n    mtl::dense2D<ct> tmp(2, 2);\n    tmp= 3, 5,\n\t 8, 9;\n\n    mtl::dense2D<ct> tmp1 = inv2(tmp), P(tmp * tmp1);\n    cout << \"tmp1 is\\n\" << tmp1 << \"\\ntmp * tmp1 is:\\n\" << P;\n    \n\n    return 0;\n}\n", "meta": {"hexsha": "9894f424864ed5363536ba56b110361c33ab0fac", "size": 1066, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/inv2_test.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/test/inv2_test.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/test/inv2_test.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 23.1739130435, "max_line_length": 94, "alphanum_fraction": 0.5994371482, "num_tokens": 386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213664574069, "lm_q2_score": 0.7799929104825007, "lm_q1q2_score": 0.701308291500116}}
{"text": "#ifndef _KERNEL_HPP_\n#define _KERNEL_HPP_\n\n#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\n#include <Eigen/SparseCore>\n#include <cstdarg>\n#include <mimkl/definitions.hpp>\n\nusing mimkl::definitions::Index;\n\nnamespace mimkl\n{\nnamespace kernel\n{\n\n//! The linear kernel with the extended kernel K = X*Y_t\n/*!\n\\param lhs left hand side NxM data-matrix.\n\\param rhs untransposed (unconjugated) right hand side KxM data-matrix.\n\\returns kernel_matrix the similarity NxK matrix.\n\\sa test/linear_induction\n*/\ntemplate <typename KDerived, typename LhsDerived, typename RhsDerived>\nKDerived linear_kernel(LhsDerived &lhs, RhsDerived &rhs)\n{\n    return lhs * rhs.adjoint();\n}\n\n//! The polynomial kernel with the extended kernel K =\n//! (X*Y_t + c)^p\n/*!\n\\param lhs left hand side NxM data-matrix.\n\\param rhs untransposed (unconjugated)  right hand side KxM data-matrix.\n\\param degree polynomial degree.\n\\param offset \"free parameter trading off the influence of higher-order versus\nlower-order terms in the polynomial\".\n\\returns kernel_matrix the similarity NxK matrix.\n\\sa TODO\n*/\ntemplate <typename KDerived, typename LhsDerived, typename RhsDerived>\nKDerived polynomial_kernel(LhsDerived &lhs,\n                           RhsDerived &rhs,\n                           const double degree,\n                           const double offset)\n{\n    return (linear_kernel<KDerived>(lhs, rhs).array() + offset).pow(degree).matrix();\n}\n\n//! The gaussian kernel  k = exp(-\n//! (x-y)_t*(x-y) / ( 2*s^2 )).\n/*!  This squared pairwise euclidean distance cannot be expressed in a concise\nmatrix multiplication.\nThe squared distance of xi to yj = \\f$(x_i^T*x_i) -(x_i^T*y_j)\n-(y_j^T*x_i) + (y_j^T*y_j) \\f$\nThis means next to \\f$XY^T\\f$ (the linear kernel) only the diagonal entries of\n\\f$XX^T\\f$ and \\f$YY^T\\f$ are needed.\n\\param lhs left hand side NxM data-matrix.\n\\param rhs untransposed  (unconjugated) right hand side KxM data-matrix.\n\\param sigma_square variance of the bell curve.\n\\returns kernel_matrix the similarity NxK matrix.\n\\sa gaussian_induction\n*/\ntemplate <typename KDerived, typename LhsDerived, typename RhsDerived>\nKDerived\ngaussian_kernel(LhsDerived &lhs, RhsDerived &rhs, const double sigma_square)\n{\n\n    return (-(\n            /*! -2* lhs_inducer_rhs only in case of scalar matrices.\n             with complex numbers we need: -lhs_rhs\n             -lhs_rhs.adjoint\n             imaginary parts cancel out! */\n            ((-2 * (lhs * rhs.adjoint()).real()).colwise() +\n             lhs.rowwise().squaredNorm())\n            .rowwise() +\n            lhs.rowwise().squaredNorm().transpose()) /\n            (2 * sigma_square))\n    .array()\n    .exp()\n    .matrix();\n}\n\n//! The sigmoidal kernel with the extended kernel k = tanh(a*\n//! (x_t*y) +b).\n/*!\n\\param lhs left hand side NxM data-matrix.\n\\param rhs untransposed  (unconjugated) right hand side KxM data-matrix.\n\\param a\n\\param b\n\\returns kernel_matrix the similarity NxK matrix.\n\\sa test/sigmoidal_induction\n*/\ntemplate <typename KDerived, typename LhsDerived, typename RhsDerived>\nKDerived\nsigmoidal_kernel(LhsDerived &lhs, RhsDerived &rhs, const double a, const double b)\n{\n\n    return (a * linear_kernel<KDerived>(lhs, rhs).array() + b).tanh().matrix();\n}\n\n} // namespace kernel\n} // namespace mimkl\n\n#endif /*_KERNEL_HPP_*/\n", "meta": {"hexsha": "6b31edd957363619153f9612ace1f9591a8e8bd3", "size": 3281, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mimkl/kernels/kernel.hpp", "max_stars_repo_name": "vishalbelsare/mimkl", "max_stars_repo_head_hexsha": "53a5a9db5aa09c6e8808ba5b845601c5768d23e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2019-05-28T23:18:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T20:00:03.000Z", "max_issues_repo_path": "include/mimkl/kernels/kernel.hpp", "max_issues_repo_name": "vishalbelsare/mimkl", "max_issues_repo_head_hexsha": "53a5a9db5aa09c6e8808ba5b845601c5768d23e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2019-05-18T13:21:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T22:20:55.000Z", "max_forks_repo_path": "include/mimkl/kernels/kernel.hpp", "max_forks_repo_name": "vishalbelsare/mimkl", "max_forks_repo_head_hexsha": "53a5a9db5aa09c6e8808ba5b845601c5768d23e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2019-07-24T09:39:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-29T14:40:27.000Z", "avg_line_length": 30.9528301887, "max_line_length": 85, "alphanum_fraction": 0.6936909479, "num_tokens": 848, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218391455084, "lm_q2_score": 0.7606506418255928, "lm_q1q2_score": 0.701260438659062}}
{"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    // TODO\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    // TODO\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    \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_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_fast.start();\n            multAmin(x, y);\n            tm_fast.stop();\n        }\n        times_slow.push_back( tm_slow.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_fast.begin(); it != times_fast.end(); ++it) {\n        std::cout << *it << \" \";\n    }\n    std::cout << std::endl;\n}\n", "meta": {"hexsha": "eb750078c171b8d680fc8a546768714908c8ef69", "size": 2127, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/PS1/templates/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/templates/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/templates/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": 29.1369863014, "max_line_length": 69, "alphanum_fraction": 0.5181006112, "num_tokens": 647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.8104789063814616, "lm_q1q2_score": 0.7012458738552432}}
{"text": "/* Copyright 2017 The sfcpp Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*/\n\n\n\n#pragma once\n\n#include <Eigen/Dense>\n\n#include <iostream>\n\nnamespace sfcpp {\nnamespace math {\n\nclass VectorSubspace {\n  Eigen::MatrixXd baseMat, kernelMat;\n  size_t numCoordinates;\n  static constexpr double myeps = 1e-8;\n  static constexpr double mysqeps = myeps * myeps;\n\n public:\n  VectorSubspace(size_t numCoordinates)\n      : baseMat(Eigen::MatrixXd::Zero(numCoordinates, 1)),\n        kernelMat(Eigen::MatrixXd::Identity(numCoordinates, numCoordinates)),\n        numCoordinates(numCoordinates) {}\n\n  void addVector(Eigen::VectorXd const &vec) {\n    if (!containsVector(vec)) {\n      addIndependentVector(vec);\n    }\n  }\n\n  void addIndependentVector(Eigen::VectorXd const &vec) {\n    baseMat.conservativeResize(baseMat.rows(), baseMat.cols() + 1);\n    baseMat.col(baseMat.cols() - 1) = vec;\n\n    kernelMat = baseMat.transpose().fullPivLu().kernel();\n  }\n\n  bool containsVector(Eigen::VectorXd const &vec) const {\n    return (vec.transpose() * kernelMat).squaredNorm() <= mysqeps;\n  }\n\n  bool isOrthogonalTo(Eigen::VectorXd const &vec) const {\n    return (vec.transpose() * baseMat).squaredNorm() <= mysqeps;\n  }\n\n  /**\n   * @return a vector orthogonal to the subspace, which is nonzero iff the\n   * subspace is not the whole space.\n   */\n  Eigen::VectorXd orthogonalVector() { return kernelMat.col(0); }\n};\n\n} /* namespace math */\n} /* namespace sfcpp */\n", "meta": {"hexsha": "0c1f6c3ac97b530988ea4a24ad84ff8497fdd91c", "size": 2025, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/math/VectorSubspace.hpp", "max_stars_repo_name": "dholzmueller/sfcpp", "max_stars_repo_head_hexsha": "b929419b13c35fff199c6c65e87ecffae9963cfc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2017-10-20T07:53:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-23T15:54:54.000Z", "max_issues_repo_path": "src/math/VectorSubspace.hpp", "max_issues_repo_name": "dholzmueller/sfcpp", "max_issues_repo_head_hexsha": "b929419b13c35fff199c6c65e87ecffae9963cfc", "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": "src/math/VectorSubspace.hpp", "max_forks_repo_name": "dholzmueller/sfcpp", "max_forks_repo_head_hexsha": "b929419b13c35fff199c6c65e87ecffae9963cfc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-10-20T20:02:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-02T12:47:53.000Z", "avg_line_length": 29.347826087, "max_line_length": 80, "alphanum_fraction": 0.6898765432, "num_tokens": 474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480252950991, "lm_q2_score": 0.7634837635542925, "lm_q1q2_score": 0.7012447602733212}}
{"text": "#pragma once\n#include \"coordinate_transform.hpp\"\n#include \"integrate.hpp\"\n#include \"shape.hpp\"\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <functional>\n\n//! Computes the L^2 differences between\n//! u1 (considered as coefficients for the shape functions)\n//! and u2.\ndouble computeL2Difference(const Eigen::MatrixXd &vertices,\n                           const Eigen::MatrixXi &triangles,\n                           const Eigen::VectorXd &u1,\n                           const std::function<double(double, double)> &u2) {\n\tconst int numberOfElements = triangles.rows();\n\n\tdouble error = 0;\n\tfor (int i = 0; i < numberOfElements; ++i) {\n\t\tauto &indexSet = triangles.row(i);\n\n\t\tconst int i0 = indexSet(0);\n\t\tconst int i1 = indexSet(1);\n\t\tconst int i2 = indexSet(2);\n\n\t\tconst auto &a = vertices.row(i0);\n\t\tconst auto &b = vertices.row(i1);\n\t\tconst auto &c = vertices.row(i2);\n\n\t\tauto coordinateTransform = makeCoordinateTransform(b - a, c - a);\n\t\tauto volumeFactor        = std::abs(coordinateTransform.determinant());\n\n\t\terror += integrate([&](double x, double y) {\n\t\t\tEigen::Vector2d z = coordinateTransform * Eigen::Vector2d(x, y) + Eigen::Vector2d(a(0), a(1));\n\n\t\t\tdouble approximateValue = u1(i0) * lambda(0, x, y) + u1(i1) * lambda(1, x, y) + u1(i2) * lambda(2, x, y);\n\n\t\t\treturn std::pow(std::abs(u2(z(0), z(1)) - approximateValue), 2) * volumeFactor;\n\t\t});\n\t}\n\n\treturn std::sqrt(error);\n}\n", "meta": {"hexsha": "04fbcad5bbb02747a747298fcf42ce069efd8578", "size": 1401, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "series2/2d-linFEM/L2_norm.hpp", "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/L2_norm.hpp", "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/L2_norm.hpp", "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": 31.8409090909, "max_line_length": 108, "alphanum_fraction": 0.6374018558, "num_tokens": 385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.7012447485157993}}
{"text": "#include <random>\n#include <algorithm>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics.hpp>\n#include <Polynomial.hh>\n\ndouble discount(const double risk_free_rate, const int days){\n    return std::exp(-risk_free_rate * (double(days) / 252.0));\n}\n\nvoid monte_carlo(std::vector<double> &data, std::vector<std::vector<double> > &sim_vec, int sim_len, const int iterations){\n    double sigma;\n    double mu;\n    double drift;\n    std::vector<double> log_returns;\n    std::vector<double> sim;\n    log_returns.reserve(data.size()-1);\n    sim.reserve(sim_len);\n\n\n    for(int i=1; i!=data.size(); ++i){\n        log_returns.emplace_back(log(data[i] / data[i-1]));\n    }\n\n    // get standard deviation and mean\n    using namespace boost::accumulators;\n    accumulator_set<double, features<tag::mean, tag::variance>> acc;\n\n    for(std::vector<double>::iterator it=log_returns.begin(); it!=log_returns.end(); ++it){\n        acc(*it);\n    }\n\n    sigma = std::sqrt(variance(acc));\n    mu = mean(acc);\n    drift = mu - (0.5 * pow(sigma, 2.0));\n\n    std::random_device rand; \n    std::mt19937_64 gen(rand());\n    std::normal_distribution<double> dist(0.0, sigma);\n\n    // generate simulation\n    for(int i=0; i!=iterations; ++i){\n        sim.emplace_back(data[data.size()-1] * exp(drift + dist(gen)));\n        for(int x=1; x!=sim_len; ++x){\n            sim.emplace_back(sim.back() * exp(drift + dist(gen)));\n        }\n        sim_vec.emplace_back(sim);\n        sim.clear();\n    }\n}\n\ndouble monte_carlo_fixed_strike_arithmatic_avg_asian_call(std::vector<double> &data_underlying, const double strike, const double risk_free_rate, const int days_to_exp, const int iterations){\n    std::vector<double> average_prices;\n    std::vector<double> payout;\n    std::vector<std::vector<double> > vec;\n    double sum;\n\n    // perform Monte Carlo on underlying asset\n    monte_carlo(data_underlying, vec, days_to_exp, iterations);\n\n    average_prices.reserve(iterations);\n    payout.reserve(iterations);\n\n    for(int i=0; i!=vec.size(); ++i){\n        sum = 0.0;\n        for(std::vector<double>::iterator it=vec[i].begin(); it!=vec[i].end(); ++it){\n            sum += *it;\n        }\n        average_prices.emplace_back(sum / double(days_to_exp));  \n    }\n\n    // determine average payout & discount back\n    sum = 0.0;\n    for(std::vector<double>::iterator it=average_prices.begin(); it!=average_prices.end(); ++it){\n        sum += std::max(*it - strike, 0.0);\n    }\n    return (sum / double(iterations)) * std::exp(-risk_free_rate * (double(days_to_exp) / 252.0));\n}\n\ndouble monte_carlo_fixed_strike_arithmatic_avg_asian_put(std::vector<double> &data_underlying, const double strike, const double risk_free_rate, const int days_to_exp, const int iterations){\n    std::vector<double> average_prices;\n    std::vector<double> payout;\n    std::vector<std::vector<double> > vec;\n    double sum;\n\n    // perform Monte Carlo on underlying asset\n    monte_carlo(data_underlying, vec, days_to_exp, iterations);\n\n    average_prices.reserve(iterations);\n    payout.reserve(iterations);\n\n    for(int i=0; i!=vec.size(); ++i){\n        sum = 0.0;\n        for(std::vector<double>::iterator it=vec[i].begin(); it!=vec[i].end(); ++it){\n            sum += *it;\n        }\n        average_prices.emplace_back(sum / double(days_to_exp));  \n    }\n\n    // determine average payout & discount back\n    sum = 0.0;\n    for(std::vector<double>::iterator it=average_prices.begin(); it!=average_prices.end(); ++it){\n        sum += std::max(strike - *it, 0.0);\n    }\n    return (sum / double(iterations)) * std::exp(-risk_free_rate * (double(days_to_exp) / 252.0));\n}\n\ndouble monte_carlo_floating_strike_arithmatic_avg_asian_call(std::vector<double> &data_underlying, const double strike, const double risk_free_rate, const int days_to_exp, const int iterations){\n    std::vector<double> average_prices;\n    std::vector<double> payout;\n    double maturity_price;\n    std::vector<std::vector<double> > vec;\n    double sum;\n\n    // perform Monte Carlo on underlying asset\n    monte_carlo(data_underlying, vec, days_to_exp, iterations);\n\n    average_prices.reserve(iterations);\n    payout.reserve(iterations);\n\n    for(int i=0; i!=vec.size(); ++i){\n        sum = 0.0;\n        for(std::vector<double>::iterator it=vec[i].begin(); it!=vec[i].end(); ++it){\n            sum += *it;\n        }\n        average_prices.emplace_back(sum / double(days_to_exp));  \n    }\n\n    // get average price at maturity\n    sum = 0.0;\n    for(int i=0; i!=vec.size(); ++i){\n        sum += vec[i].back();\n    }\n    maturity_price = sum / double(iterations);\n\n    // determine average payout & discount back\n    sum = 0.0;\n    for(std::vector<double>::iterator it=average_prices.begin(); it!=average_prices.end(); ++it){\n        sum += std::max(maturity_price - (*it * strike), 0.0);\n    }\n    return (sum / double(iterations)) * std::exp(-risk_free_rate * (double(days_to_exp) / 252.0));\n}\n\ndouble monte_carlo_floating_strike_arithmatic_avg_asian_put(std::vector<double> &data_underlying, const double strike, const double risk_free_rate, const int days_to_exp, const int iterations){\n    std::vector<double> average_prices;\n    std::vector<double> payout;\n    double maturity_price;\n    std::vector<std::vector<double> > vec;\n    double sum;\n\n    // perform Monte Carlo on underlying asset\n    monte_carlo(data_underlying, vec, days_to_exp, iterations);\n\n    average_prices.reserve(iterations);\n    payout.reserve(iterations);\n\n    for(int i=0; i!=vec.size(); ++i){\n        sum = 0.0;\n        for(std::vector<double>::iterator it=vec[i].begin(); it!=vec[i].end(); ++it){\n            sum += *it;\n        }\n        average_prices.emplace_back(sum / double(days_to_exp));  \n    }\n\n    // get average price at maturity\n    sum = 0.0;\n    for(int i=0; i!=vec.size(); ++i){\n        sum += vec[i].back();\n    }\n    maturity_price = sum / double(iterations);\n\n    // determine average payout & discount back\n    sum = 0.0;\n    for(std::vector<double>::iterator it=average_prices.begin(); it!=average_prices.end(); ++it){\n        sum += std::max((*it * strike) - maturity_price, 0.0);\n    }\n    return (sum / double(iterations)) * std::exp(-risk_free_rate * (double(days_to_exp) / 252.0));\n}\n\ndouble american_put_longstaff_schwartz(std::vector<double> &data_underlying, const double strike, const double risk_free_rate, const int days_to_exp, const int iterations){\n    std::vector<double> price;\n    double iter_cont;  // continuation value for this particular iteration\n    std::vector<std::vector<double> > sim_vec;\n    std::vector<std::vector<double> > cfm; // cash flow matrix\n    std::vector<double> day_cash; // cash flow for one day\n    day_cash.reserve(iterations);\n\n    double one_day_discount = discount(risk_free_rate, 1);\n\n\n    // run Monte Carlo on underlying asset\n    monte_carlo(data_underlying, sim_vec, days_to_exp, iterations);\n\n    // work backwards, starting with maturity date\n    for(std::vector<std::vector<double>>::iterator it=sim_vec.begin(); it!=sim_vec.end(); ++it){\n        day_cash.emplace_back(std::max(it->back() - strike, 0.0));\n    }\n    cfm.emplace_back(day_cash);\n\n\n    for(int i=days_to_exp-2; i!=-1; --i){\n        // iterate backward\n        for(int x=0; x!=iterations; ++x){\n            day_cash[x] = std::max(sim_vec[x][i] - strike, 0.0);\n        }\n\n        std::vector<double> xs;\n        std::vector<double> ys;\n        std::vector<double> continuation;\n        xs.reserve(iterations);\n        ys.reserve(iterations);\n        continuation.reserve(iterations);\n\n        for(int x=0; x!=iterations; ++x){\n            if(day_cash[x] > 0.0){\n                xs.emplace_back(sim_vec[x][i]);\n                ys.emplace_back(cfm[0][x] * one_day_discount);\n            }\n        }\n\n        // get 2nd order polynomial\n        Polynomial poly(xs, ys, 1, 2);\n\n        // get continuation value\n        for(int x=0; x!=iterations; ++x){\n            if(day_cash[x] > 0.0){\n                // option is in the money\n                price = {sim_vec[x][i]};\n                iter_cont = poly.eval(price) * one_day_discount;\n                if(iter_cont > day_cash[x]){\n                    // continuation value is greater than cash flow from exercising the option today\n                    // set today's cash flow to zero\n                    day_cash[x] = 0.0;\n                }\n                else{\n                    // exercise option today!\n                    // set future cash flows to zero\n                    for(int q=0; q!=cfm.size(); ++q){\n                        cfm[q][x] = 0.0;\n                    }\n                }\n            }\n            else{\n                // option is out of the money, don't exercise today\n                // set today's cash flow to zero\n                day_cash[x] = 0.0;\n            }\n        }\n\n        // exercise data to cash flow matrix\n        std::vector<std::vector<double>>::iterator insert_front = cfm.begin();\n        cfm.insert(insert_front, day_cash);\n    }\n\n    double sum = 0.0;\n    int count = 0;\n    for(int i=0; i!=iterations; ++i){\n        for(int x=0; x!=days_to_exp; ++x){\n            if(cfm[x][i] > 0.0){\n                sum += cfm[x][i] * discount(risk_free_rate, x+1);\n                ++count;\n                break;\n            }\n        }\n    }\n    // average discounted cash flows\n    return sum/double(count);\n}\n\ndouble american_call_longstaff_schwartz(std::vector<double> &data_underlying, const double strike, const double risk_free_rate, const int days_to_exp, const int iterations){\n    std::vector<double> price;\n    double iter_cont;  // continuation value for this particular iteration\n    std::vector<std::vector<double> > sim_vec;\n    std::vector<std::vector<double> > cfm; // cash flow matrix\n    std::vector<double> day_cash; // cash flow for one day\n    day_cash.reserve(iterations);\n\n    double one_day_discount = discount(risk_free_rate, 1);\n\n\n    // run Monte Carlo on underlying asset\n    monte_carlo(data_underlying, sim_vec, days_to_exp, iterations);\n\n    // work backwards, starting with maturity date\n    for(std::vector<std::vector<double>>::iterator it=sim_vec.begin(); it!=sim_vec.end(); ++it){\n        day_cash.emplace_back(std::max(strike - it->back(), 0.0));\n    }\n    cfm.emplace_back(day_cash);\n\n\n    for(int i=days_to_exp-2; i!=-1; --i){\n        // iterate backward\n        for(int x=0; x!=iterations; ++x){\n            day_cash[x] = std::max(strike - sim_vec[x][i], 0.0);\n        }\n\n        std::vector<double> xs;\n        std::vector<double> ys;\n        std::vector<double> continuation;\n        xs.reserve(iterations);\n        ys.reserve(iterations);\n        continuation.reserve(iterations);\n\n        for(int x=0; x!=iterations; ++x){\n            if(day_cash[x] > 0.0){\n                xs.emplace_back(sim_vec[x][i]);\n                ys.emplace_back(cfm[0][x] * one_day_discount);\n            }\n        }\n\n        // get 2nd order polynomial\n        Polynomial poly(xs, ys, 1, 2);\n\n        // get continuation value\n        for(int x=0; x!=iterations; ++x){\n            if(day_cash[x] > 0.0){\n                // option is in the money\n                price = {sim_vec[x][i]};\n                iter_cont = poly.eval(price) * one_day_discount;\n                if(iter_cont > day_cash[x]){\n                    // continuation value is greater than cash flow from exercising the option today\n                    // set today's cash flow to zero\n                    day_cash[x] = 0.0;\n                }\n                else{\n                    // exercise option today!\n                    // set future cash flows to zero\n                    for(int q=0; q!=cfm.size(); ++q){\n                        cfm[q][x] = 0.0;\n                    }\n                }\n            }\n            else{\n                // option is out of the money, don't exercise today\n                // set today's cash flow to zero\n                day_cash[x] = 0.0;\n            }\n        }\n\n        // exercise data to cash flow matrix\n        std::vector<std::vector<double>>::iterator insert_front = cfm.begin();\n        cfm.insert(insert_front, day_cash);\n    }\n\n    double sum = 0.0;\n    int count = 0;\n    for(int i=0; i!=iterations; ++i){\n        for(int x=0; x!=days_to_exp; ++x){\n            if(cfm[x][i] > 0.0){\n                sum += cfm[x][i] * discount(risk_free_rate, x+1);\n                ++count;\n                break;\n            }\n        }\n    }\n    // average discounted cash flows\n    return sum/double(count);\n}\n", "meta": {"hexsha": "a4d29854cb99e527870b0d15ddf3b9c94519eac7", "size": 12487, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "monte_carlo.cpp", "max_stars_repo_name": "cnaimo/monte-carlo-cpp", "max_stars_repo_head_hexsha": "622bd04d4756296a5f69d28ebc432e35810ebd63", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-11-30T01:15:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-11T19:19:53.000Z", "max_issues_repo_path": "monte_carlo.cpp", "max_issues_repo_name": "hyc9527/monte-carlo-cpp", "max_issues_repo_head_hexsha": "622bd04d4756296a5f69d28ebc432e35810ebd63", "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": "monte_carlo.cpp", "max_forks_repo_name": "hyc9527/monte-carlo-cpp", "max_forks_repo_head_hexsha": "622bd04d4756296a5f69d28ebc432e35810ebd63", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-11-29T14:15:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-29T14:15:17.000Z", "avg_line_length": 34.782729805, "max_line_length": 194, "alphanum_fraction": 0.5871706575, "num_tokens": 3128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810421953309, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.701227163944675}}
{"text": "#include <catch.hpp>\n#include <typeclass/eq/list.h>\n#include <typeclass/eq/optional.h>\n#include <typeclass/eq/vector.h>\n#include <typeclass/eq/scalar.h>\n#include <typeclass/monoid/list.h>\n#include <typeclass/monoid/vector.h>\n#include <typeclass/monoid/scalar.h>\n#include <boost/optional.hpp>\n\n\nTEST_CASE(\"typeclass monoid\") {\n    using namespace funcpp::typeclass::monoid;\n    using namespace funcpp::typeclass::monoid::operators;\n    using namespace funcpp::typeclass::eq;\n    using namespace funcpp::typeclass::eq::operators;\n\n    GIVEN(\"two lists of ints\") {\n        std::list<int> a{1,2,3}, b{4,5,6,7};\n\n        THEN(\"Addition equal concatenation\") {\n            REQUIRE((std::list<int>{1,2,3,4,5,6,7} == a + b));\n            REQUIRE((std::list<int>{1,2,3,4,5,6,7} == mappend(a,b)));\n        }\n    }\n\n    GIVEN(\"a list of ints\") {\n        std::list<int> a{1,2,3};\n\n        THEN(\"Adding mempty() doesn't change anything\") {\n            REQUIRE((a == a + mempty<std::list<int>>()    ));\n            REQUIRE((a ==     mempty<std::list<int>>() + a));\n\n            REQUIRE( a == mappend(a, mempty<std::list<int>>()    ));\n            REQUIRE( a == mappend(   mempty<std::list<int>>(),  a));\n        }\n    }\n\n    GIVEN(\"two vectors of ints\") {\n        std::vector<int> a{1,2,3}, b{4,5,6,7};\n\n        THEN(\"Addition equal concatenation\") {\n            REQUIRE((std::vector<int>{1,2,3,4,5,6,7} == a + b));\n            REQUIRE((std::vector<int>{1,2,3,4,5,6,7} == mappend(a,b)));\n        }\n    }\n\n    GIVEN(\"a vectors of ints\") {\n        std::vector<int> a{1,2,3};\n\n        THEN(\"Adding mempty() doesn't change anything\") {\n            REQUIRE((a == a + mempty<std::vector<int>>()    ));\n            REQUIRE((a ==     mempty<std::vector<int>>() + a));\n\n            REQUIRE( a == mappend(a, mempty<std::vector<int>>()    ));\n            REQUIRE( a == mappend(   mempty<std::vector<int>>(),  a));\n        }\n    }\n\n    GIVEN(\"two ints\") {\n        int a = 7, b = 10;\n\n        THEN(\"mappend(a,b) is just the sum a+b\") {\n            REQUIRE(a+b == mappend(a,b));\n        }\n\n        THEN(\"mappend(a,mempty()) is just a\") {\n            REQUIRE(a == mappend(a,mempty<int>()));\n            REQUIRE(a == mappend(mempty<int>(),a));\n        }\n\n        THEN(\"Multiplication a*b is the same as mappend<int,std::multiplies<>>(a,b)\") {\n            REQUIRE(a*b == (mappend<int,std::multiplies<>>(a,b)));\n        }\n    }\n}", "meta": {"hexsha": "869e76902a600c162b97ec7ac2be2a608014ff48", "size": 2397, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/typeclass/test/src/typeclass/monoid.cpp", "max_stars_repo_name": "julian-becker/funcpp", "max_stars_repo_head_hexsha": "0e94c7c115d542fd0b1a16450975df7b02c56b4d", "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": "modules/typeclass/test/src/typeclass/monoid.cpp", "max_issues_repo_name": "julian-becker/funcpp", "max_issues_repo_head_hexsha": "0e94c7c115d542fd0b1a16450975df7b02c56b4d", "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": "modules/typeclass/test/src/typeclass/monoid.cpp", "max_forks_repo_name": "julian-becker/funcpp", "max_forks_repo_head_hexsha": "0e94c7c115d542fd0b1a16450975df7b02c56b4d", "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.5394736842, "max_line_length": 87, "alphanum_fraction": 0.5264914476, "num_tokens": 698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460333, "lm_q2_score": 0.7931059438487663, "lm_q1q2_score": 0.7011368089485732}}
{"text": "#include <Eigen/Dense>\n#include \"../include/loss.h\"\n\nnamespace MyDL\n{\n\n    double cross_entropy_error(MatrixXd &y, MatrixXd &t)\n    {\n        int batch_size = y.rows();\n        double loss = -(t.array() * y.array().log()).sum() / batch_size;\n        return loss;\n    }\n\n}", "meta": {"hexsha": "1f41a7f095c83a98eb1fac7de64b9454b58baadf", "size": 271, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/loss.cpp", "max_stars_repo_name": "potedo/zeroDL_cpp", "max_stars_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-22T15:26:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-22T15:26:20.000Z", "max_issues_repo_path": "src/loss.cpp", "max_issues_repo_name": "potedo/zeroDL_cpp", "max_issues_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "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/loss.cpp", "max_forks_repo_name": "potedo/zeroDL_cpp", "max_forks_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "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.3571428571, "max_line_length": 72, "alphanum_fraction": 0.5830258303, "num_tokens": 70, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299612154571, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.7011340516827382}}
{"text": "#include <Eigen/Dense>\n\n#include <iostream>\n\n#include \"refill/distributions/gaussian_distribution.h\"\n#include \"refill/filters/extended_kalman_filter.h\"\n#include \"refill/measurement_models/linear_measurement_model.h\"\n#include \"refill/system_models/linear_system_model.h\"\n\n/*\n * This is an example program for using Refill to estimate the 3D position\n * using a constant position model and assuming measurements are 3D position\n * measurements of the real position.\n *\n * The system model can then be written as:\n *\n * x(k) = I * x(k-1) + v(k)\n *\n * with\n *\n * x(k) element of R^3\n *\n * I = Identity matrix element of R^3x3\n *\n * v(k) random variable distributed with N(0, dt * Q)\n *\n * where Q element of R^3x3 is the system model covariance.\n *\n * The measurement model can be written as:\n *\n * y(k) = I * x(k) + w(k)\n *\n * with\n *\n * w(k) ~ N(0, R)\n *\n * where R element of R^3x3 is the measurement model covariance.\n */\n\nint main(int argc, char **argv) {\n  /* initialize Q and R\n   * Q = I * 2.0\n   * R = I */\n  Eigen::Matrix3d system_noise_cov = Eigen::Matrix3d::Identity() * 2.0;\n  Eigen::Matrix3d measurement_noise_cov = Eigen::Matrix3d::Identity() * 1.0;\n\n  /* initialize v(k) */\n  refill::GaussianDistribution system_noise(Eigen::Vector3d::Zero(),\n                                            system_noise_cov);\n  /* initialize w(k) */\n  refill::GaussianDistribution measurement_noise(\n      Eigen::Vector3d::Zero(), measurement_noise_cov);\n\n  /* initialize the system model */\n  refill::LinearSystemModel system_model(Eigen::Matrix3d::Identity(),\n                                         system_noise);\n  /* initialize the measurement model */\n  refill::LinearMeasurementModel measurement_model(Eigen::Matrix3d::Identity(),\n                                                   measurement_noise);\n\n  /* initialize the initial state distribution\n   * Assumed to be at position [1, 1, 1]^T with cov[I * 5] */\n  refill::GaussianDistribution initial_state(Eigen::Vector3d::Ones(),\n                                             Eigen::Matrix3d::Identity() * 5.0);\n  /* initialize the kf with the initial state */\n  refill::ExtendedKalmanFilter ekf(initial_state);\n\n  /* assume that 1.0 seconds has passed and we get a position measurement at\n   * [1.5, 1.5, 1.5]^T\n   * t = 1.0 */\n  double dt = 1.0;\n  Eigen::Vector3d measurement = Eigen::Vector3d::Constant(1.5);\n\n  /* adapt the system model noise according to the time step */\n  system_noise.setCov(system_noise_cov * dt);\n  /* adapt the system model */\n  system_model.setModelParameters(Eigen::Matrix3d::Identity(), system_noise);\n\n  /* predict the kf to the current time */\n  ekf.predict(system_model);\n  /* update the kf with the measurement and the measurement model */\n  ekf.update(measurement_model, measurement);\n\n  /* print the current state */\n  std::cout << \"State at t = 1.0:\\n\";\n  std::cout << \"Mean:\\n\\n\" << ekf.state().mean() << \"\\n\\n\";\n  std::cout << \"Covariance:\\n\\n\" << ekf.state().cov() << \"\\n\\n\";\n\n  /* Assume that another 0.5 seconds have passed and another measurement\n   * is received\n   * t = 1.5 */\n  dt = 0.5;\n  measurement = Eigen::Vector3d::Constant(1.5);\n\n  // adapt the system noise according to the time step\n  system_noise.setCov(system_noise_cov * dt);\n  // adapt the system model\n  system_model.setModelParameters(Eigen::Matrix3d::Identity(), system_noise);\n\n  /* predict the kf to the current time */\n  ekf.predict(system_model);\n  /* update the kf with the measurement and the measurement model */\n  ekf.update(measurement_model, measurement);\n\n  /* print the current state */\n  std::cout << \"State at t = 1.5:\\n\";\n  std::cout << \"Mean:\\n\\n\" << ekf.state().mean() << \"\\n\\n\";\n  std::cout << \"Covariance:\\n\\n\" << ekf.state().cov() << \"\\n\\n\";\n\n  return 0;\n}\n", "meta": {"hexsha": "696d0fcb871ce77b9ac6b1eebf6bbe640e88a5d9", "size": 3741, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/examples/kalman_filter_example.cc", "max_stars_repo_name": "jwidauer/refill", "max_stars_repo_head_hexsha": "64947e0a8e15855f4a5ad048f09f8d38715bbe91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-06-13T07:28:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-08T11:26:34.000Z", "max_issues_repo_path": "src/examples/kalman_filter_example.cc", "max_issues_repo_name": "jwidauer/refill", "max_issues_repo_head_hexsha": "64947e0a8e15855f4a5ad048f09f8d38715bbe91", "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/examples/kalman_filter_example.cc", "max_forks_repo_name": "jwidauer/refill", "max_forks_repo_head_hexsha": "64947e0a8e15855f4a5ad048f09f8d38715bbe91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-06-01T13:21:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T20:33:20.000Z", "avg_line_length": 33.4017857143, "max_line_length": 80, "alphanum_fraction": 0.6500935579, "num_tokens": 992, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009619539554, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.7010827960815816}}
{"text": "/*\n * Copyright (c) 2015, Jonathan Ventura\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef POLYNOMIAL_HPP\n#define POLYNOMIAL_HPP\n\n#include <Eigen/Core>\n#include <unsupported/Eigen/Polynomials>\n#include <vector>\n\n#include <Polynomial/PolynomialInternal.hpp>\n\nnamespace polynomial\n{\n    /**\n     * Polynomial\n     *\n     * Templated class for representing a polynomial expression.\n     *\n     * The template parameter indicates the degree of polynomial.  An n-th degree polynomial has n+1 coefficients.\n     *\n     * The coefficients are stored in this order:\n     * c0 x^deg + c1 x^(deg-1) + ...\n     *\n     * A dynamically-sized version is available: Polynomial<Eigen::Dynamic>\n     *\n     * Note that the static and dynamic versions should not be mixed, i.e. do not add a dynamic polynomial to a static one.\n     */\n    template<int deg>\n    class Polynomial\n    {\n        Eigen::Matrix<double,deg+1,1> coef;\n    public:\n        Polynomial()\n        : coef( Eigen::Matrix<double,1,deg+1>::Zero() )\n        {\n            \n        }\n        \n        Polynomial( const Eigen::Matrix<double,deg+1,1> &coefin )\n        : coef( coefin )\n        {\n\n        }\n        \n        Polynomial( const Polynomial<deg> &polyin )\n        : coef( polyin.coef )\n        {\n\n        }\n        \n        Polynomial( const double *coefin )\n        : coef( Internal::vecmap<deg+1>( coefin ) )\n        {\n            \n        }\n        \n        const Eigen::Matrix<double,deg+1,1> &coefficients() const\n        {\n            return coef;\n        }\n\n        Eigen::Matrix<double,deg+1,1> &coefficients()\n        {\n            return coef;\n        }\n\n        template<int degin>\n        Polynomial<Internal::max<degin,deg>::value> operator+(const Polynomial<degin> &poly) const\n        {\n            Polynomial<Internal::max<degin,deg>::value> p;\n            p.coefficients().tail(degin+1) = poly.coefficients();\n            p.coefficients().tail(deg+1) += coef;\n            return p;\n        }\n        \n        template<int degin>\n        Polynomial<Internal::max<degin,deg>::value> operator-(const Polynomial<degin> &poly) const\n        {\n            Polynomial<Internal::max<degin,deg>::value> p;\n            p.coefficients().tail(deg+1) = coef;\n            p.coefficients().tail(degin+1) -= poly.coefficients();\n            return p;\n        }\n        \n        template<int degin>\n        Polynomial<degin+deg> operator*(const Polynomial<degin> &poly) const\n        {\n            Polynomial<degin+deg> p;\n            Internal::PolyConv<deg,degin>::compute(p.coefficients(),coef,poly.coefficients());\n            return p;\n        }\n        \n        Polynomial<deg> operator*(const double c) const\n        {\n            return Polynomial<deg>(coef*c);\n        }\n        \n        double eval(double x) const\n        {\n            return Internal::PolyVal<deg>::compute(coef,x);\n        }\n        \n        void realRoots(std::vector<double> &roots) const\n        {\n            if ( coef[0] == 0 )\n            {\n                Internal::RootFinder<deg-1>::compute(coef.tail(deg),roots);\n            } else {\n                Internal::RootFinder<deg>::compute(coef,roots);\n            }\n        }\n        \n        void realRootsSturm(const double lb, const double ub, std::vector<double> &roots) const\n        {\n            if ( coef[0] == 0 )\n            {\n                Internal::SturmRootFinder<deg-1> sturm( coef.tail(deg) );\n                sturm.realRoots( lb, ub, roots );\n            } else {\n                Internal::SturmRootFinder<deg> sturm( coef );\n                sturm.realRoots( lb, ub, roots );\n            }\n        }\n        \n        void rootBounds( double &lb, double &ub )\n        {\n            Eigen::Matrix<double,deg,1> mycoef = coef.tail(deg).array().abs();\n            mycoef /= fabs(coef(0));\n            mycoef(0) += 1.;\n            ub = mycoef.maxCoeff();\n            lb = -ub;\n        }\n    };\n    \n    template <>\n    class Polynomial<Eigen::Dynamic>\n    {\n        Eigen::VectorXd coef;\n    public:\n        Polynomial(const int deg)\n        : coef( Eigen::VectorXd::Zero(deg+1) )\n        {\n            \n        }\n        \n        Polynomial( const Eigen::VectorXd &coefin)\n        : coef( coefin )\n        {\n\n        }\n        \n        Polynomial(const Polynomial<Eigen::Dynamic> &polyin)\n        : coef( polyin.coef )\n        {\n\n        }\n        \n        const Eigen::VectorXd &coefficients() const\n        {\n            return coef;\n        }\n        \n        Eigen::VectorXd &coefficients()\n        {\n            return coef;\n        }\n        \n        Polynomial<Eigen::Dynamic> operator+(const Polynomial<Eigen::Dynamic> &poly) const\n        {\n            int deg = coef.rows()-1;\n            int degin = poly.coef.rows()-1;\n            Polynomial<Eigen::Dynamic> p( std::max(deg,degin) );\n            p.coef.tail(degin+1) = poly.coef;\n            p.coef.tail(deg+1) += coef;\n            return p;\n        }\n\n        Polynomial<Eigen::Dynamic> operator-(const Polynomial<Eigen::Dynamic> &poly) const\n        {\n            int deg = coef.rows()-1;\n            int degin = poly.coef.rows()-1;\n            Polynomial<Eigen::Dynamic> p( std::max(deg,degin) );\n            p.coef.tail(deg+1) = coef;\n            p.coef.tail(degin+1) -= poly.coef;\n            return p;\n        }\n        \n        Polynomial<Eigen::Dynamic> operator*(const Polynomial<Eigen::Dynamic> &poly) const\n        {\n            int deg = coef.rows()-1;\n            int degin = poly.coef.rows()-1;\n            Polynomial<Eigen::Dynamic> p( deg+degin );\n            Internal::PolyConv<Eigen::Dynamic,Eigen::Dynamic>::compute(p.coef,coef,poly.coef);\n            return p;\n        }\n        \n        Polynomial<Eigen::Dynamic> operator*(const double c) const\n        {\n            return Polynomial<Eigen::Dynamic>(coef*c);\n        }\n        \n        double eval(double x) const\n        {\n            return Internal::PolyVal<Eigen::Dynamic>::compute(coef,x);\n        }\n        \n        void realRoots(std::vector<double> &roots) const\n        {\n            if ( coef[0] == 0 )\n            {\n                int deg = coef.rows()-1;\n                Internal::RootFinder<Eigen::Dynamic>::compute(coef.tail(deg),roots);\n            } else {\n                Internal::RootFinder<Eigen::Dynamic>::compute(coef,roots);\n            }\n        }\n        \n        void realRootsSturm(const double lb, const double ub, std::vector<double> &roots) const\n        {\n            if ( coef[0] == 0 )\n            {\n                int deg = coef.rows()-1;\n                Internal::SturmRootFinder<Eigen::Dynamic> sturm( coef.tail(deg) );\n                sturm.realRoots( lb, ub, roots );\n            } else {\n                Internal::SturmRootFinder<Eigen::Dynamic> sturm( coef );\n                sturm.realRoots( lb, ub, roots );\n            }\n        }\n        \n        void rootBounds( double &lb, double &ub )\n        {\n            int deg = coef.rows()-1;\n            Eigen::VectorXd mycoef = coef.tail(deg).array().abs()/fabs(coef(0));\n            mycoef(0) += 1.;\n            ub = mycoef.maxCoeff();\n            lb = -ub;\n        }\n    };\n    \n} // end namespace Polynomial\n\n#endif\n\n", "meta": {"hexsha": "b74f823619ef61cd3dd0661a8aec3613fdd80741", "size": 8399, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Polynomial/Polynomial.hpp", "max_stars_repo_name": "jonathanventura/polynomial", "max_stars_repo_head_hexsha": "ab737843199ed48881da6dcf5dc05d34903af059", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2017-04-28T11:46:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-01T11:41:00.000Z", "max_issues_repo_path": "Polynomial/Polynomial.hpp", "max_issues_repo_name": "jonathanventura/polynomial", "max_issues_repo_head_hexsha": "ab737843199ed48881da6dcf5dc05d34903af059", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-08-14T00:31:47.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-14T00:31:47.000Z", "max_forks_repo_path": "Polynomial/Polynomial.hpp", "max_forks_repo_name": "jonathanventura/polynomial", "max_forks_repo_head_hexsha": "ab737843199ed48881da6dcf5dc05d34903af059", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2016-02-27T11:37:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T05:58:18.000Z", "avg_line_length": 32.80859375, "max_line_length": 758, "alphanum_fraction": 0.547208001, "num_tokens": 1927, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.7010628120040541}}
{"text": "#include <vector>\n#include <Eigen/Dense>\n#include <GraphMol/PeriodicTable.h>\n\n#include \"AdjMatrix.h\"\n#include \"Mol.h\"\n\ndouble AtomDistance(Atom A, Atom B) {\n    double dist = std::sqrt(\n        (A.x - B.x)*(A.x - B.x) +\n        (A.y - B.y)*(A.y - B.y) +\n        (A.z - B.z)*(A.z - B.z)\n    );\n    return dist;\n}\n\nEigen::MatrixXd DistanceMatrix(std::vector<Atom> atoms) {\n\n    Eigen::MatrixXd distM(atoms.size(), atoms.size());\n\n    for (int i = 0; i < atoms.size(); i++) {\n        for (int j = i; j < atoms.size(); j++) {\n            distM(j, i) = AtomDistance(atoms[i], atoms[j]);\n            distM(i, j) = distM(j, i);\n        }\n    }\n    return distM;\n}\n\nEigen::MatrixXi AdjacencyMatrixDist(const std::vector<Atom> atoms, double covalentFactor) {\n    \n    RDKit::PeriodicTable *tbl = RDKit::PeriodicTable::getTable();   \n\n    Eigen::MatrixXi AC = Eigen::MatrixXi::Zero(atoms.size(), atoms.size());\n    Eigen::MatrixXd distM = DistanceMatrix(atoms);\n\n    for (int i = 0; i < atoms.size(); i++) {\n        for (int j = i + 1; j < atoms.size(); j++) {\n            double atomIRcov = tbl->getRcovalent(atoms[i].symbol) * covalentFactor;\n            double atomJRcov = tbl->getRcovalent(atoms[j].symbol) * covalentFactor;\n\n            if (distM(i, j) <= atomIRcov + atomJRcov) {\n                AC(i, j) = 1;\n                AC(j, i) = 1;\n            }\n        }\n    }\n    return AC;\n}                 ", "meta": {"hexsha": "f39279ac913885e4238fc193c8e1443e30b7f6e6", "size": 1399, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/xyz2smiles/AdjMatrix.cpp", "max_stars_repo_name": "koerstz/xyz2smiles", "max_stars_repo_head_hexsha": "4b1c064b64392d132a644616d4b3dc05c158ba4a", "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/xyz2smiles/AdjMatrix.cpp", "max_issues_repo_name": "koerstz/xyz2smiles", "max_issues_repo_head_hexsha": "4b1c064b64392d132a644616d4b3dc05c158ba4a", "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/xyz2smiles/AdjMatrix.cpp", "max_forks_repo_name": "koerstz/xyz2smiles", "max_forks_repo_head_hexsha": "4b1c064b64392d132a644616d4b3dc05c158ba4a", "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.5510204082, "max_line_length": 91, "alphanum_fraction": 0.5332380272, "num_tokens": 418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087965937711, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.7008697196076015}}
{"text": "\n//#include <Eigen/SVD>\n#include <algorithm> // std::sort, std::stable_sort\n#include <eigen3/Eigen/SVD>\n#include <itkDataObject.h>\n#include <itkImageRegionIterator.h>\n#include <itkIndex.h>\n#include <itkVariableLengthVector.h>\n#include <itkVectorImage.h>\n#include <m2CoreCommon.h>\n#include <m2PcaImageFilter.h>\n#include <m2Timer.h>\n#include <mitkIOUtil.h>\n#include <mitkImage.h>\n#include <mitkImageAccessByItk.h>\n#include <mitkImageCast.h>\n#include <mitkImagePixelReadAccessor.h>\n#include <numeric> // std::iota\n#include <vnl/vnl_matrix.h>\n#include <boost/progress.hpp>\n\nvoid m2::PcaImageFilter::initMatrix()\n{\n  // this->GetValidIndices();\n  auto input = this->GetIndexedInputs();\n  auto mitkImage = dynamic_cast<mitk::Image *>(input.front().GetPointer());\n  size_t pixels = 1;\n  for (unsigned int i = 0; i < mitkImage->GetDimension(); ++i)\n    pixels *= mitkImage->GetDimensions()[i];\n  const unsigned long numberOfrow = pixels;\n  const unsigned long numberOfcolumn = this->GetIndexedInputs().size();\n\n  this->m_DataMatrix.resize(numberOfrow, numberOfcolumn);\n  unsigned int c = 0;\n  boost::progress_display p(numberOfcolumn);\n  \n  /*Fill matrix with image values one column includes values of one image*/\n  for (auto it = input.begin(); it != input.end(); ++it, ++c)\n  {\n    mitkImage = dynamic_cast<mitk::Image *>(it->GetPointer());\n    mitk::ImagePixelReadAccessor<m2::DisplayImagePixelType, 3> access(mitkImage);\n    std::copy(access.GetData(), access.GetData() + pixels, m_DataMatrix.col(c).data());\n    ++p;\n  }\n\n  // auto maxCoeffs = m_DataMatrix.colwise().maxCoeff();\n  // auto minCoeffs = m_DataMatrix.colwise().minCoeff();\n  // auto scalingFactors = maxCoeffs - minCoeffs;\n  // m_DataMatrix = ((m_DataMatrix.rowwise() - minCoeffs).array().rowwise() / scalingFactors.array()).matrix();\n\n  // auto means = m_DataMatrix.colwise().mean();\n  // m_DataMatrix = m_DataMatrix.rowwise() - means;\n  // m_DataMatrix /= (m_DataMatrix.rows() - 1);\n\n  // for (unsigned int c = 0; c < m_DataMatrix.cols(); ++c)\n  // m_DataMatrix.col(c) = m_DataMatrix.col(c) / stdDevs[c];\n}\n\nEigen::MatrixXf m2::PcaImageFilter::GetEigenImageMatrix(){\n  return m_EigenImageMatrix;\n}\n\nEigen::VectorXf m2::PcaImageFilter::GetMeanImage(){\n  return m_MeanImage;\n}\n\nvoid m2::PcaImageFilter::GenerateData()\n{\n  auto timer = m2::Timer(\"PCA - Generate data ...\");\n  this->initMatrix();\n\n  // eigenionimages\n  m_MeanImage = m_DataMatrix.rowwise().mean();\n  Eigen::MatrixXf eigenionData = m_DataMatrix.colwise() - m_MeanImage;\n\n  Eigen::JacobiSVD<Eigen::MatrixXf> svd(eigenionData, Eigen::ComputeThinU | Eigen::ComputeThinV);\n  MITK_INFO << \"S size: \" << svd.singularValues().rows() << \" \" << svd.singularValues().cols();\n  MITK_INFO << \"U size: \" << svd.matrixU().rows() << \" \" << svd.matrixU().cols();\n  MITK_INFO << \"V size: \" << svd.matrixV().rows() << \" \" << svd.matrixV().cols();\n  MITK_INFO << \"m_DataMatrix: \" << m_DataMatrix.rows() << \" \" << m_DataMatrix.cols();\n\n  const Eigen::MatrixXf &U = svd.matrixU();\n  m_EigenImageMatrix = U;\n\n  auto eigenIonVectorImage = initializeItkVectorImage(m_NumberOfComponents);\n  m2::DisplayImagePixelType *data;\n  data = eigenIonVectorImage->GetBufferPointer();\n\n  for (unsigned int c = 0; c < m_NumberOfComponents; ++c)\n  {\n    const auto &col = U.col(c);\n    for (unsigned int p = 0; p < U.rows(); ++p)\n    {\n      data[p * m_NumberOfComponents + c] = col(p);\n    }\n  }\n\n  // feature pca\n  Eigen::MatrixXf pcaData = m_DataMatrix.rowwise() - m_DataMatrix.colwise().mean();\n  Eigen::MatrixXf cov = (pcaData.transpose() * pcaData) / (pcaData.rows() - 1);\n\n  Eigen::EigenSolver<Eigen::MatrixXf> solver(cov);\n  Eigen::VectorXf values = solver.eigenvalues().real();\n  Eigen::MatrixXf vectors = solver.eigenvectors().real();\n  Eigen::MatrixXf vectorsSorted(vectors);\n  // fill indices\n  std::vector<unsigned int> indices(values.size());\n  std::iota(indices.begin(), indices.end(), 0);\n  // sort indices according to\n  std::stable_sort(indices.begin(), indices.end(), [&values](auto i1, auto i2) { return values[i1] > values[i2]; });\n\n  unsigned int i = 0;\n  for (auto u : indices)\n    vectorsSorted.col(i++) = vectors.col(u);\n\n  Eigen::MatrixXf pc = pcaData * vectorsSorted;\n  auto pcVectorImage = initializeItkVectorImage(m_NumberOfComponents);\n  data = pcVectorImage->GetBufferPointer();\n\n  for (unsigned int c = 0; c < m_NumberOfComponents; ++c)\n  {\n    const auto &col = pc.col(c);\n    for (unsigned int p = 0; p < pc.rows(); ++p)\n    {\n      data[p * m_NumberOfComponents + c] = col(p);\n    }\n  }\n  \n\n  mitk::Image::Pointer eigenIonImage = this->GetOutput(0);\n  mitk::CastToMitkImage(eigenIonVectorImage, eigenIonImage);\n  eigenIonImage->SetSpacing(this->GetInput()->GetGeometry()->GetSpacing());\n  eigenIonImage->SetOrigin(this->GetInput()->GetGeometry()->GetOrigin());\n\n  mitk::Image::Pointer pcImage = this->GetOutput(1);\n  mitk::CastToMitkImage(pcVectorImage, pcImage);\n  pcImage->SetSpacing(this->GetInput()->GetGeometry()->GetSpacing());\n  pcImage->SetOrigin(this->GetInput()->GetGeometry()->GetOrigin());\n \n}\n", "meta": {"hexsha": "333c10c193ce82dee207ec2f62e5e11c1e8fe146", "size": 5028, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Modules/M2aiaDimensionReduction/src/m2PcaImageFilter.cpp", "max_stars_repo_name": "ivowolf/M2aia", "max_stars_repo_head_hexsha": "03cfe3495bc706cbb0b00a2916b8f0a3cb398e25", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2021-07-22T06:52:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T12:53:31.000Z", "max_issues_repo_path": "Modules/M2aiaDimensionReduction/src/m2PcaImageFilter.cpp", "max_issues_repo_name": "ivowolf/M2aia", "max_issues_repo_head_hexsha": "03cfe3495bc706cbb0b00a2916b8f0a3cb398e25", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-07-25T22:29:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-22T13:21:30.000Z", "max_forks_repo_path": "Modules/M2aiaDimensionReduction/src/m2PcaImageFilter.cpp", "max_forks_repo_name": "ivowolf/M2aia", "max_forks_repo_head_hexsha": "03cfe3495bc706cbb0b00a2916b8f0a3cb398e25", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-06-23T11:53:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-22T06:14:24.000Z", "avg_line_length": 35.6595744681, "max_line_length": 116, "alphanum_fraction": 0.6855608592, "num_tokens": 1468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554475, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.7008697123598818}}
{"text": "// test camera intrinsic calibration\n\n#include <minisam/3rdparty/Catch2/catch.hpp>\n#include <minisam/utils/testAssertions.h>\n#include <minisam/nonlinear/numericalJacobian.h>\n\n#include <minisam/geometry/CalibK.h>\n#include <minisam/geometry/CalibKD.h>\n#include <minisam/geometry/CalibBundler.h>\n\n#include <Eigen/Dense>  // inverse\n\nusing namespace std;\nusing namespace Eigen;\nusing namespace minisam;\n\n\n// wrapper for numerical jacobians\ntemplate<class CALIBRATION>\nVector2d wrapper_project(const CALIBRATION& K, const Vector2d& p) {\n  return K.project(p);\n}\ntemplate<class CALIBRATION>\nVector2d wrapper_unproject(const CALIBRATION& K, const Vector2d& p) {\n  return K.unproject(p);\n}\n\n// static test vars\nCalibK ucal1(1, 1, 0, 0);           // identity\nCalibK ucal2(100, 100, 300, 200);   // non-identity\nCalibK ucal3(37.4, 28.9, 107.1, -223.3);  // random non-identity\n\nCalibKD dcal1(1, 1, 0, 0, 0, 0, 0 ,0);                // identity\nCalibKD dcal2(100, 100, 300, 200, 0.1, 0.01, 0, 0);   // non-identity\nCalibKD dcal3(37.4, 28.9, 107.1, -223.3, 0.089, 0.063, -0.03, 0.08);  // random non-identity\nCalibKD dcal4(100, 100, 300, 200, -0.01, 0.001, 0, 0);   // non-identity\n\nCalibBundler bcal1(1, 0 ,0);              // identity\nCalibBundler bcal2(100, -0.01, 0.001);    // non-identity\nCalibBundler bcal3(37.4, 0.089, 0.063);   // random non-identity\n\n\n/* ************************************************************************** */\nTEST_CASE(\"CalibKTraits\", \"[geometry]\") {\n  CHECK(has_traits<CalibK>::value);\n  CHECK(is_manifold<CalibK>::value);\n  CHECK_FALSE(is_lie_group<CalibK>::value);\n}\n\n/* ************************************************************************** */\nTEST_CASE(\"CalibKConstructor\", \"[geometry]\") {\n  CHECK(assert_equal(CalibK((Vector4d() << 1, 2, 3, 4).finished()), CalibK(1, 2, 3, 4)));\n}\n\n/* ************************************************************************** */\nTEST_CASE(\"CalibKMatrix\", \"[geometry]\") {\n\n  Matrix3d K2, K3;\n  K2 << 100, 0, 300, 0, 100, 200, 0, 0, 1;\n  K3 << 37.4, 0, 107.1, 0, 28.9, -223.3, 0, 0, 1;\n\n  CHECK(assert_equal_matrix(Matrix3d::Identity(), ucal1.matrix()));\n  CHECK(assert_equal_matrix(Matrix3d::Identity(), ucal1.inverse_matrix()));\n\n  CHECK(assert_equal_matrix(K2, ucal2.matrix()));\n  CHECK(assert_equal_matrix(K2.inverse(), ucal2.inverse_matrix()));\n\n  CHECK(assert_equal_matrix(K3, ucal3.matrix()));\n  CHECK(assert_equal_matrix(K3.inverse(), ucal3.inverse_matrix()));\n}\n\n/* ************************************************************************** */\nTEST_CASE(\"CalibKc2i\", \"[geometry]\") {\n\n  Vector2d pc1 = Vector2d(0, 0);\n  Vector2d pc3 = Vector2d(23.4, 16.2);\n\n  // point\n  CHECK(assert_equal(pc1, ucal1.project(pc1)));\n  CHECK(assert_equal(pc3, ucal1.project(pc3)));\n\n  CHECK(assert_equal(Vector2d(300, 200), ucal2.project(pc1)));\n  CHECK(assert_equal(Vector2d(2640, 1820), ucal2.project(pc3)));\n\n  // jacobians\n  Eigen::Matrix<double, 2, 4> J_K_actual;\n  Eigen::Matrix<double, 2, 2> J_p_actual;\n\n  ucal1.projectJacobians(pc1, J_K_actual, J_p_actual);\n  CHECK(assert_equal_matrix(numericalJacobian21(wrapper_project<CalibK>, ucal1, pc1), J_K_actual));\n  CHECK(assert_equal_matrix(numericalJacobian22(wrapper_project<CalibK>, ucal1, pc1), J_p_actual));\n  ucal1.projectJacobians(pc3, J_K_actual, J_p_actual);\n  CHECK(assert_equal_matrix(numericalJacobian21(wrapper_project<CalibK>, ucal1, pc3), J_K_actual));\n  CHECK(assert_equal_matrix(numericalJacobian22(wrapper_project<CalibK>, ucal1, pc3), J_p_actual));\n\n  ucal2.projectJacobians(pc1, J_K_actual, J_p_actual);\n  CHECK(assert_equal_matrix(numericalJacobian21(wrapper_project<CalibK>, ucal2, pc1), J_K_actual));\n  CHECK(assert_equal_matrix(numericalJacobian22(wrapper_project<CalibK>, ucal2, pc1), J_p_actual));\n  ucal2.projectJacobians(pc3, J_K_actual, J_p_actual);\n  CHECK(assert_equal_matrix(numericalJacobian21(wrapper_project<CalibK>, ucal2, pc3), J_K_actual));\n  CHECK(assert_equal_matrix(numericalJacobian22(wrapper_project<CalibK>, ucal2, pc3), J_p_actual));\n\n  ucal3.projectJacobians(pc1, J_K_actual, J_p_actual);\n  CHECK(assert_equal_matrix(numericalJacobian21(wrapper_project<CalibK>, ucal3, pc1), J_K_actual));\n  CHECK(assert_equal_matrix(numericalJacobian22(wrapper_project<CalibK>, ucal3, pc1), J_p_actual));\n  ucal3.projectJacobians(pc3, J_K_actual, J_p_actual);\n  CHECK(assert_equal_matrix(numericalJacobian21(wrapper_project<CalibK>, ucal3, pc3), J_K_actual));\n  CHECK(assert_equal_matrix(numericalJacobian22(wrapper_project<CalibK>, ucal3, pc3), J_p_actual));\n}\n\n/* ************************************************************************** */\nTEST_CASE(\"CalibKi2c\", \"[geometry]\") {\n\n  Vector2d pi1 = Vector2d(300, 200);\n  Vector2d pi3 = Vector2d(2640, 1820);\n\n  // point\n  CHECK(assert_equal(pi1, ucal1.unproject(pi1)));\n  CHECK(assert_equal(pi3, ucal1.unproject(pi3)));\n\n  CHECK(assert_equal(Vector2d(0, 0), ucal2.unproject(pi1)));\n  CHECK(assert_equal(Vector2d(23.4, 16.2), ucal2.unproject(pi3)));\n\n  // jacobians\n  Eigen::Matrix<double, 2, 4> J_K_actual;\n  Eigen::Matrix<double, 2, 2> J_p_actual;\n\n  ucal1.unprojectJacobians(pi1, J_K_actual, J_p_actual);\n  CHECK(assert_equal_matrix(numericalJacobian21(wrapper_unproject<CalibK>, ucal1, pi1), J_K_actual));\n  CHECK(assert_equal_matrix(numericalJacobian22(wrapper_unproject<CalibK>, ucal1, pi1), J_p_actual));\n  ucal1.unprojectJacobians(pi3, J_K_actual, J_p_actual);\n  CHECK(assert_equal_matrix(numericalJacobian21(wrapper_unproject<CalibK>, ucal1, pi3), J_K_actual));\n  CHECK(assert_equal_matrix(numericalJacobian22(wrapper_unproject<CalibK>, ucal1, pi3), J_p_actual));\n\n  ucal2.unprojectJacobians(pi1, J_K_actual, J_p_actual);\n  CHECK(assert_equal_matrix(numericalJacobian21(wrapper_unproject<CalibK>, ucal2, pi1), J_K_actual));\n  CHECK(assert_equal_matrix(numericalJacobian22(wrapper_unproject<CalibK>, ucal2, pi1), J_p_actual));\n  ucal2.unprojectJacobians(pi3, J_K_actual, J_p_actual);\n  CHECK(assert_equal_matrix(numericalJacobian21(wrapper_unproject<CalibK>, ucal2, pi3), J_K_actual));\n  CHECK(assert_equal_matrix(numericalJacobian22(wrapper_unproject<CalibK>, ucal2, pi3), J_p_actual));\n\n  ucal3.unprojectJacobians(pi1, J_K_actual, J_p_actual);\n  CHECK(assert_equal_matrix(numericalJacobian21(wrapper_unproject<CalibK>, ucal3, pi1), J_K_actual));\n  CHECK(assert_equal_matrix(numericalJacobian22(wrapper_unproject<CalibK>, ucal3, pi1), J_p_actual));\n  ucal3.unprojectJacobians(pi3, J_K_actual, J_p_actual);\n  CHECK(assert_equal_matrix(numericalJacobian21(wrapper_unproject<CalibK>, ucal3, pi3), J_K_actual));\n  CHECK(assert_equal_matrix(numericalJacobian22(wrapper_unproject<CalibK>, ucal3, pi3), J_p_actual));\n}\n\n/* ************************************************************************** */\nTEST_CASE(\"CalibKDTraits\", \"[geometry]\") {\n  CHECK(has_traits<CalibKD>::value);\n  CHECK(is_manifold<CalibKD>::value);\n  CHECK_FALSE(is_lie_group<CalibKD>::value);\n}\n\n/* ************************************************************************** */\nTEST_CASE(\"CalibKDConstructor\", \"[geometry]\") {\n  CHECK(assert_equal(CalibKD((VectorXd(8) << 1, 2, 3, 4, 5, 6, 7, 8).finished()), \n      CalibKD(1, 2, 3, 4, 5, 6, 7, 8)));\n}\n\n/* ************************************************************************** */\nTEST_CASE(\"CalibKDc2i\", \"[geometry]\") {\n\n  Vector2d pc1 = Vector2d(0, 0);\n  Vector2d pc3 = Vector2d(2.4, 1.3);\n\n  // point\n  CHECK(assert_equal(pc1, dcal1.project(pc1)));\n  CHECK(assert_equal(pc3, dcal1.project(pc3)));\n\n  CHECK(assert_equal(Vector2d(300, 200), dcal2.project(pc1)));\n  CHECK(assert_equal(Vector2d(852.006, 499.00325), dcal2.project(pc3)));\n\n  CHECK(assert_equal(Vector2d(300, 200), dcal4.project(pc1)));\n  CHECK(assert_equal(Vector2d(535.4406, 327.530325), dcal4.project(pc3)));\n\n  // jacobians\n  Eigen::Matrix<double, 2, 8> J_K_actual;\n  Eigen::Matrix<double, 2, 2> J_p_actual;\n\n  dcal1.projectJacobians(pc1, J_K_actual, J_p_actual);\n  CHECK(assert_equal_matrix(numericalJacobian21(wrapper_project<CalibKD>, dcal1, pc1), J_K_actual));\n  CHECK(assert_equal_matrix(numericalJacobian22(wrapper_project<CalibKD>, dcal1, pc1), J_p_actual));\n  dcal1.projectJacobians(pc3, J_K_actual, J_p_actual);\n  CHECK(assert_equal_matrix(numericalJacobian21(wrapper_project<CalibKD>, dcal1, pc3), J_K_actual));\n  CHECK(assert_equal_matrix(numericalJacobian22(wrapper_project<CalibKD>, dcal1, pc3), J_p_actual));\n\n  dcal2.projectJacobians(pc1, J_K_actual, J_p_actual);\n  CHECK(assert_equal_matrix(numericalJacobian21(wrapper_project<CalibKD>, dcal2, pc1), J_K_actual));\n  CHECK(assert_equal_matrix(numericalJacobian22(wrapper_project<CalibKD>, dcal2, pc1), J_p_actual));\n  dcal2.projectJacobians(pc3, J_K_actual, J_p_actual);\n  CHECK(assert_equal_matrix(numericalJacobian21(wrapper_project<CalibKD>, dcal2, pc3), J_K_actual));\n  CHECK(assert_equal_matrix(numericalJacobian22(wrapper_project<CalibKD>, dcal2, pc3), J_p_actual));\n  \n  dcal3.projectJacobians(pc1, J_K_actual, J_p_actual);\n  CHECK(assert_equal_matrix(numericalJacobian21(wrapper_project<CalibKD>, dcal3, pc1), J_K_actual));\n  CHECK(assert_equal_matrix(numericalJacobian22(wrapper_project<CalibKD>, dcal3, pc1), J_p_actual));\n  dcal3.projectJacobians(pc3, J_K_actual, J_p_actual);\n  CHECK(assert_equal_matrix(numericalJacobian21(wrapper_project<CalibKD>, dcal3, pc3), J_K_actual));\n  CHECK(assert_equal_matrix(numericalJacobian22(wrapper_project<CalibKD>, dcal3, pc3), J_p_actual));\n  \n  dcal4.projectJacobians(pc1, J_K_actual, J_p_actual);\n  CHECK(assert_equal_matrix(numericalJacobian21(wrapper_project<CalibKD>, dcal4, pc1), J_K_actual));\n  CHECK(assert_equal_matrix(numericalJacobian22(wrapper_project<CalibKD>, dcal4, pc1), J_p_actual));\n  dcal4.projectJacobians(pc3, J_K_actual, J_p_actual);\n  CHECK(assert_equal_matrix(numericalJacobian21(wrapper_project<CalibKD>, dcal4, pc3), J_K_actual));\n  CHECK(assert_equal_matrix(numericalJacobian22(wrapper_project<CalibKD>, dcal4, pc3), J_p_actual));\n}\n\n/* ************************************************************************** */\nTEST_CASE(\"CalibKDi2c\", \"[geometry]\") {\n\n  Vector2d pi1 = Vector2d(300, 200);\n  Vector2d pi3 = Vector2d(535.4406, 327.530325);\n\n  CHECK(assert_equal(pi1, dcal1.unproject(pi1), 1e-6));\n  CHECK(assert_equal(pi3, dcal1.unproject(pi3), 1e-6));\n\n  CHECK(assert_equal(Vector2d(0, 0), dcal4.unproject(pi1), 1e-6));\n  CHECK(assert_equal(Vector2d(2.4, 1.3), dcal4.unproject(pi3), 1e-6));\n}\n\n\n/* ************************************************************************** */\nTEST_CASE(\"CalibBundlerTraits\", \"[geometry]\") {\n  CHECK(has_traits<CalibBundler>::value);\n  CHECK(is_manifold<CalibBundler>::value);\n  CHECK_FALSE(is_lie_group<CalibBundler>::value);\n}\n\n/* ************************************************************************** */\nTEST_CASE(\"CalibBundlerConstructor\", \"[geometry]\") {\n  CHECK(assert_equal(CalibBundler((VectorXd(3) << 1, 2, 3).finished()), \n      CalibBundler(1, 2, 3)));\n}\n\n/* ************************************************************************** */\nTEST_CASE(\"CalibBundlerc2i\", \"[geometry]\") {\n\n  Vector2d pc1 = Vector2d(0, 0);\n  Vector2d pc3 = Vector2d(2.4, 1.3);\n\n  // point\n  CHECK(assert_equal(pc1, bcal1.project(pc1)));\n  CHECK(assert_equal(pc3, bcal1.project(pc3)));\n\n  CHECK(assert_equal(Vector2d(0, 0), bcal2.project(pc1)));\n  CHECK(assert_equal(Vector2d(235.4406, 127.530325), bcal2.project(pc3)));\n\n  // jacobians\n  Eigen::Matrix<double, 2, 3> J_K_actual;\n  Eigen::Matrix<double, 2, 2> J_p_actual;\n\n  bcal1.projectJacobians(pc1, J_K_actual, J_p_actual);\n  CHECK(assert_equal_matrix(numericalJacobian21(wrapper_project<CalibBundler>, bcal1, pc1), J_K_actual));\n  CHECK(assert_equal_matrix(numericalJacobian22(wrapper_project<CalibBundler>, bcal1, pc1), J_p_actual));\n  bcal1.projectJacobians(pc3, J_K_actual, J_p_actual);\n  CHECK(assert_equal_matrix(numericalJacobian21(wrapper_project<CalibBundler>, bcal1, pc3), J_K_actual));\n  CHECK(assert_equal_matrix(numericalJacobian22(wrapper_project<CalibBundler>, bcal1, pc3), J_p_actual));\n\n  bcal2.projectJacobians(pc1, J_K_actual, J_p_actual);\n  CHECK(assert_equal_matrix(numericalJacobian21(wrapper_project<CalibBundler>, bcal2, pc1), J_K_actual));\n  CHECK(assert_equal_matrix(numericalJacobian22(wrapper_project<CalibBundler>, bcal2, pc1), J_p_actual));\n  bcal2.projectJacobians(pc3, J_K_actual, J_p_actual);\n  CHECK(assert_equal_matrix(numericalJacobian21(wrapper_project<CalibBundler>, bcal2, pc3), J_K_actual));\n  CHECK(assert_equal_matrix(numericalJacobian22(wrapper_project<CalibBundler>, bcal2, pc3), J_p_actual));\n  \n  bcal3.projectJacobians(pc1, J_K_actual, J_p_actual);\n  CHECK(assert_equal_matrix(numericalJacobian21(wrapper_project<CalibBundler>, bcal3, pc1), J_K_actual));\n  CHECK(assert_equal_matrix(numericalJacobian22(wrapper_project<CalibBundler>, bcal3, pc1), J_p_actual));\n  bcal3.projectJacobians(pc3, J_K_actual, J_p_actual);\n  CHECK(assert_equal_matrix(numericalJacobian21(wrapper_project<CalibBundler>, bcal3, pc3), J_K_actual));\n  CHECK(assert_equal_matrix(numericalJacobian22(wrapper_project<CalibBundler>, bcal3, pc3), J_p_actual));\n}\n\n/* ************************************************************************** */\nTEST_CASE(\"CalibBundleri2c\", \"[geometry]\") {\n\n  Vector2d pi1 = Vector2d(0, 0);\n  Vector2d pi3 = Vector2d(235.4406, 127.530325);\n\n  CHECK(assert_equal(pi1, bcal1.unproject(pi1), 1e-6));\n  CHECK(assert_equal(pi3, bcal1.unproject(pi3), 1e-6));\n\n  CHECK(assert_equal(Vector2d(0, 0), bcal2.unproject(pi1), 1e-6));\n  CHECK(assert_equal(Vector2d(2.4, 1.3), bcal2.unproject(pi3), 1e-6));\n}\n", "meta": {"hexsha": "4fb777688263b5a8ff89f50908dbad1a8dc26b67", "size": 13444, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/testCalibration.cpp", "max_stars_repo_name": "versatran01/minisam", "max_stars_repo_head_hexsha": "b3840d2629551fdfa287df8aac2e7956873d2b0e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 338.0, "max_stars_repo_stars_event_min_datetime": "2019-09-03T10:44:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:12:08.000Z", "max_issues_repo_path": "tests/testCalibration.cpp", "max_issues_repo_name": "bhsphd/minisam", "max_issues_repo_head_hexsha": "ef84796fa11ac6e5e4d4aa9d60d9b94a99a973fb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 23.0, "max_issues_repo_issues_event_min_datetime": "2019-09-26T09:00:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-04T06:04:02.000Z", "max_forks_repo_path": "tests/testCalibration.cpp", "max_forks_repo_name": "bhsphd/minisam", "max_forks_repo_head_hexsha": "ef84796fa11ac6e5e4d4aa9d60d9b94a99a973fb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 87.0, "max_forks_repo_forks_event_min_datetime": "2019-09-04T05:17:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T09:47:23.000Z", "avg_line_length": 46.3586206897, "max_line_length": 105, "alphanum_fraction": 0.6975602499, "num_tokens": 4104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637541053281, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7008258203354233}}
{"text": "#include <Eigen/Core>\n#include <cstdlib>\n#include <ctime>\n#include <fstream>\n#include <iostream>\n#include <mathtoolbox/bayesian-optimization.hpp>\n#include <optimization-test-functions.hpp>\n\nvoid ExportMatrixToCsv(const std::string& file_path, const Eigen::MatrixXd& X)\n{\n    std::ofstream   file(file_path);\n    Eigen::IOFormat format(Eigen::StreamPrecision, Eigen::DontAlignCols, \",\");\n    file << X.format(format);\n}\n\nint main()\n{\n    constexpr otf::FunctionType type       = otf::FunctionType::Sphere;\n    constexpr int               num_dims   = 5;\n    constexpr int               num_iters  = 15;\n    constexpr int               num_trials = 2;\n\n    std::srand(static_cast<unsigned>(std::time(nullptr)));\n\n    const auto            objective_func = [&](const Eigen::VectorXd& x) { return -otf::GetValue(x, type); };\n    const Eigen::VectorXd lower_bound    = Eigen::VectorXd::Constant(num_dims, -1.0);\n    const Eigen::VectorXd upper_bound    = Eigen::VectorXd::Constant(num_dims, 1.0);\n\n    Eigen::MatrixXd bo_result(num_iters, num_trials);\n\n    for (int trial = 0; trial < num_trials; ++trial)\n    {\n        std::cout << \"#trial: \" << std::to_string(trial + 1) << std::endl;\n\n        mathtoolbox::optimization::BayesianOptimizer optimizer(objective_func, lower_bound, upper_bound);\n\n        for (int iter = 0; iter < num_iters; ++iter)\n        {\n            const auto new_point = optimizer.Step();\n\n            const Eigen::VectorXd current_solution      = optimizer.GetCurrentOptimizer();\n            const double          current_optimal_value = optimizer.EvaluatePoint(current_solution);\n\n            std::cout << current_solution.transpose().format(Eigen::IOFormat(2));\n            std::cout << \" (\" << current_optimal_value << \")\" << std::endl;\n\n            bo_result(iter, trial) = current_optimal_value;\n        }\n    }\n\n    Eigen::MatrixXd rand_result(num_iters, num_trials);\n\n    for (int trial = 0; trial < num_trials; ++trial)\n    {\n        std::cout << \"#trial: \" << std::to_string(trial + 1) << std::endl;\n\n        Eigen::VectorXd current_solution;\n        double          current_optimal_value;\n\n        for (int iter = 0; iter < num_iters; ++iter)\n        {\n            const auto new_point = [&]() {\n                const Eigen::VectorXd normalized_sample =\n                    0.5 * (Eigen::VectorXd::Random(num_dims) + Eigen::VectorXd::Ones(num_dims));\n                const Eigen::VectorXd sample =\n                    (normalized_sample.array() * (upper_bound - lower_bound).array()).matrix() + lower_bound;\n\n                return sample;\n            }();\n\n            const double new_value = objective_func(new_point);\n\n            if (current_solution.size() == 0 || current_optimal_value < new_value)\n            {\n                current_solution      = new_point;\n                current_optimal_value = new_value;\n            }\n\n            std::cout << current_solution.transpose().format(Eigen::IOFormat(2));\n            std::cout << \" (\" << current_optimal_value << \")\" << std::endl;\n\n            rand_result(iter, trial) = current_optimal_value;\n        }\n    }\n\n    const Eigen::VectorXd expected_solution = otf::GetSolution(num_dims, type);\n    const double          expected_value    = objective_func(expected_solution);\n\n    std::cout << \"Expected solution: \" << expected_solution.transpose() << \" (\" << expected_value << \")\" << std::endl;\n\n    ExportMatrixToCsv(\"./bo_result.csv\", bo_result);\n    ExportMatrixToCsv(\"./rand_result.csv\", rand_result);\n\n    return 0;\n}\n", "meta": {"hexsha": "10d1c18d3506f28bc3de68f08bee34e257630b4d", "size": 3512, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/bayesian-optimization/main.cpp", "max_stars_repo_name": "yuki-koyama/mathtoolbox", "max_stars_repo_head_hexsha": "eb7449c3c489f465849a74405e72aff016a296f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 195.0, "max_stars_repo_stars_event_min_datetime": "2018-04-28T16:12:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:52:56.000Z", "max_issues_repo_path": "examples/bayesian-optimization/main.cpp", "max_issues_repo_name": "amazing89/mathtoolbox", "max_issues_repo_head_hexsha": "8904bb06ced2ac501594f9574ef1ba3454b8e38e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 52.0, "max_issues_repo_issues_event_min_datetime": "2018-04-15T01:24:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-02T09:14:23.000Z", "max_forks_repo_path": "examples/bayesian-optimization/main.cpp", "max_forks_repo_name": "amazing89/mathtoolbox", "max_forks_repo_head_hexsha": "8904bb06ced2ac501594f9574ef1ba3454b8e38e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 21.0, "max_forks_repo_forks_event_min_datetime": "2018-06-05T04:11:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T13:28:12.000Z", "avg_line_length": 36.5833333333, "max_line_length": 118, "alphanum_fraction": 0.6053530752, "num_tokens": 793, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637361282706, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7008258076094909}}
{"text": "\n#pragma once\n\n#include <array>\n#include <Eigen/Core>\n\nnamespace Discregrid\n{\n\nenum class NearestEntity\n{\n\tVN0, VN1, VN2, EN0, EN1, EN2, FN\n};\n\ndouble point_triangle_sqdistance(Eigen::Vector3d const& point, \n\tstd::array<Eigen::Vector3d const*, 3> const& triangle,\n\tEigen::Vector3d* nearest_point = nullptr,\n\tNearestEntity* ne = nullptr);\n\n}\n\n", "meta": {"hexsha": "00f73d1d97f741a3f4f394318e7082fbe3528784", "size": 342, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/geometry/point_triangle_distance.hpp", "max_stars_repo_name": "Q-Minh/Discregrid", "max_stars_repo_head_hexsha": "a48a4955f9342b2029e3222ea7e3f9ebaff4fc99", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2022-03-14T03:51:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T17:47:44.000Z", "max_issues_repo_path": "src/geometry/point_triangle_distance.hpp", "max_issues_repo_name": "Q-Minh/Discregrid", "max_issues_repo_head_hexsha": "a48a4955f9342b2029e3222ea7e3f9ebaff4fc99", "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/geometry/point_triangle_distance.hpp", "max_forks_repo_name": "Q-Minh/Discregrid", "max_forks_repo_head_hexsha": "a48a4955f9342b2029e3222ea7e3f9ebaff4fc99", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2022-03-24T10:55:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T17:08:16.000Z", "avg_line_length": 15.5454545455, "max_line_length": 63, "alphanum_fraction": 0.7251461988, "num_tokens": 104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970717197768, "lm_q2_score": 0.7956581073313275, "lm_q1q2_score": 0.7008133310275332}}
{"text": "/**\n * @file\n * @brief NPDE homework ElementMatrixComputation code\n * @author Janik Sch\u00fcttler, edited by Oliver Rietmann\n * @date 03.03.2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"mylinearfeelementmatrix.h\"\n\n#include <lf/base/base.h>\n#include <lf/geometry/geometry.h>\n#include <lf/mesh/mesh.h>\n#include <lf/uscalfe/uscalfe.h>\n\n#include <Eigen/Core>\n\nnamespace ElementMatrixComputation {\n\n/* SAM_LISTING_BEGIN_1 */\nEigen::Matrix<double, 4, 4> MyLinearFEElementMatrix::Eval(\n    const lf::mesh::Entity &cell) {\n  // Topological type of the cell\n  const lf::base::RefEl ref_el{cell.RefEl()};\n\n  // Obtain the vertex coordinates of the cell, which completely\n  // describe its shape.\n  const lf::geometry::Geometry *geo_ptr = cell.Geometry();\n  // Matrix storing corner coordinates in its columns\n  auto vertices = geo_ptr->Global(ref_el.NodeCoords());\n  // Matrix for returning element matrix\n  Eigen::Matrix<double, 4, 4> elem_mat;\n#if SOLUTION\n  // Initialize matrix containing the mass part of the element matrix\n  Eigen::Matrix<double, 4, 4> mass_elem_mat;\n  // Retrieve laplace part of element matrix from LehrFEM's built-in laplace\n  // element matrix builder\n  lf::uscalfe::LinearFELaplaceElementMatrix laplace_elmat_builder;\n  auto laplace_elem_mat = laplace_elmat_builder.Eval(cell);\n  // Computations differ depending on the type of the cell\n  switch (ref_el) {\n    case lf::base::RefEl::kTria(): {\n      double area = 0.5 * ((vertices(0, 1) - vertices(0, 0)) *\n                               (vertices(1, 2) - vertices(1, 0)) -\n                           (vertices(1, 1) - vertices(1, 0)) *\n                               (vertices(0, 2) - vertices(0, 0)));\n      // clang-format off\n      mass_elem_mat << 2.0, 1.0, 1.0, 0.0, \n\t1.0, 2.0, 1.0, 0.0, \n\t1.0, 1.0, 2.0, 0.0, \n\t0.0, 0.0, 0.0, 0.0;\n      // clang-format on\n      mass_elem_mat *= area / 12.0;\n      break;\n    }\n    case lf::base::RefEl::kQuad(): {\n      double area =\n          (vertices(0, 1) - vertices(0, 0)) * (vertices(1, 3) - vertices(1, 0));\n      // clang-format off\n      mass_elem_mat << 4.0, 2.0, 1.0, 2.0, \n\t2.0, 4.0, 2.0, 1.0, \n\t1.0, 2.0, 4.0, 2.0, \n\t2.0, 1.0, 2.0, 4.0;\n      // clang-format on\n      mass_elem_mat *= area / 36.0;\n      break;\n    }\n    default: {\n      LF_ASSERT_MSG(false, \"Illegal cell type\");\n    }\n  }  // end switch\n  elem_mat = laplace_elem_mat + mass_elem_mat;\n#else\n\n  //====================\n  // Your code goes here\n  //====================\n\n#endif\n  return elem_mat;\n}\n/* SAM_LISTING_END_1 */\n}  // namespace ElementMatrixComputation\n", "meta": {"hexsha": "2e6c228b201169673b71f2e0673cfc997dee42b5", "size": 2560, "ext": "cc", "lang": "C++", "max_stars_repo_path": "developers/ElementMatrixComputation/mastersolution/mylinearfeelementmatrix.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": "developers/ElementMatrixComputation/mastersolution/mylinearfeelementmatrix.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": "developers/ElementMatrixComputation/mastersolution/mylinearfeelementmatrix.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": 30.4761904762, "max_line_length": 80, "alphanum_fraction": 0.6171875, "num_tokens": 823, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797051879431, "lm_q2_score": 0.7690802370707283, "lm_q1q2_score": 0.7007703036799796}}
{"text": "#pragma once\r\n\r\n/* \"THE BEER-WARE LICENSE\" (Revision 42): Devin Lane wrote this file. As long as you retain\r\n* this notice you can do whatever you want with this stuff. If we meet some day, and you\r\n* think this stuff is worth it, you can buy me a beer in return.\r\nhttps://shiftedbits.org/2011/01/30/cubic-spline-interpolation/\r\n\r\nThe code has been converted to use Armadillo data type for slabcc by https://github.com/MFTabriz\r\n\r\n*/\r\n#include <vector>\r\n#include <iostream>\r\n#include <armadillo>\r\n\r\n\r\ntemplate <typename X>\r\nclass Spline {\r\npublic:\r\n\r\n\t// A spline with x and y values\r\n\tSpline(const arma::Row<X>& x, const arma::Col<X>& y) {\r\n\t\tif (x.n_elem != y.n_elem) {\r\n\t\t\tstd::cerr << \"Spline: X and Y must be the same size!\\n\";\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tif (x.n_elem < 3) {\r\n\t\t\tstd::cerr << \"Spline: Must have at least three points for interpolation!\\n\";\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tconst arma::uword n = y.n_elem - 1;\r\n\r\n\t\tarma::Row<X> b(n), d(n), a(n), c(n + 1), l(n + 1), u(n + 1), z(n + 1), h(n + 1);\r\n\r\n\t\tl(0) = 1;\r\n\t\tu(0) = 0; z(0) = 0;\r\n\t\th(0) = x(1) - x(0);\r\n\t\tfor (arma::uword i = 1; i < n; ++i) {\r\n\t\t\th(i) = x(i + 1) - x(i);\r\n\t\t\tl(i) = 2 * (x(i + 1) - x(i - 1)) - h(i - 1) * u(i - 1);\r\n\t\t\tu(i) = h(i) / l(i);\r\n\t\t\ta(i) = (3 / h(i)) * (y(i + 1) - y(i)) - (3 / h(i - 1)) * (y(i) - y(i - 1));\r\n\t\t\tz(i) = (a(i) - h(i - 1) * z(i - 1)) / l(i);\r\n\t\t}\r\n\t\tl(n) = 1;\r\n\t\tz(n) = 0; c(n) = 0;\r\n\t\tfor (arma::sword j = n - 1; j >= 0; --j) {\r\n\t\t\tc(j) = z(j) - u(j) * c(j + 1);\r\n\t\t\tb(j) = (y(j + 1) - y(j)) / h(j) - (h(j) * (c(j + 1) + 2 * c(j))) / 3;\r\n\t\t\td(j) = (c(j + 1) - c(j)) / (3 * h(j));\r\n\t\t}\r\n\t\tfor (arma::uword i = 0; i < n; ++i) {\r\n\t\t\tmElements.push_back(Element(x(i), y(i), b(i), c(i), d(i)));\r\n\t\t}\r\n\t}\r\n\r\n\t//return the value of the spline function for x\r\n\tX interpolate(const X&x) const {\r\n\t\tif (mElements.empty()) return X();\r\n\r\n\t\tauto it = std::lower_bound(mElements.begin(), mElements.end(), element_type(x));\r\n\t\tif (it != mElements.begin()) { --it; }\r\n\t\treturn it->eval(x);\r\n\t}\r\n\r\n\t//return the value of the spline function for a Row\r\n\tarma::Col<X> interpolate(const arma::Row<X>& xx) const {\r\n\t\tif (mElements.empty()) return arma::Row<X>(xx.size());\r\n\r\n\t\tarma::Col<X> ys = arma::zeros<arma::Col<X>>(xx.n_elem);\r\n\r\n\t\tfor (arma::uword it = 0; it < xx.n_elem; ++it) {\r\n\t\t\tys(it) = interpolate(xx(it));\r\n\t\t}\r\n\t\treturn ys;\r\n\t}\r\n\r\nprotected:\r\n\r\n\tclass Element {\r\n\tpublic:\r\n\r\n\t\tX x = 0, a = 0, b = 0, c = 0, d = 0;\r\n\r\n\t\tElement(X _x) noexcept : x(_x) {}\r\n\t\tElement(X _x, X _a, X _b, X _c, X _d) noexcept\r\n\t\t\t: x(_x), a(_a), b(_b), c(_c), d(_d) {}\r\n\r\n\t\tX eval(const X& xx) const noexcept {\r\n\t\t\tX xix(xx - x);\r\n\t\t\treturn a + b * xix + c * (xix * xix) + d * (xix * xix * xix);\r\n\t\t}\r\n\r\n\t\tbool operator<(const Element& e) const noexcept {\r\n\t\t\treturn x < e.x;\r\n\t\t}\r\n\t};\r\n\ttypedef Element element_type;\r\n\tstd::vector<element_type> mElements;\r\n\r\n};\r\n", "meta": {"hexsha": "68665715c7f916d7d1501fb8aa93159a0786d190", "size": 2838, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/spline/spline.hpp", "max_stars_repo_name": "Anower120/slabcc", "max_stars_repo_head_hexsha": "8b8d17224314ad4c37c6c57d3c613592572870f8", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-02T01:11:56.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-02T01:11:56.000Z", "max_issues_repo_path": "src/spline/spline.hpp", "max_issues_repo_name": "Anower120/slabcc", "max_issues_repo_head_hexsha": "8b8d17224314ad4c37c6c57d3c613592572870f8", "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/spline/spline.hpp", "max_forks_repo_name": "Anower120/slabcc", "max_forks_repo_head_hexsha": "8b8d17224314ad4c37c6c57d3c613592572870f8", "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": 27.5533980583, "max_line_length": 97, "alphanum_fraction": 0.5253699789, "num_tokens": 1054, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505453836383, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.7007272903447878}}
{"text": "#define _CRT_SECURE_NO_WARNINGS\n#define _USE_MATH_DEFINES\n\n#include <iostream>\n#include <fstream>\n#include <iomanip>\n#include <string>\n#include <cmath>\n#include <complex>\n#include <utility>\n#include <tuple>\n\n#include \"xtensor/xarray.hpp\"\n#include \"xtensor/xio.hpp\"\n#include \"xtensor/xview.hpp\"\n#include \"xtensor/xmanipulation.hpp\"\n#include \"xtensor-io/xnpz.hpp\"\n#include \"xtensor-io/ximage.hpp\"\n\n#include <boost/program_options.hpp>\n\n\nvoid mandelbrot(\n    std::pair<long, long> resolution, \n    std::pair<std::complex<double>, \n    std::complex<double>> bounds, \n    long max_iter,\n    double r = 2.,\n    int k = 2) {\n    \n    const double a0 = bounds.first.real();\n    const double b0 = bounds.first.imag();\n    const double a1 = bounds.second.real();\n    const double b1 = bounds.second.imag();\n    const long height = resolution.first;\n    const long width = resolution.second;\n    const long channels = 3;\n\n    long n;\n    double imag, real;\n    auto I = std::complex<double>(0.0, 1.);\n\n    std::complex<double> z0(0., 0.);\n    std::complex<double> z(z0);\n    std::complex<double> c;\n\n    xt::xtensor<double, 1> xrange = xt::linspace<double>(a0, a1, width);\n    xt::xtensor<double, 1> yrange = xt::linspace<double>(b0, b1, height);\n\n    xt::xtensor<long, 2> counts = xt::zeros<long>({ height, width });\n    xt::xtensor<long, 2> norms = xt::zeros<double>({ height, width });\n    xt::xtensor<long, 2> args = xt::zeros<double>({ height, width });\n\n    for (size_t i = 0; i < height; i++) {\n        imag = yrange(i);\n\n        std::cout << std::fixed << std::setprecision(2) << \"\\rRunning... \" << 100.0 * (i + 1.0) / height << \"%\" << std::flush;\n\n        for (size_t j = 0; j < width; j++) {\n            real = xrange(j);\n\n            n = 0;\n            z = z0;\n            c = std::complex<double>(real, imag);\n\n            const bool period_one = std::abs(1. - std::sqrt(1. - 4. * c)) <= 1.;\n            const bool period_two = std::abs(c + 1.) < 0.25;\n\n            if (period_one || period_two) {\n                n = max_iter;\n            }\n            else {\n                while (n < max_iter && std::abs(z) < r) {\n                    n++;\n                    z = std::pow(z, k) + c;\n                }\n            }\n\n            norms(i, j) = std::norm(z);\n            args(i, j) = std::arg(z);\n            counts(i, j) = n - std::log( std::log(std::norm(z))/std::log(r))/std::log(k);  // renormalized\n        }\n    }\n\n    const double min_counts = xt::amin(counts)();\n    const double max_counts = xt::amax(counts)();\n\n    const double min_norms = xt::amin(norms)();\n    const double max_norms = xt::amax(norms)();\n\n    const double min_args = xt::amin(args)();\n    const double max_args = xt::amax(args)();\n\n    auto scaled_counts = (counts - min_counts) / (max_counts - min_counts);\n    auto scaled_norms = (norms - min_norms) / (max_norms - min_norms);\n    auto scaled_args = (args   - min_args  ) / (max_args   - min_args  );\n\n    xt::dump_image(\"../../mandelbrot_counts.png\", xt::cast<uint8_t>(255 * scaled_counts));\n    xt::dump_image(\"../../mandelbrot_norms.png\" , xt::cast<uint8_t>(255 * scaled_norms ));\n    xt::dump_image(\"../../mandelbrot_args.png\"  , xt::cast<uint8_t>(255 * scaled_args  ));\n\n    xt::xtensor<uint8_t, 3> image = xt::zeros<uint8_t>({ height, width, channels });\n    std::tuple<uint8_t, uint8_t, uint8_t> color;\n\n    for (size_t i = 0; i < height; i++) {\n        std::cout << std::fixed << std::setprecision(2) << \"\\rColoring... \" << 100.0 * (i + 1.0) / height << \"%\" << std::flush;\n\n        for (size_t j = 0; j < width; j++) {\n            image(i, j, 0) = (uint8_t) 255 * scaled_counts(i, j);\n            image(i, j, 1) = (uint8_t) 255 * scaled_args(i, j);\n            image(i, j, 2) = (uint8_t) 255 * scaled_norms(i, j);\n        }\n    }\n\n    xt::dump_image(\"../../mandelbrot_color.png\", image);\n}\n\nnamespace opt = boost::program_options;\n\nint main(int argc, char** argv) {\n    int height, width, max_iter;\n    double xi, xf, yi, yf, r, p;\n\n\n    opt::options_description params(\"Mandelbrot Set Parameters\");\n\n    params.add_options()\n        (\"help\", \"Show Usage\")\n        (\"height,h\", opt::value< int >(&height)->default_value(2160), \"Image Height\")  // 4320\n        (\"width,w\", opt::value< int >(&width)->default_value(3840), \"Image Width\")  // 7680\n        (\"max_iter,m\", opt::value< int >(&max_iter)->default_value(1000), \"Maximum Number Of Iterations\")\n        (\"xi\", opt::value<double>(&xi)->default_value(-2.0), \"Lower Real Bound\")\n        (\"xf\", opt::value<double>(&xf)->default_value(1.0), \"Upper Real Bound\")\n        (\"yi\", opt::value<double>(&yi)->default_value(-1.5), \"Lower Imaginary Bound\")\n        (\"yf\", opt::value<double>(&yf)->default_value(1.5), \"Upper Imaginary Bound\")\n        (\"radius,r\", opt::value<double>(&r)->default_value(2.), \"Bail-Out Radius\")\n        (\"power,p\",  opt::value<double>(&p)->default_value(2.), \"Polynomial Power Of The Logistic Map (Classic Mandelbrot Set: p = 2)\")\n        ;\n\n    opt::variables_map vm;\n    opt::store(opt::parse_command_line(argc, argv, params), vm);\n\n    if (vm.count(\"help\")) {\n        std::cout << params << std::endl;\n        return 1;\n    }\n    else {\n        opt::notify(vm);\n        mandelbrot(std::make_pair(height, width), std::make_pair(std::complex<double>(xi, yi), std::complex<double>(xf, yf)), max_iter, r, p);\n        return 0;\n    }\n}\n", "meta": {"hexsha": "228e734e3edecd8e6a173edaf24c133aba98eae1", "size": 5347, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MandelbrotSet.cpp", "max_stars_repo_name": "ethank5149/MandelbrotSet", "max_stars_repo_head_hexsha": "9b10973e63dd1884c7e12179def27b170c9a452b", "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": "MandelbrotSet.cpp", "max_issues_repo_name": "ethank5149/MandelbrotSet", "max_issues_repo_head_hexsha": "9b10973e63dd1884c7e12179def27b170c9a452b", "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": "MandelbrotSet.cpp", "max_forks_repo_name": "ethank5149/MandelbrotSet", "max_forks_repo_head_hexsha": "9b10973e63dd1884c7e12179def27b170c9a452b", "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.9477124183, "max_line_length": 142, "alphanum_fraction": 0.5713484197, "num_tokens": 1561, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.7007272783975189}}
{"text": "#include <FindPeriod.hpp>\n#include <gnuplot-iostream/gnuplot-iostream.h>\n#include <boost/tuple/tuple.hpp>\n#include <iostream>\n#include <vector>\n#include <iomanip>\nusing namespace std;\n\n/**********************************************************\n\nPlots x_n vs. n. The main function is pretty simple. The\nprintFixedPoints function (after checking for sillyness)\nIterates the logistic function until FPVAL to remove the\nerror near the origin, then prints out p values, where p\nis the period. Values at each point of the period are\nthe fixed points.\n\n**********************************************************/\n\nconst int CUTOFF = 100;\t// Cutoff value for graph\nconst long FPVAL = 10000; // Value to start finding fixed points\nconst double r = 3.5;\t// Growth rate\nconst double x_0 = 0.2;\t// Initial value\n\nvoid plotStuff(vector<int> x, vector<double> y){\n\tGnuplot gp;\t\t\t\t\t\t\t\t\t\t// Define a gnuplot output stream (runs the gnuplot command behind the scenes)\n\tgp << setprecision(3);\n\tgp << \"set xrange [0:\" << CUTOFF << \"]\\n\";\t\t// Set the x and y range for the plot\n\tgp << \"set yrange [0:1]\\n\";\n\tgp << \"set term wxt font \\\"FreeSerif,12\\\"\\n\";\n\tgp << \"set title \\\"Logistic Function with x_0 = \" << x0 << \" and r = \" << r << \"\\\"\\n\";\n\tgp << \"set xlabel \\\"n\\\"\\n\";\n\tgp << \"set ylabel \\\"x_n\\\"\\n\";\n\tgp << \"plot '-' with linespoints lc rgb \\\"black\\\" notitle\\n\";\t// Plot the data to be given as a line graph with points, title \n\tgp.send1d(boost::make_tuple(x,y));\t\t\t\t// Send the data as a tuple\n}\n\nvoid printFixedPoints(){\n\tint p = getPeriod(r);\t// Get period\n\tcout << \"Period: \" << p << \"\\n\";\n\n\tif(p == 0){\n\t\tcout << \"Chaotic!\\n\";\t// Notify user if the value of r leads to chaotic behavior\n\t} else if (x_0 == 0 || x_0 == 1){\n\t\tcout << \"Trivial!\\n\";\t// Also notify if the initial value is bad\n\t} else {\n\t\tcout << \"Fixed points:\\n\";\n\n\t\tdouble x = x_0;\n\t\tfor(int i = 0; i < FPVAL+p; i++){\n\t\t\tx = r*x*(1-x);\t\t// Perform the logistic map operation x_n+1 = r*x_n*(1-x_n)\n\t\t\tif(i >= FPVAL){\n\t\t\t\tcout << x << \"\\n\";\n\t\t\t}\n\t\t}\n\t}\n}\n\nint main(){\t\t\t\t// Main section\n\tvector<double> x_n;\t// Stores values for x at generation n\n\tvector<int> n;\t\t// Store generation n\n\t\n\tdouble x = x_0;\t\t// Current value of x (population)\n\n\tfor(int i = 0; i < CUTOFF; i++){\t// Loop until the cutoff\n\t\tx_n.push_back(x);\t\t\t\t// Push the x value onto the vector of values\n\t\tn.push_back(i);\t\t\t\t\t// same with n\n\t\tx = r*x*(1-x);\t\t\t\t\t// Perform the logistic map operation x_n+1 = r*x_n*(1-x_n)\n\t}\n\n\tfor(int i = 0; i < x_n.size(); i++){\t\t// Output loop for gnuplot!\n\t\tcout << n[i] << \"\\t\" << x_n[i] << \"\\n\";\t// x_n vs n\n\t}\n\n\tplotStuff(n,x_n);\t\t// Plot the data\n\n\tprintFixedPoints();\n\n}", "meta": {"hexsha": "10f83908c309ead7d94e7ff422e8bfe8d5ef7ea6", "size": 2628, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Logistic Map/LogisticPlot.cpp", "max_stars_repo_name": "GEslinger/PhysClass", "max_stars_repo_head_hexsha": "5e34167c34ca0e8779e4002063d95ffa24a24c9d", "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": "Logistic Map/LogisticPlot.cpp", "max_issues_repo_name": "GEslinger/PhysClass", "max_issues_repo_head_hexsha": "5e34167c34ca0e8779e4002063d95ffa24a24c9d", "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": "Logistic Map/LogisticPlot.cpp", "max_forks_repo_name": "GEslinger/PhysClass", "max_forks_repo_head_hexsha": "5e34167c34ca0e8779e4002063d95ffa24a24c9d", "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": 33.2658227848, "max_line_length": 127, "alphanum_fraction": 0.598934551, "num_tokens": 810, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505273888291, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.7007272716988646}}
{"text": "//           Copyright Matthew Pulver 2018 - 2019.\n// Distributed under the Boost Software License, Version 1.0.\n//      (See accompanying file LICENSE_1_0.txt or copy at\n//           https://www.boost.org/LICENSE_1_0.txt)\n\n#include <boost/math/differentiation/autodiff.hpp>\n#include <iostream>\n#include <stdexcept>\n\nusing namespace boost::math::constants;\nusing namespace boost::math::differentiation;\n\n// Equations and function/variable names are from\n// https://en.wikipedia.org/wiki/Greeks_(finance)#Formulas_for_European_option_Greeks\n\n// Standard normal cumulative distribution function\ntemplate <typename X>\nX Phi(X const& x) {\n  return 0.5 * erfc(-one_div_root_two<X>() * x);\n}\n\nenum class CP { call, put };\n\n// Assume zero annual dividend yield (q=0).\ntemplate <typename Price, typename Sigma, typename Tau, typename Rate>\npromote<Price, Sigma, Tau, Rate> black_scholes_option_price(CP cp,\n                                                            double K,\n                                                            Price const& S,\n                                                            Sigma const& sigma,\n                                                            Tau const& tau,\n                                                            Rate const& r) {\n  using namespace std;\n  auto const d1 = (log(S / K) + (r + sigma * sigma / 2) * tau) / (sigma * sqrt(tau));\n  auto const d2 = (log(S / K) + (r - sigma * sigma / 2) * tau) / (sigma * sqrt(tau));\n  switch (cp) {\n    case CP::call:\n      return S * Phi(d1) - exp(-r * tau) * K * Phi(d2);\n    case CP::put:\n      return exp(-r * tau) * K * Phi(-d2) - S * Phi(-d1);\n    default:\n      throw std::runtime_error(\"Invalid CP value.\");\n  }\n}\n\nint main() {\n  double const K = 100.0;                    // Strike price.\n  auto const S = make_fvar<double, 2>(105);  // Stock price.\n  double const sigma = 5;                    // Volatility.\n  double const tau = 30.0 / 365;             // Time to expiration in years. (30 days).\n  double const r = 1.25 / 100;               // Interest rate.\n  auto const call_price = black_scholes_option_price(CP::call, K, S, sigma, tau, r);\n  auto const put_price = black_scholes_option_price(CP::put, K, S, sigma, tau, r);\n\n  std::cout << \"black-scholes call price = \" << call_price.derivative(0) << '\\n'\n            << \"black-scholes put  price = \" << put_price.derivative(0) << '\\n'\n            << \"call delta = \" << call_price.derivative(1) << '\\n'\n            << \"put  delta = \" << put_price.derivative(1) << '\\n'\n            << \"call gamma = \" << call_price.derivative(2) << '\\n'\n            << \"put  gamma = \" << put_price.derivative(2) << '\\n';\n  return 0;\n}\n/*\nOutput:\nblack-scholes call price = 56.5136\nblack-scholes put  price = 51.4109\ncall delta = 0.773818\nput  delta = -0.226182\ncall gamma = 0.00199852\nput  gamma = 0.00199852\n**/\n", "meta": {"hexsha": "7078217b605e6fe0f6f8e34249188ce9ef6f71ad", "size": 2849, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/math/example/autodiff_black_scholes_brief.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/autodiff_black_scholes_brief.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/autodiff_black_scholes_brief.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": 40.1267605634, "max_line_length": 87, "alphanum_fraction": 0.5566865567, "num_tokens": 761, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465098415279, "lm_q2_score": 0.749087201911703, "lm_q1q2_score": 0.7006560998750673}}
{"text": "#include <iostream>\n#include <armadillo>\n#include <string>\n#include <math.h>\n#include <utility>\n\nvoid plotData(std::vector<double> data);\nclass LogisticRegression {\n    arma::mat weights;\n    double bias;\n    arma::mat input;\n    arma::mat target;\n    double learningRate;\n    int numIterations;\n\n    public:\n    LogisticRegression(arma::mat w, double b, arma::mat x, arma::mat y, double rate, int iterations) {\n        weights = w;\n        bias = b;\n        input = x;\n        target = y;\n        learningRate = rate;\n        numIterations = iterations;\n    }\n\n    double computeLogitError() {\n        double totalError = 0.0;\n        for(int i=0; i<input.n_rows; i++) {\n            double weightedSum = bias;\n            for(int j=0; j<input.n_cols; j++) {\n                 weightedSum += weights(j)*input(i,j);\n            }\n            double prediction = 1.0/(1.0 + exp(-weightedSum));\n            totalError += target(i) - prediction;\n        }\n        return totalError / input.n_rows;\n    }\n\n    void updateParameters() {\n        double biasGradient = 0.0;\n        arma::mat weightGradients(weights.n_rows, 1, arma::fill::zeros);\n        double N = input.n_rows;\n        for(int i=0; i<N; i++) {\n            double weightedSum = bias;\n            for(int j=0; j<input.n_cols; j++) {\n                weightedSum += weights(j) * input(i,j);\n            }\n            double prediction = 1.0 / (1.0 + exp(-weightedSum));\n\n            biasGradient += -2.0/N * (target[i] - prediction);\n            weightGradients += -2.0/N * input[i] * (target[i] - prediction);\n        }\n        weights = weights - learningRate * weightGradients;\n        bias = bias - learningRate * biasGradient;\n    }\n\n    std::vector<double> gradientDescent() {\n        double logitError = computeLogitError();\n        std::vector<double> errorList (numIterations, 0.0);\n\n        for(int i=0; i<numIterations; i++) {\n            errorList[i] = logitError;\n            if (i%1000==0) {\n                std::cout << \"Step \" << i << \" \" << logitError << std::endl;\n            }\n            updateParameters();\n            logitError = computeLogitError();\n        }\n\n        return errorList;\n    }\n};\n\nvoid plotData(std::vector<double> data) {\n    FILE *pipe = popen(\"gnuplot -persist\" , \"w\");\n\n    if (pipe != NULL) {\n\n        fprintf(pipe, \"set style line 5 lt rgb 'cyan' lw 3 pt 6 \\n\");\n        fprintf(pipe, \"plot '-' with linespoints ls 5 \\n\");\n\n        for (int i=0; i<data.size(); i++) {\n            fprintf(pipe, \"%lf %lf\\n\", double(i), data[i]);\n        }\n        fprintf(pipe, \"e\");\n\n        fflush(pipe);\n        pclose(pipe);\n    }\n    else {\n        std::cout << \"Could not open gnuplot pipe\" << std::endl;\n    }\n}\n\nint main() {\n    int numIterations = 10000;\n    std::vector<double> errorList (numIterations, 0.0);\n    std::string fileName = \"diabetes.csv\";\n    arma::mat csvData;\n    csvData.load(fileName, arma::csv_ascii);\n    arma::mat input = csvData.cols(0, 7);\n    arma::mat target = csvData.col(8);\n    arma::mat weights(8, 1, arma::fill::zeros);\n    double bias = 0.0;\n    double learningRate = 0.001;\n\n    std::cout << \"Gradient Descent on \" << fileName << std::endl;\n    LogisticRegression model(weights, bias, input, target, learningRate, numIterations);\n    errorList = model.gradientDescent();\n    plotData(errorList);\n\n    fileName = \"myopia.csv\";\n    csvData.load(fileName, arma::csv_ascii);\n    input = csvData.cols(1, 13);\n    target = csvData.col(0);\n    weights.zeros(13, 1);\n    learningRate = 0.0001;\n\n    std::cout << std::endl;\n    std::cout << \"Gradient Descent on \" << fileName << std::endl;\n    model = LogisticRegression(weights, bias, input, target, learningRate, numIterations);\n    errorList = model.gradientDescent();\n    plotData(errorList);\n\n    return 0;\n}", "meta": {"hexsha": "156864bfdbdfed04a319ef38baf63f10701a5d5f", "size": 3781, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "logisticRegression.cpp", "max_stars_repo_name": "pjIowa/MLTools", "max_stars_repo_head_hexsha": "a90908255b771fedba5625c0963a419c064309c1", "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": "logisticRegression.cpp", "max_issues_repo_name": "pjIowa/MLTools", "max_issues_repo_head_hexsha": "a90908255b771fedba5625c0963a419c064309c1", "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": "logisticRegression.cpp", "max_forks_repo_name": "pjIowa/MLTools", "max_forks_repo_head_hexsha": "a90908255b771fedba5625c0963a419c064309c1", "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.0079365079, "max_line_length": 102, "alphanum_fraction": 0.565194393, "num_tokens": 996, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896758909756, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.7003992679449794}}
{"text": "//\tObjective: To implement the option class that is defined in the header file: GapOption.hpp\r\n//\r\n// (c) Sudhansh Dua\r\n\r\n#include \"GapOption.hpp\"\r\n#include <string>\r\n#include <boost/math/distributions.hpp>\r\n#include <cmath>\r\n\r\nusing namespace std;\r\nusing namespace boost::math;\r\n\r\n\r\ndouble GapOption::CallPrice() const\r\n{\r\n\treturn ::GapCallPrice(S, K1, K2, T, r, sig, b, type);\r\n}\r\n\r\ndouble GapOption::PutPrice() const\r\n{\r\n\treturn ::GapPutPrice(S, K1, K2, T, r, sig, b, type);\r\n}\r\n\r\n\r\nvoid GapOption::init()\t\t\t\t\t// Initialising all the default values\r\n{\r\n\t//\tDefault values\r\n\tT = 0.5;\r\n\tr = 0.09;\r\n\tsig = 0.2;\r\n\tK1 = 50;\r\n\tK2 = 57;\r\n\tS = 50;\t\t\t\t//\tDefault stock price \r\n\tb = r;\t\t\t\t//\tBlack - Scholes(1973) stock option model : b = r\r\n\r\n\ttype = \"C\";\t\t\t//\tCall option as the default\r\n\r\n}\r\n\r\nvoid GapOption::copy(const GapOption& option)\r\n{\r\n\tT = option.T;\r\n\tr = option.r;\r\n\tsig = option.sig;\r\n\tK1 = option.K1;\r\n\tK2 = option.K2;\r\n\tb = option.b;\r\n\ttype = option.type;\r\n\tS = option.S;\r\n}\r\n\r\n//\tConstructors and destructor\r\n//\tDefault Constructor\r\nGapOption::GapOption() : Option()\r\n{\r\n\tinit();\r\n}\r\n\r\n//\tCopy constructor\r\nGapOption::GapOption(const GapOption& option) : Option(option)\r\n{\r\n\tcopy(option);\r\n}\r\n\r\n//\tConstructor that accepts values\r\nGapOption::GapOption(const double& S1, const double& K1, const double& K2, const double& T1, const double& r1, const double& sig1,\r\n\tconst double& b1, const string type1) : Option(), S(S1), K1(K1), K2(K2), T(T1), r(r1), sig(sig1), b(b1), type(type1) {}\r\n\r\n//\tDestructor\r\nGapOption::~GapOption() {}\r\n\r\n\r\n//\tAssignment Operator\r\nGapOption& GapOption::operator = (const GapOption& option)\r\n{\r\n\tif (this == &option)\r\n\t{\r\n\t\treturn *this;\t\t//\tSelf-assignment check!\r\n\t}\r\n\tOption::operator = (option);\r\n\tcopy(option);\r\n\treturn *this;\r\n}\r\n\r\n\r\n// Functions that calculate the option price\r\ndouble GapOption::Price() const\r\n{\r\n\tif (type == \"C\")\r\n\t{\r\n\t\treturn CallPrice();\r\n\t}\r\n\telse\r\n\t{\r\n\t\treturn PutPrice();\r\n\t}\r\n}\r\n\r\n\r\n// Modifier functions\r\nvoid GapOption::toggle()\t\t\t\t\t\t\t\t//\tChange the option type\r\n{\r\n\ttype = ((type == \"C\") ? \"P\" : \"C\");\r\n}\r\n\r\n// Global Functions\r\ndouble GapCallPrice(const double S, const double K1, const double K2, const double T, const double r, const double sig, const double b, const string type)\r\n{\r\n\tdouble d1 = (log(S / K1) + (b + (sig * sig * 0.5)) * T) / (sig * sqrt(T));\r\n\tdouble d2 = d1 - (sig * sqrt(T));\r\n\tnormal_distribution<> standard_normal(0.0, 1.0);\r\n\r\n\treturn (S * exp((b - r) * T) * cdf(standard_normal, d1)) - (K2 * exp(-r * T) * cdf(standard_normal, d2));\r\n}\r\n\r\ndouble GapPutPrice(const double S, const double K1, const double K2, const double T, const double r, const double sig, const double b, const string type)\r\n{\r\n\tdouble d1 = (log(S / K1) + (b + (sig * sig * 0.5)) * T) / (sig * sqrt(T));\r\n\tdouble d2 = d1 - (sig * sqrt(T));\r\n\tnormal_distribution<> standard_normal(0.0, 1.0);\r\n\r\n\treturn (K2 * exp(-r * T) * cdf(standard_normal, -d2)) - (S * exp((b - r) * T) * cdf(standard_normal, -d1));\r\n}\r\n\r\n", "meta": {"hexsha": "00f9badaa715ad01ef97217f15c5a23612e92a51", "size": 2978, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "GapOption.cpp", "max_stars_repo_name": "sudhanshdua/Option_Classes", "max_stars_repo_head_hexsha": "b483d71ac78cd5cdd3c69205eb0ee37bca3ae668", "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": "GapOption.cpp", "max_issues_repo_name": "sudhanshdua/Option_Classes", "max_issues_repo_head_hexsha": "b483d71ac78cd5cdd3c69205eb0ee37bca3ae668", "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": "GapOption.cpp", "max_forks_repo_name": "sudhanshdua/Option_Classes", "max_forks_repo_head_hexsha": "b483d71ac78cd5cdd3c69205eb0ee37bca3ae668", "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.824, "max_line_length": 155, "alphanum_fraction": 0.6171927468, "num_tokens": 901, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767938900121, "lm_q2_score": 0.7981867777396212, "lm_q1q2_score": 0.7003903746563624}}
{"text": "// Polyvec\n#include <polyvec/utils/num.hpp>\n#include <polyvec/api.hpp>\n\n// Eigen\n#include <Eigen/LU>\n\n// std\n#include <cstdlib>\n\nusing namespace std;\n\nNAMESPACE_BEGIN ( polyvec )\nNAMESPACE_BEGIN ( Num )\n\ndouble\ndeterminant(Eigen::Ref<const Eigen::MatrixXd> mat) {\n  return mat.determinant();\n}\n\t\nbool test_and_calculate_interval_overlap(\n    const double i0, const double i1,\n    const double j0, const double j1,\n    double& overlap\n) {\n    if (j0 > i1 || i0 > j1) {\n        return false;\n    }\n\n    overlap = min(i1, j1) - max(i0, j0);\n    return overlap > -PF_EPS;\n}\n\nEigen::MatrixXd \nsolve_linear_system (\n    const Eigen::Ref<const Eigen::MatrixXd> LHS,\n    const Eigen::Ref<const Eigen::MatrixXd> RHS )  {\n      assert_break(LHS.rows() == LHS.cols());\n      assert_break(RHS.rows() == LHS.cols());\n      assert_break(RHS.cols() == 1);\n      assert_break(std::abs(LHS.determinant()) > 1e-12 );\n      return LHS.lu().solve( RHS );\n}\n\ndouble smooth_probability_incr(double x, double zero_up_to, double one_beyond)\n{\n\tif (x <= zero_up_to)\n\t\treturn 0;\n\tif (x >= one_beyond)\n\t\treturn 1;\n\treturn 0.5 + 0.5 * std::cos(M_PI * (x - one_beyond) / (one_beyond - zero_up_to));\n}\n\ndouble smooth_probability_decr(double x, double one_up_to, double zero_beyond)\n{\n\treturn 1 - smooth_probability_incr(x, one_up_to, zero_beyond);\n}\n\nNAMESPACE_END ( Num )\nNAMESPACE_END ( polyvec )\n\n", "meta": {"hexsha": "5c077370ef1400eeb1ab636553a7f17fd95ada5a", "size": 1370, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/polyvec/utils/num.cpp", "max_stars_repo_name": "ShnitzelKiller/polyfit", "max_stars_repo_head_hexsha": "51ddc6365a794db1678459140658211cb78f65b1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2020-08-17T17:25:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T05:49:12.000Z", "max_issues_repo_path": "source/polyvec/utils/num.cpp", "max_issues_repo_name": "ShnitzelKiller/polyfit", "max_issues_repo_head_hexsha": "51ddc6365a794db1678459140658211cb78f65b1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-08-26T13:54:59.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-21T07:19:22.000Z", "max_forks_repo_path": "source/polyvec/utils/num.cpp", "max_forks_repo_name": "ShnitzelKiller/polyfit", "max_forks_repo_head_hexsha": "51ddc6365a794db1678459140658211cb78f65b1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-08-26T23:26:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-04T09:06:07.000Z", "avg_line_length": 22.0967741935, "max_line_length": 82, "alphanum_fraction": 0.6693430657, "num_tokens": 392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767906859265, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.700390367886404}}
{"text": "// Boost.Geometry\n// QuickBook Example\n// Copyright (c) 2018, Oracle and/or its affiliates\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\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//[discrete_hausdorff_distance_strategy\n//` Calculate Similarity between two geometries as the discrete hausdorff distance between them.\n\n#include <iostream>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point.hpp>\n#include <boost/geometry/geometries/linestring.hpp>\n\nint main()\n{\n    namespace bg = boost::geometry;\n    typedef bg::model::point<double, 2, bg::cs::geographic<bg::degree> > point_type;\n    typedef bg::model::linestring<point_type> linestring_type;\n\n    linestring_type ls1, ls2;\n    bg::read_wkt(\"LINESTRING(0 0,1 1,1 2,2 1,2 2)\", ls1);\n    bg::read_wkt(\"LINESTRING(1 0,0 1,1 1,2 1,3 1)\", ls2);\n\n    bg::srs::spheroid<double> spheroid(6378137.0, 6356752.3142451793);\n    bg::strategy::distance::geographic<> strategy(spheroid);\n\n    double res = bg::discrete_hausdorff_distance(ls1, ls2, strategy);\n\n    std::cout << \"Discrete Hausdorff Distance: \" << res << std::endl;\n\n    return 0;\n}\n\n//]\n\n//[discrete_hausdorff_distance_strategy_output\n/*`\nOutput:\n[pre\nDiscrete Hausdorff Distance: 110574\n]\n*/\n//]\n", "meta": {"hexsha": "28f0f90437c04a9ddf0bb9ccbc6dd09eb21a3e77", "size": 1390, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/src/examples/algorithms/discrete_hausdorff_distance_strategy.cpp", "max_stars_repo_name": "jkerkela/geometry", "max_stars_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1155.0, "max_stars_repo_stars_event_min_datetime": "2015-01-10T19:04:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:30:30.000Z", "max_issues_repo_path": "doc/src/examples/algorithms/discrete_hausdorff_distance_strategy.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": "doc/src/examples/algorithms/discrete_hausdorff_distance_strategy.cpp", "max_forks_repo_name": "jkerkela/geometry", "max_forks_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 228.0, "max_forks_repo_forks_event_min_datetime": "2015-01-13T12:55:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T11:11:05.000Z", "avg_line_length": 28.9583333333, "max_line_length": 96, "alphanum_fraction": 0.7237410072, "num_tokens": 421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110483133801, "lm_q2_score": 0.7853085808877581, "lm_q1q2_score": 0.7003468687710044}}
{"text": "/**\n * @file test_getGravitationalAttraction.cpp\n * @author Bensuperpc (bensuperpc@gmail.com)\n * @brief \n * @version 1.0.0\n * @date 2021-04-01\n * \n * MIT License\n * \n */\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE getGravitationalAttraction\n\n#include <boost/test/unit_test.hpp>\n#include \"math/constant.hpp\"\n#include \"math/getGravitationalAttraction_imp.hpp\"\n\nBOOST_AUTO_TEST_CASE(test_getGravitationalAttraction_1)\n{\n    BOOST_CHECK_MESSAGE(static_cast<long int>(my::math::ga::getGravitationalAttraction<long double>(10000, 20000, 30000)) == static_cast<long int>(0),\n        static_cast<long int>(my::math::ga::getGravitationalAttraction<long double>(10000, 20000, 30000)) << \" instead: \" << static_cast<long int>(0));\n}\nBOOST_AUTO_TEST_CASE(test_getGravitationalAttraction_2)\n{\n    BOOST_CHECK_MESSAGE(static_cast<long int>(my::math::ga::getGravitationalAttraction<long double>(0, 0, 1)) == static_cast<long int>(0),\n        static_cast<long int>(my::math::ga::getGravitationalAttraction<long double>(0, 0, 1)) << \" instead: \" << static_cast<long int>(0));\n}", "meta": {"hexsha": "c16d5acb8d36be7b7fbd076b617fc5c3f1aa8814", "size": 1071, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/math/test_getGravitationalAttraction.cpp", "max_stars_repo_name": "Bensuperpc/BenLib", "max_stars_repo_head_hexsha": "1708a27e272a54f437cda50b2ca98ed92f03d721", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-12-02T21:17:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-24T19:57:42.000Z", "max_issues_repo_path": "src/test/math/test_getGravitationalAttraction.cpp", "max_issues_repo_name": "bensuperpc/BenLib", "max_issues_repo_head_hexsha": "1708a27e272a54f437cda50b2ca98ed92f03d721", "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/test/math/test_getGravitationalAttraction.cpp", "max_forks_repo_name": "bensuperpc/BenLib", "max_forks_repo_head_hexsha": "1708a27e272a54f437cda50b2ca98ed92f03d721", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-28T08:43:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-28T08:43:46.000Z", "avg_line_length": 38.25, "max_line_length": 151, "alphanum_fraction": 0.7422969188, "num_tokens": 308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.7003468665128885}}
{"text": "\n#include <Eigen/LU>\n\n\nusing namespace std;\nusing namespace Eigen;\n\nint main()\n{\n   Matrix3f A;\n   Vector3f b;\n   A << 1,2,3,  4,5,6,  7,8,10;\n   b << 3, 3, 4;\n   cout << \"Here is the matrix A:\" << endl << A << endl;\n   cout << \"Here is the vector b:\" << endl << b << endl;\n   Vector3f x = A.lu().solve(b);\n   cout << \"The solution is:\" << endl << x << endl;\n}\n", "meta": {"hexsha": "d5308c22af3cd890638fc670ff17c327e80f5375", "size": 361, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "External/eigen-3.3.7/doc/examples/Tutorial_PartialLU_solve.cpp", "max_stars_repo_name": "RokKos/eol-cloth", "max_stars_repo_head_hexsha": "b9c6f55f25ba17f33532ea5eefa41fedd29c5206", "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": "External/eigen-3.3.7/doc/examples/Tutorial_PartialLU_solve.cpp", "max_issues_repo_name": "RokKos/eol-cloth", "max_issues_repo_head_hexsha": "b9c6f55f25ba17f33532ea5eefa41fedd29c5206", "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": "External/eigen-3.3.7/doc/examples/Tutorial_PartialLU_solve.cpp", "max_forks_repo_name": "RokKos/eol-cloth", "max_forks_repo_head_hexsha": "b9c6f55f25ba17f33532ea5eefa41fedd29c5206", "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.0, "max_line_length": 56, "alphanum_fraction": 0.5318559557, "num_tokens": 131, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.785308578375437, "lm_q1q2_score": 0.7003468642723728}}
{"text": "// Author: Tassilo Kugelstadt\n// License: MIT\n// Source:\n//   https://github.com/InteractiveComputerGraphics/Discregrid/blob/\n//   6e7270eff242e87aa3f8d938da570c87e13e7761/discregrid/\n//   include/Discregrid/acceleration/bounding_sphere.hpp\n\n#ifndef MCL_BOUNDINGSPHERE_HPP\n#define MCL_BOUNDINGSPHERE_HPP 1\n\n#include <Eigen/Core>\n#include <vector>\n\nnamespace mcl\n{\n\nclass BoundingSphere\n{\npublic:\n    BoundingSphere() : m_x(Eigen::Vector3d::Zero()), m_r(0.0) {}\n\n    BoundingSphere(Eigen::Vector3d const& x, double r) : m_x(x), m_r(r) {}\n\n    BoundingSphere(const Eigen::Vector3d& a)\n    {\n        m_x = a;\n        m_r = 0.0;\n    }\n\n    BoundingSphere(const Eigen::Vector3d& a, const Eigen::Vector3d& b)\n    {\n        const Eigen::Vector3d ba = b - a;\n        m_x = (a + b) * 0.5;\n        m_r = 0.5 * ba.norm();\n    }\n\n    BoundingSphere(const Eigen::Vector3d& a, const Eigen::Vector3d& b, const Eigen::Vector3d& c)\n    {\n        const Eigen::Vector3d ba = b - a;\n        const Eigen::Vector3d ca = c - a;\n        const Eigen::Vector3d baxca = ba.cross(ca);\n        Eigen::Vector3d r;\n        Eigen::Matrix3d T;\n        T << ba[0], ba[1], ba[2],\n        ca[0], ca[1], ca[2],\n        baxca[0], baxca[1], baxca[2];\n        r[0] = 0.5 * ba.squaredNorm();\n        r[1] = 0.5 * ca.squaredNorm();\n        r[2] = 0.0;\n        m_x = T.inverse() * r;\n        m_r = m_x.norm();\n        m_x += a;\n    }\n\n    BoundingSphere(const Eigen::Vector3d& a, const Eigen::Vector3d& b, const Eigen::Vector3d& c, const Eigen::Vector3d& d)\n    {\n        const Eigen::Vector3d ba = b - a;\n        const Eigen::Vector3d ca = c - a;\n        const Eigen::Vector3d da = d - a;\n        Eigen::Vector3d r;\n        Eigen::Matrix3d T;\n        T << ba[0], ba[1], ba[2],\n        ca[0], ca[1], ca[2],\n        da[0], da[1], da[2];\n        r[0] = 0.5 * ba.squaredNorm();\n        r[1] = 0.5 * ca.squaredNorm();\n        r[2] = 0.5 * da.squaredNorm();\n        m_x = T.inverse() * r;\n        m_r = m_x.norm();\n        m_x += a;\n    }\n\n    BoundingSphere(const std::vector<Eigen::Vector3d>& p)\n    {\n        m_r = 0;\n        m_x.setZero();\n        setPoints(p);\n    }\n\n    // Center\n    Eigen::Vector3d const& x() const { return m_x; }\n    Eigen::Vector3d& x() { return m_x; }\n\n    // Radius\n    double r() const { return m_r; }\n    double& r() { return m_r; }\n\n    void setPoints(const std::vector<Eigen::Vector3d>& p)\n    {\n        //remove duplicates\n        std::vector<Eigen::Vector3d> v(p);\n        std::sort(v.begin(), v.end(), [](const Eigen::Vector3d& a, const Eigen::Vector3d& b)\n        {\n            if (a[0] < b[0]) return true;\n            if (a[0] > b[0]) return false;\n            if (a[1] < b[1]) return true;\n            if (a[1] > b[1]) return false;\n            return (a[2] < b[2]);\n        });\n        v.erase(std::unique(v.begin(), v.end(), [](Eigen::Vector3d& a, Eigen::Vector3d& b) { return a.isApprox(b); }), v.end());\n\n        Eigen::Vector3d d;\n        const int n = int(v.size());\n\n        //generate random permutation of the points and permute the points by epsilon to avoid corner cases\n        const double epsilon = 1.0e-6;\n        for (int i = n - 1; i > 0; i--)\n        {\n            const Eigen::Vector3d epsilon_vec = epsilon * Eigen::Vector3d::Random();\n            const int j = static_cast<int>(floor(i * double(rand()) / RAND_MAX));\n            d = v[i] + epsilon_vec;\n            v[i] = v[j] - epsilon_vec;\n            v[j] = d;\n        }\n\n        BoundingSphere S = BoundingSphere(v[0], v[1]);\n\n        for (int i = 2; i < n; i++)\n        {\n            //SES0\n            d = v[i] - S.x();\n            if (d.squaredNorm() > S.r()* S.r())\n            S = ses1(i, v, v[i]);\n        }\n\n        m_x = S.m_x;\n        m_r = S.m_r + epsilon;\t//add epsilon to make sure that all non-pertubated points are inside the sphere\n    }\n\n    bool overlaps(BoundingSphere const& other) const\n    {\n        const double rr = m_r + other.m_r;\n        return (m_x - other.m_x).squaredNorm() < rr * rr;\n    }\n\n    bool contains(BoundingSphere const& other) const\n    {\n        const double rr = r() - other.r();\n        return (x() - other.x()).squaredNorm() < rr * rr;\n    }\n\n    bool contains(Eigen::Vector3d const& other) const\n    {\n        return (x() - other).squaredNorm() < m_r * m_r;\n    }\n\nprivate:\n\n    BoundingSphere ses3(int n, std::vector<Eigen::Vector3d>& p, Eigen::Vector3d& q1, Eigen::Vector3d& q2, Eigen::Vector3d& q3)\n    {\n        BoundingSphere S(q1, q2, q3);\n\n        for (int i = 0; i < n; i++)\n        {\n            Eigen::Vector3d d = p[i] - S.x();\n            if (d.squaredNorm() > S.r()* S.r())\n            S = BoundingSphere(q1, q2, q3, p[i]);\n        }\n        return S;\n    }\n\n    BoundingSphere ses2(int n, std::vector<Eigen::Vector3d>& p, Eigen::Vector3d& q1, Eigen::Vector3d& q2)\n    {\n        BoundingSphere S(q1, q2);\n\n        for (int i = 0; i < n; i++)\n        {\n            Eigen::Vector3d d = p[i] - S.x();\n            if (d.squaredNorm() > S.r()* S.r())\n            S = ses3(i, p, q1, q2, p[i]);\n        }\n        return S;\n    }\n\n    BoundingSphere ses1(int n, std::vector<Eigen::Vector3d>& p, Eigen::Vector3d& q1)\n    {\n        BoundingSphere S(p[0], q1);\n\n        for (int i = 1; i < n; i++)\n        {\n            Eigen::Vector3d d = p[i] - S.x();\n            if (d.squaredNorm() > S.r()* S.r())\n            S = ses2(i, p, q1, p[i]);\n        }\n        return S;\n    }\n\n    Eigen::Vector3d m_x;\n    double m_r;\n};\n\n} // ns mcl\n\n#endif", "meta": {"hexsha": "6384b9ad56e567cd5bceb6219f0c1826098d1b2f", "size": 5455, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/MCL/BoundingSphere.hpp", "max_stars_repo_name": "mattoverby/mclgeom", "max_stars_repo_head_hexsha": "d3ecd2a878900f33ba1412b8d82e643895201e51", "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/MCL/BoundingSphere.hpp", "max_issues_repo_name": "mattoverby/mclgeom", "max_issues_repo_head_hexsha": "d3ecd2a878900f33ba1412b8d82e643895201e51", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-26T22:44:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T02:54:23.000Z", "max_forks_repo_path": "include/MCL/BoundingSphere.hpp", "max_forks_repo_name": "mattoverby/mclgeom", "max_forks_repo_head_hexsha": "d3ecd2a878900f33ba1412b8d82e643895201e51", "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.118556701, "max_line_length": 128, "alphanum_fraction": 0.5118240147, "num_tokens": 1762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870287, "lm_q2_score": 0.7853085708384736, "lm_q1q2_score": 0.7003468530345938}}
{"text": "#include \"geometrycentral/arap.h\"\n#include <Eigen/SparseCholesky>\n#include <Eigen/SVD>\n#include <Eigen/Dense>\nusing namespace geometrycentral;\n\nARAP::ARAP(HalfedgeMesh* m, Geometry<Euclidean>* g) : mesh(m), geom(g), vertexIndices(mesh), isoTriangleParam(mesh), uvCoords(mesh) {\n    vertexIndices = mesh->getVertexIndices();\n}\n\nEigen::SparseMatrix<std::complex<double>> ARAP::createLaplaceMatrix() {\n    size_t n = mesh->nVertices();\n    Eigen::SparseMatrix<std::complex<double>> A(n,n);\n    std::vector<Eigen::Triplet<std::complex<double>>> triplets;\n    \n    for (VertexPtr v1 : mesh->vertices()) {\n        int index1 = vertexIndices[v1];\n        double sum = __DBL_EPSILON__;\n\n        // add neighbor weights\n        for (HalfedgePtr heOut : v1.outgoingHalfedges()) {\n            VertexPtr v2 = heOut.twin().vertex();\n            int index2 = vertexIndices[v2];\n            double weight = (geom->cotan(heOut) + geom->cotan(heOut.twin())) / 2.0;\n            \n            sum += weight;\n            triplets.push_back(Eigen::Triplet<std::complex<double>>(index1, index2, std::complex<double>(-weight,0)));\n        }\n\n        // add diagonal weight\n        triplets.push_back(Eigen::Triplet<std::complex<double>>(index1, index1, std::complex<double>(sum,0)));  \n    }\n\n    A.setFromTriplets(triplets.begin(), triplets.end());\n    return A;\n}\n\nvoid ARAP::computeIsoTriangleParam() {\n    for (FacePtr f : mesh->faces()) {\n        // Gather elements\n        HalfedgePtr he = f.halfedge();\n        double l_ab = geom->length(he.edge());\n        double l_ac = geom->length(he.prev().edge());\n        double theta_a = geom->angle(he.next()); // radians\n\n        // Place first vertex at (0,0)\n        isoTriangleParam[he] = Vector2{0,0};\n\n        // Place second vertex at (|ab|,0)\n        isoTriangleParam[he.next()] = Vector2{l_ab,0};\n\n        // Place third vertex at (|ac|,0) rotated by theta_a CCW\n        isoTriangleParam[he.prev()] = Vector2{cos(theta_a) * l_ac, sin(theta_a) * l_ac}; \n    }\n}\n\nFaceData<Eigen::Matrix2d> ARAP::computeLRotations(VertexData<Vector2> const &u) {\n    FaceData<Eigen::Matrix2d> L(mesh);\n    for (FacePtr f : mesh->faces()) {\n        // Gather elements\n        HalfedgePtr he1 = f.halfedge();\n        HalfedgePtr he2 = he1.next();\n        HalfedgePtr he3 = he1.prev();\n        std::vector<Vector2> ut = { u[he1.vertex()], u[he2.vertex()], u[he3.vertex()] };\n        std::vector<Vector2> xt = { isoTriangleParam[he1], isoTriangleParam[he2], isoTriangleParam[he3] };\n        std::vector<double> thetat = { geom->cotan(he1), geom->cotan(he2), geom->cotan(he3) };\n\n        // Compute St matrix\n        Eigen::Matrix2d St = Eigen::Matrix2d::Zero();\n        for (int i = 0; i < 3; i++) {\n            Vector2 ui = ut[i] - ut[(i+1) % 3];\n            Vector2 xi = xt[i] - xt[(i+1) % 3];\n            \n            St(0,0) += thetat[i] * ui.x * xi.x;\n            St(0,1) += thetat[i] * ui.x * xi.y;\n            St(1,0) += thetat[i] * ui.y * xi.x;\n            St(1,1) += thetat[i] * ui.y * xi.y;\n        }\n\n        // Perform SVD decomposition, where L_t = UV^T\n        Eigen::JacobiSVD<Eigen::Matrix2d> svd( St, Eigen::ComputeFullU | Eigen::ComputeFullV );\n        Eigen::Matrix2d U = svd.matrixU();\n        Eigen::Matrix2d V = svd.matrixV();\n\n        Eigen::Matrix2d UVT = U * V.transpose();\n        if (UVT.determinant() < 0) {\n            V.col(1) *= -1;\n            UVT = U * V.transpose();\n        }\n        L[f] = UVT;\n    }\n    return L;\n}\n\nEigen::MatrixXcd ARAP::computebVector(FaceData<Eigen::Matrix2d> const &L) {\n    Eigen::MatrixXcd b = Eigen::MatrixXcd::Zero(mesh->nVertices(),1);\n    for (VertexPtr v : mesh->vertices()) {\n        size_t index = vertexIndices[v];\n\n        for (HalfedgePtr he_ij : v.outgoingHalfedges()) {\n            HalfedgePtr he_ji = he_ij.twin();\n\n            // first triangle term\n            if (he_ij.isReal()) {\n                Vector2 xi = isoTriangleParam[he_ij];\n                Vector2 xj = isoTriangleParam[he_ij.next()];\n\n                double cotan_ij = geom->cotan(he_ij);\n                Eigen::Matrix2d Lt_ij = L[he_ij.face()];\n\n                std::complex<double> sub((xi-xj).x, (xi-xj).y); \n                std::complex<double> rot(Lt_ij(0,0), Lt_ij(1,0));\n                b(index,0) += cotan_ij * rot * sub / 2.0;\n            }\n\n            // second triangle term\n            if (he_ji.isReal()) {\n                Vector2 xi = isoTriangleParam[he_ji.next()];\n                Vector2 xj = isoTriangleParam[he_ji];\n\n                double cotan_ji = geom->cotan(he_ji);\n                Eigen::Matrix2d Lt_ji = L[he_ji.face()];  \n\n                std::complex<double> sub((xi-xj).x, (xi-xj).y);    \n                std::complex<double> rot(Lt_ji(0,0), Lt_ji(1,0));\n                b(index,0) += cotan_ji * rot * sub / 2.0;\n            }            \n        } \n    }\n    return b;\n}\n\nvoid ARAP::computeARAP() {\n    // Build Laplace Matrix A (n x n) and factorize\n    Eigen::SparseMatrix<std::complex<double>> A = createLaplaceMatrix();\n    Eigen::SimplicialLDLT<Eigen::SparseMatrix<std::complex<double>>> solver;\n    solver.compute(A);\n\n    // Compute isometric parameterization for each triangle t\n    computeIsoTriangleParam();\n\n    // Initial parameterization u (using SCP)\n    SpectralConformal s = SpectralConformal(mesh,geom);\n    VertexData<Vector2> u = s.computeSpectralConformal();\n    \n    // Repeat the following until convergence:\n    for (int i = 0; i < 10; i++) {\n        // Fix the mapping u (n x 1) and solve for L_t (2x2) for each triangle t\n        FaceData<Eigen::Matrix2d> L = computeLRotations(u);\n\n        // Compute b (n x 1) using L\n        Eigen::MatrixXcd b = computebVector(L);\n\n        // Solve Au = b\n        Eigen::MatrixXcd u_new = solver.solve(b);\n\n        // Update u\n        for (VertexPtr v : mesh->vertices()) {\n            std::complex<double> uv = u_new(vertexIndices[v],0);\n            u[v] = Vector2{uv.real(), uv.imag()};\n        }\n        std::cout << \"finished iteration: \" << i << std::endl;\n    }\n\n    // normalize\n    uvCoords = u;\n    normalize();\n\n    // write output obj file\n    std::ofstream outfile (\"ARAP.obj\");\n    writeToFile(outfile);\n    outfile.close();\n    std::cout<<\"Done ARAP!\"<<std::endl;\n}\n\nvoid ARAP::writeToFile(std::ofstream &outfile) {\n    // write vertices\n    for (VertexPtr v : mesh->vertices()) {\n        outfile << \"v \" << geom->position(v).x << \" \" << geom->position(v).y << \" \" << geom->position(v).z << std::endl;\n    }\n\n    // write uvs\n    for (VertexPtr v : mesh->vertices()) {\n        outfile << \"vt \" << uvCoords[v].x << \" \" << uvCoords[v].y << std::endl;\n    }\n\n    // write indices\n    VertexData<size_t> index = mesh->getVertexIndices();\n    for (FacePtr f : mesh->faces()) {\n       HalfedgePtr he = f.halfedge();\n       outfile << \"f\";\n       do {\n           VertexPtr v = he.vertex();\n           outfile << \" \" << index[v] + 1 << \"/\" << index[v] + 1;\n\n           he = he.next();\n       } while (he != f.halfedge());\n       outfile << std::endl;\n    }\n\n   outfile.close();\n}\n\nvoid ARAP::normalize() {\n    // compute center of mass\n    Vector2 cm = {0,0};\n    for (VertexPtr v : mesh->vertices()) {\n        Vector2 uv = uvCoords[v];\n        cm += uv;\n    }\n    cm /= mesh->nVertices();\n\n    double r = 0;\n    for (VertexPtr v : mesh->vertices()) {\n        Vector2 &uv = uvCoords[v];\n        uv -= cm;\n        r = std::max(r, norm(uv));\n    }\n\n    for (VertexPtr v : mesh->vertices()) {\n        Vector2 &uv = uvCoords[v];\n        uv /= r;\n    }\n}", "meta": {"hexsha": "1b8f3e544e71a595a1c9784891a9bffb5f94b8d6", "size": 7499, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/arap.cpp", "max_stars_repo_name": "connorzl/geometry-central", "max_stars_repo_head_hexsha": "99114ffaf3efb58c912f94402dd0426cbb17d3f1", "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/arap.cpp", "max_issues_repo_name": "connorzl/geometry-central", "max_issues_repo_head_hexsha": "99114ffaf3efb58c912f94402dd0426cbb17d3f1", "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/arap.cpp", "max_forks_repo_name": "connorzl/geometry-central", "max_forks_repo_head_hexsha": "99114ffaf3efb58c912f94402dd0426cbb17d3f1", "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.4776785714, "max_line_length": 133, "alphanum_fraction": 0.5519402587, "num_tokens": 2148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026528034426, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.7003456767441589}}
{"text": "#include \"interpolation.hpp\"\n#include \"dynamic_grid.hpp\"\n#include \"multiindex.hpp\"\n#include \"test_helpers.hpp\"\n\n#include <boost/test/unit_test.hpp>\n#include <boost/lexical_cast.hpp>\n\n// reference implementation for 2d bilinear interpolation\ntemplate<class Grid>\ndouble bilinearInterpolate( const Grid& grid, double x, double y )\n{\n    typedef std::vector<int> vc;\n    int x0 = std::floor(x);\n    int x1 = std::ceil(x);\n    int y0 = std::floor(y);\n    int y1 = std::ceil(y);\n    double f00 = grid( vc{x0, y0});\n    double f10 = grid( vc{x1, y0});\n    double f01 = grid( vc{x0, y1});\n    double f11 = grid( vc{x1, y1});\n\n    return f00 + (f10-f00) * (x - x0) + (f01 - f00) * (y - y0) + (f00+f11-f01-f10) * (x-x0) * (y - y0);\n}\n\n// helper function for generating vector indices\ngen_vect vec2( double a, double b )\n{\n    gen_vect v(2);\n    v[0] = a;\n    v[1] = b;\n    return v;\n}\n\ngen_vect vec3( double a, double b, double c )\n{\n    gen_vect v(3);\n    v[0] = a;\n    v[1] = b;\n    v[2] = c;\n    return v;\n}\n\nBOOST_AUTO_TEST_SUITE(linear_interpolation_test)\n\nBOOST_AUTO_TEST_CASE( bilinearInterpolate_test )\n{\n    default_grid vg( 2, 2, TransformationType::PERIODIC );\n    vg[0] = 0;\n    vg[1] = 1;\n    vg[2] = 1;\n    vg[3] = std::sqrt(2);\n    BOOST_CHECK_EQUAL( (bilinearInterpolate(vg, 0.5, 0.0)), 0.5 );\n    BOOST_CHECK_EQUAL( (bilinearInterpolate(vg, 0.0, 0.5)), 0.5 );\n    BOOST_CHECK_EQUAL( (bilinearInterpolate(vg, 1.0, 1.0)), std::sqrt(2) );\n    BOOST_CHECK_EQUAL( (bilinearInterpolate(vg, 0.5, 0.5)), (2+std::sqrt(2))*0.25 );\n}\n\nBOOST_AUTO_TEST_CASE( test_nd_method )\n{\n    // compare results of general n-d method with hand-coded 2d\n    // position in 0-1\n    // use periodic indexing for safety\n    default_grid vg(2, 2, TransformationType::PERIODIC);\n    vg[0] = rand_value();\n    vg[1] = rand_value();\n    vg[2] = rand_value();\n    vg[3] = rand_value();\n\n    // check the corners\n    BOOST_CHECK_EQUAL( linearInterpolate(vg, vec2(0.0,0.0)), vg[0] );\n    BOOST_CHECK_EQUAL( linearInterpolate(vg, vec2(0.0,1.0)), vg[1] );\n    BOOST_CHECK_EQUAL( linearInterpolate(vg, vec2(1.0,0.0)), vg[2] );\n    BOOST_CHECK_EQUAL( linearInterpolate(vg, vec2(1.0,1.0)), vg[3] );\n\n    // check edges\n    BOOST_CHECK_CLOSE( linearInterpolate(vg, vec2(0.0,0.5)), 0.5*(vg[0]+vg[1]), 1e-12 );\n    BOOST_CHECK_CLOSE( linearInterpolate(vg, vec2(0.5,0.0)), 0.5*(vg[0]+vg[2]), 1e-12 );\n    BOOST_CHECK_CLOSE( linearInterpolate(vg, vec2(1.0,0.5)), 0.5*(vg[2]+vg[3]), 1e-12 );\n    BOOST_CHECK_CLOSE( linearInterpolate(vg, vec2(0.5,1.0)), 0.5*(vg[1]+vg[3]), 1e-12 );\n\n    for(int i = 0; i < 10; ++i)\n    {\n        double x = rand01();\n        double y = rand01();\n        BOOST_CHECK_CLOSE(bilinearInterpolate(vg, x, y), linearInterpolate(vg, vec2(x, y)), 1e-12);\n    }\n}\n\n\nBOOST_AUTO_TEST_CASE( test_nd_method_3d )\n{\n    typedef std::vector<int> id;\n    // compare results of general n-d method with hand-coded 2d\n    // position in 0-1\n    default_grid vg(3, 3, TransformationType::PERIODIC);\n    for(int i = 0; i < 27; ++i)\n        vg[i] = rand_value();\n\n    // check the corners\n    BOOST_CHECK_EQUAL( linearInterpolate(vg, vec3(0.0,0.0,0.0)), vg(id{0,0,0}) );\n    BOOST_CHECK_EQUAL( linearInterpolate(vg, vec3(0.0,0.0,1.0)), vg(id{0,0,1}) );\n    BOOST_CHECK_EQUAL( linearInterpolate(vg, vec3(0.0,1.0,0.0)), vg(id{0,1,0}) );\n    BOOST_CHECK_EQUAL( linearInterpolate(vg, vec3(0.0,1.0,1.0)), vg(id{0,1,1}) );\n    BOOST_CHECK_EQUAL( linearInterpolate(vg, vec3(1.0,0.0,0.0)), vg(id{1,0,0}) );\n    BOOST_CHECK_EQUAL( linearInterpolate(vg, vec3(1.0,0.0,1.0)), vg(id{1,0,1}) );\n    BOOST_CHECK_EQUAL( linearInterpolate(vg, vec3(1.0,1.0,0.0)), vg(id{1,1,0}) );\n    BOOST_CHECK_EQUAL( linearInterpolate(vg, vec3(1.0,1.0,1.0)), vg(id{1,1,1}) );\n\n    // check edges\n    BOOST_CHECK_EQUAL( linearInterpolate(vg, vec3(0.0,0.0,0.5)), 0.5*(vg(id{0,0,0})+vg(id{0,0,1})) );\n    BOOST_CHECK_EQUAL( linearInterpolate(vg, vec3(0.0,0.5,0.0)), 0.5*(vg(id{0,0,0})+vg(id{0,1,0})) );\n    BOOST_CHECK_EQUAL( linearInterpolate(vg, vec3(0.0,1.0,0.5)), 0.5*(vg(id{0,1,0})+vg(id{0,1,1})) );\n    BOOST_CHECK_EQUAL( linearInterpolate(vg, vec3(0.0,0.5,1.0)), 0.5*(vg(id{0,0,1})+vg(id{0,1,1})) );\n\n    BOOST_CHECK_EQUAL( linearInterpolate(vg, vec3(1.0,0.0,0.5)), 0.5*(vg(id{1,0,0})+vg(id{1,0,1})) );\n    BOOST_CHECK_EQUAL( linearInterpolate(vg, vec3(1.0,0.5,0.0)), 0.5*(vg(id{1,0,0})+vg(id{1,1,0})) );\n    BOOST_CHECK_EQUAL( linearInterpolate(vg, vec3(1.0,1.0,0.5)), 0.5*(vg(id{1,1,0})+vg(id{1,1,1})) );\n    BOOST_CHECK_EQUAL( linearInterpolate(vg, vec3(1.0,0.5,1.0)), 0.5*(vg(id{1,0,1})+vg(id{1,1,1})) );\n\n    BOOST_CHECK_EQUAL( linearInterpolate(vg, vec3(0.5,0.0,0.0)), 0.5*(vg(id{0,0,0})+vg(id{1,0,0})) );\n    BOOST_CHECK_EQUAL( linearInterpolate(vg, vec3(0.5,0.0,1.0)), 0.5*(vg(id{0,0,1})+vg(id{1,0,1})) );\n    BOOST_CHECK_EQUAL( linearInterpolate(vg, vec3(0.5,1.0,0.0)), 0.5*(vg(id{0,1,0})+vg(id{1,1,0})) );\n    BOOST_CHECK_EQUAL( linearInterpolate(vg, vec3(0.5,1.0,1.0)), 0.5*(vg(id{0,1,1})+vg(id{1,1,1})) );\n}\n\n// test generic linear function\nBOOST_AUTO_TEST_CASE( test_method_3d_fn )\n{\n    auto f = [](const gen_vect& p){ return 3*p[0] + 7*p[1] - 2*p[2]; };\n\n    default_grid vg(3, 3, TransformationType::PERIODIC);\n    auto index = vg.getIndex();\n    for(; index.valid(); ++index)\n    {\n        vg(index) = f( vec3((double)index[0], (double)index[1], (double)index[2]) );\n    }\n\n    for(int i = 0; i < 100; ++i)\n    {\n        gen_vect pos(3);\n        pos[0] = rand01();\n        pos[1] = rand01();\n        pos[2] = rand01();\n        BOOST_CHECK_CLOSE( f(pos), linearInterpolate(vg, pos), 1e-4 );\n    }\n\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n// interpolated drawing\nBOOST_AUTO_TEST_SUITE( linear_interpolate_draw_test )\n\nBOOST_AUTO_TEST_CASE( distrib_1d )\n{\n    DynamicGrid<float> vg(1, 3, TransformationType::PERIODIC);\n    /// \\todo maybe, a fill method would be nice.\n    for(auto& val : vg )\n        val = 0;\n\n    gen_vect pos(1);\n    pos[0] = 1;\n\n    float w = rand_value();\n\n    std::array<int, 1> index = {1};\n\n    // draw dot exactly at a grid point, so all goes there\n    drawInterpolatedDot(vg, pos, w);\n    BOOST_CHECK_CLOSE( vg(index), w, 1e-7 );\n    vg(index) = 0; // reset\n\n    // now draw at 1/3 point\n    w = rand_value();\n    pos[0] = 1/3.f;\n    drawInterpolatedDot(vg, pos, w);\n    BOOST_CHECK_CLOSE( vg(index), w/3, 1e-7 );\n}\n\nBOOST_AUTO_TEST_CASE( distrib_2d )\n{\n    DynamicGrid<float> vg(2, 3, TransformationType::PERIODIC);\n    /// \\todo maybe, a fill method would be nice.\n    for(auto& val : vg ) val = 0;\n\n    gen_vect pos(2);\n    pos[0] = 1;\n    pos[1] = 1;\n\n    float w = rand_value();\n\n    std::array<int, 2> index = {1, 1};\n    // draw at 1/3 point\n    w = 1 + rand_value();\n    pos[0] = 1/3.f;\n    drawInterpolatedDot(vg, pos, w);\n    BOOST_CHECK_CLOSE( vg(index), w/3, 1e-6 );\n\n    for(auto& val : vg ) val = 0;\n    pos[1] = 1/3.f;\n    drawInterpolatedDot(vg, pos, w);\n    BOOST_CHECK_CLOSE( vg(index), w/9, 1e-4 );\n\n    float sum = 0;\n    for(auto& val : vg) sum += val;\n    BOOST_CHECK_CLOSE( sum, w, 1e-6 );\n}\n\nBOOST_AUTO_TEST_CASE( distrib_3d )\n{\n    DynamicGrid<float> vg(3, 3, TransformationType::PERIODIC);\n    /// \\todo maybe, a fill method would be nice.\n    for(auto& val : vg ) val = 0;\n\n    gen_vect pos(3);\n    pos[0] = 1;\n    pos[1] = 1;\n    pos[2] = 1;\n\n    float w = rand_value();\n\n    std::array<int, 3> index = {1, 1, 1};\n    // draw at 1/3 point\n    w = 1 + rand_value();\n    pos[0] = 1/3.f;\n    drawInterpolatedDot(vg, pos, w);\n    BOOST_CHECK_CLOSE( vg(index), w/3, 1e-6 );\n\n    for(auto& val : vg ) val = 0;\n    pos[1] = 1/3.f;\n    drawInterpolatedDot(vg, pos, w);\n    BOOST_CHECK_CLOSE( vg(index), w/9, 1e-4 );\n\n    double sum = 0;\n    for(auto& val : vg) sum += val;\n    BOOST_CHECK_CLOSE( sum, w, 1e-6 );\n\n    for(auto& val : vg ) val = 0;\n    pos[2] = 1/4.f;\n    drawInterpolatedDot(vg, pos, w);\n    BOOST_CHECK_CLOSE( vg(index), w/9/4, 1e-4 );\n\n    sum = 0;\n    for(auto& val : vg) sum += val;\n    BOOST_CHECK_CLOSE( sum, w, 1e-6 );\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "95c30fcd01fcb6648d88f229f1af5e94909ce6eb", "size": 7969, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/common/test/linear_interpolation_test.cpp", "max_stars_repo_name": "ngc92/branchedflowsim", "max_stars_repo_head_hexsha": "d38c0e7f892d07d0abd9b63d30570c41b3b83b34", "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/common/test/linear_interpolation_test.cpp", "max_issues_repo_name": "ngc92/branchedflowsim", "max_issues_repo_head_hexsha": "d38c0e7f892d07d0abd9b63d30570c41b3b83b34", "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/common/test/linear_interpolation_test.cpp", "max_forks_repo_name": "ngc92/branchedflowsim", "max_forks_repo_head_hexsha": "d38c0e7f892d07d0abd9b63d30570c41b3b83b34", "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.876, "max_line_length": 103, "alphanum_fraction": 0.6040908521, "num_tokens": 3034, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969136, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.7003181394849308}}
{"text": "//           Copyright Matthew Pulver 2018 - 2019.\n// Distributed under the Boost Software License, Version 1.0.\n//      (See accompanying file LICENSE_1_0.txt or copy at\n//           https://www.boost.org/LICENSE_1_0.txt)\n\n#include <boost/math/differentiation/autodiff.hpp>\n#include <iostream>\n\nint main() {\n  using namespace boost::math::differentiation;\n\n  auto const x = make_fvar<double, 3>(13);\n  auto const y = make_fvar<double, 0, 4>(14);\n  auto const z = 10 * x * x + 50 * x * y + 100 * y * y;  // promoted to autodiff_fvar<double,3,4>\n  for (int i = 0; i <= 3; ++i)\n    for (int j = 0; j <= 4; ++j)\n      std::cout << \"z.derivative(\" << i << \",\" << j << \") = \" << z.derivative(i, j) << std::endl;\n  return 0;\n}\n/*\nOutput:\nz.derivative(2,0) = 20\nz.derivative(1,1) = 50\nz.derivative(0,2) = 200\n**/\n", "meta": {"hexsha": "27d1b64ccb6344c985a6d9b7116dbc2c6a007cfb", "size": 806, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/simple.cpp", "max_stars_repo_name": "pulver/autodiff", "max_stars_repo_head_hexsha": "22f6a44c26c2cb27e6b1ff2228aa242db8b4d91c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 50.0, "max_stars_repo_stars_event_min_datetime": "2018-12-19T19:37:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-07T05:04:52.000Z", "max_issues_repo_path": "example/simple.cpp", "max_issues_repo_name": "pulver/autodiff", "max_issues_repo_head_hexsha": "22f6a44c26c2cb27e6b1ff2228aa242db8b4d91c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 33.0, "max_issues_repo_issues_event_min_datetime": "2018-12-19T18:36:18.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-04T12:09:11.000Z", "max_forks_repo_path": "example/simple.cpp", "max_forks_repo_name": "pulver/autodiff", "max_forks_repo_head_hexsha": "22f6a44c26c2cb27e6b1ff2228aa242db8b4d91c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2018-12-23T05:46:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-25T06:29:55.000Z", "avg_line_length": 31.0, "max_line_length": 97, "alphanum_fraction": 0.5992555831, "num_tokens": 276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765140114859, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.7001445094004424}}
{"text": "// test_lagrange_polynomial.cpp\n// (c) Tivole\n\n#include <boost/test/unit_test.hpp>\n#include \"../src/numerary.hpp\"\n\nnamespace numerary\n{\n    \n    BOOST_AUTO_TEST_SUITE(TestLagrangePolynomial)\n\n\n    double test_lagrange_polynomial_function_1(double x) {\n        return sin(x);\n    }\n\n\n    BOOST_AUTO_TEST_CASE(test_lagrange_polynomial)\n    {\n        const int N = 11;\n        const int TEST_N = 51;\n        int i;\n        double a, b, step, x, min_y, max_y;\n        double *X = new double[N], *Y = new double[N], *TEST_X = new double[TEST_N], *TEST_Y = new double[TEST_N];\n\n        // The main segment\n        a = -5;\n        b = 5;\n\n\n        // Calculating values of function in N points for using future in LP.\n        step = (b - a) / double(N - 1);\n        x = a;\n        min_y = test_lagrange_polynomial_function_1(a);\n        max_y = test_lagrange_polynomial_function_1(a);\n        for (i = 0; i < N; i++, x += step) {\n            X[i] = x;\n            Y[i] = test_lagrange_polynomial_function_1(X[i]);\n\n            if (min_y > Y[i]) min_y = Y[i];\n            if (max_y < Y[i]) max_y = Y[i];\n        }\n\n        // Calculating values of LP in TEST_N points\n        step = (b - a) / double(TEST_N - 1);\n        x = a;\n        for (i = 0; i < TEST_N; i++, x += step) {\n            TEST_X[i] = x;\n            TEST_Y[i] = Numerary::lagrange_polynomial(X, Y, TEST_X[i], N);\n        }\n\n\n        // Calculating norm_1, norm_2, norm_3\n        double norm_1, norm_2, norm_3;\n        norm_1 = abs(TEST_Y[0] - test_lagrange_polynomial_function_1(TEST_X[0])); // max abs\n        norm_2 = abs(TEST_Y[0] - test_lagrange_polynomial_function_1(TEST_X[0])); // sum abs\n        norm_3 = (TEST_Y[0] - test_lagrange_polynomial_function_1(TEST_X[0]))*(TEST_Y[0] - test_lagrange_polynomial_function_1(TEST_X[0])); // sqrt of sum of sqr\n\n        for (i = 1; i < TEST_N; i ++) {\n            x = abs(TEST_Y[i] - test_lagrange_polynomial_function_1(TEST_X[i]));\n            if (x > norm_1) norm_1 = x;\n            norm_2 += x;\n            norm_3 += (x*x);\n        }\n        norm_3 = sqrt(norm_3);\n\n        BOOST_CHECK(norm_1 < 1.e-2);\n        BOOST_CHECK(norm_2 < 1.e-1);\n        BOOST_CHECK(norm_3 < 1.e-1);\n\n        delete[] X;\n        delete[] Y;\n        delete[] TEST_X;\n        delete[] TEST_Y;\n    }\n\n    BOOST_AUTO_TEST_SUITE_END()\n}\n\n", "meta": {"hexsha": "6bf3bc79509cfc0e7644f2c26d075bd86641202c", "size": 2319, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_lagrange_polynomial.cpp", "max_stars_repo_name": "tivole/Numerary", "max_stars_repo_head_hexsha": "2034cd0fbd5d68cd2120baf2c613da54b10a738b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2020-02-21T06:09:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T10:00:06.000Z", "max_issues_repo_path": "test/test_lagrange_polynomial.cpp", "max_issues_repo_name": "tivole/Ti_Numerary", "max_issues_repo_head_hexsha": "2034cd0fbd5d68cd2120baf2c613da54b10a738b", "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/test_lagrange_polynomial.cpp", "max_forks_repo_name": "tivole/Ti_Numerary", "max_forks_repo_head_hexsha": "2034cd0fbd5d68cd2120baf2c613da54b10a738b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-12T11:12:27.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-12T11:12:27.000Z", "avg_line_length": 28.9875, "max_line_length": 161, "alphanum_fraction": 0.5549805951, "num_tokens": 701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517044, "lm_q2_score": 0.8198933447152497, "lm_q1q2_score": 0.7001173831125796}}
{"text": "#include <iostream>\n#include <chrono>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\nEigen::Vector3d position_in_world(double x, double y)\n{\n      const double target_width_px = 1123;\n      const double target_height_px = 791;\n      const double target_width_mm = 297;\n      const double target_height_mm = 210.025;\n      const double X = ((x + 0.5) / target_width_px) * target_width_mm - 0.5 * target_width_mm;\n      const double Y = ((y + 0.5) / target_height_px) * target_height_mm - 0.5 * target_height_mm;\n      const double Z = 0.0;\n      return Eigen::Vector3d(X, Y, Z);\n}\n\nEigen::Vector3d phi_projection_function(const Eigen::Matrix3d& K, \n                                        const Eigen::Matrix3d& R, \n                                        const Eigen::Vector3d& t, \n                                        const Eigen::Vector3d& point)\n{\n    //   const Eigen::Vector3d point_in_camera = R * point + t;\n      const Eigen::Vector3d point_in_image = K * (R * point + t);\n      return point_in_image / point_in_image(2);\n}\n\nEigen::VectorXd compute_homograpy_DLT(const Eigen::MatrixXd& M, const Eigen::MatrixXd& P)\n{\n      Eigen::MatrixXd A (8, 9);\n      A.setZero();\n      for(int32_t i(0); i < M.rows(); i++)\n      {\n          A.block(2 * i, 0, 1, 3) = M.row(i);\n          A.block(2 * i, 6, 1, 3) = - P.row(i)(0) * M.row(i);\n          A.block(2 * i + 1, 3, 1, 3) = M.row(i);\n          A.block(2 * i + 1, 6, 1, 3) = - P.row(i)(1) * M.row(i);\n      }\n    //   std::cout << \"A: \\n\" << A << std::endl;\n    Eigen::JacobiSVD< Eigen::MatrixXd, Eigen::HouseholderQRPreconditioner > svd_null(\n          A, Eigen::ComputeFullV );\n\n    // std::cout << \"V: \" << svd_null.matrixV() << std::endl;\n    return svd_null.matrixV().col(8);\n}\n\n\nint main()\n{\n    auto start = std::chrono::high_resolution_clock::now();\n    const int repeat = 100000;\n    for (int i(0); i < repeat; i++)\n    {\n        Eigen::Matrix3d K;\n        K << 1169.19630, 0.0, 652.98743, 0.0, 1169.61014, 528.83429, 0.0, 0.0, 1.0;\n        Eigen::MatrixXd T(3,4);\n        T << 0.961255, -0.275448, 0.0108487,    112.79, 0.171961,  0.629936,   0.75737,  -217.627,\n            -0.21545,  -0.72616,  0.652895,   1385.13;\n        // std::cout << \"K: \" << K << std::endl;\n        // std::cout << \"T: \" << T << std::endl;\n\n        const auto& R = T.block(0,0,3,3);\n        const auto& t = T.col(3);\n        // auto end1 = std::chrono::high_resolution_clock::now();\n        // std::cout << \"elapsed time K,T,R,t (ns): \"\n        //               << std::chrono::duration_cast< std::chrono::nanoseconds >( end1 - start ).count() << std::endl;\n        // std::cout << \"R: \" << R << std::endl;\n        // std::cout << \"t: \" << t << std::endl;\n\n        const Eigen::Vector3d tl = position_in_world(0.0, 0.0);\n        const Eigen::Vector3d tr = position_in_world(1123.0, 0.0);\n        const Eigen::Vector3d br = position_in_world(1123.0, 791.0);\n        const Eigen::Vector3d bl = position_in_world(0.0, 791.0);\n        // std::cout << \"tl: \" << tl.transpose() << std::endl;\n        // std::cout << \"tr: \" << tr.transpose() << std::endl;\n        // std::cout << \"br: \" << br.transpose() << std::endl;\n        // std::cout << \"bl: \" << bl.transpose() << std::endl;\n        // auto end2 = std::chrono::high_resolution_clock::now();\n        // std::cout << \"elapsed time function point in world (ns): \"\n        //               << std::chrono::duration_cast< std::chrono::nanoseconds >( end2 - start ).count() << std::endl;\n\n        const Eigen::Vector3d p1 = phi_projection_function(K, R, t, tl);\n        const Eigen::Vector3d p2 = phi_projection_function(K, R, t, tr);\n        const Eigen::Vector3d p3 = phi_projection_function(K, R, t, br);\n        const Eigen::Vector3d p4 = phi_projection_function(K, R, t, bl);\n        // auto end3 = std::chrono::high_resolution_clock::now();\n        // std::cout << \"elapsed time function phi (ns): \"\n        //               << std::chrono::duration_cast< std::chrono::nanoseconds >( end3 - start ).count() << std::endl;\n\n        Eigen::MatrixXd P(4, 3);\n        P.row(0) = p1;\n        P.row(1) = p2;\n        P.row(2) = p3;\n        P.row(3) = p4;\n        // std::cout << \"P: \\n\" << P << std::endl;\n\n        const Eigen::Vector3d m1(0.0, 0.0, 1.0);\n        const Eigen::Vector3d m2(1123.0, 0.0, 1.0);\n        const Eigen::Vector3d m3(1123.0, 791.0, 1.0);\n        const Eigen::Vector3d m4(0.0, 791.0, 1.0);\n        Eigen::MatrixXd M(4,3);\n        M.row(0) = m1;\n        M.row(1) = m2;\n        M.row(2) = m3;\n        M.row(3) = m4;\n        // std::cout << \"M: \\n\" << M << std::endl;\n\n        Eigen::VectorXd res = compute_homograpy_DLT(M, P);\n        // std::cout << \"res: \" << res.transpose() << std::endl;\n        Eigen::Map < Eigen::Matrix3d > homography(res.data(), 3, 3);\n        homography.transposeInPlace();\n        // std::cout << \"Homography: \\n\" << homography << std::endl;\n    }\n    auto end = std::chrono::high_resolution_clock::now();\n    double tt = std::chrono::duration_cast< std::chrono::microseconds >( end - start ).count();\n    std::cout << \"elapsed time (micro s): \"\n                  << tt / repeat << std::endl;\n    Eigen::Matrix<double, 3,1> d(1.0, 10.0, 2.0);\n    return 0;\n}", "meta": {"hexsha": "d5a84accc05acee7e48eb7634d02e6440836adc9", "size": 5187, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "amin-abouee/test-cplusplus-and-julia", "max_stars_repo_head_hexsha": "10850bc6f57b61f211e9d2b527c933d83b26790f", "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": "amin-abouee/test-cplusplus-and-julia", "max_issues_repo_head_hexsha": "10850bc6f57b61f211e9d2b527c933d83b26790f", "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": "amin-abouee/test-cplusplus-and-julia", "max_forks_repo_head_hexsha": "10850bc6f57b61f211e9d2b527c933d83b26790f", "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.867768595, "max_line_length": 120, "alphanum_fraction": 0.5344129555, "num_tokens": 1675, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273633016692238, "lm_q2_score": 0.7549149978955811, "lm_q1q2_score": 0.7000804649280612}}
