{"text": "#include \n#include \n#include \n#include \n#include \n\n#include \n#include \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\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 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& 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 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& 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& labelSet,\n const std::vector& classSummaries,\n const std::vector& 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 trainingData = ReadData(\n TRAINING_FILE_NAME,\n 256,\n 7291\n );\n std::vector testData = ReadData(\n TEST_FILE_NAME,\n 256,\n 2007\n );\n\n std::cout << \"Training Models...\" << std::endl;\n std::vector 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 \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 \n#include \n#include \n\nvoid polyfit(const std::vector &xv, const std::vector &yv, std::vector &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 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 \n#include \n#include \n#include \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 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 matrix_NN;\n matrix_NN = Eigen::MatrixXd::Random (MATRIX_SIZE, MATRIX_SIZE);\n Eigen::Matrixv_Nd;\n v_Nd = Eigen::MatrixXd::Random(MATRIX_SIZE, 1);\n clock_t time_stt = clock();\n Matrix x = matrix_NN.inverse() * v_Nd;\n cout<<\"time used\"<\n#include \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 – Revisited,\"\n BIT, Vol. 40, 2000, pp. 84-101\n\n*/\n\n#include \n#include \n#include \n#include \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 \n#include \nusing namespace std;\n\n// for Eigen\n#include \n#include \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 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\n\t// e.g. Matrix3d is Eigen::Matrix\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 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 result_wrong_type = matrix_23 * v_3d;\n\n\t// should cast\n\tEigen::Matrix result = matrix_23.cast() * v_3d;\n\tcout << result << endl;\n\n\t// size shouldn't be wrong\n //Eigen::Matrix result_wrong_dimension = matrix_23.cast() * 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_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 matrix_NN;\n\tmatrix_NN = Eigen::MatrixXd::Random(MATRIX_SIZE, MATRIX_SIZE);\n\tEigen::Matrix 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 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 \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 \n#include \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": "#ifndef MATH_FUNCTIONS\n#define MATH_FUNCTIONS\n\n#include \n#include \n#include \n#include \n\n\nnamespace Math {\nclass MathFunc {\n typedef Eigen::Matrix RotationMatrix;\n typedef Eigen::Matrix EulerVector;\n typedef Eigen::Matrix Axis;\n typedef Eigen::Matrix Quaternion;\n\n\n public:\n template\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\n static inline void limitAbsoluteValue(Eigen::MatrixBase &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\n static inline Dtype standardDev(Eigen::Matrix &samples) {\n Eigen::Matrix centered = samples.array() - samples.mean();\n return std::sqrt(centered.array().square().sum() / (samples.cols() - 1));\n }\n\n template\n static inline void normalize(Eigen::Matrix &samples) {\n Eigen::Matrix 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\n static inline void normalize(Eigen::Matrix &samples) {\n Eigen::Matrix 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\n static inline void normalize(std::vector &samples) {\n Eigen::Matrix 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\n static inline void sort ( std::vector& value, std::vector& 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\n static inline void sort ( Eigen::Matrix& value, Eigen::Matrix& 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 \n#include \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 \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n\r\ntypedef Eigen::VectorXd vector_t;\r\ntypedef Eigen::MatrixXd matrix_t;\r\ntypedef Eigen::Transform trafo2d_t;\r\n\r\ntrafo2d_t forward_kinematics(vector_t const & q ) ;\r\n\r\ntemplate\r\nT pseudoInverse(const T &a, double epsilon = std::numeric_limits::epsilon());\r\n\r\n\r\ntemplate\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 InputType;\r\ntypedef Eigen::Matrix ValueType;\r\ntypedef Eigen::Matrix 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\r\n{\r\n // Simple constructor\r\n numericalDifferentiationFKFunctor(): Functor(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 inline constexpr\r\nint signum(T x, std::false_type is_signed);\r\n\r\ntemplate inline constexpr\r\nint signum(T x, std::true_type is_signed);\r\n\r\ntemplate \r\nvoid normaliseAngle(T &q);\r\n\r\ntemplate \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 \n#include \n#include \n#include \n#include \n#include \n#include \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 svd_mat(denseInputCentered, Eigen::ComputeFullU | Eigen::ComputeFullV);\n \n //U: Left principal matrix, nxn, orthogonal\n LeftPrinMat = boost::make_shared(svd_mat.matrixU());\n \n //S: Principal values nxm, diagonal\n PrinVals = boost::make_shared(svd_mat.singularValues());\n \n //V: Right singular mxm, orthognol\n RightPrinMat = boost::make_shared(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(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 \n\n#include \n#include \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 \n\n// OpenCV\n#include \n#include \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& image_points,\n const std::vector& world_points,\n const std::vector& 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 inliers;\n cv::Mat H_cv = cv::findHomography(world_points, image_points, cv::RANSAC, 3, inliers);\n\n std::vector inlier_image_points;\n std::vector inlier_world_points;\n for (size_t i=0; 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 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 \n#include \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 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 rosen_hessian (const column_vector& m)\n{\n const double x = m(0);\n const double y = m(1);\n\n matrix 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 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(4,1, -1e100), // lower bound constraint\n uniform_matrix(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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"colormap.h\"\n#include \n\n#define COL(a, b, c) colors.push_back(Color(a, b, c));\n\ntypedef Eigen::SparseMatrix mat;\ntypedef Eigen::MatrixXd mat2;\ntypedef std::vector> 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 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> 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(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 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> make_1D_Laplacian(int N, double h){\n std::vector> vals(N*3);\n int counter = 0;\n\n for(int i = 0; i < N; i++){\n vals[counter] = Eigen::Triplet(i, i, 2.f/h/h);\n counter++;\n if(i != 0){\n vals[counter] = Eigen::Triplet(i-1, i, -1.f/h/h);\n counter++;\n vals[counter] = Eigen::Triplet(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(source, std::placeholders::_1, std::placeholders::_2));\n \n function_array fns(4);\n fns[0] = std::bind([](double x){return sin(0.5*M_PI*x);}, std::placeholders::_1);\n fns[1] = std::bind([](double x){return sin(2*M_PI*x);}, std::placeholders::_1);\n fns[2] = std::bind([](double x){return 0;}, std::placeholders::_1);\n fns[3] = std::bind([](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 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(normalize, std::placeholders::_1, max_val, min_val);\n\n std::vector 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 \n#include \n#include \n#include \n#include \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 &initialData,\n const std::function &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 resolutions;\n\tstd::vector 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 \n#include \n#include \n#include \n#include \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 \n#include \n#include \n#include \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 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 P = Array::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 \n// #include \n#include \n#include \n#include \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 inline constexpr auto abs(const T& a) -> T {\n if constexpr (std::is_unsigned_v) {\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 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 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 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 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) {\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\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 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;\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 \n#include \n#include \n#include \n\n#include \n#include \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()) <::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": "//\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 \n\n// M: M \\times M matrix of data to interpolate from\ntemplate \n\nclass BilinearInterpolator\n{\npublic:\n using VectorMd = Eigen::Matrix;\n using MatrixMd = Eigen::Matrix;\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 \n#include \n#include \n#include \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\nstd::array 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 roots = {std::numeric_limits::quiet_NaN(),\n std::numeric_limits::quiet_NaN(),\n std::numeric_limits::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\nstd::array cubic_root_residual(Real a, Real b, Real c, Real d, Real root) {\n using std::fma;\n using std::abs;\n std::array 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::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 \n#include \n#include \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 \n#include \n\n#include \n\n#include \n#include \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 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\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \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: \"< es3d(CoVar);\n \n Eigen::VectorXd evals; //we'll extract the eigenvalues to here\n //cout<<\"size of evals: \"<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: \"<\n#include \n#include \n#include \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 \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,\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 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 \n#include \n#include \n#include \n#include \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 ≡ 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 \n#include \n\n#include \n#include \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 dft(vector &in) {\n\tvector 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 xs;\n\tstd::vector 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 dat =dft(samples);\n\n\tstd::vector::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 \r\n#include \r\n\r\n#include \r\n#include \r\n#include \r\n\r\nnamespace local\r\n{\r\n template\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 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())\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 \n\n#include \n#include \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 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 rotm_wrapper(rotm.memptr());\n Eigen::Map 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 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 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 rotm_wrapper(rotm.memptr());\n Eigen::Map 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 axang_wrapper(axang.memptr());\n Eigen::Map 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 quat_wrapper(quat.memptr());\n Eigen::Map 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": "#pragma once\n/*\nConvex Hull Trick\n- y = ax + b が順次追加されつつ,最大値/最小値クエリに答える\n- y = c(x - a)^2 + b 型の関数を表す(a, b)たちが順次追加されつつ,最小値クエリに答える\nVerify:\nCF 1179D https://codeforces.com/contest/1179/submission/59448330\nCF 1137E https://codeforces.com/contest/1137/submission/59448399\n*/\n#include \n#include \n#include \n#include \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 \n// using mpint = boost::multiprecision::cpp_int;\nnamespace CHT {\nusing T_CHT = long long;\nstatic const T_CHT T_MIN = std::numeric_limits::lowest() + 1;\nstruct Line {\n T_CHT a, b; // y = ax + b\n mutable std::pair\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 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 struct Lines : std::multiset {\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 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 struct ConvexHullTrick {\n using T_CHT = CHT::T_CHT;\n CHT::Lines 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 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 \n\n#include \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 >, including modding by ZZ\n\nvector > > gen_trinomial_numerator(long lower, long upper) {\n vector > > output(upper-lower);\n\n for(long i = lower; i < upper; i++) {\n Mat 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 >(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 >(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 >(M);\n }\n }\n return output;\n}\n\nvector> gen_trinomial_denominator(long lower, long upper){\n vector> output(upper-lower);\n\n for(long i = lower; i < upper; ++i) {\n if(i <= 1){\n output[i] = Elt(1);\n }\n else {\n output[i-lower] = Elt (i - 1);\n }\n }\n return output;\n}\n\n\nvector> gen_second_prime_power(long lower, long upper) {\n vector> 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(n);\n }\n else{\n output[i-lower] = Elt(1);\n }\n }\n return output;\n}\n\nvector> gen_third_prime_power(long lower, long upper) {\n vector> 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(n);\n }\n else{\n output[i-lower] = Elt(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 \n#include \n#include // for std::function\n#include \n#include \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 \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> 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 \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> 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 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(const Eigen::VectorXd &)>\n auto A = [&T, n] (const Eigen::VectorXd & x) -> Eigen::SparseMatrix & { 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\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\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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"atoms.h\"\n\n\nusing namespace std;\nusing namespace Eigen;\n\nvector split(const string &s, char delim) {\n stringstream ss(s);\n string item;\n vector 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 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 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 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 * √((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 * θ = 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 = Σ_i m_i v_i / Σ_i m_i\n for (int i=0; i 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 \n#include \n\n#include \n#include \n#include \"mrob/pc_registration.hpp\"\n\nusing namespace mrob;\nusing namespace Eigen;\n\nint PCRegistration::arun(const Ref X, const Ref 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 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 \n#include \n#include \n#include \n#include \n\n#include \n\ntemplate\nusing Matrix = Eigen::Matrix;\n\n#include \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\n class Polynomial\n {\n vector 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 differentiate() const\n {\n Polynomial 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 integrate() const\n {\n Polynomial 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\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 normalize() const\n {\n Polynomial 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 roots() const\n {\n assert(c.size() >= 1);\n size_t n = c.size() - 1;\n\n // initial guess\n Polynomial> z0(n), z1(n);\n for (size_t j = 0; j < n; j++) {\n z0[j] = pow(complex(0.4, 0.9), j);\n z1[j] = z0[j];\n }\n\n // durand-kerner-weierstrass iterations\n Polynomial p = normalize();\n for (size_t k = 0; k < 100; k++) {\n complex 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::epsilon()) { break; }\n\n z1 = z0;\n }\n\n vector roots(n);\n for (size_t j = 0; j < n; j++) {\n roots[j] = (abs(z0[j]) < 4 * std::numeric_limits::epsilon()) ? 0.0 : real(z0[j]);\n }\n\n sort(roots.begin(), roots.end());\n return roots;\n }\n\n static Polynomial legendre(const size_t order)\n {\n if (order == 0) {\n Polynomial p(1);\n p[0] = 1.0;\n return p;\n }\n\n if (order == 1) {\n Polynomial p(2);\n p[0] = 0.0;\n p[1] = 1.0;\n return p;\n }\n\n Polynomial 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\n vector compute_nodes(size_t nnodes, QuadratureType qtype)\n {\n vector nodes(nnodes);\n\n if (qtype == QuadratureType::GaussLegendre) {\n auto roots = Polynomial::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::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::legendre(nnodes);\n auto lm1 = Polynomial::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() / (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\n auto augment_nodes(vector const orig) -> pair, vector> {\n vector 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 is_proper(nodes.size(), true);\n is_proper.front() = left;\n is_proper.back() = right;\n\n return pair, vector>(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\n Matrix compute_quadrature(vector dst, vector src, vector 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 mat(ndst - 1, nsrc);\n mat.fill(0.0);\n\n Polynomial 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\n Matrix compute_interp(vector dst, vector src)\n {\n const size_t ndst = dst.size();\n const size_t nsrc = src.size();\n\n Matrix 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 \n#include \n#include \n\nusing namespace std;\nusing namespace Eigen;\n\nint main(int argc, char ** argv){\n Matrix matrix_23;\n matrix_23 << 1,2,3,4,5,6;\n cout << matrix_23 << endl;\n\n Matrix matrix_232;\n matrix_232 << 1,2,3,4,5,6;\n\n Matrix matrix_dd;\n matrix_dd = matrix_23 * matrix_232.cast().transpose();\n // cout << matrix_23*matrix_232.cast().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 matrix_nn = MatrixXd::Random(5,5);\n matrix_nn = matrix_nn * matrix_nn.transpose();\n Matrix vector_n = MatrixXd::Random(5,1);\n Matrix 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 \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace math\n{\n\ttemplate\n\tstruct vector3 \n\t : boost::addable< vector3 // vector + vector\n \t , boost::subtractable< vector3 // vector - vector\n \t , boost::dividable2< vector3, T // vector / T\n \t , boost::multipliable2< vector3, T // vector * T, T * vector\n \t , boost::equality_comparable< vector3 // 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\n\t\texplicit vector3(const vector3& 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(*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 \n#include \nusing namespace Eigen;\nusing namespace std;\n\nfloat inv_cond(const Ref& 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 \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n//Element data type\r\nstruct Element\r\n{\r\n\tvoid CalculateStiffnessMatrix(const Eigen::Matrix3f& D, std::vector >& triplets);\r\n\r\n\tEigen::Matrix 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 >& 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 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 trplt11(2 * nodesIds[i] + 0, 2 * nodesIds[j] + 0, K(2 * i + 0, 2 * j + 0));\r\n\t\t\tEigen::Triplet trplt12(2 * nodesIds[i] + 0, 2 * nodesIds[j] + 1, K(2 * i + 0, 2 * j + 1));\r\n\t\t\tEigen::Triplet trplt21(2 * nodesIds[i] + 1, 2 * nodesIds[j] + 0, K(2 * i + 1, 2 * j + 0));\r\n\t\t\tEigen::Triplet 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::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& K, const std::vector& constraints)\r\n{\r\n\tstd::vector indicesToConstraint;\r\n\r\n\tfor (std::vector::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::InnerIterator it(K, k); it; ++it)\r\n\t\t{\r\n\t\t\tfor (std::vector::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(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 > triplets;\r\n\tfor (std::vector::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 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 > 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::iterator it = elements.begin(); it != elements.end(); ++it)\r\n\t{\r\n\t\tEigen::Matrix 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::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::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::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 \n\n#include \n\ntypedef unsigned long long nombre;\ntypedef std::vector vecteur;\n\nENREGISTRER_PROBLEME(214, \"Totient Chains\") {\n // Let φ be Euler's totient function, i.e. for a natural number n, φ(n) is the number of k, 1 ≤ k ≤ n, for which\n // gcd(k,n) = 1.\n // \n // By iterating φ, 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(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 \n#include \n#include \n#include \n\nEigen::Matrix3d OthMatrix(const Eigen::Matrix3d& input) {\n Eigen::Quaterniond q(input);\n q.normalize();\n return q.toRotationMatrix();\n}\n\n// 解决如下问题\n// 1. 万向锁时,分解欧拉角是否仍然有效\n// 2. 万向锁反应了一个什么样的问题?\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 没有万向锁\n Eigen::Matrix3d composition = rz * ry * rx;\n composition = OthMatrix(composition);\n Eigen::Vector3d euler_angles = composition.eulerAngles(2, 1, 0);\n std::cout << \"正常情况:\\n\";\n std::cout << euler_angles.transpose() * 180 / M_PI << std::endl;\n\n // 2 将y改为90度,观察万向锁时的分解结果\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 << \"万向锁对应的分解:\\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用合成角度\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考虑万向锁丢失了轴,仅用两个轴得到旋转矩阵,并进行分解\\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 使用\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 \n#include \n#include \n#include \n#include \n\n//! Sparse Matrix type. Makes using this type easier.\ntypedef Eigen::SparseMatrix SparseMatrix;\n\n//! Used for filling the sparse matrix.\ntypedef Eigen::Triplet 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 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 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 &errors,\n std::vector & 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 errors;\n\tstd::vector 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 \n\n#include \n\n#include \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 &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 &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 &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 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 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 \n#include \n#include \n#include \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émentation pour la calculation mathématique\n */\n\n#include \n#include \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écurrence.\n*\n* @param n entier\n*\n* @return le résultat 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érivée\n *\n * Cette fonction a pour but d'approximer la dérivée 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écalée d'une valeur\n * @param Z1 vecteur contenant les n points où sont évaluée la fonction\n * @param Z2 vecteur contenant les n points où sont évaluée la fonction décalée d'une valeur\n *\n * @return res vecteur contenant les valeurs de la fonction dérivée\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 \n#include \nusing namespace std;\n\n#include \n#include \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: \"<matrix\n cout<<\"so3 hat vee\"<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 = \"< Vector6d;\n Vector6d se3=SE3_Rt.log();\n cout<<\"se3 = \"<\n#include \n\n#include \n#include \n\n// Generic functor\ntemplate\nstruct Functor\n{\n typedef _Scalar Scalar;\n enum {\n InputsAtCompileTime = NX,\n ValuesAtCompileTime = NY\n };\n typedef Eigen::Matrix InputType;\n typedef Eigen::Matrix ValueType;\n typedef Eigen::Matrix 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\n{\n my_functor(void): Functor(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 numDiff(functor);\n Eigen::LevenbergMarquardt,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": "#include \"convhull_volume.h\"\n#define CONVHULL_3D_ENABLE\n#include \"convhull_3d.h\"\n#include \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 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 \n#include \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 \n\t//for std::string\n#include \n\t//for std::max\n#include \n\t//for std::vector\n//..armadillo library\n#include \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 \nusing namespace std;\n\n// Eigen includes\n#include \nusing namespace Eigen;\n\n// autodiff include\n#include \n#include \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 \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \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> 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(_vertices[0]);\n auto* v1 = dynamic_cast(_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(_vertices[0]);\n auto* v1 = dynamic_cast(_vertices[1]);\n // auto T0 = v0->estimate();\n auto T1 = v1->estimate();\n\n Sophus::SE3d e = Sophus::SE3d::exp(_error);\n Eigen::Matrix J_inv = Eigen::Matrix::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::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(_vertices[0]);\n auto *v1 = dynamic_cast(_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 // 设定g2o\n typedef g2o::BlockSolver> BlockSolverType;\n typedef g2o::LinearSolverEigen LinearSolverType;\n auto solver = new g2o::OptimizationAlgorithmLevenberg(\n g2o::make_unique(g2o::make_unique()));\n g2o::SparseOptimizer optimizer;\n optimizer.setAlgorithm(solver);\n optimizer.setVerbose(true);\n\n int vertexCnt = 0, edgeCnt = 0;\n\n vector vectices;\n vector edges;\n while (!fin.eof()) {\n string name;\n fin >> name;\n if (name == \"VERTEX_SE3:QUAT\") {\n // 顶点\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 边\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 \nusing std::cout; using std::endl;\nusing std::left; using std::fixed; using std::right; using std::scientific;\n#include \nusing std::setw;\nusing std::setprecision;\n\n#include \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 \n#include \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 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 \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 \r\nstruct init {\r\n init() { std::cout << \"[\" << \"init\" << \"]\" << std::endl; }\r\n};\r\ninit init_obj;\r\n// [init]\r\n#include \r\n#include \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 > 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 \n\nnamespace hpcpp {\n\nvoid matmul1(const std::vector &matrix,\n const std::vector &vector, std::vector &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 &matrix,\n const std::vector &vector, std::vector &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 &matrix,\n const std::vector &vector, std::vector &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 &matrix,\n const std::vector &vector, std::vector &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 &matrix,\n const std::vector &vector, std::vector &result) {\n const std::size_t n{vector.size()};\n result.resize(n, 0.0);\n Eigen::Map m(matrix.data(), n, n);\n Eigen::Map v(vector.data(), n);\n Eigen::Map 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": "//! [example1]\n#include \n#include \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{\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<\n#include \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 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 \n #include \n #include \n #include \n #include \n #include \n\nnamespace bnu = boost::numeric::ublas;\n\n/* Matrix inversion routine.\nUses lu_factorize and lu_substitute in uBLAS to invert a matrix */\ntemplate\nbool InvertMatrix(const boost::numeric::ublas::matrix& input, boost::numeric::ublas::matrix& inverse)\n{\n typedef boost::numeric::ublas::permutation_matrix pmatrix;\n\n // create a working copy of the input\n boost::numeric::ublas::matrix 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 (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& 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& m ) {\n bnu::permutation_matrix 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 \n#include \n#include \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 \n#include \n#include \n#include \n#include \n\nusing Triplet = Eigen::Triplet;\nusing Triplets = std::vector;\n\nusing Vector = Eigen::VectorXd;\nusing Matrix = Eigen::SparseMatrix;\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 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 × 99.\nFind the largest palindrome made from the product of two 3 - digit numbers.\n*/\n\n#include \n#include \n#include \n#include \n#include \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": "#include \n#include \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 , He Sun \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 \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 \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \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 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 \n#include \n#include \n#include \n#include \n#include \n\n//! Sparse Matrix type. Makes using this type easier.\ntypedef Eigen::SparseMatrix SparseMatrix;\n\n//! Used for filling the sparse matrix.\ntypedef Eigen::Triplet 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 &gL, const std::function &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 &gL, const std::function &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–Tung–Striebel smoother for track observations\n\n#ifndef BIGGLES_KALMAN_FILTER_HPP__\n#define BIGGLES_KALMAN_FILTER_HPP__\n\n#include \n#include \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_covariance_pair;\n\n /// @brief The collection type used to hold states and covariances.\n //typedef std::deque > states_and_cov_deque;\n typedef std::deque 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\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\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–Tung–Striebel backwards smoothing step on the Kalman filter predicted and corrected states.\n///\n/// @note Since this is a backward process, the results are written to \\p\n/// output_reversed_states_and_covariances in reverse order; i.e. the smoothed state and covariance for the\n/// last 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–Tung–Striebel\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 in reverse\n/// order.\ntemplate\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 \"BezierSpline.h\"\n\n__pragma(warning(push, 0))\n#include \n__pragma(warning(pop))\n\n#include \n\n#include \n\nnamespace Chaf\n{\n\tvoid BezierSpline::createControlPoints(const std::vector& input_x, const std::vector& input_y, std::vector& control_x, std::vector& control_y)\n\t{\n\t\tsize_t n = input_x.size() - 1;\n\n\t\tstd::vector 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(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 \"polynomial_solver.hh\"\r\n#include \r\n\r\n\r\nnamespace Geo {\r\n\r\ntemplate\r\nstd::multiset polygon_roots(const double* _poly)\r\n{\r\n std::multiset res;\r\n if constexpr(DegT == 0)\r\n return res;\r\n if (_poly[DegT] == 0)\r\n {\r\n res = polygon_roots(_poly);\r\n res.insert(0.);\r\n }\r\n else\r\n {\r\n Eigen::Matrix 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, DegT, 1> roots = companion.eigenvalues();\r\n for (auto i = roots.rows(); i-- > 0;)\r\n {\r\n std::complex 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 polygon_roots<0>(const double*)\r\n{\r\n return std::multiset();\r\n}\r\n\r\ntemplate\r\nstd::multiset polygon_roots(const std::array& _poly)\r\n{\r\n return polygon_roots(_poly.data());\r\n}\r\n\r\ntemplate std::multiset polygon_roots<2>(const std::array& _poly);\r\ntemplate std::multiset polygon_roots<3>(const std::array& _poly);\r\n//template std::multiset polygon_roots<4>(const std::array& _poly);\r\n//template std::multiset polygon_roots<5>(const std::array& _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 \n#include \n#include \n#include \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 \nvoid errors(const Function &f, const double &T, const VectorXd &y0, const MatrixXd &A, const VectorXd &b) {\n \n RKIntegrator rk(A,b);\n vector error(15);\n vector order(14);\n double sum = 0;\n int count = 0;\n bool test = 1;\n vector 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 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]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] <\n#include \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 \nusing namespace std;\n#include \n#include \n#include \n\nint main()\n{\n Eigen::Matrixmatrix_23;\n matrix_23<<1,2,3,4,5,6;\n //cout< vd_3d;\n //cout<result=matrix_23.cast()*v_3d;\n cout<result2=matrix_23*vd_3d;\n //cout<\n\n#include \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 >, including modding by ZZ\n\nvector > > gen_kurepa_multiplicand(long lower, long upper) {\n vector > > output(upper-lower);\n\n for(long i = lower; i < upper; i++) {\n Mat 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 >(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 >(M);\n }\n }\n return output;\n}\n\nvector> gen_prime(long lower, long upper) {\n vector> 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(n);\n }\n else{\n output[i-lower] = Elt(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 \n#include \n\nvoid testLinearity(std::vector& 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 vectors, std::vector 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 makeBasis(std::vector vectors) {\n std::vector 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& 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 v;\n std::vector 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": "/*\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’s 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 \n#include \n#include \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(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(mean);\n mStd = asEigen(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(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(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 \n#include \n#include \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 solutionColMajor(solutionVec.data(),4,3);\n\n Eigen::Map >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(array);\n std::cout << a << std::endl;\n\n std::vector 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(\n reinterpret_cast(pointsVec.data()), 2, long(pointsVec.size()));\n\n Eigen::MatrixXd pointsMatrixXd = Eigen::Map(\n reinterpret_cast(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 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(eigenPointsVec[0].data(), 3, long(eigenPointsVec.size()));\n\n std::cout << pointsMatrix << std::endl;\n std::cout << \"==============================\" << std::endl;\n\n pointsMatrix = Eigen::Map(reinterpret_cast(eigenPointsVec.data()), 3, long(eigenPointsVec.size()));\n\n std::cout << pointsMatrix << std::endl;\n\n std::vector aa = { 1, 2, 3, 4 };\n Eigen::VectorXd b = Eigen::Map(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 \n#include \n#include \n#include \n#include \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 arr_x = {1, 2, 3, 4};\n std::array 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 \n#include \n#include \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 \n\ntemplate \nusing Vector = Eigen::Matrix;\ntemplate \nusing Quaternion = Eigen::Quaternion;\n\nnamespace MathsUtils\n{\n template \n Eigen::Matrix skew_symmetric(Vector v)\n {\n Eigen::Matrix 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 \n Eigen::Matrix diff_qvqstar_q(Quaternion q, Vector v)\n {\n auto& qw = q.w();\n Vector qv = q.vec();\n Eigen::Matrix 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::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 \n Eigen::Matrix diff_qvqstar_v(Quaternion q)\n {\n auto& qw = q.w();\n Vector qv = q.vec();\n Eigen::Matrix D;\n D = (qw*qw - qv.dot(qv))*Eigen::Matrix::Identity() + 2*qv*qv.transpose() + 2*qw*skew_symmetric(qv);\n return D; \n }\n\n template \n Eigen::Matrix diff_pq_p(Quaternion q)\n {\n auto& qw = q.w();\n Vector qv = q.vec();\n Eigen::Matrix 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::Identity()*qw - skew_symmetric(qv);\n return D;\n }\n\n template \n //diff_(p*q) /diff_q\n Eigen::Matrix diff_pq_q(Quaternion p)\n {\n auto& pw = p.w();\n Vector pv = p.vec();\n Eigen::Matrix 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::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 _MATH_HEADER__\n#define _MATH_HEADER__\n\n#include \n\n#include \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 \n constexpr T log2(T n) {\n return (n<2) ? 0 : 1 + log2(n/2);\n }\n\n template \n constexpr NUM abs(const NUM& n) {\n return n >= 0 ? n : -n;\n }\n\n namespace internal {\n\n template \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 \n constexpr NUM _min2(const NUM& min, const NUM& f) {\n return f < min ? f : min;\n }\n\n template \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 \n constexpr NUM _max2(const NUM& max, const NUM& f) {\n return f > max ? f : max;\n }\n\n }\n\n template \n constexpr NUM min(const NUM& f, const OTHER&... n) {\n return internal::_min2(f, n...);\n }\n\n template \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 \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(floor(log10(n))) + 1; \n }\n\n \n\n // template \n // NUM pow10(int a) {\n // NUM n{1};\n // return internal::_pow10(n, a);\n // }\n\n template \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(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 \n constexpr double getM(const NUM1& xa, const NUM2& ya, const NUM3& xb, const NUM4& yb) {\n return (static_cast(ya) - static_cast(yb)) / (static_cast(xa) - static_cast(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 \n constexpr double getQ(const NUM1& xa, const NUM2& ya, const NUM3& xb, const NUM4& yb) {\n return static_cast(ya) - getM(xa, ya, xb, yb) * static_cast(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 \n constexpr double getQ(const NUM1& xa, const NUM2& ya, const NUM3& m) {\n return static_cast(ya) - static_cast(m)*static_cast(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 \n constexpr double linearTransform(const NUM1& x, const NUM2& m, const NUM3& q) {\n return static_cast(m)*static_cast(x) + static_cast(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 \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 \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(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 \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(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(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 \n constexpr double getMonotonicallyCrescent(const NUM& x) {\n return (2./cpp_utils::pi()) * std::atan(static_cast(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 \n constexpr double getMonotonicallyCrescent(const NUM1& x, const NUM2& minY, const NUM3& maxY) {\n return static_cast(minY) + (static_cast(maxY) - static_cast(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 \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 \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 \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 \n T parseFromString(const char* s) {\n return parseFromString(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 \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 \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 \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 \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 \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 \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 \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(decimal * static_cast(denominator));\n T numeratorT = decimal * denominatorT;\n\n T numeratorTimesDivided10 = (static_cast(10.) * numeratorT)/(static_cast(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(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\n constexpr int _argmin2(int minimumIndex, int nIndex, const T& minimum) {\n return minimumIndex;\n }\n\n template\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\n constexpr int _argmin1(const T& first, const NUMS&... args) {\n return _argmin2(0, 1, first, args...);\n }\n\n template\n constexpr int _argmax2(int maximumIndex, int nIndex, const T& maximum) {\n return maximumIndex;\n }\n\n template\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\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\n constexpr int argmin(const NUMS&... args) {\n return internal::_argmin1(args...);\n }\n\n template \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\n constexpr int argmax(const NUMS&... args) {\n return internal::_argmax1(args...);\n }\n\n template\n constexpr int argmax(const T& num) {\n return 0;\n }\n\n template \n bool isDecimal(const T& n) {\n return isApproximatelyEqual(std::fmod(n, 1.0), 0.0, 1e-3);\n }\n\n template\n bool isDecimal(const int& n) {\n return true;\n }\n\n template\n bool isDecimal(const unsigned int& n) {\n return true;\n }\n\n template\n bool isDecimal(const long& n) {\n return true;\n }\n\n template\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 \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 \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 \n constexpr NUM1 bound(const NUM1& x, const NUM2& lb, const NUM3& ub) {\n if (x < lb) {\n return static_cast(lb);\n }\n if (x > ub) {\n return static_cast(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 \n#include \n#include \n#include \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 X; // Inside Calcium concentration in Molars\n //------------------ CONSTRUCTORS\n DET_MODEL_PMCA(std::vector X_): X(X_) { };\n template \n void operator() ( const State &x, Deriv &dxdt , const double t );\n};\n\n//------- PMCA class ODE Function\ntemplate \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 \n#include \n#include \n#include \n#include \n#include \n\ndouble nextNumber( double number ) {\n return number + floor( 0.5 + sqrt( number ) ) ;\n}\n\nint main( ) {\n std::vector non_squares ;\n typedef std::vector::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(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 \n#include \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 es(H); \n VectorXd ev(N), r2(N);\n for (int i=0;i\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 \n#include \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 &prim, Array &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 &cons, Array &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 &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": "#pragma once\n\n#include \n#include \n#include \n#include \n\n#include \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 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& 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& 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\n Eigen::Quaterniond GetQuaternion(Generator& prng)\n {\n std::function uniform_rand_fn\n = [&] () { return uniform_unit_dist_(prng); };\n return GenerateUniformRandomQuaternion(uniform_rand_fn);\n }\n\n template\n std::vector GetRawQuaternion(Generator& prng)\n {\n const Eigen::Quaterniond quat = GetQuaternion(prng);\n return std::vector{quat.x(), quat.y(), quat.z(), quat.w()};\n }\n\n template\n Eigen::Vector3d GetEulerAngles(Generator& prng)\n {\n std::function uniform_rand_fn\n = [&] () { return uniform_unit_dist_(prng); };\n return GenerateUniformRandomEulerAngles(uniform_rand_fn);\n }\n\n template\n std::vector GetRawEulerAngles(Generator& prng)\n {\n const Eigen::Vector3d angles = GetEulerAngles(prng);\n return std::vector{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 \n#include \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 // 数学上 inverse 很好, 但数值线性系统中用分解更快. (小矩阵的话, 分解也没有公式快)\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": "/*\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 \n\n#include \n#include \n#include \n#include \n#include \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 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 result;\n for (const pnp::RansacHypothesis& 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": "/**\n * @file matode_main.cc\n * @brief NPDE homework MatODE code\n * @copyright Developed at ETH Zurich\n */\n\n#include \n#include \n#include \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 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 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": "#include \n#include \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 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 \n#include \n#include \n\nusing Eigen::Map;\nusing Eigen::MatrixXd;\nusing Eigen::PartialPivLU;\nusing Eigen::VectorXd;\nusing std::vector;\n\nmathtoolbox::RbfInterpolator::RbfInterpolator(const std::function& 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(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 \n#include \nusing namespace std;\n\n#include \n#include \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) = \" <\n#include \n#include \n#include \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\"<\n#include \n#include \n#include \n\nnamespace LP {\n using namespace Eigen;\n\n int findEBV(VectorXd& c, Matrix& 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& 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& 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 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\n Simplex(VectorXd c, MatrixXd A, VectorXd b, Matrix BV,\n std::vector 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 \n\n#include \"matplotlibcpp.h\"\n\n#include \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 result = ExplicitRKSolvers::classical4thOrderRuleIntegrator(f, time,y0, steps);\n\n std::vector t(steps);\n std::vector prey(steps);\n std::vector 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 result = ExplicitRKSolvers::classical4thOrderRuleIntegrator(f, time,y0, steps);\n\n std::vector x(steps);\n std::vector y(steps);\n std::vector 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": "//\n// Created by Amir Masoud Abdol on 2020-04-11\n//\n\n#include \"TestStrategy.h\"\n\n#include \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 &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(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 &x,\n const arma::Row &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(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 &x, const arma::Row &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::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::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 \n#include \n#include \n#include \n#include \n#include \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 cmpx_t; \n\ntypedef ublas::matrix m_t;\ntypedef ublas::matrix 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 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 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 \n#include \n#include \n#include \n#include \n#include \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 \n#include \n//#include Vector3;\ntypedef Matrix 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 \n#include \n#include \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 \n\nnamespace mineral_deposit_tracking\n{\n\ntemplate\nclass KalmanFilter\n{\npublic:\n\tusing VectorType = Eigen::Matrix;\n\tusing MatrixType = Eigen::Matrix;\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 \r\n#include \r\n#include \r\n#include \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 \r\nclass Mesh {\r\ntypedef Eigen::Matrix Vec;\r\nprivate:\r\n\tconst std::vector> m_lengths;\r\n\tconst T m_t0, m_tend;\r\n\tT m_dt;\r\n\tconst std::vector m_nx;\r\n\tstd::vector m_dx;\r\n\tconst int m_nt;\r\n\tstd::vector m_x;\r\n\tVec m_t;\r\n\tstd::size_t m_dim; \r\npublic:\r\n\tMesh(const std::vector>& lengths, T t0, T tend, \r\n\t\tconst std::vector& 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 1. See \r\n * \\ref fig_mesh\r\n *\r\n * @return The number of divisions per axis.\r\n */\r\n std::vector 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 left(){\r\n std::vector nx = division_per_axis();\r\n std::unordered_set temp1;\r\n std::vector 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 right(){\r\n std::vector nx = division_per_axis();\r\n std::vector 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 bottom(){\r\n std::vector nx = division_per_axis();\r\n std::vector temp;\r\n if (m_dim == 2){\r\n for (int i=0; i top(){\r\n \tstd::vector nx = division_per_axis();\r\n std::vector 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 front(){\r\n std::vector nx = division_per_axis();\r\n std::vector 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 back(){\r\n std::vector nx = division_per_axis();\r\n std::vector temp;\r\n for (int i=0; i boundaries(){\r\n // points in 1D\r\n // lines in 2D\r\n // surfaces in 3D\r\n std::vector nx = division_per_axis();\r\n std::vector 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 domain(){\r\n std::vector nx = division_per_axis();\r\n std::vector all;\r\n if (m_dim == 1){\r\n all == utils::linear_spaced(0, nx[0], nx[0] + 1);\r\n }\r\n else if (m_dim ==2){\r\n all == utils::linear_spaced(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(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 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 surfaces(){\r\n std::vector 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 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 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 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::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 node;\r\n Eigen::Matrix, Eigen::Dynamic, 1> coords;\r\n for (int k=0; k 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 \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": "#include \"Kinematics.h\"\r\n#include \r\n\r\nusing namespace MotionControl;\r\n\r\nMatrix Kinematics::Rodrigues(Matrix a, double q)\r\n{\r\n\treturn AngleAxisd(q,a).toRotationMatrix();\r\n}\r\n\r\nMatrix Kinematics::rot2omega(Matrix 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 vector_R(Matrix::Zero());\r\n\r\n\tif(fabs(alpha-1) < eps)\r\n\t\treturn Matrix::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 Kinematics::FindRoute(int to)\r\n{\r\n\tvector 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 Kinematics::calcVWerr(Link Cref, Link Cnow)\r\n{\r\n\tMatrix perr = Cref.p - Cnow.p;\r\n\tMatrix Rerr = Cref.R - Cnow.R;\r\n\tMatrix werr = Cnow.R * rot2omega(Rerr);\r\n\tMatrix 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 idx)\r\n{\r\n\tsize_t jsize = idx.size();\r\n\tMatrix target = ulink[idx.back()].p;\r\n\tMatrix J = MatrixXd::Zero(6,11);\r\n\r\n\tfor(size_t i=0;i a = ulink[j].R * ulink[j].a;\r\n\t\tMatrix 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 \r\nt_matrix Kinematics::PseudoInverse(const t_matrix& m, const double &tolerance)\r\n{\r\n\ttypedef JacobiSVD 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 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 err;\r\n\r\n\tColPivHouseholderQR QR; //QR分解?\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 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\n\nusing namespace std ;\nusing namespace Eigen ;\nusing namespace vsim ;\n\nstatic float polygon_area(const vector &contour)\n{\n uint n = contour.size();\n\n float A = 0.0f;\n\n for( uint p=n-1, q=0; q= 0.0f) && (bCROSScp >= 0.0f) && (cCROSSap >= 0.0f));\n}\n\nbool snip(const vector &contour, int u,int v,int w,int n, vector &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 fitPlaneToPoints(const vector &pts) {\n uint n_pts = pts.size() ;\n assert(n_pts >= 3) ;\n\n if ( n_pts == 3 )\n return Eigen::Hyperplane::Through(pts[0], pts[1], pts[2]) ;\n else {\n Eigen::Map > 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 svd(cov, ComputeFullU);\n Vector3f normal = svd.matrixU().col(2);\n return Eigen::Hyperplane(normal, centroid) ;\n }\n}\n\n\nbool triangulate(const vector &pts, vector &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 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 contour ;\n for(uint i=0 ; i V(n) ;\n\n /* we want a counter-clockwise polygon in V */\n\n if ( polygon_area(contour) > 0 )\n for ( uint v=0; v2; )\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, */\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 &vertices, std::vector &normals, std::vector &colors,\n std::vector tex_coords[])\n{\n vector 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 &vertices, const vector &indices, vector &vtx_normals)\n{\n vtx_normals.resize(vertices.size()) ;\n for( int i=0 ; i\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 \n#include \n#include \n\n\nnamespace dcs { namespace math {\n\nnamespace detail { namespace /**/ {\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 \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(n-1, k)*bell_rec(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 \nRealT bell_triangle(unsigned int n)\n{\n\tif (n <= 1)\n\t{\n\t\treturn 1;\n\t}\n\n\t::std::vector Tup(n); // The upper row of Bell triangle\n\t::std::vector 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\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 \nRealT bell_naive(unsigned int n)\n{\n\treturn detail::bell_rec(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 Bell number \\f$B_n\\f$ (also called the exponential\n * number) 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 \nRealT bell(unsigned int n)\n{\n\treturn detail::bell_triangle(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 \n#include \n#include \n#include \n#include \n#include \n#include \n\n#define abs(x) ((x) < 0 ? -x : x)\n\nnamespace ublas = boost::numeric::ublas;\n\ntemplate\nbool invert_matrix_gj(const ublas::matrix& input, ublas::matrix& inverse) {\n typedef ublas::matrix tmatrix;\n typedef ublas::vector tvector;\n typedef ublas::identity_matrix 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 current(A, y);\n\tublas::matrix_row 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 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": "#include \n#include \n#include \n\n#include \n#include \n\nnamespace Euclid\n{\n\ntemplate\nvoid WKS::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\nvoid WKS::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\ntemplate\nvoid WKS::compute(Eigen::ArrayBase& 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(0);\n auto ce = static_cast(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 \r\n\r\n#include \r\n#define _USE_MATH_DEFINES // for C++ \r\n#include \r\n\r\n#include \"HiMatrix.h\"\r\n\r\n#include \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 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();\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());\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();\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 \n#include \n#include \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(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 \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \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& u,\n const Handle& r,\n const Handle& 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& u_;\n const Handle& r_;\n const Handle& 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& u,\n const Handle& r, const Handle& sigma)\n: strike_(strike), type_(type), exerciseDate_(exerciseDate), u_(u), r_(r), sigma_(sigma){\n cout << \"Type is \" <= 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 u = make_shared(120.0);\n Handle U(u);\n\n shared_ptr r =\n make_shared(today, 0.01, Actual360());\n RelinkableHandle R(r);\n\n shared_ptr sigma =\n make_shared(today, TARGET(), 0.20, Actual360());\n Handle 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": "// 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 \nusing std::cout; using std::endl;\nusing std::left; using std::fixed; using std::right; using std::scientific;\n#include \nusing std::setw;\nusing std::setprecision;\n#include \n#include \n#include \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 \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \"lf/refinement/test/refinement_test_utils.h\"\n\ntemplate \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()->default_value(3), \"The degree of the local quadrature rule.\")\n (\"max_level\", po::value()->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();\n int quad_degree = vm[\"quad_degree\"].as();\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{0, 1, 4},\n std::make_unique(node_coords));\n node_coords << 0, 0.5, 0, 0, 1, 1;\n mesh_factory.AddEntity(lf::base::RefEl::kTria(),\n std::vector{0, 4, 5},\n std::make_unique(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{1, 2, 3, 4},\n std::make_unique(node_coords));\n\n auto base_mesh = mesh_factory.Build();\n\n // parameters:\n auto pi = boost::math::constants::pi();\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(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 \n#include \n#include \n#include \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<<\"直接求逆\"<(t1-t0).count()<<\"ms\"<(t3-t2).count()<<\"ms\"<(t5-t4).count()<<\"ms\"<\n#include \n#include \"util.h\"\n\nusing namespace std;\n\nvoid Util::generate_divisors(const vector< pair > &prime_factorization, vector &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 > 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 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 Util::hadamard_transform(vector x) {\n int n = x.size();\n if (n == 1)\n return x;\n else {\n assert((n&1) == 0);\n vector ret(n);\n vector xl(n/2);\n vector 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 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 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 &v) {\n int i = 0;\n while ((i &v, int q, const vector &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 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 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 &v, int q, const vector &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 Util::decompose_canonical_vector(int vindex, int l, int q,\n\t\t\t\t\t const vector &qpows, const vector &qinv) {\n assert(l > 0);\n vector 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( { v[0], g, vsuff_index } );\n}\n\nint Util::mod_dot_product(const vector &u, const vector &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 = s\n// we assume here that v is not zero (else this isn't possible for all s)\nvector Util::randvec_with_specified_dot_product(const vector& v, int s, int q,\n\t\t\t\t\t\t const vector &qinv, boost::random::mt19937 &rng) {\n boost::uniform_int<> unif_int = boost::uniform_int<>(0, q - 1);\n vector ret(v.size());\n // pick ret to be a random element of (F_q)^t \\ {0} s.t. = 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": "/*-------------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 \n#include \n#include \n#include \n#include \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\n#include\n#include\n#include \n#include\n\nusing Eigen::MatrixXd;\nusing namespace std;\n\nvoid print_vector(vector > v);\nvoid print_matrix_vector(vector 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: \"< > rows; \n string line;\n while(myfile.good()){\n vector 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 > v){\n vector >::iterator mvp;\n vector::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< v){\n vector::iterator it;\n for(it= v.begin(); it!= v.end(); it++){\n cout<<*it<<\" \";\n }cout<\n#include \n#include \n#include \n\n#include \n#include \n#include \n\nstd::vector> MakeTripletList(int n) {\n\tint nnz = 3 * n - 2;\n\tstd::vector> tripletList(nnz);\n\n\tfor(int i = 0; i < n; i++) {\n\t\ttripletList.push_back(Eigen::Triplet(i, i, 2));\n\n\t\tif(i > 0) {\n\t\t\ttripletList.push_back(Eigen::Triplet(i, i - 1, -1));\n\t\t}\n\n\t\tif(i < n - 1) {\n\t\t\ttripletList.push_back(Eigen::Triplet(i, i + 1, -1));\n\t\t}\n\t}\n\n\treturn tripletList;\n}\n\ndouble Runtime(const std::function &f) {\n\tdouble runtime = std::numeric_limits::max();\n\tstd::chrono::duration > duration;\n\tstd::chrono::time_point 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 \nstd::ostream & operator<< (std::ostream &os, const std::vector &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> tripletList = MakeTripletList(m);\n\tEigen::SparseMatrix 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 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 runtimeSparse;\n\tstd::vector runtimeDense;\n\n\tfor (int n : N) {\n\t\ttripletList = MakeTripletList(n);\n\n\t\t// sparse LU decomposition\n\t\tEigen::SparseMatrix S(n, n);\n\t\tS.setFromTriplets(tripletList.begin(), tripletList.end());\n\n\t\truntimeSparse.push_back(Runtime([&]() {\n\t\t\tEigen::SparseLU> 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 \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::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 \n#include \n#include \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 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 \n#include \n#include \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(center_);\n\tEigen::Vector3d v = Eigen::Map(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(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": "#pragma once\n\n#include \n#include \n#include \n//! Sparse Matrix type. Makes using this type easier.\ntypedef Eigen::SparseMatrix SparseMatrix;\n\n//! Used for filling the sparse matrix.\ntypedef Eigen::Triplet 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> 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 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 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 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 \n#include \n#include \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& 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 ret;\n predict(X,label,ret);\n iterscores.push_back(Acc(ret,label));\n }\n}\nvoid Adagrad::predict(MatrixXd& _x,VectorXd& _l,vector& 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": "// Released under the terms of the BSD License\n// (C) 2014-2017\n// Analog Devices, Inc\n// Kevin Mehall \n// Ian Daniher \n\n\n#include \n#include \n\n#include \"debug.hpp\"\n#include \n#include \n\nconst double PI = boost::math::constants::pi();\n\nusing namespace smu;\n\nvoid Signal::constant(std::vector& 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& 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& 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& 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& 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& 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": "#include \"Optimize.h\"\r\n\r\n#include \r\n#include \r\n\r\narma::vec Gradient_Approximate( const arma::vec & x,\r\n\t\t\t\t\t\t\t\tstd::function 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( 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 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( 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( 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 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 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 function_to_minimize,\r\n\t\t\t\t\t\t\t const std::vector< std::tuple > & 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 func, std::function 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 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 \n#include \n#include \n#include \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 \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 \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 \nstruct Fraction : boost::totally_ordered,\n boost::totally_ordered2, Z,\n boost::multipliable2, Z,\n boost::dividable2, 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 \n constexpr auto cmp(const Fraction& 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& 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& 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& 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\n */\ntemplate \nconstexpr auto operator+(const Z& c, const Fraction& frac) -> Fraction\n{\n return frac + c;\n}\n\n/*!\n * @brief\n *\n * @param[in] c\n * @param[in] frac\n * @return Fraction\n */\ntemplate \nconstexpr auto operator-(const Z& c, const Fraction& frac) -> Fraction\n{\n return c + (-frac);\n}\n\n// /*!\n// * @brief\n// *\n// * @param[in] c\n// * @param[in] frac\n// * @return Fraction\n// */\n// template \n// constexpr Fraction operator*(const Z& c, const Fraction& frac)\n// {\n// return frac * c;\n// }\n\n/*!\n * @brief\n *\n * @param[in] c\n * @param[in] frac\n * @return Fraction\n */\ntemplate \nconstexpr auto operator+(int&& c, const Fraction& frac) -> Fraction\n{\n return frac + c;\n}\n\n/*!\n * @brief\n *\n * @param[in] c\n * @param[in] frac\n * @return Fraction\n */\ntemplate \nconstexpr auto operator-(int&& c, const Fraction& frac) -> Fraction\n{\n return (-frac) + c;\n}\n\n/*!\n * @brief\n *\n * @param[in] c\n * @param[in] frac\n * @return Fraction\n */\ntemplate \nconstexpr auto operator*(int&& c, const Fraction& frac) -> Fraction\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 \nauto operator<<(Stream& os, const Fraction& 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;\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 \n#include \n#include \n#include \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 \n#include \n\n#include \n#include \n#include \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 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 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 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 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::integrate(func, a, b);\n\telse if(method == \"Gauss-Kronrod\")\n\t\treturn sign * gauss_kronrod::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 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 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 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& r, std::vector& 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&, const double)> func, std::vector& 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 ia(MXDIM), kg(MXDIM);\n\tstatic std::vector 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&, const double)> func, std::vector& 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 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&, const double)> func, std::vector& 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 \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 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 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 \n#include \n\n#include \n#include \n\n#include \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 \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 \n std::vector solve(const Function &f, double T, const State & y0, unsigned int N) const {\n\t\tdouble h = T/N;\n\t\tstd::vector 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 void step(const Function &f, double h, const State & y0, State & y1) const {\n\t\ty1 = y0;\n\t\tstd::vector k;\n k.reserve(n);\n\t\tfor (int i=0;i\n#include \n#include \n#include \n#include \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 \n std::vector 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 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 \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 \r\n#include \r\n#include \r\n\r\n\r\nusing namespace std;\r\nusing namespace dlib;\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\ntypedef matrix input_vector;\r\ntypedef matrix 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& 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& 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 > 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 \"Math/math_3dh.hpp\"\n#include \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 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 \n#include \n#include \n#include \n#include \n\n/*!\n * see http://cubic.org/docs/hermite.htm\n *\n */\nnamespace interpolate\n{\n\ttemplate void hermite(const Imath::Vec3& P1,\n\t\t\t\t\t\t\t\t\t const Imath::Vec3& T1,\n\t\t\t\t\t\t\t\t\t const Imath::Vec3& P2,\n\t\t\t\t\t\t\t\t\t const Imath::Vec3& 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& 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 \r\n\r\n#include \r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n\r\nstruct triangle : public boost::array, 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(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 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": "#include \n#include \n#include \n\n#include \n#include \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 &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 &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 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 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 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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n// Simpson integrator\ninline double integrate(std::function 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 &f, const std::function &df, const std::function &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 &f, const std::function &df, const std::function &u0, const std::function &uex, const std::string &baseName) {\n\tstd::vector resolutions = {100, 200, 400, 800, 1600};\n\tstd::vector L1_errors;\n\tstd::vector 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 &f, const std::function &df, const std::function &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 &f, const std::function &df, const std::function &u0, const std::function &uex, const std::string &baseName) {\n\tstd::vector resolutions = {100, 200, 400, 800, 1600};\n\tstd::vector L1_errors;\n\tstd::vector 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 \n#include \n#include \n#include \n#include \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 _.stl\n//!\n//! @param maxLevel the max mesh level to use. Will read up to and including\n//! baseMeshName_.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 f, const std::function exactSol, const std::function exactSol_grad) {\n\tstd::vector differences_L2;\n\tstd::vector differences_H1;\n\tstd::vector 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 \n#include \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": "#include \n#include \n#include \n#include \n#include \n\nnamespace LinearRegression\n{\n\t//h(X₁,X₂)=θ₁X₁+θ₂X₂\n\t//θ₁=10,θ₂=150,X₂=1\n\tstd::tuple 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₁ = std::rand() % 100 + 20, X₂ = 1;\n\t\t\ttrain_input(i, 0) = X₁;\n\t\t\ttrain_input(i, 1) = X₂;\n\t\t\tfloat θ₁ = 10, θ₂ = 150;\n\t\t\tfloat error = std::rand() % 11 - 5;\n\t\t\tfloat hx = θ₁ * X₁ + θ₂ * X₂ + 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 * ∑(h(x) - y(x) )²\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//θ = θ - α * 1/m * ∑(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 \n\n#include \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 \r\n#include \r\n#include \r\n#include \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 covA, matrix covB, matrix posA, matrix 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 CA, CB;\r\n\tstatic matrix 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 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 covFused;\r\n\tmatrix 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 CovIntersection::CA;\r\nmatrix CovIntersection::CB;\r\nmatrix CovIntersection::ca;\r\nmatrix 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 \r\n#include \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// ガウス分布\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(&x->v[xm*x->n], x->n) - Eigen::Map(cov->u->v, x->n);\r\n\tEigen::Map 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 \n#include \n#include \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 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 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 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 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 © 2020 Zhehao Li. All rights reserved.\n//\n// Exercise 5 Statistical Functions\n\n#include \n#include \n#include // For non-member functions of distributions\n\n#include \n#include \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 pdfList;\n vector 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 \n#include \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": "#include \"utils.hpp\"\n\n#include \n#include \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 \n#include \n#include \n#include \n\n// CGAL headers\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#if BOOST_VERSION >= 105600 && (! defined(BOOST_GCC) || BOOST_GCC >= 40500)\n#include \n#endif\n\n// Qt headers\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n// GraphicsView items and event filters (input classes)\n\n#include \n#include \n\n// for viewportsBbox\n#include \n \n#include \n\n// the two base classes\n#include \"ui_Bounding_volumes.h\"\n#include \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 Polygon_2;\n\ntypedef CGAL::Min_circle_2 > Min_circle;\ntypedef CGAL::Min_ellipse_2 > 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 points; \n CGAL::Qt::PointsGraphicsItem > * pgi;\n CGAL::Qt::PolygonGraphicsItem * convex_hull_gi;\n CGAL::Qt::PolygonGraphicsItem * min_rectangle_gi;\n CGAL::Qt::PolygonGraphicsItem * 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 * 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 >(&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(&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(&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(&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(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 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 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 center;\n double radius;\n\n CGAL::rectangular_p_center_2 (points.begin(), points.end(), std::back_inserter(center), radius, static_cast(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 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 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(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__\"\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 convert; \n Iso_rectangle_2 isor = convert(rect);\n CGAL::Random_points_in_iso_rectangle_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::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 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 \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 \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 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(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(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 \n#include \n#include \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 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 rosen_hessian (const column_vector& m)\n{\n const double x = m(0);\n const double y = m(1);\n\n matrix 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 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(4,1, -1e100), // lower bound constraint\n uniform_matrix(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": "/***************************************************************************\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 \r\n#include \r\n#include \r\n\r\nusing namespace Eigen;\r\n\r\nclass PrincipalComponentAnalysis\r\n{\r\npublic:\r\n PrincipalComponentAnalysis();\r\n \r\n template \r\n void compute(const MatrixBase &dataset, const bool zscores = false);\r\n template \r\n MatrixXd dimensionalityReductionComponents(const MatrixBase &dataset, const unsigned int components);\r\n template \r\n MatrixXd dimensionalityReductionVarianceExplained(const MatrixBase &dataset, const double varianceExplained, const unsigned int minComponents = 0, const unsigned int maxComponents = 0);\r\n template \r\n Matrix filteringComponents(const MatrixBase &dataset, const unsigned int components);\r\n template \r\n Matrix filteringVarianceExplained(const MatrixBase &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 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\r\nvoid PrincipalComponentAnalysis::compute(const MatrixBase &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() * m_coefficients;\r\n return;\r\n }\r\n \r\n // Subtract mean of each variable\r\n m_mu = dataset.template cast().colwise().mean();\r\n MatrixXd centered = dataset.template cast().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\r\nMatrixXd PrincipalComponentAnalysis::dimensionalityReductionComponents(const MatrixBase &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\r\nMatrixXd PrincipalComponentAnalysis::dimensionalityReductionVarianceExplained(const MatrixBase &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 \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 \r\nMatrix PrincipalComponentAnalysis::filteringComponents(const MatrixBase &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();\r\n}\r\n\r\ntemplate \r\nMatrix PrincipalComponentAnalysis::filteringVarianceExplained(const MatrixBase &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 \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();\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 \n#include \n#include \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(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(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(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(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 \n#include \n#include \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 param;\n LBFGSSolver 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 \n#include \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 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 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 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 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 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::epsilon())\n\t\t\t\tbreak;\n\t\t}\n\n\t\tstd::pair 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 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 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 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::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 . The license is also available online at\n .\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& 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& 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::infinity();\n\n\tif (m_relError != 0 && acc != 0)\n\t\tresult = acc * std::max(m_relError,\n\t\t\tstd::numeric_limits::epsilon())\n\t\t\t/ (r*std::numeric_limits::epsilon());\n\n\tif (m_absError != 0)\n\t\tresult = std::min(result, m_absError\n\t\t\t/ (r*std::numeric_limits::epsilon()));\n\n\treturn result;\n}\n\nFloat GaussLobattoIntegrator::adaptiveGaussLobattoStep(\n\t\t\t\t\t\t\t\t const boost::function& 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 , 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::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::min() / (50 * std::numeric_limits::epsilon())) {\n\t\t\t\t\tFloat min_err = 50 * std::numeric_limits::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(®ions, 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(®ions);\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(®ions, nR, R))\n\t\t\t\tgoto bad;\n\t\t} else { /* minimize number of function evaluations */\n\t\t\tR[0] = heap_pop(®ions); /* 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(®ions, 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(®ions.items[i]);\n\t}\n\n\t/* printf(\"regions.nalloc = %d\\n\", regions.nalloc); */\n\tfree(ee);\n\theap_free(®ions);\n\tfree(R);\n\treturn NDIntegrator::ESuccess;\n\nbad:\n\tfree(ee);\n\theap_free(®ions);\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::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 \n#include \n#include \n#include \n#include \n#include \n\n#include \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 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 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 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 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 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": "#include \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などで用いるもの(ラムダ式使用・DNNのインスタンスに含まれるパラメータを参照して使用する場合)\n MatrixXd numerical_gradient(const std::function &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(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(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 \n#include \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& estimee,\n const std::vector& 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).
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& estimee,\n const std::vector& 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& estimee,\n const std::vector& 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& 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 > 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 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 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 \n\n#include \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": "// 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 \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 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 \n#include \n\ntypedef unsigned long long nombre;\ntypedef std::vector vecteur;\ntypedef std::vector 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 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::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 \n#include \n#include \n#include \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": "#include \n#include \"config.h\"\n#include \"matrix.h\"\n#include \"util.h\"\n#include \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& 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 \n#include \nusing namespace std;\n\n#include \n#include \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));//沿z轴旋转45度\n cout .precision(3);\n cout<<\"rotation matrix =\\n\"<\n#include \n#include \n#include \n#include \n#include \n#include \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 \n#include \n#include \n#include \n#include \n#include \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 &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 &v) {\n if (v.empty()) {\n return std::numeric_limits::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& v)\n{\n if (v.size() <= 1u)\n return std::numeric_limits::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 &xs) {\n if (xs.size() > 100) {\n using namespace boost::accumulators;\n accumulator_set> acc;\n // accumulator_set>\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 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& v)\n{\n std::vector abs_diff = std::vector(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 earlier_date, tuple 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 \n#include \n#include \n#include \n#include \n#include \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(1LL),\n boost::counting_iterator(n+1LL), 1LL,\n std::multiplies() );\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(1LL),\n boost::counting_iterator(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 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 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 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 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 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 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": "#include \"tut/ch3.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"boost/date_time/gregorian/gregorian.hpp\"\n#include \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::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 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 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::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() <> 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(ammount * 100)};\n int numberOfDollars { static_cast(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 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(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(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(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(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(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(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 \n#include \n\n#include \n\n#include \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 \r\n#include \r\n#include \r\n#include \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 integrator;\r\n\t return integrator.integrate(f, 0.0, boost::math::constants::half_pi());\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 multiply_poly(std::vector &a, \r\n\t std::vector &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 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 prod_poly(std::vector &a)\r\n\t{\r\n\t std::vector result = {1.0};\r\n\r\n\t\tfor(auto & a_i : a)\r\n\t\t{\r\n\t std::vector 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 prod_poly_i(std::vector &a, size_t i)\r\n\t{\r\n\t std::vector 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 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 poly_roots(std::vector &p)\r\n\t{\r\n\t\tstd::vector result;\r\n\t\r\n\t\tEigen::PolynomialSolver 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::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 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 \n#include \nusing namespace std;\n\n#include \n// Eigen 几何模块\n#include \n\n/****************************\n* 本程序演示了 Eigen 几何模块的使用方法\n****************************/\n\nint main ( int argc, char** argv )\n{\n // Eigen/Geometry 模块提供了各种旋转和平移的表示\n // 3D 旋转矩阵直接使用 Matrix3d 或 Matrix3f\n Eigen::Matrix3d rotation_matrix = Eigen::Matrix3d::Identity();\n // 旋转向量使用 AngleAxis, 它底层不直接是Matrix,但运算可以当作矩阵(因为重载了运算符)\n Eigen::AngleAxisd rotation_vector ( M_PI/2, Eigen::Vector3d ( 0,0,1 ) ); //沿 Z 轴旋转 45 度\n cout .precision(3);\n cout<<\"rotation matrix =\\n\"<\r\n#include \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 \n\nnamespace tapl {\n\tnamespace pte {\n\t\t// constructor \n\t\ttemplate \n\t\tLine::Line() {}\n\n\t\t// de-constructor \n\t\ttemplate \n\t\tLine::~Line() {}\n\n\t\ttemplate \n\t\tstd::vector Line::fitSVD(std::vector &x, std::vector &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 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 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 \n\t\tstd::vector Line::fitLS(std::vector &x, std::vector &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 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 \n\t\tfloat Line::distToPoint(std::vector 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 \n\t\tstd::unordered_set Line::Ransac(typename pcl::PointCloud::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 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 n_inliers(maxIterations, 0);\n\t\t\t// coefficients for each line\n\t\t\tstd::vector> 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 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::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::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(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 \n\t\tPlane::Plane() {}\n\n\t\t// de-constructor \n\t\ttemplate \n\t\tPlane::~Plane() {}\n\n\t\ttemplate \n\t\tstd::vector Plane::fitSVD(std::vector &x, std::vector &y, std::vector &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 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 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 \n\t\tstd::vector Plane::fitLS(std::vector &x, std::vector &y, std::vector &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 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 \n\t\tfloat Plane::distToPoint(std::vector 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 \n\t\tstd::unordered_set Plane::Ransac(typename pcl::PointCloud::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 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 n_inliers(maxIterations, 0);\n\t\t\t// coefficients for each plane\n\t\t\tstd::vector> 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 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::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::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(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 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 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 point_a, std::vector 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 target, float distTolerance, int depth, std::vector& 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 KdTree::search(std::vector target, float distTolerance)\n\t\t{\n\t\t\tstd::vector 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& checked,\n\t\t\t\t\t\t\t\tfloat distTolerance, \n\t\t\t\t\t\t\t\tstd::vector& cluster) \n\t\t{\n\t\t\tstd::vector 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> EuclideanCluster::clustering(float distTolerance)\n\t\t{\n\t\t\tstd::vector> clusters;\n\n\t\t\t// vector to keep track of checked points\n\t\t\tstd::vector 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 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(0, 0) = cos(Rz);\n R_z.at(0, 1) = -sin(Rz);\n R_z.at(1, 0) = sin(Rz);\n R_z.at(1, 1) = cos(Rz);\n // Ry\n cv::Mat R_y = cv::Mat::eye(3, 3, CV_32F);\n R_y.at(0, 0) = cos(Ry);\n R_y.at(0, 2) = sin(Ry);\n R_y.at(2, 0) = -sin(Ry);\n R_y.at(2, 2) = cos(Ry);\n // Rx\n cv::Mat R_x = cv::Mat::eye(3, 3, CV_32F);\n R_y.at(1, 1) = cos(Rx);\n R_y.at(1, 2) = -sin(Rx);\n R_y.at(2, 1) = sin(Rx);\n R_y.at(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 \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(0, 0) = point.x;\n xyz.at(1, 0) = point.y;\n xyz.at(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(0, 0);\n point.y = xyz_w.at(1, 0);\n point.z = xyz_w.at(2, 0);\n }\n\t}\n}\n\n// explicit instantiation to avoid linker error\ntemplate class tapl::pte::Line;\ntemplate class tapl::pte::Line;\ntemplate class tapl::pte::Line;\ntemplate class tapl::pte::Line;\ntemplate class tapl::pte::Plane;\ntemplate class tapl::pte::Plane;\ntemplate class tapl::pte::Plane;\ntemplate class tapl::pte::Plane;", "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モーションの補間を行う\n#include \"interpolate.h\"\n\n#include \n#include \n#include \n#include \"VMD.h\"\n\nusing namespace Eigen;\n\n// x座標値がx_argとなる点をベジェ曲線上から探し、その点のy座標値を返す\n// ベジェ曲線の制御点は(0,0), p1, p2, (1,1)とする\n// 0 < x_arg < 1 とする\nfloat bezier_y(Vector2f p1, Vector2f p2, float x_arg)\n{\n // 二分法でtを探す\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 となる t が見つかった\n break;\n }\n if (x < x_arg) {\n // x(t)は単調増加するので、\n // 真のxがもっと大きいということは、真のtはもっと大きいので、\n // 探索範囲を上半分に絞る\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 // ベジェ曲線補間\n const uint8_t* ip = tail_frame.interpolation;\n float y;\n\n // X座標値の補間\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座標値の補間\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座標値の補間\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 // 回転の補間\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 // 線形補間\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とtail_frameを元に、補間でframe_num番目のボーンフレームを作る\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とtail_frameを元に、補間でframe_num番目の表情フレームを作る\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 fill_bone_frame(const vector& fv, bool bezier)\n{\n vector 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 // もしフレーム番号が重複していたら、重複したフレームは消す\n if (f.number == f_old.number) {\n continue;\n }\n // フレーム番号が連続していない場合、途中のフレームを補間する\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 fill_morph_frame(vector& mv)\n{\n vector 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 // もしフレーム番号が重複していたら、重複したフレームは消す\n if (m.frame == m_old.frame) {\n continue;\n }\n // フレーム番号が連続していない場合、途中のフレームを補間する\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 で非線形最小二乗法フィッティングに使う構造体\ntemplate\nstruct Functor\n{\n typedef _Scalar Scalar;\n enum {\n InputsAtCompileTime = NX,\n ValuesAtCompileTime = NY\n };\n typedef Matrix InputType;\n typedef Matrix ValueType;\n typedef Matrix 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\n{\n position_functor(int nparam, int nvalue, const vector& x, const vector& y)\n : Functor(nparam, nvalue), x(x), y(y) {}\n\n const vector& x;\n const vector& y;\n\n // 各データ点(x[i], y[i])における誤差をf[i]に格納する\n // パラメータpはベジェ曲線の制御点の座標値\n // ベジェ曲線の制御点 = (0, 0), (p[0], p[1]), (p[2], p[3]), (1, 1) となる\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\n{\n rotation_functor(int nparam, int nvalue, const vector& x, const vector& y)\n : Functor(nparam, nvalue), x(x), y(y) {}\n\n const vector& x;\n const vector& y;\n\n // 各データ点における誤差をf[i]に格納する\n // パラメータpはベジェ曲線の制御点の座標値\n // ベジェ曲線の制御点 = (0, 0), (p[0], p[1]), (p[2], p[3]), (1, 1) となる\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番めからtail番目までの誤差が最小になるような補間曲線パラメータを探す\nVectorXf find_bezier_parameter_pos(const vector& v, int head, int tail, int axis)\n{\n vector x;\n vector 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 // パラメータの初期値を与える\n // ベジェ曲線の制御点 = (0, 0), (p[0], p[1]), (p[2], p[3]), (1, 1) となる\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 nd(functor);\n LevenbergMarquardt, float> lm(nd);\n lm.parameters.maxfev = 10;\n lm.minimize(p);\n return p;\n}\n\n// head番めからtail番目までの誤差が最小になるような補間曲線パラメータを探す\nVectorXf find_bezier_parameter_rot(const vector& v, int head, int tail)\n{\n vector x;\n vector 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 // パラメータの初期値を与える\n // ベジェ曲線の制御点 = (0, 0), (p[0], p[1]), (p[2], p[3]), (1, 1) となる\n VectorXf p(4);\n p << 20.0/127, 20.0/127, 107.0/127, 107.0/127;\n // パラメータpの最適化を行う\n rotation_functor functor(4, (tail - head + 1), x, y);\n NumericalDiff nd(functor);\n LevenbergMarquardt, 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番めからtail番目までの誤差が最小になるようtail_frameの補間曲線パラメータを調整する\nvoid optimize_bezier_parameter(VMD_Frame& tail_frame, const vector& v,\n int head, int tail)\n{\n uint8_t ip[4];\n VectorXf p;\n\n // Xの補間パラメータの最適化\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の補間パラメータの最適化\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の補間パラメータの最適化\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 // 回転の補間パラメータの最適化\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": "#include \n#include \n#include \n#include \n\nnamespace py = pybind11;\n\n// double + Eigen\n\nstd::tuple eigsy(const Eigen::Ref & input_sym) {\n auto solver = Eigen::SelfAdjointEigenSolver(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": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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>);\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 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 (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 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 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> 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ía la clave pública e\n // - Envía el producto N\n // Directorio público\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": "#ifndef RNDCMP_INCLUDE_ESN_HPP_\n#define RNDCMP_INCLUDE_ESN_HPP_\n\n#include \n#include \n#include \n#include \n#include \n\n\nnamespace rndcmp {\n template\n class ESN {\n public:\n using ESNMatrix = Eigen::Matrix;\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 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 states_d = states.template cast();\n Eigen::Matrix 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 pinv_d = states_square_d.completeOrthogonalDecomposition().pseudoInverse();\n Eigen::Matrix W_out_d = (pinv_d * states_d.transpose() * outputs.template cast()).transpose();\n // ESNMatrix pinv = pinv_d.template cast();\n // W_out = (pinv * states.transpose() * outputs).transpose();\n W_out = W_out_d.template cast();\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 error_m = (y - y_pred).template cast();\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 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 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> solver(W.template cast());\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 W_in;\n Eigen::Matrix W;\n Eigen::Matrix 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 \n */\n\n#ifndef MAP_STATS_HPP \n#define MAP_STATS_HPP\n\n#include \n#include \n#include \n#include \n\n#ifdef USE_BOOST\n #include \n using namespace::boost::math;\n#else\n #include \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( 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 \n#include \n#include \n#include \n#include \n#include \n\n// Print Funktion zur Vereinfachung a lá python\ntemplate \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ötigen 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ählen\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ßend 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ößer 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ück\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ür 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 * useG2O.cpp\n * Copyright (C) 2018 exbot \n *\n * Distributed under terms of the MIT license.\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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(_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 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();\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::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 time_used = chrono::duration_cast>(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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nstd::unique_ptr> p(Data::readFromFile(\"data.ascii\"));\nstd::vector 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::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::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 hDensity;\n std::vector nDensity;\n std::vector rInput;\n std::vector 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::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 softenings;\n std::vector dAnalytic;\n std::vector 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::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 solver(new Gravitysolver::Direct());\n std::vector 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 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 \n#include \n#include \n#include \n#include \n#include \n#include \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 ComponentsImageType;\n typedef itk::Image MaskType;\n try\n {\n // Get PWI\n typename ComponentsImageType::Pointer PWI = ITKUtils::ReadNIfTIImage(std::string(argv[1]));\n // Get mask\n typename MaskType::Pointer mask = ITKUtils::ReadNIfTIImage(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(PWI, mask, true, false, 0.05);\n // Convert to Eigen Matrix\n MatrixXf dataset(EigenITK::toEigen(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(PWIPCARawdata, nonZerosMask, PWI);\n // Save new filtered image\n ITKUtils::WriteNIfTIImage(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 \n#include // for malloc\n#include // for max/min\n#include \n#include \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 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 \n#include \n\n#include \n#include \n#include \n\n// Formula to get the course (direction) between two points.\n// This might be a GGL-function in the future.\ntemplate \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 \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();\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 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(48, 52, 0));\n paris.lon(dms(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(12, 2, 36)),\n longitude<>(dms(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(\"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())\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(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 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 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 \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": "#pragma once\n\n#include \n\n#include \n#include \n#include \n\nnamespace pcv\n{\n\ntemplate\ndouble getEuclideanDistance(\n const Eigen::Matrix &point0,\n const Eigen::Matrix &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\nstd::optional getSegmentIntersectionPoint2(\n const Eigen::Matrix &segmentOnePoint0,\n const Eigen::Matrix &segmentOnePoint1,\n const Eigen::Matrix &segmentTwoPoint0,\n const Eigen::Matrix &segmentTwoPoint1,\n double error = 1e-10)\n{\n static_assert(std::is_arithmetic::value,\n \"Must have a numerical point type.\");\n\n Eigen::Matrix 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 \n#include \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\n#include \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": "#include \n#include \n#include \n#include \n\ntemplate\ndouble Clenshaw1D(const vectype &c, double ind){\n int N = static_cast(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\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\nauto Clenshaw1DByRow(const MatType& c, double ind) {\n int N = static_cast(c.rows()) - 1;\n static Eigen::Array 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\ndouble Clenshaw2DEigen(const MatType& a, double x, double y) {\n auto b = Clenshaw1DByRow(a, y);\n return Clenshaw1D(b.matrix(), x);\n}\n\ntemplate\nvoid test_Eigen(int M){\n using MatType = Eigen::Array;\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(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> a;\n const int M = 8;\n for (auto i = 0; i <= M; ++i){\n a.push_back(std::vector(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 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(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(M);\n\n std::cout << \"Static:\" << std::endl;\n test_Eigen(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": "// 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 \n#include \n#include \n#include \n#include \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 \n\tinline void DoNotOptimize(const T &value) {\n\t\t__asm { lea ebx, value }\n\t}\n#else\n\ttemplate \n\t__attribute__((always_inline)) inline void DoNotOptimize(const T &value) {\n\t\tasm volatile(\"\" : \"+m\"(const_cast(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(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 \n#include \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 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 \n\n#include \n#include \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 \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 \n#include \n\nnamespace Probulator\n{\n\tSgBasis sgFitLeastSquares(const SgBasis& basis, const std::vector& 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& 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 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": "// STL includes\n#include \n#include \n\n// BGL includes\n#include \n#include \n#include \n\ntypedef boost::adjacency_list > weighted_graph;\ntypedef boost::property_map::type weight_map;\ntypedef boost::graph_traits::edge_descriptor edge_desc;\ntypedef boost::graph_traits::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 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 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::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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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 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::iterator itr = throw_cnt.find(s);\n (*itr).second++;\n }\n\n double n = static_cast(trials);\n std::cout << \"Dice Throw : Trials = \" << std::setprecision(1) << std::scientific << n << std::endl;\n for( std::map::iterator itr = throw_cnt.begin() ; itr != throw_cnt.end() ; ++itr )\n {\n double p = static_cast((*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 n_dist(mean,variance);\n boost::variate_generator< boost::mt19937 , boost::normal_distribution > normal_rv( random_num_gen , n_dist );\n\n std::vector 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::iterator itr_2slb = std::lower_bound( dist.begin() , dist.end() , -2.0*s );\n std::vector::iterator itr_2sub = std::lower_bound( dist.begin() , dist.end() , 2.0*s );\n\n std::vector::iterator itr_1slb = std::lower_bound( dist.begin() , dist.end() , -1.0*s );\n std::vector::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( trials );\n std::cout << \"Normal RV : \";\n std::cout << std::setw(8) << std::setprecision(1) << std::scientific << static_cast(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 \n#include \n#include \n#include \n\n// Borrow dense matrix eigenvalue routines.\n#include \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 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 \n#include \n#include \n\nusing namespace std;\n\nint main(int argc, char** argv)\n{\n // 机器人B在坐标系O中的坐标:\n Eigen::Vector3d B(3, 4, M_PI);\n\n // 坐标系B到坐标O的转换矩阵:\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 // 坐标系O到坐标B的转换矩阵:\n Eigen::Matrix3d TBO = TOB.inverse();\n\n // 机器人A在坐标系O中的坐标:\n Eigen::Vector3d A(1, 3, -M_PI / 2);\n\n // 求机器人A在机器人B中的坐标:\n Eigen::Vector3d BA;\n // TODO 参照第一课PPT\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 \n#include \n#include \n#include \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(mStr),boost::lexical_cast(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 \r\n#include \r\n#include \r\n#include \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": "#pragma once\n#include \"coordinate_transform.hpp\"\n#include \"integrate.hpp\"\n#include \"shape.hpp\"\n#include \n#include \n#include \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 &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\n\n#include \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 <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 \n#include \n#include \n#include \n#include \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& 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 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 \n#include \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 m1 = Matrix::Zero();\n Matrix m2 = Matrix::Ones();\n Matrix m3 = Matrix::Constant(3);\n Matrix m4 = Matrix::Random();\n Matrix m5 = Matrix::LinSpaced(size, low, high);\n Matrix m6 = Matrix::Identity();\n\n std::cout << std::endl << \"Matrix::Zero()\" << std::endl << m1 << std::endl;\n std::cout << std::endl << \"Matrix::Ones();\" << std::endl << m2 << std::endl;\n std::cout << std::endl << \"Matrix::Constant(3)\" << std::endl << m3 << std::endl;\n std::cout << std::endl << \"Matrix::Random()\" << std::endl << m4 << std::endl;\n std::cout << std::endl << \"Matrix::LinSpaced(size, low, high)\" << std::endl << m5 << std::endl;\n std::cout << std::endl << \"Matrix::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// Created by GXSN-Pro on 2018/10/17.\n//\n\n#include \"sphere_util.hpp\"\n#include \"math_util.hpp\"\n#include \n#include \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 * 计算两点间的球面距离(单位 m)\n * @param from\n * @param to\n * */\ndouble SphereUtil::distance(const LatLng &from,const LatLng &to) {\n //先计算两点之间的大圆夹角\n double rad = computeAngleBetween(from,to);\n return rad * earth_radius;\n}\n\n/**\n * 计算区域面积\n * google maps\n * */\ndouble SphereUtil::area(std::vector *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 *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 \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 hp = Hyperplane::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": "/*\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 \r\n#include \r\n#include \r\nusing namespace std;\r\nusing namespace boost;\r\n\r\nconst float PI = 3.1415926536f;\r\nconst complex I = complex(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\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\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 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 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;\r\n unsigned a0 = (r0 << (t-c)) + r1;\r\n unsigned a1 = a0 + (1 << (t-c-1));\r\n complex y0 = output[a0 + 1];\r\n complex y1 = binpow >(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\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 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 *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 tfactor0 = *twiddlePtr;\r\n\r\n complex tfactor = 1.0f;\r\n for (unsigned k = 0; k <= N/2 - 1; k++)\r\n {\r\n complex t = output[k*outputStride];\r\n complex 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 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 output[])\r\n{\r\n complex *twiddleFactors = new complex[(quickLog2(N) + 1)];\r\n CalcTwiddleFactors(N, twiddleFactors, false);\r\n\r\n fft1d(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 input[],\r\n unsigned N,\r\n std::complex output[])\r\n{\r\n complex *twiddleFactors = new complex[(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 output[] ///< Output array containing N*N elements\r\n )\r\n{\r\n int k;\r\n\r\n complex *twiddleFactors = new complex[(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 *fftrows = new std::complex[N*N*sizeof(std::complex)];\r\n #pragma omp parallel for\r\n for (k = 0; k < N; k++)\r\n fft1d(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 >(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 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 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 *twiddleFactors = new complex[(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 *fftrows = new std::complex[N*N];\r\n #pragma omp parallel for\r\n for (k = 0; k < N; k++)\r\n fft1d >(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 >(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 F1[], ///< First discrete Fourier transform (N*N elements)\r\n std::complex F2[], ///< Second discrete Fourier transform (N*N elements)\r\n std::complex 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 \r\n\r\n#include \r\n#include \r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\nBOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS(cs::cartesian)\r\n\r\n\r\ntemplate \r\nstruct triangle : public boost::array\r\n{\r\n};\r\n\r\n\r\n// Register triangle

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\r\nstruct area, ring_tag>\r\n{\r\n template \r\n static inline double apply(triangle 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 > t;\r\n triangle > 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 c;\r\n boost::tuple 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’s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n\n#include \"../../data/FluidIndex.hpp\"\n#include \n#include \n\nnamespace fluid {\nnamespace algorithm {\n\nclass Stats\n{\npublic:\n using ArrayXd = Eigen::ArrayXd;\n ArrayXd process(Eigen::Ref 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": "#include \n#include \n#include \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 \n#include \n#include \n\n#include \"Common.hpp\"\n#include \"BUSData.h\"\n\n#include \"bustools_predict.h\"\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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 {\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 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 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 solver;\n\t//change the stop criteria to speed things up\n\tcppoptlib::LbfgsbSolver::TCriteria crit = cppoptlib::LbfgsbSolver::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& hists, const std::vector& histLengths, double t, std::vector& predVals, std::vector& sizeVals, std::vector& 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 (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 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& m_hists;\n\tconst std::vector& m_histLengths;\n\tdouble m_t;\n\tstd::vector& m_predVals;\n\tstd::vector& m_sizeVals;\n\tstd::vector& m_muVals;\n\tconst uint32_t m_histmax;\n\tstd::vector> 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 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 histograms = std::vector(n_genes * histmax, 0);\n\tstd::vector histogramLengths = std::vector(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 predVals(n_genes, 0);\n\tstd::vector sizeVals(n_genes, 0);\n\tstd::vector 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 umisPerGene(n_genes, 0);\n\tstd::vector 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 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 \r\n#include \r\n#include \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 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 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::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::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 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 numericalCleanUpSparse(const Eigen::MatrixXd &M, const double epsilon){\r\n\r\n Eigen::SparseMatrix 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 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 > listOfVectors;\r\n for(unsigned int j=0;j oneVector;\r\n for(unsigned int i=0; i > sequence = generateCombinations(dimension, grade);\r\n\r\n // init the resulting transformation matrix\r\n Eigen::SparseMatrix 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 xorIndex2Combination = getSetOfCombinationsFromXorIndexation(dimension, sequence);\r\n\r\n // generate the transformation matrix\r\n for(unsigned int l=0; l currentVector = listOfVectors[0];\r\n std::vector currentCoeffs; // first line of the transformation matrix\r\n\r\n // fill the currentCoeffs using the transformation\r\n for(int idxTMat=0; idxTMat nextVector;\r\n std::vector result;\r\n\r\n for(unsigned int j=0;j resultIdxTmp; // result = mv1 ^ mvss2\r\n std::vector 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; iepsilon)\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 transformationMatricesToVectorOfComponents(\r\n const Eigen::SparseMatrix &transformationMatrix, const int grade, const bool isInverse) {\r\n std::vector outputVector;\r\n for (int k = 0; k < transformationMatrix.outerSize(); ++k)\r\n for (Eigen::SparseMatrix::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 computeInverseTransformationMatrix(const Eigen::SparseMatrix& transformationMatrix, const double epsilon){\r\n Eigen::SparseMatrix inverseTransformationMatrix(transformationMatrix.rows(),transformationMatrix.rows());\r\n Eigen::SparseLU> 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 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> computeTransformationMatricesToVector(const Eigen::MatrixXd &P, const double epsilon, std::vector& transformationMatricesSizes,\r\n std::vector >& allTransformationMatrices,\r\n std::vector >& allInverseTransformationMatrices){\r\n std::pair,std::vector> transformationMatrices; // contains non-inverse and inverse transformation matrices\r\n\r\n // push the scalar transformation matrix\r\n Eigen::SparseMatrix 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 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 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 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 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 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 \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \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 \n#include \n#include \n#include \n#include \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\nupwindFD(const Eigen::VectorXd &u0,\n double dt,\n double T,\n const std::function &a,\n const std::pair &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\ncenteredFD(const Eigen::VectorXd &u0,\n double dt,\n double T,\n const std::function &a,\n const std::pair &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{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 \n#include \n\n#include \n#include \n\n#include \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 \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 \n std::vector 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 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 \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 \n#include \n#include \n#include \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 \nEigen::Matrix crossMx(Scalar_ x, Scalar_ y, Scalar_ z) {\n Eigen::Matrix 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 crossMx(double x, double y, double z);\ntemplate Eigen::Matrix crossMx(float x, float y, float z);\n\ntemplate Eigen::Matrix crossMx(Eigen::MatrixBase > const&);\ntemplate Eigen::Matrix crossMx(Eigen::MatrixBase > const&);\n\ntemplate Eigen::Matrix crossMx(Eigen::MatrixBase > const&);\ntemplate Eigen::Matrix crossMx(Eigen::MatrixBase > 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 \n\ntypedef long long nombre;\ntypedef std::vector 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 × 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 × 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 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 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 \n#include \n#include \n#include \n#include \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 operator()( const vec& U, const vec& Y )\n\t{\n\t\tassert( U.size() == Y.size() );\n\t\tint T = U.size();\n\t\tvec 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 operator()( const vec& Y )\n\t{\n\t\tint T = Y.size();\n\t\tvec 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 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 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(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 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 operator()( const vec& Z )\n\t{\n\t\tint T = Z.size();\n\t\tvec 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, 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( 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 {\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 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 operator()( const vec& Z )\n\t{\n\t\tint T = Z.size();\n\t\tvec 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 \n#include \n\n#include \n#include \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 \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 pos_hat(pos_hat_ptr);\n\t\t// Eigen::Matrix residuals(residuals_ptr);\n\t\t// residuals.template block<3, 1>(0, 0) = pos_hat - pos_measured_.template cast();\n\t\tEigen::Matrix pos_delta = pos_hat - pos_measured_.template cast();\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(\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 \n bool operator()(const T* const pos_hat_ptr,\n const T* const q_hat_ptr,\n T* residuals_ptr) const { \n // Eigen::Matrix pos_hat(pos_hat_ptr);\n\t\t// Eigen::Matrix pos_delta = pos_hat - pos_measured_.template cast();\n\n // Eigen::Quaternion q_hat(q_hat_ptr);\n // Eigen::Quaternion q_delta = q_hat.conjugate() * q_measured_.template cast();\n\t\t// residuals_ptr[0] = pos_delta.norm() + T(2.0) * q_delta.vec().norm();\n\n\t\tEigen::Matrix residuals;\n Eigen::Matrix pos_hat(pos_hat_ptr);\n\t\tresiduals.template block<3, 1>(0, 0) = pos_hat - pos_measured_.template cast();\n\n Eigen::Quaternion q_hat(q_hat_ptr);\n Eigen::Quaternion q_delta = q_hat.conjugate() * q_measured_.template cast();\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(\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> readSensorData(std::string path) {\n std::vector> ret;\n\n std::ifstream csvFile;\n csvFile.open(path);\n\n std::string line;\n while(std::getline(csvFile, line)) {\n std::vector 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> 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> 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 \n#include \n#include \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(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& w,\n\tstd::vector& 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 // root finding.\r\n\r\n#include // for normal_distribution\r\n using boost::math::normal; // typedef provides default type is double.\r\n\r\n#include \r\n using std::cout; using std::endl; using std::left; using std::showpoint; using std::noshowpoint;\r\n#include \r\n using std::setw; using std::setprecision;\r\n#include \r\n using std::numeric_limits;\r\n#include \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 \n#include \n\n#include \n#include \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::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(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": "#ifndef MOCHIMOCHI_SCW_HPP_\n#define MOCHIMOCHI_SCW_HPP_\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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::max() > 0, \"Dimension Error. (Dimension > 0)\");\n static_assert(std::numeric_limits::max() > 0, \"Hyper Parameter Error. (c > 0)\");\n static_assert(std::numeric_limits::max() > 0, \"Hyper Parameter Error. (η > 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 \n void save(Archive& ar, const unsigned int version) const {\n std::vector covariances_vector(_covariances.data(), _covariances.data() + _covariances.size());\n std::vector 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(kDim));\n ar & boost::serialization::make_nvp(\"phi\", const_cast(kPhi));\n ar & boost::serialization::make_nvp(\"c\", const_cast(kC));\n }\n\n template \n void load(Archive& ar, const unsigned int version) {\n std::vector covariances_vector;\n std::vector 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(kDim));\n ar & boost::serialization::make_nvp(\"phi\", const_cast(kPhi));\n ar & boost::serialization::make_nvp(\"c\", const_cast(kC));\n _covariances = Eigen::Map(&covariances_vector[0], covariances_vector.size());\n _means = Eigen::Map(&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 \n#include \n#include \n\n#include \n\n#include \"FEM/FEM1DApp.hpp\"\n#include \"imgui/implot.h\"\n#include \"Visualization/Visualizer.h\"\n\n#include \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 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 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& ref, std::vector& eval, Float& L_1, Float& L_2, Float& L_inf)\n\t{\n\t\tassert(ref.size() == eval.size());\n\n\t\tstd::vector 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(0), [](Float r, Float a) {return r + a * a; }) / Float(ref.size()));\n\t\tL_1 = std::accumulate(minus.begin(), minus.end(), static_cast(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 xs = std::vector(Length);\n\tstd::vector precise_val = std::vector(Length);\n\tstd::vector quadratic_val = std::vector(Length);\n\tstd::vector linear_val = std::vector(Length);\n\tstd::vector quadratic_diff = std::vector(Length);\n\tstd::vector linear_diff = std::vector(Length);\n\n\tstd::vector pointcount;\n\tstd::vector linear_L1;\n\tstd::vector linear_L2;\n\tstd::vector linear_Linf;\n\n\tstd::vector quadratic_L1;\n\tstd::vector quadratic_L2;\n\tstd::vector 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 \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;\n\tusing CostFunction = real(*)(const MatrixType& output, const MatrixType& truth);\n\tusing CostDerivativeFunction = MatrixType(*)(const MatrixType& output, const MatrixType& truth);\n\n\ttemplate real cost(const MatrixType& output, const MatrixType& truth);\n\ttemplate MatrixType cost_derivative(const MatrixType& output, const MatrixType& truth);\n\n\t// mse\n\ttemplate<>\n\treal cost(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(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(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(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 \n#include \n#include \n#include \n#include \n#include \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 > mapOfProportionToRiskAndReturn;\n std::map 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 >::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 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 efficientFrontier;\n for (std::map >::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::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 // For is_integral, is_same\n#include // for numeric_limits\n#include // For cpp_rational (infinite\n // precision boost rational)\n // used at y_star\n#include // For boost::math::lcm used\n // at huangtang\n\nnamespace hbm {\n template \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::get() + \"\\n\"\n + \"type_P: \" + hbm::type_name

::get() + \"\\n\"\n + \"type_I: \" + hbm::type_name::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 \n W huangtang(instance_t &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 \n W y_star(const item_t &b, const item_t &b2) {\n assert(b < b2);\n if (std::is_integral::value && std::is_same::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(b.p), p2 = static_cast(b2.p);\n\n cpp_rational r_p1 = static_cast(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::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::max() ? static_cast(y) : numeric_limits::max();\n } else if (std::is_floating_point

::value) {\n W w1 = b.w, w2 = b2.w;\n P p1 = b.p, p2 = b2.p;\n\n P e1 = p1 / static_cast

(w1);\n P e2 = p2 / static_cast

(w2);\n\n if (e1 - e2 < numeric_limits

::epsilon())\n return numeric_limits::max();\n\n return static_cast(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 \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 \n W y_star(vector< item_t > &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 \n W y_star(instance_t &ukpi, bool already_sorted = false) {\n return y_star(ukpi.items, already_sorted);\n }\n\n// template \n// W run_with_y_star(void(*ukp_solver)(instance_t &, solution_t &, void*),\n// instance_t &ukpi, solution_t &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 > &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

(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 \n void y_star_wrapper(instance_t &ukpi, solution_t &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* ptr =\n new per_extra_info_t(ukpi.c, y_star_cap);\n\n extra_info_t* upcast_ptr = dynamic_cast(ptr);\n sol.extra_info = std::shared_ptr(upcast_ptr);\n\n return;\n }\n\n template\n struct y_star_wrap : wrapper_t {\n virtual void operator()(instance_t &ukpi, solution_t &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\n void y_star_wrapper(instance_t &ukpi, solution_t &sol, int argc, argv_t argv) {\n simple_wrapper(y_star_wrap(), 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 \n W y_star(const item_t &b, const item_t &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 - )/best_item.w\n /// copies of the best item.\n template \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 \n W huangtang(instance_t &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 &b, const item_t &b2)\n template \n W y_star(instance_t &ukpi, bool already_sorted = false) {\n return hbm_periodicity_impl::y_star(ukpi, already_sorted);\n }\n\n// template \n// W run_with_y_star(void(*ukp_solver)(instance_t &, solution_t &, bool),\n// instance_t &ukpi, solution_t &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 \n void y_star_wrapper(instance_t &ukpi, solution_t &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\n void y_star_wrapper(instance_t &ukpi, solution_t &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 \n#include \n#include \n#include \n\n#include \n#include \n#include \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 factors, ZZ pub_exp) {\n\tvector::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::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 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 \n#include \nusing namespace std;\n\nlong long int table_size = 1001;\nlong long int current_step = 1;\n\n\nint main() {\n\n\tEigen::Matrix 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 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": "//\n// Created by tr on 21-10-14.\n//\n#include \n#include \n#include \n#include \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: \"< points1={p1,p2,p3};\n\n vector points2;\n\n for(auto p:points1)\n {\n points2.push_back(R*p);\n cout<<\"p1:\"< 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\"<\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 \n using std::cout; using std::endl;\n using std::noshowpoint; using std::fixed; using std::right; using std::left;\n#include \n using std::setprecision; using std::setw; \n\n#include \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):\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änkt), 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 \n\n#include \n \nusing namespace std; \n\ntemplate \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 \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::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 A(a_value);\n mtl::dense_vector v(4, 1.0);\n\n power_iteration(A, v, 0.00001);\n check_eigenvector(A, v, 0.001);\n\n mtl::compressed2D B(9, 9);\n {\n\tmtl::mat::inserter > 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 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 \n #include \n #include \n\n #include \n #include \n\n template \n T fun(Eigen::Matrix 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 \n\tT dist(Eigen::Matrix const &x, Eigen::Matrix 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 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 vec;\n\ttypedef Eigen::AutoDiffScalar AD;\n\ttypedef Eigen::Matrix 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();\n\tay = vec2.cast();\n\n\tax.setZero(s1);\n\tay.setZero(s2);\n\n\tfor(int i=0; i derivative_t;\n typedef Eigen::AutoDiffScalar scalar_t;\n typedef Eigen::Matrix 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 inner_derivative_t;\n typedef Eigen::AutoDiffScalar inner_scalar_t;\n typedef Eigen::Matrix derivative_t;\n typedef Eigen::AutoDiffScalar scalar_t;\n typedef Eigen::Matrix 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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n//~ #include \n//~ #include \n//~ #include \n//~ #include \n#include \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 Vec;\ntemplate class Mat;\ntypedef double SGPreal; // long double is not supported by GSL\ntypedef Vec SGPrealVec;\ntypedef Mat SGPrealMat;\ntypedef Vec intVec;\ntypedef Mat intMat;\n\n// class numerical vector\ntemplate 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 void Vec:: print(){\t\n\tfor(int i = 0; i void Vec:: printH(){\t\n\tfor(int i = 0; i void Vec :: readNumberBlock(ifstream &file){\t\n\t//~ file << fixed << setprecision(PRECISAO);\n\tfor(int i = 0; i> v[i] ;\t\n}\n\ntemplate void Vec :: writeNumberBlock(ofstream &file){\t\n\tfile << scientific << setprecision(PRECISAO);\n\tfor(int i = 0; i void Vec :: 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 T Vec :: max(){\t\n\tT vmax = -9999.0;\n\t\n\tfor(int i = 0; ivmax) vmax = v[i];\n\t}\t\n\t\n\treturn vmax;\n}\n\ntemplate T Vec :: sum(){\t\n\tT vsum = 0.0;\n\t\n\tfor(int i = 0; i T Vec :: amax(){\t\n\tT vmax = 0.0;\n\tT aux;\n\t\n\tfor(int i = 0; ivmax) 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 Mat : public Vec{\n\tpublic:\n\tint m1,m2; // m1 is Nrows, m2 is Ncolumns \n\tMat() {}\n\tMat(int mm1, int mm2):Vec(mm1*mm2) { m1 = mm1; m2 = mm2; }\n\tMat(Vec &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; in ; i++) this->v[i]=a;}\n\tvoid operator=(Mat &w) { for(int i=0; in ; 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 void Mat :: prettyPrint(){\n\t//~ cout << m1 << \" \" << m2 << endl;\n\tfor (int i=0;i void Mat :: prettyPrintClean(){\n\t//~ cout << m1 << \" \" << m2 << endl;\n\tfor (int i=0;i T dot_product(Vec &u,Vec &w){\n\tT dot = 0.0;\n\t\n\tfor(int i=0; i void Mat :: 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;i0.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; i0.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 \n#include \n#include \n#include \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 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 \n#include \n#include \n#include \n#include \n#include \n#include \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 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 \n#include \n#include \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主成分分析 2x2 mat\n\t*/\n\tinline std::tuple PCA(const Eigen::Matrix2d covarianceMatrix) {\n\t\tEigen::EigenSolver 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主成分分析 3x3 mat\n\t*/\n\tinline std::tuple PCA(const Eigen::Matrix3d covarianceMatrix) {\n\t\tEigen::EigenSolver 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 * ,\n * Copyright (c) 2020 Christian Eskil Vaugelade Berg\n * @author Christian Eskil Vaugelade Berg\n*/\n#pragma once\n\n#include \n\n#include \n\nnamespace orient {\n\ntemplate\nEigen::Matrix rotationMatrixFromEuler(Scalar angle)\n{\n const auto s = std::sin(angle);\n const auto c = std::cos(angle);\n\n constexpr auto i1 = asIndex;\n constexpr auto i2 = (i1 + 1) % 3;\n constexpr auto i3 = (i2 + 1) % 3;\n Eigen::Matrix R = Eigen::Matrix::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\nstd::pair, Eigen::Matrix> rotationMatrixFromEulerWD(Scalar angle)\n{\n const auto s = std::sin(angle);\n const auto c = std::cos(angle);\n\n constexpr auto i1 = asIndex;\n constexpr auto i2 = (i1 + 1) % 3;\n constexpr auto i3 = (i2 + 1) % 3;\n Eigen::Matrix J = Eigen::Matrix::Zero();\n Eigen::Matrix R = Eigen::Matrix::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\nEigen::Matrix rotationMatrixFromEuler(Eigen::Matrix const& angles)\n{\n return \n rotationMatrixFromEuler(angles[0]) *\n rotationMatrixFromEuler(angles[1]) *\n rotationMatrixFromEuler(angles[2]);\n}\n\ntemplate\nstd::pair, Eigen::Matrix> rotationMatrixFromEulerWD(Eigen::Matrix const& angles)\n{\n const auto [R1, J1] = rotationMatrixFromEulerWD(angles[0]);\n const auto [R2, J2] = rotationMatrixFromEulerWD(angles[1]);\n const auto [R3, J3] = rotationMatrixFromEulerWD(angles[2]);\n\n Eigen::Matrix J;\n Eigen::Map>(J.template block<9,1>(0,0).data(), 3, 3) = J1 * R2 * R3;\n Eigen::Map>(J.template block<9,1>(0,1).data(), 3, 3) = R1 * J2 * R3;\n Eigen::Map>(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 \n#include \n\nint main(int argc, char **argv) {\n\n // Simple initialization.\n Eigen::Matrix 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": "#ifndef VECTOR_MATH_HPP\n# define VECTOR_MATH_HPP\n\n#include \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": "///////////////////////////////////////////////////////////////////\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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\ntemplate\nvoid print(const std::vector& 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 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 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 > cplx_V(V.begin(),V.end()),cplx_C;\n boost::math::fft::bsl_dft< std::complex > 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": "#include \"problemes.h\"\n#include \"arithmetique.h\"\n#include \"timer.h\"\n\n#include \n\ntypedef unsigned long long nombre;\ntypedef std::vector 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 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) = 1, z(14) = 2, z(100) = 3 etc.\n // Also, for 0(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": "#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \"perceptron.h\"\r\n#include \"utils.h\"\r\n#include \r\n#include \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<= 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": "#ifndef MATH_TYPES_HPP_INCLUDED\n#define MATH_TYPES_HPP_INCLUDED\n\n#include \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 \n#include \n#include \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 \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 inline T jacobi_theta1(T z, T q);\n// template inline T jacobi_theta2(T z, T q);\n// template inline T jacobi_theta3(T z, T q);\n// template 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 inline T jacobi_theta1tau(T z, T tau);\n// template inline T jacobi_theta2tau(T z, T tau);\n// template inline T jacobi_theta3tau(T z, T tau);\n// template 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() * 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()); // 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()); // 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 inline T jacobi_theta3m1(T z, T q);\n// template inline T jacobi_theta4m1(T z, T q);\n// template inline T jacobi_theta3m1tau(T z, T tau);\n// template 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 \n#include \n#include \n#include \n#include \n\nnamespace boost{ namespace math{\n\n// Simple functions - parameterized by q\ntemplate \ninline typename tools::promote_args::type jacobi_theta1(T z, U q);\ntemplate \ninline typename tools::promote_args::type jacobi_theta2(T z, U q);\ntemplate \ninline typename tools::promote_args::type jacobi_theta3(T z, U q);\ntemplate \ninline typename tools::promote_args::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 \ninline typename tools::promote_args::type jacobi_theta1tau(T z, U tau);\ntemplate \ninline typename tools::promote_args::type jacobi_theta2tau(T z, U tau);\ntemplate \ninline typename tools::promote_args::type jacobi_theta3tau(T z, U tau);\ntemplate \ninline typename tools::promote_args::type jacobi_theta4tau(T z, U tau);\n\n// Minus one versions for small q / large tau\ntemplate \ninline typename tools::promote_args::type jacobi_theta3m1(T z, U q);\ntemplate \ninline typename tools::promote_args::type jacobi_theta4m1(T z, U q);\ntemplate \ninline typename tools::promote_args::type jacobi_theta3m1tau(T z, U tau);\ntemplate \ninline typename tools::promote_args::type jacobi_theta4m1tau(T z, U tau);\n\n// Policied versions - parameterized by q\ntemplate \ninline typename tools::promote_args::type jacobi_theta1(T z, U q, const Policy& pol);\ntemplate \ninline typename tools::promote_args::type jacobi_theta2(T z, U q, const Policy& pol);\ntemplate \ninline typename tools::promote_args::type jacobi_theta3(T z, U q, const Policy& pol);\ntemplate \ninline typename tools::promote_args::type jacobi_theta4(T z, U q, const Policy& pol);\n\n// Policied versions - parameterized by tau\ntemplate \ninline typename tools::promote_args::type jacobi_theta1tau(T z, U tau, const Policy& pol);\ntemplate \ninline typename tools::promote_args::type jacobi_theta2tau(T z, U tau, const Policy& pol);\ntemplate \ninline typename tools::promote_args::type jacobi_theta3tau(T z, U tau, const Policy& pol);\ntemplate \ninline typename tools::promote_args::type jacobi_theta4tau(T z, U tau, const Policy& pol);\n\n// Policied m1 functions\ntemplate \ninline typename tools::promote_args::type jacobi_theta3m1(T z, U q, const Policy& pol);\ntemplate \ninline typename tools::promote_args::type jacobi_theta4m1(T z, U q, const Policy& pol);\ntemplate \ninline typename tools::promote_args::type jacobi_theta3m1tau(T z, U tau, const Policy& pol);\ntemplate \ninline typename tools::promote_args::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 \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 \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());\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 \ninline RealType\n_IMAGINARY_jacobi_theta1tau(RealType z, RealType tau, const Policy&) {\n BOOST_MATH_STD_USING\n RealType eps = policies::get_epsilon();\n RealType result = RealType(0);\n\n // n>=0 even\n result -= _jacobi_theta_sum(tau, RealType(z + constants::half_pi()), constants::two_pi(), eps);\n // n>0 odd\n result += _jacobi_theta_sum(tau, RealType(z + constants::half_pi() + constants::pi()), constants::two_pi(), eps);\n // n<0 odd\n result += _jacobi_theta_sum(tau, RealType(z - constants::half_pi()), RealType (-constants::two_pi()), eps);\n // n<0 even\n result -= _jacobi_theta_sum(tau, RealType(z - constants::half_pi() - constants::pi()), RealType (-constants::two_pi()), eps);\n\n return result * sqrt(tau);\n}\n\ntemplate \ninline RealType\n_IMAGINARY_jacobi_theta2tau(RealType z, RealType tau, const Policy&) {\n BOOST_MATH_STD_USING\n RealType eps = policies::get_epsilon();\n RealType result = RealType(0);\n\n // n>=0\n result += _jacobi_theta_sum(tau, RealType(z + constants::half_pi()), constants::pi(), eps);\n // n<0\n result += _jacobi_theta_sum(tau, RealType(z - constants::half_pi()), RealType (-constants::pi()), eps);\n\n return result * sqrt(tau);\n}\n\ntemplate \ninline RealType\n_IMAGINARY_jacobi_theta3tau(RealType z, RealType tau, const Policy&) {\n BOOST_MATH_STD_USING\n RealType eps = policies::get_epsilon();\n RealType result = 0;\n\n // n=0\n result += exp(-z*z*tau/constants::pi());\n // n>0\n result += _jacobi_theta_sum(tau, RealType(z + constants::pi()), constants::pi(), eps);\n // n<0\n result += _jacobi_theta_sum(tau, RealType(z - constants::pi()), RealType(-constants::pi()), eps);\n\n return result * sqrt(tau);\n}\n\ntemplate \ninline RealType\n_IMAGINARY_jacobi_theta4tau(RealType z, RealType tau, const Policy&) {\n BOOST_MATH_STD_USING\n RealType eps = policies::get_epsilon();\n RealType result = 0;\n\n // n = 0\n result += exp(-z*z*tau/constants::pi());\n\n // n > 0 odd\n result -= _jacobi_theta_sum(tau, RealType(z + constants::pi()), constants::two_pi(), eps);\n // n < 0 odd\n result -= _jacobi_theta_sum(tau, RealType(z - constants::pi()), RealType (-constants::two_pi()), eps);\n // n > 0 even\n result += _jacobi_theta_sum(tau, RealType(z + constants::two_pi()), constants::two_pi(), eps);\n // n < 0 even\n result += _jacobi_theta_sum(tau, RealType(z - constants::two_pi()), RealType (-constants::two_pi()), 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 \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();\n RealType q_n = 0, last_q_n, delta, result = 0;\n\n if (tau <= 0.0)\n return policies::raise_domain_error(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());\n while (z > constants::pi()) {\n z -= constants::two_pi();\n }\n while (z < -constants::pi()) {\n z += constants::two_pi();\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(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 \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(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()), 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 \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();\n RealType q_n = 0, last_q_n, delta, result = 0;\n\n if (tau <= 0.0) {\n return policies::raise_domain_error(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());\n while (z > constants::pi()) {\n z -= constants::two_pi();\n }\n while (z < -constants::pi()) {\n z += constants::two_pi();\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(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 \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(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()), 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 \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();\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(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 \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(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());\n while (z > constants::half_pi()) {\n z -= constants::pi();\n }\n while (z < -constants::half_pi()) {\n z += constants::pi();\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 \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(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()), pol);\n}\n\n// Third Jacobi theta function (parameterized by q)\n// = 1 + 2 * SUM q^n^2 * cos(2nz)\ntemplate \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(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()), 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 \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();\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(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 \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(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());\n while (z > constants::half_pi()) {\n z -= constants::pi();\n }\n while (z < -constants::half_pi()) {\n z += constants::pi();\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 \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(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()), pol);\n}\n\n// Fourth Jacobi theta function, parameterized by q\n// = 1 + 2 * SUM q^n^2 * cos(2nz)\ntemplate \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(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()), pol, function);\n}\n\n// Begin public API\n\ntemplate \ninline typename tools::promote_args::type jacobi_theta1tau(T z, U tau, const Policy&) {\n BOOST_FPU_EXCEPTION_GUARD\n typedef typename tools::promote_args::type result_type;\n typedef typename policies::normalise<\n Policy,\n policies::promote_float,\n policies::promote_double,\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(\n jacobi_theta1tau_imp(static_cast(z), static_cast(tau),\n forwarding_policy(), function), function);\n}\n\ntemplate \ninline typename tools::promote_args::type jacobi_theta1tau(T z, U tau) {\n return jacobi_theta1tau(z, tau, policies::policy<>());\n}\n\ntemplate \ninline typename tools::promote_args::type jacobi_theta1(T z, U q, const Policy&) {\n BOOST_FPU_EXCEPTION_GUARD\n typedef typename tools::promote_args::type result_type;\n typedef typename policies::normalise<\n Policy,\n policies::promote_float,\n policies::promote_double,\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(\n jacobi_theta1_imp(static_cast(z), static_cast(q),\n forwarding_policy(), function), function);\n}\n\ntemplate \ninline typename tools::promote_args::type jacobi_theta1(T z, U q) {\n return jacobi_theta1(z, q, policies::policy<>());\n}\n\ntemplate \ninline typename tools::promote_args::type jacobi_theta2tau(T z, U tau, const Policy&) {\n BOOST_FPU_EXCEPTION_GUARD\n typedef typename tools::promote_args::type result_type;\n typedef typename policies::normalise<\n Policy,\n policies::promote_float,\n policies::promote_double,\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(\n jacobi_theta2tau_imp(static_cast(z), static_cast(tau),\n forwarding_policy(), function), function);\n}\n\ntemplate \ninline typename tools::promote_args::type jacobi_theta2tau(T z, U tau) {\n return jacobi_theta2tau(z, tau, policies::policy<>());\n}\n\ntemplate \ninline typename tools::promote_args::type jacobi_theta2(T z, U q, const Policy&) {\n BOOST_FPU_EXCEPTION_GUARD\n typedef typename tools::promote_args::type result_type;\n typedef typename policies::normalise<\n Policy,\n policies::promote_float,\n policies::promote_double,\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(\n jacobi_theta2_imp(static_cast(z), static_cast(q),\n forwarding_policy(), function), function);\n}\n\ntemplate \ninline typename tools::promote_args::type jacobi_theta2(T z, U q) {\n return jacobi_theta2(z, q, policies::policy<>());\n}\n\ntemplate \ninline typename tools::promote_args::type jacobi_theta3m1tau(T z, U tau, const Policy&) {\n BOOST_FPU_EXCEPTION_GUARD\n typedef typename tools::promote_args::type result_type;\n typedef typename policies::normalise<\n Policy,\n policies::promote_float,\n policies::promote_double,\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(\n jacobi_theta3m1tau_imp(static_cast(z), static_cast(tau),\n forwarding_policy()), function);\n}\n\ntemplate \ninline typename tools::promote_args::type jacobi_theta3m1tau(T z, U tau) {\n return jacobi_theta3m1tau(z, tau, policies::policy<>());\n}\n\ntemplate \ninline typename tools::promote_args::type jacobi_theta3tau(T z, U tau, const Policy&) {\n BOOST_FPU_EXCEPTION_GUARD\n typedef typename tools::promote_args::type result_type;\n typedef typename policies::normalise<\n Policy,\n policies::promote_float,\n policies::promote_double,\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(\n jacobi_theta3tau_imp(static_cast(z), static_cast(tau),\n forwarding_policy(), function), function);\n}\n\ntemplate \ninline typename tools::promote_args::type jacobi_theta3tau(T z, U tau) {\n return jacobi_theta3tau(z, tau, policies::policy<>());\n}\n\n\ntemplate \ninline typename tools::promote_args::type jacobi_theta3m1(T z, U q, const Policy&) {\n BOOST_FPU_EXCEPTION_GUARD\n typedef typename tools::promote_args::type result_type;\n typedef typename policies::normalise<\n Policy,\n policies::promote_float,\n policies::promote_double,\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(\n jacobi_theta3m1_imp(static_cast(z), static_cast(q),\n forwarding_policy(), function), function);\n}\n\ntemplate \ninline typename tools::promote_args::type jacobi_theta3m1(T z, U q) {\n return jacobi_theta3m1(z, q, policies::policy<>());\n}\n\ntemplate \ninline typename tools::promote_args::type jacobi_theta3(T z, U q, const Policy&) {\n BOOST_FPU_EXCEPTION_GUARD\n typedef typename tools::promote_args::type result_type;\n typedef typename policies::normalise<\n Policy,\n policies::promote_float,\n policies::promote_double,\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(\n jacobi_theta3_imp(static_cast(z), static_cast(q),\n forwarding_policy(), function), function);\n}\n\ntemplate \ninline typename tools::promote_args::type jacobi_theta3(T z, U q) {\n return jacobi_theta3(z, q, policies::policy<>());\n}\n\ntemplate \ninline typename tools::promote_args::type jacobi_theta4m1tau(T z, U tau, const Policy&) {\n BOOST_FPU_EXCEPTION_GUARD\n typedef typename tools::promote_args::type result_type;\n typedef typename policies::normalise<\n Policy,\n policies::promote_float,\n policies::promote_double,\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(\n jacobi_theta4m1tau_imp(static_cast(z), static_cast(tau),\n forwarding_policy()), function);\n}\n\ntemplate \ninline typename tools::promote_args::type jacobi_theta4m1tau(T z, U tau) {\n return jacobi_theta4m1tau(z, tau, policies::policy<>());\n}\n\ntemplate \ninline typename tools::promote_args::type jacobi_theta4tau(T z, U tau, const Policy&) {\n BOOST_FPU_EXCEPTION_GUARD\n typedef typename tools::promote_args::type result_type;\n typedef typename policies::normalise<\n Policy,\n policies::promote_float,\n policies::promote_double,\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(\n jacobi_theta4tau_imp(static_cast(z), static_cast(tau),\n forwarding_policy(), function), function);\n}\n\ntemplate \ninline typename tools::promote_args::type jacobi_theta4tau(T z, U tau) {\n return jacobi_theta4tau(z, tau, policies::policy<>());\n}\n\ntemplate \ninline typename tools::promote_args::type jacobi_theta4m1(T z, U q, const Policy&) {\n BOOST_FPU_EXCEPTION_GUARD\n typedef typename tools::promote_args::type result_type;\n typedef typename policies::normalise<\n Policy,\n policies::promote_float,\n policies::promote_double,\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(\n jacobi_theta4m1_imp(static_cast(z), static_cast(q),\n forwarding_policy(), function), function);\n}\n\ntemplate \ninline typename tools::promote_args::type jacobi_theta4m1(T z, U q) {\n return jacobi_theta4m1(z, q, policies::policy<>());\n}\n\ntemplate \ninline typename tools::promote_args::type jacobi_theta4(T z, U q, const Policy&) {\n BOOST_FPU_EXCEPTION_GUARD\n typedef typename tools::promote_args::type result_type;\n typedef typename policies::normalise<\n Policy,\n policies::promote_float,\n policies::promote_double,\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(\n jacobi_theta4_imp(static_cast(z), static_cast(q),\n forwarding_policy(), function), function);\n}\n\ntemplate \ninline typename tools::promote_args::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": "#include \n#include \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 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 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 \n#include /* sin */\n#include \n#include \n#include \n#include \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\n#include \nusing namespace std;\n\n#include \n#include \n\n#define MATRIX_SIZE 50\n\nint main( int argc, char** argv)\n{\n Eigen::Matrix3d matrix_33 = Eigen::Matrix3d::Zero(); //初始化为零\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_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 \n#include \n#include \n#include \n\nusing Eigen::MatrixXd;\n\ninline bool CheckInvertibleness(const MatrixXd& matrix)\n{\n const Eigen::FullPivLU 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 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(\"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(\"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(\"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(\"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 \n\n#include \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\nvoid ChebyshevPoints(int N, El::Matrix& X, double a = -1, double b = 1) {\n const double s = (b - a) / 2.0;\n const double pi = boost::math::constants::pi();\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\nvoid ChebyshevDiffMatrix(int N, El::Matrix& D, El::Matrix &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 \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 \nstruct LinearTransitionModel\n{\n /*! \\f$F\\f$ */\n using TransitionMatrix = Eigen::Matrix;\n /*! \\f$B\\f$ */\n using InputMatrix = Eigen::Matrix;\n /*! \\f$G\\f$ */\n using NoiseMatrix = Eigen::Matrix;\n /*! \\f$x_k\\f$ */\n using State = Eigen::Matrix;\n /*! \\f$U_k\\f$ */\n using Input = Eigen::Matrix;\n /*! \\f$P_k\\f$ */\n using StateCovariance = Eigen::Matrix;\n /*! \\f$Q_k\\f$ */\n using NoiseCovariance = Eigen::Matrix;\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 \n#include \n#include \n#include \n#include \n#include \n\n#include \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 svd_mat(*denseInput, Eigen::ComputeFullU | Eigen::ComputeFullV);\n\n LeftSingMat = boost::make_shared(svd_mat.matrixU());\n\n SingVals = boost::make_shared(svd_mat.singularValues());\n\n RightSingMat = boost::make_shared(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(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": "#include \n#include \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 \n#include \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": "#pragma once\n\n#include \n#include \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\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\nclass Generator > {\nprivate:\npublic:\n typedef Eigen::Matrix Vec;\n typedef Eigen::Matrix Mat;\n NormalGenerator ng;\n Vec mean;\n Mat transform;\npublic:\n Generator(const Gaussian& gaussian) :\n Generator(gaussian.invCovariance.inverse(), gaussian.mean){\n }\n Generator(const Mat& covar, const Vec& _mean) :\n mean{_mean} \n {\n Eigen::SelfAdjointEigenSolver 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\nclass Generator > {\nprivate:\n typedef Eigen::Matrix Vec;\n typedef Eigen::Matrix Mat;\n Generator > gg;\npublic:\n Generator(const IndependentGaussian& 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 \n#include \n#include \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(product_term);\n }\n return factorial_result;\n}\n\nstd::complex 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 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(\n static_cast(l - s), static_cast(r)) *\n boost::math::binomial_coefficient(\n static_cast(l + s), static_cast(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(l) + static_cast(m)) *\n factorial(static_cast(l - m)) * (2.0 * l + 1) /\n (4.0 * M_PI *\n factorial(static_cast(l) + static_cast(s)) *\n factorial(static_cast(l - s)))) *\n (std::complex(cos(m * phi), sin(m * phi))) *\n pow(sin(theta / 2.0), 2.0 * l);\n return swshval;\n}\n\ntemplate <>\nstd::complex derivative_of_spin_weighted_spherical_harmonic(\n const int s, const int l, const int m, const double theta,\n const double phi) {\n return sqrt(static_cast>((l - s) * (l + s + 1))) *\n spin_weighted_spherical_harmonic(s + 1, l, m, theta, phi);\n}\n\ntemplate <>\nstd::complex\nderivative_of_spin_weighted_spherical_harmonic(const int s,\n const int l,\n const int m,\n const double theta,\n const double phi) {\n return -sqrt(static_cast>((l + s) * (l - s + 1))) *\n spin_weighted_spherical_harmonic(s - 1, l, m, theta, phi);\n}\n\ntemplate <>\nstd::complex\nderivative_of_spin_weighted_spherical_harmonic(const int s,\n const int l,\n const int m,\n const double theta,\n const double phi) {\n return sqrt(static_cast>((l - s) * (l + s + 1))) *\n derivative_of_spin_weighted_spherical_harmonic(s + 1, l, m,\n theta, phi);\n}\n\ntemplate <>\nstd::complex\nderivative_of_spin_weighted_spherical_harmonic(\n const int s, const int l, const int m, const double theta,\n const double phi) {\n return sqrt(static_cast>((l - s) * (l + s + 1))) *\n derivative_of_spin_weighted_spherical_harmonic(\n s + 1, l, m, theta, phi);\n}\n\ntemplate <>\nstd::complex\nderivative_of_spin_weighted_spherical_harmonic(\n const int s, const int l, const int m, const double theta,\n const double phi) {\n return -sqrt(static_cast>((l + s) * (l - s + 1))) *\n derivative_of_spin_weighted_spherical_harmonic(s - 1, l, m,\n theta, phi);\n}\n\ntemplate <>\nstd::complex\nderivative_of_spin_weighted_spherical_harmonic(\n const int s, const int l, const int m, const double theta,\n const double phi) {\n return -sqrt(static_cast>((l + s) * (l - s + 1))) *\n derivative_of_spin_weighted_spherical_harmonic(\n s - 1, l, m, theta, phi);\n}\n\ntemplate <>\nstd::complex\nderivative_of_spin_weighted_spherical_harmonic(\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>((l - s + 1) *\n (l + s)));\n}\n\ntemplate <>\nstd::complex\nderivative_of_spin_weighted_spherical_harmonic(\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>((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 \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 \n\n#include \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 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& 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& 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& 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& 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& 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& edgeIsHittable, bool errorOnProblem) {\n\n // Gather values\n std::array 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::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 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 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 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 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 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::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 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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nPlotView *createPlotView(const std::string& title, const std::string& xLabel, const std::string yLabel, const PRectF& viewRange);\n\ntypedef std::vector 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 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 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 \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::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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace boost { namespace math { namespace statistics { namespace detail {\n\ntemplate\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,\n boost::math::policies::promote_double >\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(num_samples - 1);\n Real pvalue;\n if (test_statistic > 0) {\n pvalue = 2*boost::math::cdf(student, -test_statistic);;\n }\n else {\n pvalue = 2*boost::math::cdf(student, test_statistic);\n }\n return std::make_pair(test_statistic, pvalue);\n}\n\ntemplate\nReturnType one_sample_t_test_impl(ForwardIterator begin, ForwardIterator end, typename std::iterator_traits::value_type assumed_mean) \n{\n using Real = typename std::tuple_element<0, ReturnType>::type;\n std::pair 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(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\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_double>;\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(mean_1) - static_cast(mean_2))/s_estimator;\n auto student = boost::math::students_t_distribution(dof);\n Real pvalue;\n if (test_statistic > 0) \n {\n pvalue = 2*boost::math::cdf(student, -test_statistic);;\n }\n else \n {\n pvalue = 2*boost::math::cdf(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\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_double>;\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(size_1) + 1.0/static_cast(size_2)));\n\n auto student = boost::math::students_t_distribution(dof);\n Real pvalue;\n if (test_statistic > 0) \n {\n pvalue = 2*boost::math::cdf(student, -test_statistic);;\n }\n else \n {\n pvalue = 2*boost::math::cdf(student, test_statistic);\n }\n\n return std::make_pair(test_statistic, pvalue);\n}\n\ntemplate\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(mean_1, variance_1, Real(n1), mean_2, variance_2, Real(n2));\n }\n else\n {\n return two_sample_t_test_impl(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\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_double>;\n using std::sqrt;\n \n std::vector 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(*it_1++) - static_cast(*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 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(n - 1);\n Real pvalue;\n if (test_statistic > 0) \n {\n pvalue = 2*boost::math::cdf(student, -test_statistic);;\n }\n else \n {\n pvalue = 2*boost::math::cdf(student, test_statistic);\n }\n\n return std::make_pair(test_statistic, pvalue);\n}\n} // namespace detail\n\ntemplate::value, bool>::type = true>\ninline auto one_sample_t_test(Real sample_mean, Real sample_variance, Real num_samples, Real assumed_mean) -> std::pair\n{\n return detail::one_sample_t_test_impl>(sample_mean, sample_variance, num_samples, assumed_mean);\n}\n\ntemplate::value, bool>::type = true>\ninline auto one_sample_t_test(Real sample_mean, Real sample_variance, Real num_samples, Real assumed_mean) -> std::pair\n{\n return detail::one_sample_t_test_impl>(sample_mean, sample_variance, num_samples, assumed_mean);\n}\n\ntemplate::value_type, \n typename std::enable_if::value, bool>::type = true>\ninline auto one_sample_t_test(ForwardIterator begin, ForwardIterator end, Real assumed_mean) -> std::pair\n{\n return detail::one_sample_t_test_impl>(begin, end, assumed_mean);\n}\n\ntemplate::value_type, \n typename std::enable_if::value, bool>::type = true>\ninline auto one_sample_t_test(ForwardIterator begin, ForwardIterator end, Real assumed_mean) -> std::pair\n{\n return detail::one_sample_t_test_impl>(begin, end, assumed_mean);\n}\n\ntemplate::value, bool>::type = true>\ninline auto one_sample_t_test(Container const & v, Real assumed_mean) -> std::pair\n{\n return detail::one_sample_t_test_impl>(std::begin(v), std::end(v), assumed_mean);\n}\n\ntemplate::value, bool>::type = true>\ninline auto one_sample_t_test(Container const & v, Real assumed_mean) -> std::pair\n{\n return detail::one_sample_t_test_impl>(std::begin(v), std::end(v), assumed_mean);\n}\n\ntemplate::value_type, \n typename std::enable_if::value, bool>::type = true>\ninline auto two_sample_t_test(ForwardIterator begin_1, ForwardIterator end_1, ForwardIterator begin_2, ForwardIterator end_2) -> std::pair\n{\n return detail::two_sample_t_test_impl>(begin_1, end_1, begin_2, end_2);\n}\n\ntemplate::value_type, \n typename std::enable_if::value, bool>::type = true>\ninline auto two_sample_t_test(ForwardIterator begin_1, ForwardIterator end_1, ForwardIterator begin_2, ForwardIterator end_2) -> std::pair\n{\n return detail::two_sample_t_test_impl>(begin_1, end_1, begin_2, end_2);\n}\n\ntemplate::value, bool>::type = true>\ninline auto two_sample_t_test(Container const & u, Container const & v) -> std::pair\n{\n return detail::two_sample_t_test_impl>(std::begin(u), std::end(u), std::begin(v), std::end(v));\n}\n\ntemplate::value, bool>::type = true>\ninline auto two_sample_t_test(Container const & u, Container const & v) -> std::pair\n{\n return detail::two_sample_t_test_impl>(std::begin(u), std::end(u), std::begin(v), std::end(v));\n}\n\ntemplate::value_type, \n typename std::enable_if::value, bool>::type = true>\ninline auto paired_samples_t_test(ForwardIterator begin_1, ForwardIterator end_1, ForwardIterator begin_2, ForwardIterator end_2) -> std::pair\n{\n return detail::paired_samples_t_test_impl>(begin_1, end_1, begin_2, end_2);\n}\n\ntemplate::value_type, \n typename std::enable_if::value, bool>::type = true>\ninline auto paired_samples_t_test(ForwardIterator begin_1, ForwardIterator end_1, ForwardIterator begin_2, ForwardIterator end_2) -> std::pair\n{\n return detail::paired_samples_t_test_impl>(begin_1, end_1, begin_2, end_2);\n}\n\ntemplate::value, bool>::type = true>\ninline auto paired_samples_t_test(Container const & u, Container const & v) -> std::pair\n{\n return detail::paired_samples_t_test_impl>(std::begin(u), std::end(u), std::begin(v), std::end(v));\n}\n\ntemplate::value, bool>::type = true>\ninline auto paired_samples_t_test(Container const & u, Container const & v) -> std::pair\n{\n return detail::paired_samples_t_test_impl>(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": "#include \n#include \n#include \n#include \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(N);\n MatrixXf rowSums = X.rowwise().sum();\n MatrixXf colSums = X.colwise().sum();\n MatrixXf comFacs = X.unaryExpr(std::ptr_fun(boost::math::factorial));\n MatrixXf rFacs = rowSums.unaryExpr(std::ptr_fun(boost::math::factorial));\n MatrixXf cFacs = colSums.unaryExpr(std::ptr_fun(boost::math::factorial));\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 & 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;i0){\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 \r\n#include \r\n\r\n#include \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( 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& out )\r\n{\r\n int numThreads = GLFunctions::idealThreadCount;\r\n\r\n QVector 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 \r\n\r\n#include \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(mxGetData(A)); // column major\r\n\tdouble *pB = reinterpret_cast(mxGetData(B)); // column major\r\n\tdouble *pC = reinterpret_cast(mxGetData(plhs[0]));\r\n\tEigen::Map > matA(pA, nA, mA);\r\n\tEigen::Map > matB(pB, nB, mB);\r\n\tEigen::Map > 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 \n#include \n#include \n#include \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 K_vec) \n{\n Matrix3f K = Map>(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 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& bad_associations) \n{\n Matrix3f K = Map(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 reprojNorm(n_edges, 0.f);\n vector 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 cam_eta = Map>(&cam_beliefs_eta_[measurements_camIDs[e] * 6]);\n Matrix cam_lam = Map>(&cam_beliefs_lambda_[measurements_camIDs[e] * 36]);\n VectorXf cam_mu = cam_lam.transpose().inverse() * cam_eta;\n\n Vector3f lmk_eta = Map(&lmk_beliefs_eta_[measurements_lIDs[e] * 3]);\n Matrix3f lmk_lam = Map(&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(&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 cam_priors_lambda_,\n std::vector cam_priors_mean_,\n std::vector& cam_priors_eta_,\n std::vector lmk_priors_lambda_,\n std::vector lmk_priors_mean_,\n std::vector& lmk_priors_eta_)\n{\n for (unsigned cID = 0; cID < n_keyframes; ++cID) {\n Matrix lambda;\n Matrix mu;\n lambda = Map>(&cam_priors_lambda_[cID * 36]);\n mu = Map>(&cam_priors_mean_[cID*6]);\n\n Matrix 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(&lmk_priors_lambda_[lID*9]);\n mu = Map(&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& cam_priors_eta_, std::vector& lmk_priors_eta_,\n float* cam_beliefs_eta_, float* cam_beliefs_lambda_,\n std::vector cam_priors_lambda_, std::vector lmk_priors_lambda_,\n std::vector lmk_weaken_flag_, \n unsigned data_counter, unsigned n_points)\n{\n Matrix previous_kf_eta = Map>(&cam_beliefs_eta_[data_counter * 6]);\n Matrix previous_kf_lam = Map>(&cam_beliefs_lambda_[data_counter * 36]);\n VectorXf previous_kf_mu = previous_kf_lam.transpose().inverse() * previous_kf_eta;\n Matrix new_kf_lam = Map>(&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(&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": "// 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 \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \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 x_values;\r\n\tstd::vector 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 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\"< 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 \n#include \n#include \n#include \n//#include \n#include \n#include \n#define PREC 300 //change this to set precision\n\nusing namespace boost::multiprecision;\n\ntypedef number > 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 &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 &diag, std::vector &offdiag, const std::vector & 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 verblunsky, std::vector diag, std::vector 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::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 verblunsky(terms);\n std::vector diag(jterms);\n std::vector 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": "#pragma once\n\n//! All the number theory goes in here\n\n#include \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 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 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 \n#include \n#include \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 // for std::max_element\n#include \n\n#include \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& x,\n const vector& 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 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": "// 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 \n\n#include \n#include \n#include \n\n#include \"piecewise_poly.hpp\"\n\nnamespace cbr\n{\n\nclass PiecewiseLinear\n{\nprotected:\n using row_t = Eigen::Matrix;\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\n static PiecewisePoly fit(\n T1 && x,\n const Eigen::DenseBase & y)\n {\n static_assert(is_eigen_dense_v, \"x must be an Eigen::DenseBase object.\");\n\n auto coeffs = generateCoeffs(x, y);\n return PiecewisePoly(std::forward(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\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\n static PiecewisePolyND fitND(\n T1 && x,\n const T2 & ys)\n {\n static_assert(is_eigen_dense_v, \"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 coefLists;\n\n if constexpr (is_eigen_dense_v) {\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(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&& 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(x), std::move(coefLists));\n }\n\nprotected:\n template\n static matrix_t generateCoeffs(\n const Eigen::DenseBase & x,\n const Eigen::DenseBase & 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": "#include \n\n#include \n\n// #include \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; iM_vertexs[i] = i;\n\n }\n\n\n\n for ( i=0; iM_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 // 初始化\n\n for ( v=0; v<=M_vertexNum-1; v++ ) {\n\n final[v] = false;\n\n dist[v] = M_edges[v0][v]; // 如果不直接连通,dist[v]就是MAXWEIGHT,否则是相应的权值, 我称此时dist[v] 为 \"估计值\"\n\n pre[v] = -1; // 所有的顶点都无前驱,置pre数组为 -1\n\n\n\n if ( dist[v] < MAXWEIGHT ) // v 到 v0 (直接)连通\n\n pre[v] = v0;\n\n }\n\n\n\n // 开始时V0属于S集合,默认已经找到最短路径\n\n dist[v0] = 0;\n\n final[v0] = true; // (final[i] = true 相当于把i 加入S集合)\n\n\n\n // main loop\n\n // 寻找其余6个节点\n\n for ( i=1; i if (v==-1)\n\n current_tmp_min = MAXWEIGHT; // 当前距V0路径最短的权值 ,初始化为不连通状态\n\n\n\n // 寻找当前离V0最近的顶点 V\n\n // 第一次main loop 下, current_tmp_min 变化情况: dist[1] -> dist[2]\n\n for ( w=0; w v -> w 比 v0 -> w 短\n\n {\n\n // 第一次main loop, dist[1] 更新成 4, 2 作为1 的前驱\n\n dist[w] = current_tmp_min + (M_edges[v][w]); // 更新最短路径长度, 此时dist[w]为 \"确定值\"\n\n pre[w] = v; // v作为w的前驱顶点\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 s;\n\n cout << \"从顶点 \" << v0 << \" 到其他顶点: \" << endl;\n\n\n\n for ( v=0; v 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 \n#include \n#include \n#include \n#include \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>;\n\ntemplate \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};\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 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 \n#include \n#include \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 \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 \n#include \n#include \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 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 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 \n\n#include \n\nnamespace polynomial {\n\n // Evaluate polynomial using Horner's scheme\n template double eval(const Eigen::DenseBase& 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 double deriv(const Eigen::DenseBase& 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 double solve(const Eigen::DenseBase& 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": "/**\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 \n#include \n#include \n#include \n#include \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 \nstd::vector> 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> 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 rtol{0.1, 0.01, 0.001, 0.0001, 0.00001, 0.000001};\n std::array 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 \n -t \n -f \n -b \n -w (STDOUT | FEATURE | BOTH) // prints weights to stdout or at end of features_file\n ***************************************************************************************/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\ntypedef boost::multiprecision::mpz_int Z;\ntypedef boost::rational Q;\ntypedef std::vector 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(-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": "/**\n * @date 2021.3.4 \n * @author hqy - sentinel\n * @note 数字图像处理第一次作业\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \"include/utils.hpp\"\n\n/// 求得图像均值以及方差\nstd::pair getMeanVar(const cv::Mat& src, bool use_buildin = false) {\n if (use_buildin == false){ // 手写实现\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 调库两行\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操作\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\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\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操作\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(wx, u);\n getWeightVector(wy, v);\n uchar crop[16];\n imgCrop(padding.data, px, py, padding.cols, crop);\n dst.data[base + j] = calcWeightSum(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 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 \r\n#include \r\n#include \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 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<\n#include \n#include \n#include \n#include \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(std::chrono::duration_cast(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(std::chrono::duration_cast(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(std::chrono::duration_cast(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(std::chrono::duration_cast(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(std::chrono::duration_cast(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élie Loher, Philippe Peter\n * @date 07.01.2021\n * @copyright Developed at ETH Zurich\n */\n\n#include \"expfittedupwind.h\"\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \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> CompBeta(\n std::shared_ptr 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 \n\n#include \n#include \n#include \n#include \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::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::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::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 \n#include \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 qr(A);\n //ColPivHouseholderQR 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 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 superdiagonal(\n const Eigen::Matrix & M)\n{\n const int numElements = std::min(M.rows(), M.cols()) - 1;\n Eigen::Matrix 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 subdiagonal(\n const Eigen::Matrix & M)\n{\n const int numElements = std::min(M.rows(), M.cols()) - 1;\n Eigen::Matrix 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* jacobian)\n{\n Eigen::Matrix Tci2cj =Eigen::Matrix::Identity();\n Tci2cj.topLeftCorner<3,3>()= Rj.transpose()*Ri;\n Tci2cj.block<3,1>(0,3).noalias() = Rj.transpose()*(pi-pj);\n Eigen::Matrix 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 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 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& 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 jacobian;\n\n reparameterize_AIDP(Ri, Rj, abrhoi, pi, pj, abrhoj, &jacobian);\n Eigen::Matrix jacobian3;\n reparameterizeNumericalJacobian(Ri, Rj, abrhoi, pi, pj, abrhoj, jacobian3);\n std::cout<<\"analytic jacobian \" << std::endl<< jacobian< jacobian;\n\n reparameterize_AIDP(Ri, Rj, abrhoi, pi, pj, abrhoj, &jacobian);\n Eigen::Matrix 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< > 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()<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()<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()<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()<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 > 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()<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 \n#include \n#include \n#include \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 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\n Matrix;\n\n\n LinearDynamicsWithAccelerationConstraint(Eigen::Matrix 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\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::infinity() ||\n max_position == std::numeric_limits::infinity())\n {\n return false;\n }\n if(jerk_ > 0)\n {\n certificate_time = std::numeric_limits::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::infinity();\n min_position_ = -std::numeric_limits::infinity();\n max_velocity_ = std::numeric_limits::infinity();\n max_position_ = std::numeric_limits::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": "#include \n#include \n#include \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 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();\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 \n#include \n#include \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 \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 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 <\n#include \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 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": "/**\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 *


\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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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 \nBOOST_UBLAS_INLINE\ntypename matrix_traits::size_type rank(matrix_expression const& A, RealT tol)\n{\n\ttypedef typename matrix_traits::value_type value_type;\n\ttypedef typename type_traits::real_type real_type;\n\n\tvector s = svd_values(A);\n\treturn size(which(s, ::std::bind2nd(::std::greater(), 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 \nBOOST_UBLAS_INLINE\ntypename matrix_traits::size_type rank(matrix_expression const& A)\n{\n\ttypedef typename matrix_traits::value_type value_type;\n\ttypedef typename type_traits::real_type real_type;\n\n\tvector 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(), 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 \n#include \n\n#include \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 \n#include // pi\n#include // 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 \nconstexpr static_poly, N+1> cyclotomic() {\n static_assert(N > 0, \"No nonpositive numbers please!\");\n using namespace boost::math::double_constants;\n\n static_poly, N+1> cyc{1};\n\n for (int k = 1; k <= N; ++k) {\n if (gcd(k, N) == 1) {\n static_poly, 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 \nconstexpr int euler_totient() {\n return cyclotomic().degree();\n}\n\ntemplate \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()> 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": "#include \"RSA.h\"\n#include \"math/Euclidean.h\"\n#include \"Encryptor.h\"\n#include \"Decryptor.h\"\n#include \n#include \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üttler, edited by Oliver Rietmann\n * @date 03.03.2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"mylinearfeelementmatrix.h\"\n\n#include \n#include \n#include \n#include \n\n#include \n\nnamespace ElementMatrixComputation {\n\n/* SAM_LISTING_BEGIN_1 */\nEigen::Matrix 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 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": "// 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 \n#include \n#include \n\nnamespace vtr {\nnamespace vision {\n\n// Returns tf s.t. a = tf * b\ntemplate \nbool registerSVD(const Eigen::Matrix& a,\n const Eigen::Matrix& b,\n Eigen::Matrix* tf,\n const Eigen::Array& weights =\n Eigen::Array(1, 0),\n bool scaling = false) {\n // Types\n // typedef Eigen::Matrix Transform;\n typedef Eigen::Matrix Point;\n typedef Eigen::Matrix Points;\n typedef Eigen::Matrix 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 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() = R;\n tf->template topRightCorner() = t;\n\n // Return\n return true;\n}\n\n// Explicit instantiation for common params\nextern template bool registerSVD<2>(\n const Eigen::Matrix& a,\n const Eigen::Matrix& b,\n Eigen::Matrix* tf,\n const Eigen::Array& weights, bool scaling);\nextern template bool registerSVD<3>(\n const Eigen::Matrix& a,\n const Eigen::Matrix& b,\n Eigen::Matrix* tf,\n const Eigen::Array& 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 \n#include \n#include \n#include \n\n#include \n\n#include \n\n#include \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 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": "/*\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’s 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 \n#include \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 in)\n {\n using namespace std;\n double const epsilon = std::numeric_limits::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(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 \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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\n double\n radialbasis(const boost::array & v1, const boost::array & v2)\n {\n boost::numeric::ublas::vector 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\n class ThinPlateSpline\n {\n public:\n boost::numeric::ublas::matrix Wa;\n std::vector > refPositions;\n\n ThinPlateSpline()\n {}\n\n ThinPlateSpline(std::vector > positions,\n std::vector > values)\n {\n boost::numeric::ublas::matrix 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 (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(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 pmatrix;\n\n boost::numeric::ublas::matrix 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 invL(boost::numeric::ublas::identity_matrix(A.size1()));\n lu_substitute(A, pm, invL);\n\n\n Wa = boost::numeric::ublas::matrix(WaLength, ValDim );\n\n boost::numeric::ublas::matrix 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\n interpolate(const boost::array &position) const\n {\n boost::array 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(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 \n//#include \n#include \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 i(0, 1);\n\t\tstd::complex delta0(b*b - 3 * a*c, 0);\n\t\tstd::complex delta1(2 * b*b*b - 9 * a*b*c + 27 * a*a*d, 0);\n\t\tstd::complex C = pow((delta1 + sqrt(delta1*delta1 - 4.0 * delta0*delta0*delta0)) / 2.0, 1.0 / 3.0);\n\n\t\tstd::complex u2 = (-1.0 + sqrt(3.0)*i) / 2.0;\n\t\tstd::complex u3 = (-1.0 - sqrt(3.0)*i) / 2.0;\n\n\t\tstd::complex t1 = (b + C + delta0 / C) / (-3.0*a);\n\t\tstd::complex t2 = (b + u2*C + delta0 / (u2*C)) / (-3.0*a);\n\t\tstd::complex t3 = (b + u3*C + delta0 / (u3*C)) / (-3.0*a);\n\n\t\tif ((std::abs(std::imag(t1))0))\n\t\t\tt = std::real(t1);\n\t\tif ((std::abs(std::imag(t2))0) && ((std::real(t2) < t) || (t < 0)))\n\t\t\tt = std::real(t2);\n\t\tif ((std::abs(std::imag(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::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 \n#include \n\nvoid testEuclideanNorm()\n{\n Eigen::Matrix 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 B;\n B = A.array().rowwise() / A.colwise().norm().array();\n std::cout << B << std::endl;\n\n for(int i=0; i\n#include \n\n#include \n#include \n#include \n#include \n\n#include \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 \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 \n#include \n\n#include \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 \n#include \n#include \"coordinate_transform.hpp\"\n#include \"integrate.hpp\"\n#include \"shape.hpp\"\n#include \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\nvoid computeLoadVector(Vector& loadVector,\n const Point& a, const Point& b, const Point& c,\n const std::function& 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 \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace cbr\n{\n\n/***************************************************************************\n * \\brief Converts degrees to radians\n ***************************************************************************/\ntemplate\nconstexpr T deg2rad(const T deg) noexcept\n{\n static_assert(std::is_floating_point_v, \"Input type must be a floating point.\");\n return deg * M_PI / 180.;\n}\n\n/***************************************************************************\n * \\brief Converts radians to degrees\n ***************************************************************************/\ntemplate\nconstexpr T rad2deg(const T rad) noexcept\n{\n static_assert(std::is_floating_point_v, \"Input type must be a floating point.\");\n return rad * 180. / M_PI;\n}\n\n/***************************************************************************\n * \\brief Computes b^e\n ***************************************************************************/\ntemplate\nconstexpr TBase powFast(const TBase b, const TExp e) noexcept\n{\n static_assert(std::is_unsigned_v, \"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\nconstexpr T powFastImpl([[maybe_unused]] T val, std::index_sequence)\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\nconstexpr TBase powFast(const TBase b) noexcept\n{\n return detail::powFastImpl(b, std::make_index_sequence{});\n}\n\n/***************************************************************************\n* \\brief Wraps angle in radians between 0 and 2*pi\n***************************************************************************/\ntemplate\nT wrap2Pi(const T in) noexcept\n{\n static_assert(std::is_floating_point_v, \"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\nT wrapPi(const T in) noexcept\n{\n static_assert(std::is_floating_point_v, \"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\nT yaw2heading(const T rad) noexcept\n{\n static_assert(std::is_floating_point_v, \"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\nconstexpr T factorial(const T x, const T x0 = T(1)) noexcept\n{\n static_assert(std::is_unsigned_v, \"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\nconstexpr T prob_to_log_odds(const T p)\n{\n static_assert(std::is_floating_point_v, \"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\nconstexpr T log_odds_to_prob(const T l)\n{\n static_assert(std::is_floating_point_v, \"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\nEigen::Matrix\nquat2eulZYX(const Eigen::QuaternionBase & q) noexcept\n{\n const auto qn = q.normalized();\n using T = typename derived::Scalar;\n Eigen::Matrix 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\nvoid quat2eulZYX(\n const Eigen::QuaternionBase & q,\n Eigen::Matrix & eul) noexcept\n{\n eul = quat2eulZYX(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\nEigen::Quaternion eul2quatZYX(const Eigen::Matrix & eul) noexcept\n{\n Eigen::Quaternion 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\nvoid eul2quatZYX(\n const Eigen::Matrix & eul,\n Eigen::QuaternionBase & q) noexcept\n{\n q = eul2quatZYX(eul);\n}\n\n/***************************************************************************\n * \\brief Converts a pure yaw to a quaternion\n ***************************************************************************/\ntemplate\nEigen::Quaternion yaw2quat(const T & yaw) noexcept\n{\n return Eigen::Quaternion(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\ntypename derived::Scalar quat2yaw(const Eigen::QuaternionBase & 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\nconstexpr T sub2ind(const std::array & sz, const std::array & idx)\n{\n static_assert(std::is_arithmetic_v, \"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\nconstexpr std::array ind2sub(const std::array & sz, T idx)\n{\n static_assert(std::is_arithmetic_v, \"Type must be arithmetic.\");\n static_assert(N > 1, \"Size of first input must be > 1.\");\n\n std::array sub{};\n\n if constexpr (N > 2) {\n std::array 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\nauto powAntisym(T1 base, T2 exp)\n{\n static_assert(std::is_arithmetic_v, \"Base type must be arithmetic.\");\n static_assert(std::is_arithmetic_v, \"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\nEigen::AlignedBox overapp_bbox(S && pose, Eigen::AlignedBox bbox_B)\n{\n Eigen::Array bbmin = std::numeric_limits::max() * Eigen::Array::Ones();\n Eigen::Array bbmax = std::numeric_limits::min() * Eigen::Array::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::CornerType>(n));\n bbmin = bbmin.min(p.array());\n bbmax = bbmax.max(p.array());\n }\n return Eigen::AlignedBox{bbmin, bbmax};\n}\n\n/***************************************************************************\n * \\brief Smooth saturation function\n ***************************************************************************/\ntemplate\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, \"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\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(out, mi, ma, satSmoothCoeff);\n return out;\n}\n\n/***************************************************************************\n * \\brief Check if point is inside polygon\n ***************************************************************************/\ntemplate\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\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;\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\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;\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\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\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\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\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\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\nconstexpr std::array linspace(T x0, T xT)\n{\n static_assert(std::is_floating_point_v, \"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(N - 1);\n std::array 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\nT sigmoid(T x, T center, T k)\n{\n static_assert(std::is_floating_point_v, \"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\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\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, ResT>, \"fcn must map to eigen type\");\n\n static constexpr int N = ResT::RowsAtCompileTime;\n using InfT = Eigen::Matrix;\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(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\nauto sqrt_information(const Eigen::MatrixBase & cov, typename Derived::Scalar min_eig)\n{\n Eigen::SelfAdjointEigenSolver 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 \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \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 m_components;\r\n\tint length;\r\n\tint l;\r\n\tvector 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 generate_random(int LENGTH) {\r\n\t\tvector 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 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 generate_random() {\r\n\t\tvector 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 convertToBinary(ZZ& number) {\r\n\tunsigned int number_size = NumBits(number);\r\n\tvector 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& 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& 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 printToFiles(const vector& 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& v,const int& i,string generator) {\r\n\tcout << \"File compression test:\\n\";\r\n\tpair files=printToFiles(v, i,generator);\r\n\tpair 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 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 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 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 \n#include \n#if BOOST_VERSION >= 106400\n#include \n#endif\n#include \n#include \n#include \n#include \n\nusing namespace svgpp;\nnamespace ublas = boost::numeric::ublas;\n\ntypedef ublas::matrix matrix_t;\n\nstruct TransformEventsPolicy\n{\n typedef matrix_t context_type;\n\n static void transform_matrix(matrix_t & transform, const boost::array & 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(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(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();\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();\n matrix_t m = ublas::identity_matrix(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();\n matrix_t m = ublas::identity_matrix(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(3, 3));\n value_parser<\n tag::type::transform_list,\n transform_policy,\n transform_events_policy\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": "/*!\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 \n#include \n\n/*************************\n *** Utility functions ***\n *************************/\n\n/*\ndouble cross2D(Eigen::Ref const &x, Eigen::Ref 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\nEigen::Matrix affWrap_impl(Eigen::Matrix const &mat, std::index_sequence)\n{\n return Eigen::Matrix{mat(is)...,1.0};\n}\n\ntemplate\nEigen::Matrix affWrap(Eigen::Matrix const &mat)\n{\n return affWrap_impl(mat, std::make_index_sequence());\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 const &t1_, std::array const &t2_)\n{\n /*** Preparation ***/\n // Rotation matrix of M_PI/2 in radian.\n Eigen::Matrix 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((t1_[1]-t1_[0]).adjoint()*mat*(t1_[2]-t1_[0])) > 0;\n bool is_ccwise2 = static_cast((t2_[1]-t2_[0]).adjoint()*mat*(t2_[2]-t2_[0])) > 0;\n std::array,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(rv*(*(t[1][0])-*(t[0][i]))) < 0\n && static_cast(rv*(*(t[1][1])-*(t[0][i]))) < 0\n && static_cast(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(rv*(*(t[0][0])-*(t[1][i]))) < 0\n && static_cast(rv*(*(t[0][1])-*(t[1][i]))) < 0\n && static_cast(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 \n#include \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 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 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\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 signed_triangle_area_gradients(\n\tconst Eigen::Vector2d &a, const Eigen::Vector2d &b, const Eigen::Vector2d &c)\n{\n\tstd::vector 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 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 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 faces_from_tet(const Eigen::RowVector4i &t)\n{\n\tusing namespace Eigen;\n\tstd::vector 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 \n#include \n# include \n#include \nusing namespace Eigen;\nusing namespace std;\n\ntuple 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 tt {(0.0,0.0)};\n for(int j= 0; j < 2; ++j){\n for(int i= 0; i < k; ++i){\n complex 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": "/*\n * Copyright 2020 © Centre Interdisciplinaire de développement en Cartographie des Océans (CIDCO), Tous droits réservés\n */\n\n/* \n * File: PlaneFitter.hpp\n * Author: Jordan McManus\n */\n\n#ifndef PLANEFITTER_HPP\n#define PLANEFITTER_HPP\n\n#include \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 \n#include \n#include \n//#include \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 \r\n\r\n#if defined(USE_BARE_METAL)\r\n#else\r\n #include \r\n #include \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 \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\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 \r\n // and deactivate #define BOOST_FIXED_POINT_DISABLE_IOSTREAM.\r\n std::cout << std::setprecision(std::numeric_limits::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 \n#include \n#include \n#include \n#include \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 x_vec;\n\tstd::vector 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 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 \n#include \n\n#include \n\n#include \"UtilMath.hpp\"\n\nnamespace RGM\n{\n\ntemplate\nT MathUtil_::median(std::vector & vData, int num/*=std::numeric_limits::max()*/, bool sortData/*=false*/)\n{\n\n if (vData.size()==0 || num==0) {\n return std::numeric_limits::quiet_NaN();\n }\n\n num = std::max(std::min(vData.size(), num), 1);\n\n if ( vData.size()==1 || num==1 ) {\n return vData[0];\n }\n\n std::vector * 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 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\nstd::vector MathUtil_::pdist(const std::vector > & pts, int num)\n{\n\n std::vector dist;\n\n num = std::min(pts.size(), num);\n\n for ( int i=0; i & pt1( pts[i] );\n for ( int j=i+1; j & 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\nstd::vector MathUtil_::linspace(T s, T e, T interval)\n{\n\n std::vector 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\nstd::vector MathUtil_::hist(std::vector & y, std::vector & x)\n{\n\n std::vector n(x.size(), 0);\n\n std::vector xx(x.size()+1);\n xx[0] = -std::numeric_limits::infinity();\n std::copy(x.begin(), x.end(), xx.begin()+1);\n\n for ( int i=0; ixx[j] && y[i]<=xx[j+1]) {\n break;\n }\n }\n\n n[j]++;\n }\n\n return n;\n}\n\ntemplate\nstd::vector MathUtil_::convnSame(std::vector & x, std::vector & filter)\n{\n\n std::vector 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 result(xx.size()-filter.size());\n for ( int i=0; i 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\nT MathUtil_::calcErr(std::vector & pscores, std::vector & 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 > scores(num);\n\n for ( int i=0; i(-pscores[i], i);\n }\n for ( int i=numpos, j=0; j(-nscores[j], i);\n }\n\n std::sort(scores.begin(), scores.end());\n\n std::vector tp(num, 0), fp(num, 0);\n\n for (int i=0; i(-scores[r].first, *std::min_element(pscores.begin(), pscores.end()));\n\n return minerr;\n}\n\ntemplate\nT MathUtil_::calcVar(std::vector & pscores, T & thr)\n{\n int num = pscores.size();\n\n //thr = std::numeric_limits::max();\n\n T m = 0;\n for ( int i=0; i(thr, pscores[i]);\n }\n\n m /= num;\n\n T v = 0;\n for ( int i=0; i;\ntemplate class MathUtil_;\ntemplate class MathUtil_;\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 \n#include \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 è 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> 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 \n#include \n#include \n#include \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 \n#include \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": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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 \ndouble genMean(Iteratable& _dataSet) {\n double sum = 0;\n for (auto i : _dataSet)\n sum += i;\n return sum / _dataSet.size();\n}\n\ntemplate \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 \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& _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& _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 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::infinity(), theta + errorRadius);\n else if (tailOrient < 0)\n return make_pair(theta - errorRadius, numeric_limits::infinity());\n else\n return make_pair(theta - errorRadius, theta + errorRadius);\n}\n\nvector> invertInterval(pair originInterval) {\n if (originInterval.first == -numeric_limits::infinity())\n return {make_pair(originInterval.second, numeric_limits::infinity())};\n else if (originInterval.second == numeric_limits::infinity())\n return {make_pair(-numeric_limits::infinity(), originInterval.first)};\n else\n return {make_pair(-numeric_limits::infinity(), originInterval.first),\n make_pair(originInterval.second, numeric_limits::infinity())};\n}\n\npair standardlizeInterval(pair 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 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 \nostream& operator<<(ostream& os, const pair& v) {\n pair boundSign('[', ']');\n if (v.first == -numeric_limits::infinity())\n boundSign.first = '(';\n if (v.second == numeric_limits::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 \nstring readSingleLineCSV(vector& _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 \nstring readSingleLineCSV(map& 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(rawData, 1));\n }\n inFile.close();\n return title;\n}\n\nstring readMultiLineCSV(map>& 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 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 \n#include \n#include \n#include \n#include \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": "#pragma once\n\n#include \"random_engine.hpp\"\n#include \n#include \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 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::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 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::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 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 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 \n\n#include \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 linear_regressor_svd(false);\n\tbenchmark(linear_regressor_svd, XN, YN, 100);\n\tmlt::models::regressors::LeastSquaresLinearRegression linear_regressor_ldlt(false);\n\tbenchmark(linear_regressor_ldlt, XN, YN, 100);\n\tstd::cout << std::endl;\n\tmlt::models::regressors::LeastSquaresLinearRegression 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();\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> 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> 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> sgd(loss, grad_descent, 0.5, true);\n\n\tsgd.fit(X2, Y2, true);\n\n\tstd::cout << \"OptimizableLinearRegressor: \" << 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": "#include \"logreg.hpp\"\n#include \n#include \n#include \n#include \n#include \n#include \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() * mu.array().log();\n\tArrayXf t2 = (1 - y01.array().cast()) * ((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()) + 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 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() - 1.0;\n\tfloat y_err = (y_pred - LR.y.cast()).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 \n#include \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 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 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 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 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 \n#include \n#include \n\n// Boost Libraries\n#include \n\n// Common Libraries\n#include \"../common/StringUtilities.hpp\"\n\n\nusing namespace std;\nusing namespace boost::multiprecision;\ntypedef number> 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\n#include \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 \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": "/*\nReed Solomon coding \n*/\n\n\n#ifndef ReedSolomon\n#define ReedSolomon\n\n#include \n#include \n#include \n#include \n#include \n#include \"polynomial.hpp\"\n\n\nusing namespace std;\n\n\n\ntemplate\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& RSencode(const vector& infvec, vector& 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& RS_shortened_encode(const vector& infvec, vector& 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& RS_systematic_encode(const vector& infvec, vector& 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 RSdecode(vector& crec, const vector& 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 RS_shortened_decode(vector& infvec, vector& c);\n\n\t// decode when information is encoded in the spectrum of c, that is C\n\tpair RS_decode_spec(vector& infvec, const vector& c);\n};\n\n\ntemplate \nvector& RScode::RSencode(const vector& infvec, vector& c){\n\tassert(infvec.size() == k);\n\n\t// encode\n\tc.resize(n); // c is the codeword\n\tvector C(n); // Fourier transform of codeword\n\t// first n-k entries are zero\n\tfor(unsigned i=0;i\n//vector& RS_shortened_encode(const vector& infvec, vector& c, const GFE& a, unsigned k, unsigned n, unsigned n_u){\nvector& RScode::RS_shortened_encode(const vector& infvec, vector& c){\n\tvector extrazeros(n_u-n, GFE(0));\n\tvector 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\nvector& RScode::RS_systematic_encode(const vector& infvec, vector& c){\n\tassert(infvec.size() == k_u);\n\n\t// compute the generator polynomial \n\tpolynomial gp = polynomial(1);\n\tGFE ai = GFE(a); \n\tfor(unsigned i=1;i <= n_u-k_u; ++i){\n\t\tvector prov(2);\n\t\tprov[0] = GFE(0) - ai;\n\t\tprov[1] = GFE(1);\n\t\tgp *= polynomial(prov);\n\t\tai *= a;\n\t}\n\t// generate message polynomial\n\tpolynomial mp(infvec);\n\n\t// construct the polynomial x^(n-k)\n\tvector xnmkv(n_u-k_u+1,GFE(0));\n\txnmkv[n_u-k_u] = GFE(1);\n\tpolynomial xnmk(xnmkv);\n\n\tpolynomial 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 > res = divide(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\npair RScode::RScode::RSdecode(vector& crec, const vector& c){\n\t\n\tpair 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 er_pos(n_u);\n\tunsigned j=0;\n\tfor(unsigned i=0;i elp = polynomial(1);\n\tfor(unsigned i=0;i 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(prov);\n\t}\n\t\n\n\t// obtain Crec from the received vector crec\n\tvector Crec(n_u);\n\tdftd.dft(crec,Crec); \n\n\t// compute syndrome from received C\n\tvector 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 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 xdm1(d,GFE(0)); \n\txdm1[d-1] = GFE(1);\n\n\tpolynomial rem1 = xdm1;\n\tpolynomial rem2 = synd;\n\tpolynomial aux1 = polynomial(0);\n\tpolynomial aux2 = polynomial(1);\n\t//polynomial aux2 = elp;//polynomial(1);\n\t\n\t\n\twhile(! (rem2.degree() < (d-1+j)/2 ) ){\n\t\tpair, polynomial > res = divide(rem1,rem2);\n\t\tpolynomial aux_new = polynomial(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 A0 = polynomial(elp.poly[0]);\n\t// rem2 is polynomial Omega\n\tpair, polynomial > res_tmp= divide(rem2, A0);\n\tpair, polynomial > res_tmp2= divide(elp, A0);\n\tpolynomial Omega = res_tmp.first;\n\telp = res_tmp2.first;\n\t//// Forney's algorithm to find the error values\n\n\tpolynomial elpder = elp;\n\telpder.derive(); // derivative of the error locator polynomial\n\n\t// compute the error values\n\t\n\t//vector err_val(n);\n\tGFE ami = GFE(1);\t\n\tfor(unsigned i=0;i\npair RScode::RS_shortened_decode(vector& infvec, vector& c){\n\t\n\tvector 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 crec(n_u);\n\tpair erctr = RSdecode(crec,c);\n\t\n\t// copy the information; recall that c is endoded systematically.. \t\n\tinfvec = vector(crec.begin()+n-k, crec.begin()+n );\n\tinfvec.resize(k);\n\treturn erctr;\n}\n\n\n//\ntemplate\npair RScode::RS_decode_spec(vector& infvec, const vector& c){\n\t\n\tpair erctr;\n\n\tassert(n == c.size());\n\tvector crec; // the recovered codeword\n\tcout << \"start RS decode.. \" << endl;\n\terctr = RSdecode(crec,c);\n\tcout << \"..end RS decode.. \" << endl;\n\n\tvector 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\n#include \n\n#include \n\n#include \n#include \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 \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 \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": "/* 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 \n#include \n#include \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(Npoints,Npoints);\n mat q = zeros(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(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) \r\n#include \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{\r\npublic:\r\n FDMDiffusionA(numerical::fdm::Parameters* p): \r\n numerical::fdm::Problem(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& 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& 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{\r\npublic:\r\n FDMDiffusionB(numerical::fdm::Parameters* p): \r\n numerical::fdm::Problem(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& 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& 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{\r\npublic:\r\n FDMDiffusionC(numerical::fdm::Parameters* p): \r\n numerical::fdm::Problem(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& 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& 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{\r\npublic:\r\n FDMDiffusionD(numerical::fdm::Parameters* p): \r\n numerical::fdm::Problem(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& 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& 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{\r\npublic:\r\n FDMDiffusionE(numerical::fdm::Parameters* p): \r\n numerical::fdm::Problem(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& 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& 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 \n#include \n\nusing namespace Eigen;\n\nPolynomial 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(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 \n#include \n#include \n#include \n#include \n#include\n\n#include \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 > &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 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 > 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 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 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 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 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 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 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(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 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 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 \n#include \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\n#include\n#include\n\n#include \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>(new GenFromDistr(_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>>(_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 \n#include \n#include \n#include \n#include \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;\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();\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(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, ¤t_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();\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(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, ¤t_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(arg / boost::math::constants::pi());\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();\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();\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, 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()))) << 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 \n#include \n#include \n#include \n\n#include \n#include \n#include \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 obs_noise_distrib(0.0, obs_sigma);\n\n\n int N = 100;\n std::vector x_data(N), y_data(N);\n for (int i = 0; i < N; ++i)\n {\n x_data[i] = static_cast(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 time_used = chrono::duration_cast>(t2 - t1);\n cout << \"solve time cost = \" << time_used.count() << \" seconds. \" << endl;\n \n std::cout << \"final = \" << a << \" \" << b << \" \" << c << \"\\n\";\n\n vector 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 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 //std::cout\n#include //formatting\n#include //Container\n#include // Rationals\n#include //1024bit precision\n\n\ntypedef boost::rational rational; // reduce boilerplate\n\nrational bernulli(size_t n){\n\n auto out = std::vector();\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(\"<\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\ntypedef Eigen::Matrix 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 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] << \" \" <\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(_vertices[0]);\n VertexSE3LieAlgebra* v2 = static_cast(_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(_vertices[0]))->estimate();\n Sophus::SE3 v2 = (static_cast(_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(_vertices[0]))->estimate();\n Sophus::SE3 v2 = (static_cast(_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> Block;\n Block::LinearSolverType* linear_solver = new g2o::LinearSolverCholmod();\n Block* block_solver_ptr = new Block(std::unique_ptr(linear_solver));\n g2o::OptimizationAlgorithmLevenberg* optimization_algorithm_ptr = new g2o::OptimizationAlgorithmLevenberg(std::unique_ptr(block_solver_ptr));\n// g2o::OptimizationAlgorithmGaussNewton* optimization_algorithm_ptr = new g2o::OptimizationAlgorithmGaussNewton(std::unique_ptr(block_solver_ptr));\n// g2o::OptimizationAlgorithmDogleg* optimization_algorithm_ptr = new g2o::OptimizationAlgorithmDogleg(std::unique_ptr(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 vertices;\n std::vector 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 /* 因为用了自定义顶点且没有向g2o注册,这里保存自己来实现伪装成 SE3 顶点和边,让 g2o_viewer 可以认出 */\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": "#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 \n#include \n\nnamespace Eigen {\n\n// namespace internal {\n\ntemplate\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().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 &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 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 &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::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::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::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::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::epsilon() * R_norm)\n\t\t// problem degenerate\n\t\treturn false;\n\tR_norm = std::max(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 \n#include \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 \r\n#include \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": "#include \n#include \n#include \n#undef IGL_STATIC_LIBRARY\n#include \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 \n\n#include \n#include \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 * @file systemode_main.cc\n * @brief NPDE homework SystemODE\n * @copyright Developed at ETH Zurich\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \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 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> 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 \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 \n#include \n\n#include \n \nusing Eigen::MatrixXd;\n\ntypedef Eigen::Matrix Matrix33f;\ntypedef Eigen::Matrix Vector3f;\ntypedef Eigen::Matrix 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 v(data,4);\n std::vector data1 = {1,2,3,4,5,6,7,8,9};\n Eigen::Map 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": "/***********************************************************************\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* \n***********************************************************************/\n\n#ifndef R3LINALG_HPP_INCLUDED\n#define R3LINALG_HPP_INCLUDED\n\n#include \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 Matrix;\ntypedef blitz::TinyVector 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 double norm(const V&);\ntemplate double distance(const V& u, const V& v);\ntemplate double dot(const V& u, const V& v);\ntemplate Vector cross(const V& u, const V& v);\nconst Vector& product(const Vector&, const Matrix&);\n\ntemplate \n bool MatricesAlmostEqual(const M& A, const M& B, double precision=0.0);\n\ntemplate \n bool VectorsAlmostEqual(const V& A, const V& B, double precision=0.0);\n\n\n////////////////////////////////////////////////////////////////////////\n// Definitions\n////////////////////////////////////////////////////////////////////////\n\n\ntemplate \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 \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 \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 \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 \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 \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 \n\n#include \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 \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 \n#include \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": "#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace Eigen;\n\n// ガウス分布の数\n#define K 2\n\n// 次元数\n#define D 2\n\n// データの数\n#define N 10\n\n#define PI 4*atan(1.0)\n\n// TODO: D,1 にする\ntypedef Eigen::Matrix m_d;\n\n// 多次元 (多変量) ガウス分布\nfloat gaussian(m_d& x, m_d& mu, Matrix& 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& pi,\n std::vector& x,\n std::vector& mu,\n std::vector >& sigma\n) {\n float s = 0.0;\n for(int n=0; n にする\n // TODO: 実際に使えるデータを用意する\n // N 行 D 列\n std::vector x(N, m_d::Random());\n\n // 平均 mu, 分散 sigma, 混合係数 pi を初期化する\n // 平均\n /*\n [\n [mu_x, mu_y], // 次元数 (D) 個\n [mu_x, mu_y],\n ... K 個\n ]\n ガウス分布 K に対する, X軸の平均,Y軸の平均 ...\n */\n std::vector mu(K, m_d::Zero());\n\n std::random_device rd;\n std::mt19937 mt(rd());\n std::uniform_real_distribution distribution(0.0, 1.0);\n\n // 分散 (分散共分散行列)\n // D x D 行列\n Matrix v;\n for(int i=0;i > sigma(K, Matrix(v.asDiagonal()));\n\n // TODO: 制約 Sigma(k) pi_k = 1 を満たすように初期化する\n std::vector pi(K);\n for(int i=0; i > gamma(N, std::vector(K));\n\n // 尤度\n float like = likelihood(pi, x, mu, sigma);\n\n while(true) {\n // E-step: パラメータ (mu, sigma, pi) を使って負担率 gamma を計算する\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: 負担率を使ってパラメータを更新する\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 // 平均\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 // 分散\n Matrix _sigma = Matrix::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 // 混合係数\n pi[k] = Nk / N;\n\n }\n\n // TODO: x と mu の値が同じになる問題, x の初期値に Random を使っているせい ?\n std::cout << x[0] << \"\\n\" << mu[0] << \"\\n\" << sigma[0] << std::endl;\n\n // 収束性の確認\n // 対数尤度関数 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/*!\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();\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 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();\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 \n#include \n#include \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 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 // cpp_int\n\n#include // assert\n#include // cout\n#include // 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 \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \"dataImport.h\"\r\n\r\n// parallel computing library: OpenOMP library\r\n// #include \r\n\r\n// generate increaseing sequence\r\n#include \r\n\r\n#include \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& A, vector& 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 >& X, vector& theta, vector& 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 >& X, vector& theta, vector& sum, \r\n\tvector& 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 >& X, vector >& sum, vector& theta,\r\n\tvector& y, double lambda, float startTime){\r\n\tsum.clear();\r\n\tvector 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 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 > local_sum;\r\n\t\tvector 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 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 > X;\r\n vector 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 theta(d + 1, 0);\r\n\tvector theta2(d + 1, 0);\r\n\r\n\tfor (int itr = 0; itr < iteration; itr++)\r\n\t{\r\n\t\tvector 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 > 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 cg;\r\n\t\tcg.compute(A);\r\n\t\tx = cg.solve(b);\r\n\r\n\t\t//vector > 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 \n#include \n#include \n\ntypedef std::pair trainingData;\n\nclass Network {\npublic:\n explicit Network(std::vector 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 &trainingSet, const int epochs,\n const int miniBatchSize, const double eta);\n void updateMiniBatch(std::vector &miniBatch,\n const double eta);\n void backprop(arma::vec &in, arma::vec &out, std::vector &partialB,\n std::vector &partialW);\n arma::vec costDerivative(arma::vec &out, arma::vec &y);\n\nprivate:\n Network(){};\n\n int layerNumber;\n std::vector sizes;\n // biases[i] represents bias at (i+1)th layer\n std::vector biases, biasesShape;\n // weights[i] represents weight from ith layer to (i+1)th layer\n std::vector 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": "/**\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 \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace AdvectionFV2D {\n\n/* SAM_LISTING_BEGIN_1 */\nEigen::Matrix gradbarycoordinates(\n const Eigen::Matrix &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>>\ncomputeCellNormals(std::shared_ptr mesh_p) {\n // Appears only in mastersolution\n\n // Initialize datastruture for the result\n lf::mesh::utils::CodimMeshDataSet>\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 normal_vectors(2, 3);\n\n // Compute normal vectors\n Eigen::Matrix 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 normal_vectors(2, 4);\n\n // Split the quadrilateral into two triangles (1,2,3) and (1,3,4)\n Eigen::Matrix tria_1;\n Eigen::Matrix 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 bary_coord_1 = gradbarycoordinates(tria_1);\n Eigen::Matrix 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>>(result);\n\n}\n/* SAM_LISTING_END_2 */\n\n/* SAM_LISTING_BEGIN_3 */\nstd::shared_ptr<\n lf::mesh::utils::CodimMeshDataSet>>\ngetAdjacentCellPointers(std::shared_ptr mesh_p) {\n // Initialize auxilary object\n lf::mesh::utils::CodimMeshDataSet>\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>\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>>(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 mesh_p) {\n // Vector to store the distances between cells\n std::vector min_h;\n\n // Get Adjectent Cells\n std::shared_ptr>>\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 \n#include \n#include \n\n#include \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 \n#include \n#include \n\nusing namespace Eigen;\n\nnamespace{\ntemplate\nvoid Print_Formatted(const T_MATRIX& A,std::ostream& output)\n{\n for(int i=0;i\nvoid Singular_Value_Decomposition_Reference(const T A[9], T U[9], T Sigma[3], T V[9])\n{\n Map> mA=Map>(A);\n\n Map> mU=Map>(U);\n Map> mSigma=Map>(Sigma);\n Map> mV=Map>(V);\n\n JacobiSVD> 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\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> mU=Map>(U);\n Map> mSigma=Map>(Sigma);\n Map> mV=Map>(V);\n\n Map> mU_reference=Map>(U_reference);\n Map> mSigma_reference=Map>(Sigma_reference);\n Map> mV_reference=Map>(V_reference);\n\n Matrix mU_adjusted = mU_reference;\n Matrix mSigma_adjusted = mSigma_reference;\n Matrix 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 :\"< mA=mU*mSigma.asDiagonal()*mV.transpose();\n Matrix mA_reference=mU_reference*mSigma_reference.asDiagonal()*mV_reference.transpose();\n\n std::cout<\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 \n#include \n\n/** @class \n * @brief Linear interpolation for 2D functions.\n * @author C.D. Clark III, Aaron Hoffman\n */\n\nnamespace _2D {\n\ntemplate\nclass BilinearInterpolator : public InterpolatorBase>\n{\n public:\n using BASE = InterpolatorBase>;\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;\n using Matrix22Array = Eigen::Array< Matrix22, Eigen::Dynamic, Eigen::Dynamic >;\n using ColVector2 = Eigen::Matrix;\n using RowVector2 = Eigen::Matrix;\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\n BilinearInterpolator( I n, Real *x, Real *y, Real *z ) {this->setData(n,x,y,z);}\n\n template\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(lhs), static_cast(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\nvoid\nBilinearInterpolator::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\nReal\nBilinearInterpolator::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 \n#include \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 &dst_x,\n std::vector &dst_y,\n const std::vector &src_x,\n const std::vector &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": "/*****************************************************************************\n * array.cpp Blitz++ Array stencilling example\n *****************************************************************************/\n\n#include \n\nBZ_USING_NAMESPACE(blitz)\n\nint main()\n{\n int N = 64;\n\n // Create three-dimensional arrays of float\n Array 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(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 \n#include \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 \nusing namespace std;\n\n#include \n#include \n#include \nusing namespace Eigen;\n\n#define MATRIX_SIZE 50\n\nint main(int argc, char **argv)\n{\n Matrix matrix_23;\n Vector3d v_3d;\n Matrix vd_3d;\n Matrix3d matrix_33 = Matrix3d::Zero();\n Matrix 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 result = matrix_23.cast() * 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 \n#include \n\n#include \n#include \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(xp, t_loc);\n yp_loc = pear::extract(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 \n#include \n#include \n#include \n#include \n#include \n\nint main()\n{\n constexpr otf::FunctionType type = otf::FunctionType::Rosenbrock;\n constexpr int dimensions = 100;\n\n std::srand(static_cast(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 \n#include \n#include \n#include \n\n#include \n#include \n#include \n\nnamespace odeint = boost::numeric::odeint;\n\ntypedef std::array 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\nstd::pair\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());\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::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 \n#include \n#include \n#include \n#include \n\ntemplate\nstd::vector multiply_complex(\n const std::vector& A, \n const std::vector& B)\n{\n const std::size_t N = A.size();\n std::vector< Complex > TA(N),TB(N);\n boost::math::fft::bsl_rdft 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 C(N);\n \n for(unsigned int i=0;i\nReal difference(const std::vector& A, const std::vector& B)\n{\n using std::abs;\n Real diff{};\n if(A.size()!=B.size()) return -1;\n for(unsigned int i=0;i\nvoid multiply() {\n using std::abs;\n std::vector A{1.,4.,-5.,1.,0.,0.,0.,0.};\n std::vector B{-1.,1.,2.,3.,0.,0.,0.,0.};\n std::vector C{-1,-3,11,5,3,-13,3,0};\n \n std::vector result;\n Real diff;\n \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<\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 \n#include \n#include \n#include \n\nEigen::MatrixXd sigmoid(Eigen::MatrixXd mat){\n int r = mat.rows() ; int c = mat.cols();\n for (int i=0; i biases;\n std::vector weights;\n int num_layers;\n std::vector sizes;\n\n NeuralNetwork(std::vector 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\n#include \n#include \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 \ninline std::vector scale(const std::vector& 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 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 \ninline std::vector scale_clip(const std::vector& 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 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 &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 dur2x( std::vector & vec)\n{\n std::vector 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 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 x, std::vector y );\n\nEigen::ArrayXd lineLookup( const Eigen::ArrayXd& t, const std::vector& x, const std::vector& y );\n\ntemplate \nstd::vector aseq(T from, T to, T step = 1)\n{\n std::vector 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 \n#include \n\nnamespace icarus\n{\n template\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 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 mean() const\n {\n return mMean;\n }\n\n Eigen::Matrix variance() const\n {\n return mMoment / mSampleSize;\n }\n private:\n size_t mSampleSize;\n size_t mSampleNumber;\n Eigen::Matrix mMean;\n Eigen::Matrix 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 \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\ninline void ignoreExtraInputs() {\r\n\tstd::cin.ignore(std::numeric_limits::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 decimalToBinaryReturningArray(int decInput) {\r\n\r\n\tint exponent = 0;\r\n\tint previousExponent = 0;\r\n\tstd::vector 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 nibbleGuaranteeer(std::vector sub_h_binInput, int requiredSize)\r\n{\r\n\tint binaryLength = requiredSize;\r\n\tstd::vector 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 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 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 \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 .\n------------------------------------------------------------------------\n*/\n\n#ifndef __TEST_FUNCTIONS_HPP__\n#define __TEST_FUNCTIONS_HPP__\n\n#define _USE_MATH_DEFINES\n#include \n#include \n#include \n#include \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();\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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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 (_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(),\n\t\t\t\t\t\"first parameter\")\t\t\t\n (\"second,b\", po::value(),\n\t\t\t\t\t\"second parameter\")\n\t\t\t\t(\"third,c\", po::value(),\n\t\t\t\t\t\"third parameter\")\t\t\t\t\n (\"number,n\", po::value(&N)->default_value(100)->implicit_value(500),\n\t\t\t\t\t\"number of data\") \n (\"iteration,i\", po::value(&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(&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 ​​should 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();\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();\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();\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 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 > Block; \n //zouma\n // Linear equation solver\n std::unique_ptr linearSolver \n\t\t\t\t(new g2o::LinearSolverDense());\n\n // Matrix block solver\n std::unique_ptr 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; isetId(i);\n edge->setVertex( 0, v ); // Set the connected vertices\n edge->setMeasurement( y_data[i] ); // Observed value\n edge->setInformation( Eigen::Matrix::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 time_used = std::chrono::duration_cast>( t2-t1 );\n std::cout<<\"solve time cost = \"<estimate();\n std::ofstream mySol;\n mySol.open (&pathParameter[0]);\n mySol<<\"estimated model a, b, c: \"<\n#include \n#include \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(eigen_end - eigen_begin).count() / pow(10,9) << \" STRASSEN: \" << std::chrono::duration_cast(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 \nusing namespace Eigen;\n\n#include \n#include \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\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 \n\n__BEGIN_LIBRARIES_DISABLE_WARNINGS\n#include \n__END_LIBRARIES_DISABLE_WARNINGS\n\nnamespace AdventOfCode\n{\nnamespace Year2019\n{\nnamespace Day22\n{\n\nSlamShuffler::SlamShuffler(std::vector 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 SlamShuffler::getAllCardsAfterSingleIteration()\n{\n std::vector 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": "#include \n#include \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 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 \n\n#include // 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 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": "//EuropeanOption.cpp\n\n//Modification date: 6/17/15\n\n#include \"EuropeanOption.hpp\"\n#include \"GlobalFunctions.hpp\"\n#include \n#include \n#include \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=\" < EuropeanCallOption::Price(double LowerLimit, double UpperLimit, int Num, FunctionPointer Ptr)\n{\n\tvector mesh = MeshArray(LowerLimit, UpperLimit, Num);\n\t\n\tvector result;\n\tresult.reserve(mesh.size());\n\t\n\tfor (vector::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 EuropeanPutOption::Price(double LowerLimit, double UpperLimit, int Num, FunctionPointer Ptr)\n{\n\tvector mesh = MeshArray(LowerLimit, UpperLimit, Num);\n\n\tvector result;\n\tresult.reserve(mesh.size());\n\n\tfor (vector::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": "/* 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 \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n\n#include \n#include \n#include // infinity\n#include // for pair\n#include // for transform\n\n\n// Types definition\nusing Simplex_tree = Gudhi::Simplex_tree;\nusing Filtration_value = Simplex_tree::Filtration_value;\nusing Rips_complex = Gudhi::rips_complex::Rips_complex;\nusing Field_Zp = Gudhi::persistent_cohomology::Field_Zp;\nusing Persistent_cohomology = Gudhi::persistent_cohomology::Persistent_cohomology;\nusing Kernel = CGAL::Epick_d< CGAL::Dynamic_dimension_tag >;\nusing Point_d = Kernel::Point_d;\nusing Points_off_reader = Gudhi::Points_off_reader;\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 compute_root_square(std::pair 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 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(&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(&threshold)->default_value(std::numeric_limits::infinity()),\n \"Maximal length of an edge for the Rips complex construction.\")\n (\"cpx-dimension,d\", po::value(&dim_max)->default_value(1),\n \"Maximal dimension of the Rips complex we want to compute.\")\n (\"field-charac,p\", po::value(&p)->default_value(11),\n \"Characteristic p of the coefficient field Z/pZ for computing homology.\")\n (\"min-persistence,m\", po::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& 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& 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 \nusing std::vector;\n#include \nusing ::sin;\n//#include // for BOOST_ASSERT\n#include \n\n#include \nusing boost::svg::quantile;\n\n// double boost::svg::quantile(vector& 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 \n using boost::array;\n\n#include \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 Hoaglin_data = {53., 56., 75., 81., 82., 85., 87., 89., 95., 99., 100.};\n // q1 median q3\n\n vector 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 Hoaglin4(Hoaglin_data.begin(), Hoaglin_data.end());\n vector Hoaglin5(Hoaglin_data.begin(), Hoaglin_data.end());\n vector Hoaglin6(Hoaglin_data.begin(), Hoaglin_data.end());\n vector Hoaglin7(Hoaglin_data.begin(), Hoaglin_data.end());\n vector 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 \n#include \n#include \n\n#include \"geometry/matrix.h\"\n\nnamespace gca {\n\n int determinant_sign(const ublas::permutation_matrix& 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 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(a.size1());\n ublas::permutation_matrix 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 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": "/**\n *@file main.cpp\n */\n\n#include \n#include \n#include \"Poly.h\"\n#include \"Basis.h\"\n#include \"Density.h\"\n#include \"time.h\"\n\n/**\n * @mainpage Calcul et tracé de la densité d'un système nucléaire\n *# Densité nucléaire 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ée\n *et \\f[\\psi_a(\\mathbf{r})\\f] la fonction d'onde solution de l'équation de Schrödinger 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ödinger\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ées nécessaires pour tracer les grraphes\n *\n *@return la fonction créer 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é 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é 2D===\" << std::endl;\n //Calcul de la densité 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é 3D===\" << std::endl;\n //Calcul de la densité 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écuter 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\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 \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;\n using SplineCoefficients = typename SplineImplementation::SplineCoefficients;\n using EigenTimeVectorType = Eigen::Matrix;\n using EigenCoefficientVectorType = Eigen::Matrix;\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(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 timeVec, double tk) {\n timeVec = Eigen::Map(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 dtimeVec, double tk) {\n dtimeVec = Eigen::Map(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 ddtimeVec, double tk) {\n ddtimeVec = Eigen::Map(SplineImplementation::ddtau(tk).data());\n }\n\n //! Get the time vector tau evaluated at zero.\n static inline void getTimeVectorAtZero(Eigen::Ref timeVec) {\n timeVec = Eigen::Map((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 dtimeVec) {\n dtimeVec = Eigen::Map((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 ddtimeVec) {\n ddtimeVec = Eigen::Map((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": "/**\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 \n#include \n#include \n#include \n#include \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 SolvePredPreyTaylor(const PredPreyModel& model,\n double T,\n const Eigen::Vector2d& y0,\n unsigned int M) {\n std::vector 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 \n#include \n#include \n#include \n#include \n#include \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 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 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 \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, 3, 3>& M,\n Eigen::Matrix, 3, 3>& U,\n Eigen::Matrix, 3, 1>& D,\n Eigen::Matrix, 3, 3>& V);\nvoid svd_UDV(const Eigen::Matrix, 3, 3>& M,\n Eigen::Matrix, 3, 3>& U,\n Eigen::Matrix, 3, 1>& D,\n Eigen::Matrix, 3, 3>& V);\nvoid svd_UDV(const Eigen::Matrix, 3, 3>& M,\n Eigen::Matrix, 3, 3>& U,\n Eigen::Matrix, 3, 1>& D,\n Eigen::Matrix, 3, 3>& V);\n\nvoid svd_UDV(\n const Eigen::\n Matrix, Eigen::Dynamic, Eigen::Dynamic>& M,\n Eigen::Matrix, Eigen::Dynamic, Eigen::Dynamic>& U,\n Eigen::Matrix, Eigen::Dynamic, 1>& D,\n Eigen::Matrix, Eigen::Dynamic, Eigen::Dynamic>&\n V);\n\nvoid svd_UDV(\n const Eigen::Matrix, Eigen::Dynamic, Eigen::Dynamic>&\n M,\n Eigen::Matrix, Eigen::Dynamic, Eigen::Dynamic>& U,\n Eigen::Matrix, Eigen::Dynamic, 1>& D,\n Eigen::Matrix, Eigen::Dynamic, Eigen::Dynamic>& V);\n\nvoid svd_UDV(\n const Eigen::Matrix, Eigen::Dynamic, Eigen::Dynamic>& M,\n Eigen::Matrix, Eigen::Dynamic, Eigen::Dynamic>& U,\n Eigen::Matrix, Eigen::Dynamic, 1>& D,\n Eigen::Matrix, 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 struct CentreEigenVectorResult\n{\n T C; // centre\n vector> Es; // {eigenvectors, eigenvalues}\n};\n\ntemplate\nauto calc_centre_and_eigenvectors(InputIt begin, InputIt end)\n -> CentreEigenVectorResult<\n typename std::iterator_traits::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 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 inline unsigned matrix_rank(const T& M)\n{\n Eigen::FullPivLU lu(M);\n return lu.rank();\n}\n\n// ------------------------------------------------------------------ null space\ntemplate inline T matrix_kernel(const T& M)\n{\n Eigen::FullPivLU 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\nauto calc_centre_and_eigenvectors(InputIt begin, InputIt end)\n -> CentreEigenVectorResult<\n typename std::iterator_traits::value_type>\n{\n using T = typename std::iterator_traits::value_type;\n using Ret = CentreEigenVectorResult;\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 SVD3DRet svd_3d_UDV(InputIt start, InputIt finish)\n{\n using T = typename std::iterator_traits::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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \nusing adept::adouble;\nusing adept::aMatrix;\nusing adept::aVector;\n\nusing adept::Vector;\n\nextern int enzyme_const;\ntemplate\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 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}\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(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\r\n#include \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 \n#include \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(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 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 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 \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 \r\n#include \r\n#include \r\n\r\n#include \r\n\r\nnamespace interpol {\r\n\r\ntemplate\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\r\nclass DH1Tangent\r\n{\r\npublic:\r\n DH1Tangent(const Eigen::Quaternion& r,const Eigen::Quaternion& d) : m_real(r), m_dual(d) {}\r\n\r\n // dqTangent * scalar\r\n DH1Tangent operator*(const T& scale) const{\r\n DH1Tangent 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 expScrewBen(void) const;\r\n DH1 expScrew(void) const;\r\n DH1 expT(bool useBenKenwrightImpl=false) const{\r\n return useBenKenwrightImpl ? expScrewBen() : expScrew();\r\n }\r\n\r\n Eigen::Quaternion m_real; // real part\r\n Eigen::Quaternion m_dual; // dual part\r\n\r\n DH1 toDH(void){//for derivative\r\n return DH1(m_real,m_dual);\r\n }\r\n};\r\n\r\n// scalar * dqTangent\r\ntemplate\r\ninline DH1Tangent operator*(T scale, DH1Tangent t){\r\n t.m_real.w() *= scale;\r\n t.m_dual.w() *= scale;\r\n return t;\r\n}\r\ntypedef DH1Tangent DH1Tangentf;\r\ntypedef DH1Tangent DH1Tangentd;\r\n\r\n\r\n\r\ntemplate\r\nDH1\r\noperator+(const DH1& dq1, const DH1& dq2);\r\n\r\ntemplate\r\nclass DH1\r\n{\r\npublic:\r\n DH1(){}\r\n DH1(const Eigen::Quaternion& r,\r\n const Eigen::Quaternion& d) : DH1(px::DualQuaternion(r,d)) {}\r\n DH1(const Eigen::Quaternion& r,\r\n const Eigen::Matrix& t) : DH1(px::DualQuaternion(r,t)) {}\r\n\r\n\r\n void fromScrew(T theta, T d,\r\n const Eigen::Matrix& l,\r\n const Eigen::Matrix& m);\r\n void toScrew (T& theta, T& d, //added by us\r\n Eigen::Matrix& l,\r\n Eigen::Matrix& m) const;\r\n\r\n\r\n DH1Tangent logScrewBen(void) const;\r\n DH1Tangent logScrew(void) const;\r\n DH1Tangent logT(bool useBenKenwrightImpl=false) const{\r\n return useBenKenwrightImpl ? logScrewBen() : logScrew();\r\n }\r\n\r\n DH1 conjugate(void) const { return DH1(dq.conjugate());}\r\n DH1 normalized(void) const {return DH1(dq.normalized());}\r\n Eigen::Quaternion real() const {return dq.real();}\r\n Eigen::Quaternion dual() const {return dq.dual();}\r\n Eigen::Quaternion rotation(void) const {return dq.rotation();}\r\n Eigen::Matrix translation(void) const {return dq.translation();}\r\n DH1 operator*(T scale) const {return DH1(dq*scale);}\r\n DH1 operator*(const DH1& other) const {return DH1(dq*other.dq);}\r\n friend DH1 operator+<>(const DH1& dq1, const DH1& dq2);\r\n\r\n DH1& operator*=(const DH1& other);//added by us\r\n\r\n\r\nprivate:\r\n DH1(const px::DualQuaternion& dq) : dq(dq) {}\r\n px::DualQuaternion dq;\r\n //there must be a mistake here for the dual part....\r\n //DH1 exp(void) const;\r\n //DH1 exp(const DH1 base) const;\r\n //px::DualQuaternion log(void) const;\r\n //px::DualQuaternion log(const px::DualQuaternion &b) const;\r\n};\r\n\r\ntemplate\r\nDH1&\r\nDH1::operator*=(const DH1& other)\r\n{\r\n dq = dq * other.dq;\r\n return *this;\r\n}\r\n\r\ntemplate\r\nDH1\r\noperator+(const DH1& dh1, const DH1& dh2)\r\n{\r\n return DH1(dh1.dq+dh2.dq);\r\n}\r\n\r\ntemplate\r\nvoid\r\nDH1::fromScrew(T theta, T d,\r\n const Eigen::Matrix& l,\r\n const Eigen::Matrix& 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(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\r\nvoid\r\nDH1::toScrew(T& theta, T& d,\r\n Eigen::Matrix& l,\r\n Eigen::Matrix& m) const\r\n{\r\n\r\n Eigen::AngleAxis 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\r\nDH1Tangent\r\nDH1::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(realTangent, dualTangent);\r\n}\r\n\r\n//Second half of ScLERPGeometricCosSin\r\ntemplate\r\nDH1\r\nDH1Tangent::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(real, dual);\r\n}\r\n\r\n\r\ntemplate\r\nDH1Tangent\r\nDH1::logScrew(void) const\r\n{\r\n T theta,d;\r\n Eigen::Matrix 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 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=\"<(real, dual);\r\n}\r\n\r\ntemplate\r\nDH1\r\nDH1Tangent::expScrew(void) const\r\n{\r\n DH1 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 DH1f;\r\ntypedef DH1 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//\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 \nusing namespace std;\n\n#include \n#include \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 \nT angleT( Eigen::Matrix& v1, Eigen::Matrix& v2 ) {\n Eigen::Matrix 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 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 \n#include \n#include \n#include \"kron.hpp\"\n\n\nEigen::SparseMatrix buildC(const Eigen::MatrixXd &A){\n\tint n= A.cols();\n\tEigen::SparseMatrix 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 > triplets;\n\tfor (int i=0; i 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 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 > 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 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": "#include \"writer.hpp\"\n#include \n#include \n#include \n#include \n#include \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\nupwindFD(const Eigen::VectorXd &u0,\n double dt,\n double T,\n const std::function &a,\n const std::pair &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\ncenteredFD(const Eigen::VectorXd &u0,\n double dt,\n double T,\n const std::function &a,\n const std::pair &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{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 \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 \n#include \n#include \n#include \n#include \n#include \n#include \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<\n#include \n#include \n#include \n#include \n#include \n#include \n\ntypedef boost::multiprecision::number, 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::lowest())) | \n (range_min > cpp_bin_float_80(std::numeric_limits::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::lowest() << \", \" << std::numeric_limits::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::lowest())) |\n (range_max > cpp_bin_float_80(std::numeric_limits::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::lowest() << \", \" << std::numeric_limits::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::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::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(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::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::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::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::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::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::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::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::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::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::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::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::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::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::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::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::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::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::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::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::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::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::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::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::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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\ntypedef CGAL::Triangulation_vertex_base_with_info_2 Vb;\ntypedef CGAL::Triangulation_data_structure_2 Tds;\ntypedef CGAL::Delaunay_triangulation_2 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 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 \"\n << \" \" << 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> 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::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::New();\n ptsArr->SetVoidArray((void *)positions.data(), 3 * N, 1);\n ptsArr->SetNumberOfComponents(3);\n auto pts = vtkSmartPointer::New();\n pts->SetData(ptsArr);\n auto poly = vtkSmartPointer::New();\n poly->SetPoints(pts);\n poly->SetPolys(triangles);\n auto normArr = vtkSmartPointer::New();\n normArr->SetVoidArray((void *)normals.data(), 3 * N, 1);\n normArr->SetNumberOfComponents(3);\n poly->GetPointData()->SetNormals(normArr);\n auto wr = vtkSmartPointer::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": "#include \nusing namespace std;\n\n#include \n#include \n\nint main( int argc, char** argv )\n{\n Eigen::Matrix matrix_23;\n Eigen::Vector3d v_3d;\n Eigen::Matrix 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 result = matrix_23.cast() * v_3d;\n cout << result << endl;\n\n Eigen::Matrix 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 \n#include \n#include \n#include /* srand, rand */\n#include /* time */\n#include \"logistic_function.hpp\"\n#include \"neural.hpp\"\nusing matrix=arma::Mat;\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 \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\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 \n#include \n#include \n#include \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());\n std::cout << \"φ ≈ \" << phi_cfrac << \"\\n\\n\";\n\n auto pi_cfrac = simple_continued_fraction(pi());\n std::cout << \"π ≈ \" << 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());\n std::cout << \"√2 ≈ \" << rt_cfrac << \"\\n\\n\";\n\n auto e_cfrac = simple_continued_fraction(e());\n std::cout << \"e ≈ \" << 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());\n std::cout << \"ζ(3) ≈ \" << 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": "#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\ntypedef CGAL::Interpolation_gradient_fitting_traits_2 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 \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, K,\n CGAL::Regular_triangulation_vertex_base_2 > Vb;\ntypedef CGAL::Regular_triangulation_face_base_2 Fb;\ntypedef CGAL::Triangulation_data_structure_2 Tds;\ntypedef CGAL::Regular_triangulation_2 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\n {\n return std::make_pair(a->info().value, true);\n };\n\n auto gradient_function = [](const Vertex_handle& a) -> std::pair\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& 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 >(),\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 > coords;\n typedef CGAL::Identity > 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 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 \n#include \n#include \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& 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(A.transpose() * A + lambda * I).solve(A.transpose() * b);\n }\n else\n {\n solution = PartialPivLU(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(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 \n#include \n#include \n\n//Eigen includes\n#include \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 voxel_traversal(Eigen::Vector3d ray_start, Eigen::Vector3d ray_end) {\n std::vector 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 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 \n#include \n#include \n#include \n\n#include \"fluxlimitedfv.h\"\n\ntypedef std::numeric_limits 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": "#pragma once\n\n#include \n#include \n#include \n#include \n#include \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 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 &des_ori, Eigen::Quaternion &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": "// Fractool\n#include \n#include \n\n// Internal\n#include \n#include \n\n// External\n#include \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 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 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(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 \n#include \n#include \n#include \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 \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 \n#include \n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n cout.precision(3);\n Vector2f v = Vector2f::Random();\nJacobiRotation 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": "#include \n#include \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 // cpp_int\n\n#include // 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": "// 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 \n#include \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 \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 initialize_binom_probs(int N, float p){\n std::vector probs = std::vector(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 initialize_beta_binom_probs(int N, float prior_0, float prior_1){\n std::vector probs = std::vector(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 © 2020 Zhehao Li. All rights reserved.\n//\n\n#include \"EuropeanOption.hpp\"\n#include \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 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 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 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 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 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 \n#include \n#include \n\n#include \n#include \n#include \n\n#include \"types/types.hpp\"\n\nnamespace ublas = boost::numeric::ublas;\n\nvoid AngularGauss::InvMatrix(const ublas::matrix& input_mat, ublas::matrix& inverse_mat) {\n ublas::matrix A(input_mat);\n\n ublas::permutation_matrix 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(A.size1()));\n lu_substitute(A, pm, inverse_mat);\n}\n\ndouble AngularGauss::Det(const ublas::matrix& 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& 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(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 AngularGauss::Mean(void) const {\n return std::array{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 \n#include \n#include \n#include \n#include \n#include \n\n// O(NlogN)\nint kthMin1(std::vector& 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& data, int k) {\n std::priority_queue 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& 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& 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& 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> createVectors(int row, int col) {\n static std::uniform_int_distribution distribution(\n std::numeric_limits::min(),\n std::numeric_limits::max()\n );\n static std::default_random_engine generator;\n\n std::vector 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 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": "/***********************************************************************\nThis file is part of the librjmcmc project source files.\n\nCopyright : Institut Geographique National (2008-2012)\nContributors : Mathieu Brédif, 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 \n#include \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 rand_distribution_type;\n typedef boost::math::gamma_distribution 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\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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nusing namespace NTL;\n\n//ex. compile:\n//g++ -o 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 remainder_alg_first_pass.cpp\n// ./\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 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 & 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 & 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 zero_vector(int N)\n{\n\tVec 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 product_tree(Vec &X, Vec &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 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 accumulating_tree(Vec &X, Vec &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 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 accumulating_remainder_tree(Vec &A, Vec &m)\n{\n\tassert (A.length() == m.length());\n\n\tint depth = log2(A.length());\n\n\tVec ztree = zero_vector(2*m.length()-1);\n\n\tVec m_ptree = product_tree(m, ztree);\n\n\t//print_tree(m_ptree);\n\treflect_tree(m_ptree);\n\tVec m_acctree = accumulating_tree(m_ptree, ztree);\n\treflect_tree(m_acctree);\n\treflect_tree(m_ptree);\n\n\t//Vec 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 A_ptree = product_tree(A, m_acctree);\n\t//delete m_acctree;\n\n\t//print_tree(A_ptree);\n\n\tVec 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 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 A;\n\tVec m;\n\n\tA.SetLength(N);\n\tm.SetLength(N);\n\n\trandom_device rd;\n\tmt19937 mt(rd());\n\tuniform_int_distribution 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 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 remainders = accumulating_remainder_tree(A,m);\n\tauto finish = chrono::high_resolution_clock::now();\n\n\tchrono::duration 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 © 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ₒ = 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 \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(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(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 \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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 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(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 \n#include \n#include \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 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::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 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 \r\n#include \r\n#include \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;i1) 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 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 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 g;\r\n g = boost::bind(boost::mem_fn(&EarlyExercise::operator()),&ut,_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 \n\n#include \n#include \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 &estimations,\n const vector &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 estimations_map(reinterpret_cast(estimations.data()),\n 4, data_size);\n Eigen::Map ground_truth_map(reinterpret_cast(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 Tools::CalculateJacobian(const VectorXd& x_state) {\n auto J = Eigen::Matrix();\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 \n#include \n#include \n#include \n#include \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 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 w1,\n\tstd::function 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 \n#include \n#include \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*\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 \n#include \n#include \n#include \n\nnamespace rokko {\n\nclass laplacian_matrix {\npublic:\n template\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\n static void multiply(int dim, const std::vector& v, std::vector& w) {\n multiply(dim, &v[0], &w[0]);\n }\n\n template\n static void generate(rokko::localized_matrix& 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 \n#include \n#include \"OptionData.hpp\" \n#include \"UtilitiesDJD/RNG/NormalGenerator.hpp\"\n#include \"UtilitiesDJD/Geometry/Range.cpp\"\n#include \n#include \n\ntemplate void print(const std::vector& 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::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 \nboost::tuple SDSE(const std::vector& 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 TupleFive;\n\tvector 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 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 range(0.0, myOption.T);\n\t\tdouble VOld = S_0;\n\t\tdouble VNew;\n\n\t\tstd::vector 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 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 tupleCall = SDSE(vecCallPrice, myOption.r, myOption.T);\n\t\tboost::tuple tuplePut = SDSE(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// (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 \n#include \n#include \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 \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(pow(fabs(sin_theta), T(m))), pol);\n \n T prefix = boost::math::tgamma_delta_ratio(static_cast(n - m + 1), static_cast(2 * m), pol);\n prefix *= (2 * n + 1) / (4 * constants::pi());\n prefix = sqrt(prefix);\n return prefix * leg;\n}\n//\n// Real Part:\n//\ntemplate \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()));\n if(mod < 0)\n mod += 2 * constants::pi();\n if(mod > constants::pi())\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 \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()));\n if(mod < 0)\n mod += 2 * constants::pi();\n if(mod > constants::pi())\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 \nstd::complex 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());\n if(mod < 0)\n mod += 2 * constants::pi();\n if(mod > constants::pi())\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(policies::checked_narrowing_cast(r, function), policies::checked_narrowing_cast(i, function));\n}\n\n} // namespace detail\n\ntemplate \ninline std::complex::type> \n spherical_harmonic(unsigned n, int m, T1 theta, T2 phi, const Policy& pol)\n{\n typedef typename tools::promote_args::type result_type;\n typedef typename policies::evaluation::type value_type;\n return detail::spherical_harmonic(n, m, static_cast(theta), static_cast(phi), pol);\n}\n\ntemplate \ninline std::complex::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 \ninline typename tools::promote_args::type \n spherical_harmonic_r(unsigned n, int m, T1 theta, T2 phi, const Policy& pol)\n{\n typedef typename tools::promote_args::type result_type;\n typedef typename policies::evaluation::type value_type;\n return policies::checked_narrowing_cast(detail::spherical_harmonic_r(n, m, static_cast(theta), static_cast(phi), pol), \"bost::math::spherical_harmonic_r<%1%>(unsigned, int, %1%, %1%)\");\n}\n\ntemplate \ninline typename tools::promote_args::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 \ninline typename tools::promote_args::type \n spherical_harmonic_i(unsigned n, int m, T1 theta, T2 phi, const Policy& pol)\n{\n typedef typename tools::promote_args::type result_type;\n typedef typename policies::evaluation::type value_type;\n return policies::checked_narrowing_cast(detail::spherical_harmonic_i(n, m, static_cast(theta), static_cast(phi), pol), \"boost::math::spherical_harmonic_i<%1%>(unsigned, int, %1%, %1%)\");\n}\n\ntemplate \ninline typename tools::promote_args::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 \n#include \n\n\nvoid eigenValueSolver()\n{\n // ComplexEigenSolver ces;\n Eigen::EigenSolver 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:\" < 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": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \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::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::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 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 \" << 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(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": "#ifndef RKIMPLEMENTER\n\n#define RKIMPLEMENTER\n\n#include \n#include \n\n\n\n\n/**\n * \n * Implementation of an explicit Runge Kutta Solver. See the documentation for more information.\n * \n */\ntemplate 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\n std::vector solve(Function &&f, double time, const Step &y0, unsigned int steps){\n\n std::vector 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\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 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 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\n std::vector solve(Function &&f, Jacobian && J, double time, const Step &y0, unsigned int steps){\n\n std::vector 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\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\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 \n#include \n\n#include \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(\n \"imu\", 10, std::bind(&Imu2rpy::imu_callback, this, _1));\n\n roll_publisher_ = this->create_publisher(\"roll\", 10);\n pitch_publisher_ = this->create_publisher(\"pitch\", 10);\n yaw_publisher_ = this->create_publisher(\"yaw\", 10);\n\n roll_rate_publisher_ = this->create_publisher(\"roll_rate\", 10);\n pitch_rate_publisher_ = this->create_publisher(\"pitch_rate\", 10);\n yaw_rate_publisher_ = this->create_publisher(\"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::SharedPtr imu_sub_;\n rclcpp::Publisher::SharedPtr roll_publisher_;\n rclcpp::Publisher::SharedPtr pitch_publisher_;\n rclcpp::Publisher::SharedPtr yaw_publisher_;\n rclcpp::Publisher::SharedPtr roll_rate_publisher_;\n rclcpp::Publisher::SharedPtr pitch_rate_publisher_;\n rclcpp::Publisher::SharedPtr yaw_rate_publisher_;\n};\n\nint main(int argc, char * argv[])\n{\n rclcpp::init(argc, argv);\n rclcpp::spin(std::make_shared());\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 \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 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(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 ¶meterize(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 \n\n/// \\file jacobian_determinant.hpp\n\nnamespace neon\n{\nnamespace detail\n{\ntemplate \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 \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": "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n// using Eigen::ArrayXi;\nusing namespace std;\n// using namespace arma;\nusing ArrayXL = Eigen::Array; \n\n\nstruct shannonEntropy {\n \n typedef unordered_map histoMap;\n// typedef unordered_map 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 \n#include \n#include \n\n#include \"stiffness_matrix.hpp\"\n\n//! Sparse Matrix type. Makes using this type easier.\ntypedef Eigen::SparseMatrix SparseMatrix;\n\n//! Used for filling the sparse matrix.\ntypedef Eigen::Triplet 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\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 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 \r\n#include \r\n#include \r\n#include \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 © 2020 Zhehao Li. All rights reserved.\n//\n\n#include \"EuropeanOption.hpp\"\n#include \n#include \n#include \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 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 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 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 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 \r\n\r\n#include \r\n#include \r\n#include \r\n\r\nint main()\r\n{\r\n typedef boost::geometry::model::d2::point_xy point_type;\r\n typedef boost::geometry::model::linestring 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": "#include \"AKS.hpp\"\n\n#include \"AKSCoefficient.hpp\"\n#include \"AKSPolynomial.hpp\"\n#include \"GMPWrappers.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \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::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(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(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(a);\n NTL::PowerMod(lhs, lhs, nNTL, module);\n lhs -= static_cast(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 \n#include \n#include \n\nstd::vector KolmogorovSmirnov::cdf(const std::vector & S, int & N)\n{\n std::vector 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 & S, \n\t\t\t const std::vector & X) \n{\n int N, M; \n std::vector Scdf = cdf(S, N);\n std::vector 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 \n#include \n\n#include \n#include \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& J_pose,\n Eigen::Matrix& 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& J_pose,\n Eigen::Matrix& 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& J_pose,\n Eigen::Matrix& 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& J_pose,\n Eigen::Matrix& J_calib,\n Eigen::Matrix& 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 J_pi;\n calib.projectJacobians(pi, J_calib, J_pi);\n\n Eigen::Matrix 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 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 // for std::size_t\n#include \n\n// Eigen linear algebra library headers\n#include \n\nnamespace jaco {\n\n template \n Eigen::Matrix\n transformation_matrix(const std::vector &masses) {\n const std::size_t n = masses.size();\n std::vector 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 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 \n Eigen::Matrix\n transformation_matrix_inverse(const std::vector &masses) {\n const std::size_t n = masses.size();\n std::vector 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 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 \n Eigen::Matrix\n inverse_mass_matrix(const std::vector &masses) {\n const std::size_t n = masses.size();\n const Eigen::Matrix u =\n transformation_matrix(masses);\n Eigen::Matrix 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 \n Eigen::Matrix\n reduced_inverse_mass_matrix(const std::vector &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 m =\n inverse_mass_matrix(masses);\n Eigen::Matrix 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 \n Eigen::Matrix\n pairwise_weights(const std::vector &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 v =\n transformation_matrix_inverse(masses);\n Eigen::Matrix 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 \n std::vector>\n permutation_matrices(\n const std::vector &masses,\n const std::vector> &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 u =\n transformation_matrix(masses);\n const Eigen::Matrix v =\n transformation_matrix_inverse(masses);\n std::vector> result;\n for (const auto &permutation : permutations) {\n Eigen::Matrix 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 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’s 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 \n#include \n#include \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(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 \n#include \n#include \n#include \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 > 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 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 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 const& p)\n -> std::pair >,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 \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \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 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 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 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 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 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": "// 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 \n#include \n// matrix generators\n#include \n#include \n\ntemplate\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::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 time_span = duration_cast>(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\nvoid CroutCycle(mtl::dense2D< sw::unum::posit >& A, mtl::dense_vector< sw::unum::posit >& x, mtl::dense_vector< sw::unum::posit >& 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 > 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 time_span = duration_cast>(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\nvoid CroutFDPCycle(mtl::dense2D< sw::unum::posit >& A, mtl::dense_vector< sw::unum::posit >& x, mtl::dense_vector< sw::unum::posit >& 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 > 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 time_span = duration_cast>(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\nvoid ComparePositDecompositions(std::vector< sw::unum::posit >& A, std::vector< sw::unum::posit >& x, std::vector< sw::unum::posit >& b) {\n\tsize_t d = b.size();\n\tassert(A.size() == d*d);\n\tusing namespace sw::hprblas;\n\tstd::vector< sw::unum::posit > 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 time_span = duration_cast>(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 time_span = duration_cast>(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 time_span = duration_cast>(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\nvoid RandomMatrix() {\n\tusing namespace std;\n\tmtl::dense_vector x(5), b(5), xprime(5);\n\tmtl::dense2D 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(A, xprime, b);\n\tprintVector(cout, \"RHS x(5) :\\n\", xprime);\n\tcout << endl;\n\tCroutFDPCycle(A, xprime, b);\n\tprintVector(cout, \"RHS x(5) :\\n\", xprime);\n}\n#endif\n\ntemplate\nvoid CompareIEEEDecompositions(std::vector& A, std::vector& x, std::vector& b) {\n\tsize_t d = b.size();\n\tassert(A.size() == d*d);\n\tusing namespace sw::hprblas;\n\tstd::vector 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 time_span = duration_cast>(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 time_span = duration_cast>(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 time_span = duration_cast>(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\nvoid TraceDeltas() {\n\tusing namespace std;\n\tusing namespace sw::unum;\n\tScalar eps = std::numeric_limits::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\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\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 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()) << \" \" << minpos() << endl;\n\t// TraceDeltas();\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::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 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 xprime(N);\n\tCroutCycle(A, b);\n\tcout << endl;\n}\n\ntemplate\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;\n\tdense2D 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()) << \" \" << minpos() << endl;\n\t// TraceDeltas();\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::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 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;\n\t//\n\t//GenerateAndSolveSystemOfLinearEquations(N);\n\t//GenerateAndSolveSystemOfLinearEquations(N);\n\n\t{\n\t\tusing Real = double;\n\t\tcout << \"Crout LU for type: \" << typeid(Real).name() << endl;\n\t\tdense2D 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 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 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 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 \"nlmatode.h\"\n\n#include \n#include \n#include \n#include \n#include \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 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::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 \n // using std::cout;\n using std::endl;\n using std::dec;\n using std::hex;\n using std::boolalpha;\n#include \n // using std::setprecision;\n // using std::setw;\n#include \n //using std::string;\n#include \n //using std::numeric_limits;\n\n#include \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 tf;\n std::cout << \"smallest tf size = \" << tf.size() << std::endl; // smallest 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 tf10(1e-10F); // Note value must be a float - to match.\n std::cout << \"smallest tf10(1e-10); = \" << tf10.size() << std::endl; // smallest 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::min())\n // typedef smallest 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 z;\n std::cout << z.size() << std::endl;\n std::cout << z(1e-308) << std::endl;\n\n tiny zz; // typedef smallest tiny;\n std::cout << zz.size() << std::endl;\n std::cout << zz(1e-308) << std::endl;\n\n constexpr double v = (std::numeric_limits::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::epsilon(), FPC_WEAK);\n\n std::cout << is_near_100eps(1., 1 + 90 * std::numeric_limits::epsilon() ) << std::endl;\n std::cout << is_near_100eps(1., 1 + 110 * std::numeric_limits::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 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 tdf; // default tolerance = 2 *epsilon and strength = strong\n std::cout << \"close_to 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 tds(1e-14, FPC_STRONG); // default strength = strong\n std::cout << \"close_to tds.size() = \" << tds.size() << ' ' << (tds.strength() == 0 ? \"strong \" : \"weak\" ) << std::endl;\n close_to tdw(1e-14, FPC_WEAK); // default strength = strong\n std::cout << \"close_to tdw.size() = \" << tdw.size() << ' ' << (tdw.strength() == 0 ? \"strong \" : \"weak\" ) << std::endl;\n close_to tdd; // default tolerance = 2 *epsilon and strength = strong\n std::cout << \"close_to tdd.size() = \" << tdd.size() << ' ' << (tdd.strength() == 0 ? \"strong \" : \"weak\" ) << std::endl;\n close_to tdds(1e-14); // specific tolerance but use default strength = strong\n std::cout << \"close_to tdds.size() = \" << tdds.size() << ' ' << (tdds.strength() == 0 ? \"strong \" : \"weak\" ) << std::endl;\n\n close_to<> t; //\n std::cout << \"close_to t.size() = \" << t.size() << ' ' << (t.strength() == 0 ? \"strong \" : \"weak\" ) << std::endl;\n std::cout << \"close_to tdd.size() = \" << tdd.size() << ' ' << (tdd.strength() == 0 ? \"strong \" : \"weak\" ) << std::endl;\n\n // neareq\n // Use nearby the convenience typedef for close_to\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::min)()) \" << neq(1 * (std::numeric_limits::min)(), 2 * (std::numeric_limits::min)()) << std::endl; // true\n\n neareq neqd(1 * (std::numeric_limits::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::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::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::epsilon() ) << std::endl; // true\n std::cout << is_near_100eps(1., 1. + 110 * std::numeric_limits::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 tf size = 2.35099e-038\n tf(1e-38F) true\n tf(9.e-38F) false\nsmallest 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 tdf.size() = 2.38419e-007 strong\nclose_to tds.size() = 1e-014 strong\nclose_to tdw.size() = 1e-014 weak\nclose_to tdd.size() = 4.44089e-016 strong\nclose_to tdds.size() = 1e-014 strong\nclose_to t.size() = 4.44089e-016 strong\nclose_to tdd.size() = 4.44089e-016 strong\nneq(0) true\nneq(0.) true\nneq(1 * (numeric_limits::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// 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 \n#include \n#include \n#include \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;\n using tensor = ublas::tensor_dynamic;\n using matrix = ublas::matrix;\n using vector = ublas::vector;\n using shape = typename tensor::extents_type;\n constexpr auto ones = ublas::ones{};\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;\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;\n using matrix = ublas::matrix;\n using vector = ublas::vector;\n using tensor2 = ublas::tensor_static_rank;\n using tensor3 = ublas::tensor_static_rank;\n using tensor4 = ublas::tensor_static_rank;\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{};\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;\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 \n#include \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 \n#include \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": "#include \"internal.h\"\n#include \n#include \n#include \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 \n#include \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 \n#include \n\n#include \n#include \n#include \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 \n#include \n\n#ifdef NDEBUG\n#define EIGEN_NO_DEBUG\n#endif\n\n#include \"main.h\"\n#include \n#include \n\n#include \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 \n\nconst size_t NUM_SAMPLE_POINTS =\n#ifdef NDEBUG\n500000;\n#else\n50000;\n#endif\n\ntemplate \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 triplets(npoints * 2 * 5); // npoints * rows_per_point * nonzeros_per_row\n for(int i=0; i > 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 > DenseQRSolver2x1;\n\n // QR for J1 is block diagonal\n typedef BlockDiagonalSparseQR LeftSuperBlockSolver;\n \n // QR for J1'J2 is general dense (faster than general sparse by about 1.5x for n=500K)\n typedef ColPivHouseholderQR > RightSuperBlockSolver;\n\n // QR for J is concatenation of the above.\n typedef BlockSparseQR 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 A;\n A << 12, 3, -5, 17, -7, 132, 1.0, 1.1, -3.1, 4.7;\n ColPivHouseholderQR > qr(A);\n\n MatrixXd R = qr.matrixR().template triangularView();\n\n Matrix 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() << 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::InputType params;\n params.resize(EllipseFitting::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 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": "/**\n * @file eigen_vector_operations.cpp\n * @author Maximilian Harr \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 /* Header that defines the standard input/output stream objects */\n#include /* Header that defines several general purpose functions */\n#include \n#include /* template library for linear algebra http://eigen.tuxfamily.org */\n#include /* Defines M_PI for pi value */\n#include \n#include \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 \r\n#include \r\n#include \r\n#include \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());\r\n\r\n std::cout << std::setprecision(std::numeric_limits::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()*third() << \"\\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 \n#include \n#include \n#include \n#include \n#include \n#include \n\nstatic std::vector vec_diff(const std::vector & input)\n{\n std::vector 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 cum_sum(const std::vector & input)\n{\n std::vector 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 x;\n std::vector y;\n int nx;\n std::vector h;\n std::vector a;\n std::vector b;\n std::vector c;\n // Eigen::VectorXf c;\n std::vector 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 & x_, const std::vector & 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 s;\n\n Spline2D(const std::vector & x, const std::vector & 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 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 calc_s(const std::vector & x, const std::vector & y)\n {\n std::vector ds;\n std::vector out_s{0};\n std::vector dx = vec_diff(x);\n std::vector 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 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 s;\n\n Spline3D(\n const std::vector & x, const std::vector & y, const std::vector & 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 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 calc_s(const std::vector & x, const std::vector & y)\n {\n std::vector ds;\n std::vector out_s{0};\n std::vector dx = vec_diff(x);\n std::vector 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 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 s;\n\n Spline4D(\n const std::vector & x, const std::vector & y, const std::vector & z,\n const std::vector & 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 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 calc_s(const std::vector & x, const std::vector & y)\n {\n std::vector ds;\n std::vector out_s{0};\n std::vector dx = vec_diff(x);\n std::vector 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 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 \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 \n#include \n\n#include \n\n\n// anonymous namespace for internal types\nnamespace {\ntemplate struct FourthRootMachineEps;\ntemplate <> struct FourthRootMachineEps\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\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 \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::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 \ninline Eigen::Quaternion\nquat_exp(Eigen::MatrixBase 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–48. 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 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 \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 \ninline Eigen::Matrix\nquat_ln(Eigen::Quaternion 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(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 \n#include \n#include \n\n#include \n\n#include \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 \n#include \n#include \n#include \n\n#include \n\ntemplate \nclass combination_iterator\n : public boost::iterator_facade, const std::vector&, 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& dereference() const { return comb_; }\n\n bool end_{true};\n const int n_{0};\n const int k_{0};\n std::vector comb_;\n};\n\ntemplate \nclass combination_iterator_minimax_order\n : public boost::iterator_facade,\n const std::vector&,\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& 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 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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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 uniform_dist(0.0, 1.0);\n std::normal_distribution 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(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 \n#include \n\n#include \n#include \n\n namespace boost { namespace math { namespace detail {\n\n // forward declaration for initial values\n template \n inline T hypergeometric_1F1_imp(const T& a, const T& b, const T& z, const Policy& pol);\n\n template \n inline T hypergeometric_1F1_imp(const T& a, const T& b, const T& z, const Policy& pol, int& log_scaling);\n\n template \n struct hypergeometric_1F1_recurrence_a_coefficients\n {\n typedef boost::math::tuple 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 \n struct hypergeometric_1F1_recurrence_b_coefficients\n {\n typedef boost::math::tuple 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 \n struct hypergeometric_1F1_recurrence_small_b_coefficients\n {\n typedef boost::math::tuple 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 \n struct hypergeometric_1F1_recurrence_a_and_b_coefficients\n {\n typedef boost::math::tuple 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 \n struct hypergeometric_1F1_recurrence_2a_and_2b_coefficients\n {\n typedef boost::math::tuple 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 \n struct hypergeometric_1F1_recurrence_2a_coefficients\n {\n typedef boost::math::tuple 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 \n struct hypergeometric_1F1_recurrence_2b_coefficients\n {\n typedef boost::math::tuple 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 \n struct hypergeometric_1F1_recurrence_a_plus_b_minus_coefficients\n {\n typedef boost::math::tuple 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 \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(policies::get_max_series_iterations()))\n return policies::raise_evaluation_error(function, \"1F1 arguments sit in a range with a so negative that we have no evaluation method, got a = %1%\", std::numeric_limits::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 s(ak, b, z);\n\n return tools::apply_recurrence_relation_backward(s,\n static_cast(std::abs(integer_part)),\n first,\n second, &log_scaling);\n }\n\n\n template \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::math::policies::get_max_series_iterations()))\n return hypergeometric_1F1_checked_series_impl(a, b, z, pol, log_scaling);\n\n if (a_shift > static_cast(boost::math::policies::get_max_series_iterations()))\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(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(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(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 \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 \n\n#include \n#include \n\n#include \n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\n\ntypedef CGAL::Projection_on_sphere_traits_3 Traits;\ntypedef CGAL::Delaunay_triangulation_on_sphere_2 DToS2;\n\ntypedef Traits::Point_3 Point_3;\n\nint main(int, char**)\n{\n std::vector 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 \n\n#include \n#include \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 ftle_map_generator::generate ()\n{\n auto ftle_map = std::make_unique();\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(0, gradient->data.shape()[0], 0, gradient->data.shape()[1], 0, gradient->data.shape()[2]), \n [&] (const tbb::blocked_range3d& 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 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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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 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(\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> data (n x d)\n @param delim:char delimiter character\n @param eps:double approximation error (default: 0.001)\n*/\nvoid Mvee::compute(vector>& 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 (d x 1)\n Note: Invoke mveeInstance.compute() prior to retrieving \n the ellipse parameters.\n*/\nvector Mvee::centroid()\n{\n return _centroid;\n}\n\n\n/*\n Ellipse radii\n @return radii:vector (d x 1)\n Note: Invoke mveeInstance.compute() prior to retrieving \n the ellipse parameters.\n*/\nvector Mvee::radii()\n{\n return _radii;\n}\n\n\n/*\n Ellipse pose (rotation)\n @return pose:vector> (d x d)\n Note: Invoke mveeInstance.compute() prior to retrieving \n the ellipse parameters.\n*/\nvector> 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 *
\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 \n#include \n#include \n#include \n#include \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\nBOOST_UBLAS_INLINE\nvector 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 © 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ₒ = 1)\n target ----- target (output) values\n params ----- parameters (weights) with initial values (zeros)\n hypothesis - hypothesis function;\n\n*/\n\n#include \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(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(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 \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 \n\n#include \n#include \n#include \n#include \n\n#include \n\n#include \n\nnamespace sphericalsfm {\n\n struct RotationError\n {\n RotationError( const Eigen::Matrix3d &_meas ) : meas(_meas) { }\n \n template \n bool operator()(const T* const r0,\n const T* const r1,\n T* residuals) const\n {\n Eigen::Matrix 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 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 &rotations, const std::vector &relative_rotations )\n {\n std::vector 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(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 \n#include \n#include \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(time(0)));\n\tnormal_distribution 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 \n#include \n#include \n#include \n#include \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(); }\n\n/**\n * Return the value of pi.\n *\n * @return Pi.\n */\ninline double pi() { return boost::math::constants::pi(); }\n\n/**\n * Smallest positive value.\n */\nconst double EPSILON = std::numeric_limits::epsilon();\n\n/**\n * Positive infinity.\n */\nconst double INFTY = std::numeric_limits::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::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 \n\n// STL\n#include \n#include \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 \nclass MatrixCoeff : public TensorFunction<2,dim>\n{\npublic:\n\tMatrixCoeff ();\n\n\tvirtual Tensor<2, dim> value(const Point &point) const override;\n\tvirtual void value_list(const std::vector> &points,\n\t\t\tstd::vector> &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 \nTensor<2, dim>\nMatrixCoeff::value(const Point &p) const\n{\n\tTensor<2, dim> value;\n\tvalue.clear();\n\n\tfor (unsigned int d=0; d\nvoid\nMatrixCoeff::value_list(const std::vector> &points,\n\t\tstd::vector> &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\n#include \"simple_activation.h\"\n\nnamespace MyDL{\n using namespace Eigen;\n\n // 実装がめんどくさいので直接Eigen::MatrixXdを引数にとるよう実装\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のオーバーフロー回避 → 各バッチベクトルごとに最大の要素を抽出\n x = x.array().exp(); // expを各要素に実行\n rowwise_sum = x.rowwise().sum(); // バッチベクトルごとに総和を計算\n\n x.array().colwise() /= rowwise_sum.array(); // 出力の総和が1になるよう調整\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 \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> KPointsUtil::generate_k_points(const double rcut) {\n std::vector> 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({i, j, k}));\n }\n }\n }\n std::stable_sort(\n k_points.begin(),\n k_points.end(),\n [](const std::array& a, const std::array& b) -> bool {\n return squared_norm(a) < squared_norm(b);\n });\n return k_points;\n}\n\nstd::vector> KPointsUtil::get_k_diffs(\n const std::vector>& k_points) {\n // Generate all possible differences between two different k points.\n std::unordered_set, boost::hash>> k_diffs_set;\n std::vector> 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& a, const std::array& 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": "#include \n#include \n\n#include \n#include \n#include \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;\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 golden_search_simple(std::function 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 golden_search(std::function 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 adaptive_golden_search(\n std::function(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 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 << \"±\"\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 << \"±\"\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 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 << \"±\"\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 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 α 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 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 α for 2D case (λ=\" << 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(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({mean, std});\n };\n\n auto [xmin, xmax] = adaptive_golden_search(f, .1, 1, 1e-6);\n cout << \"Optimal (adaptive) α for 2D case (λ=\" << lambda << \") is between \"\n << xmin << \" and \" << xmax << endl;\n}\n\nvoid energy_function_test() {\n cout << \"E_2d(1, 0, 2, 0|λ=1,α=1)=\" << energy_2d({1, 0, 2, 0}, 1, 1) << endl;\n cout << \"E_2d(1.1, 3.1, -5.6, -5|λ=2.1,α=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 \n\nnamespace {\n using namespace NTL;\n}\n\nnamespace gnfs {\n long param_d(const ZZ& n) {\n RR ln = log(conv(n));\n RR base = (3 * ln) / log(ln);\n return conv(pow(base, RR(1.0/3)));\n }\n\n long param_B(const ZZ& n) {\n RR ln = log(conv(n));\n RR base = 8.0 / 9 * ln * log(ln) * log(ln);\n return conv(exp(pow(base, RR(1.0/3))));\n }\n\n std::pair param_mf(const ZZ& n, long d) {\n ZZ m = conv(pow(conv(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 \n#include \n#include \n#include \n#include \n#include \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 t (N); // time vector, sec\n\t\tfor (unsigned i = 0; i < t.size(); ++i) t(i) = i;\n\t\tcout << \"t(\"< dis_y( 0, 10 );\n\t\tublas::vector y (N); // measured value\n\t\tfor (unsigned i = 0; i < y.size(); ++i) y(i) = dis_y(gen);\n\t\tcout << \"y(\"< u(N, i);\n\t\t\tcout << \"unit_vector(\"< z(N);\n\t\tcout << \"zero_vector(\"< s(N, 3);\n\t\tcout << \"scalar_vector(\"< one(N, 1);\n\t\tcout << \"one(\"< 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(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(m_temp.size2(),1);\n\t\t\tcout << \"m_temp = \" << m_temp << endl;\n\t\t}\n\n\t\tublas::identity_matrix mi(N);\n\t\tcout << \"identity(N) = \" << mi << endl;\n\n\t\tublas::zero_matrix zero(N);\n\t\tcout << \"zero(N) = \" << zero << endl;\n\n\t\tublas::scalar_matrix ones(1, 1, 1);\n\t\tcout << \"sizeof( scalar_matrix(1, 1, 1) ) = \" << sizeof(ones) << endl;\n\t\tublas::scalar_matrix twos(1000, 2000000, 2);\n\t\tcout << \"sizeof( scalar_matrix(1000, 2000000, 2) ) = \" << sizeof(twos) << endl;\n\n\t\tublas::matrix ones1(1, 1, 1);\n\t\tcout << \"sizeof( matrix(1, 1, 1) ) = \" << sizeof(ones1) << endl;\n\t\tublas::matrix 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 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 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 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 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 \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 \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().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 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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#pragma once\n\n/* Arbitrary precision integers */\n#include \n#include \n#include \n#include \n\nusing namespace boost::multiprecision;\nusing namespace boost::random;\n\ntypedef boost::multiprecision::cpp_int bigint;\ntypedef independent_bits_engine 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(ifs) ),\n\t\t\t\t\t\t(std::istreambuf_iterator() ) );\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(pow(xp,2))+a)*inv;\n\t\tcpp_int xr = modulo((static_cast(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 \n#include \n#include \n#include \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 \n#include \n#include \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": "//---------------------------------------------------------------------------//\n// Copyright (c) 2021 Mikhail Komarov \n// Copyright (c) 2021 Nikita Kaskov \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 \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \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 {\n constant_() {\n // clang-format off\n add\n (\"e\" , boost::math::constants::e())\n (\"epsilon\", std::numeric_limits::epsilon())\n (\"phi\" , boost::math::constants::phi())\n (\"pi\" , boost::math::constants::pi())\n ;\n // clang-format on\n }\n } constant;\n\n struct ufunc_ : x3::symbols {\n ufunc_() {\n // clang-format off\n add\n (\"abs\" , static_cast(&std::abs))\n (\"acos\" , static_cast(&std::acos))\n (\"acosh\" , static_cast(&std::acosh))\n (\"asin\" , static_cast(&std::asin))\n (\"asinh\" , static_cast(&std::asinh))\n (\"atan\" , static_cast(&std::atan))\n (\"atanh\" , static_cast(&std::atanh))\n (\"cbrt\" , static_cast(&std::cbrt))\n (\"ceil\" , static_cast(&std::ceil))\n (\"cos\" , static_cast(&std::cos))\n (\"cosh\" , static_cast(&std::cosh))\n (\"deg\" , static_cast(&math::deg))\n (\"erf\" , static_cast(&std::erf))\n (\"erfc\" , static_cast(&std::erfc))\n (\"exp\" , static_cast(&std::exp))\n (\"exp2\" , static_cast(&std::exp2))\n (\"floor\" , static_cast(&std::floor))\n (\"isinf\" , static_cast(&math::isinf))\n (\"isnan\" , static_cast(&math::isnan))\n (\"log\" , static_cast(&std::log))\n (\"log2\" , static_cast(&std::log2))\n (\"log10\" , static_cast(&std::log10))\n (\"rad\" , static_cast(&math::rad))\n (\"round\" , static_cast(&std::round))\n (\"sgn\" , static_cast(&math::sgn))\n (\"sin\" , static_cast(&std::sin))\n (\"sinh\" , static_cast(&std::sinh))\n (\"sqrt\" , static_cast(&std::sqrt))\n (\"tan\" , static_cast(&std::tan))\n (\"tanh\" , static_cast(&std::tanh))\n (\"tgamma\", static_cast(&std::tgamma))\n ;\n // clang-format on\n }\n } ufunc;\n\n struct bfunc_ : x3::symbols {\n bfunc_() {\n // clang-format off\n add\n (\"atan2\", static_cast(&std::atan2))\n (\"max\" , static_cast(&std::fmax))\n (\"min\" , static_cast(&std::fmin))\n (\"pow\" , static_cast(&std::pow))\n ;\n // clang-format on\n }\n } bfunc;\n\n struct unary_op_ : x3::symbols {\n unary_op_() {\n // clang-format off\n add\n (\"+\", static_cast(&math::plus))\n (\"-\", static_cast(&math::minus))\n (\"!\", static_cast(&math::unary_not))\n ;\n // clang-format on\n }\n } unary_op;\n\n struct additive_op_ : x3::symbols {\n additive_op_() {\n // clang-format off\n add\n (\"+\", static_cast(&math::plus))\n (\"-\", static_cast(&math::minus))\n ;\n // clang-format on\n }\n } additive_op;\n\n struct multiplicative_op_ : x3::symbols {\n multiplicative_op_() {\n // clang-format off\n add\n (\"*\", static_cast(&math::multiplies))\n (\"/\", static_cast(&math::divides))\n (\"%\", static_cast(&std::fmod))\n ;\n // clang-format on\n }\n } multiplicative_op;\n\n struct logical_op_ : x3::symbols {\n logical_op_() {\n // clang-format off\n add\n (\"&&\", static_cast(&math::logical_and))\n (\"||\", static_cast(&math::logical_or))\n ;\n // clang-format on\n }\n } logical_op;\n\n struct relational_op_ : x3::symbols {\n relational_op_() {\n // clang-format off\n add\n (\"<\" , static_cast(&math::less))\n (\"<=\", static_cast(&math::less_equals))\n (\">\" , static_cast(&math::greater))\n (\">=\", static_cast(&math::greater_equals))\n ;\n // clang-format on\n }\n } relational_op;\n\n struct equality_op_ : x3::symbols {\n equality_op_() {\n // clang-format off\n add\n (\"==\", static_cast(&math::equals))\n (\"!=\", static_cast(&math::not_equals))\n ;\n // clang-format on\n }\n } equality_op;\n\n struct power_ : x3::symbols {\n power_() {\n // clang-format off\n add\n (\"**\", static_cast(&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\"};\n auto const logical = x3::rule{\"logical\"};\n auto const equality = x3::rule{\"equality\"};\n auto const relational = x3::rule{\"relational\"};\n auto const additive = x3::rule{\"additive\"};\n auto const multiplicative = x3::rule{\"multiplicative\"};\n auto const factor = x3::rule{\"factor\"};\n auto const primary = x3::rule{\"primary\"};\n auto const unary = x3::rule{\"unary\"};\n auto const binary = x3::rule{\"binary\"};\n auto const variable = x3::rule{\"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 \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;\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 \n\n#include \n\ntypedef unsigned long long nombre;\ntypedef std::vector vecteur;\n\ntypedef boost::rational 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();\n nombre k_max = static_cast(std::ceil(k0));\n nombre k_min = static_cast(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 × r × ... × 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, ΣD(N) for 5 ≤ N ≤ 100 is 2438.\n //\n // Find ΣD(N) for 5 ≤ N ≤ 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 \n#include \n#include \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;iy ? 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 .\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 = . Indexes are specified\n in the range 0 to . It cannot be used when the search space is\n normalized.\nnormalize = true, false\n Specifies if the search space should be normalized. If , parameter\n 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 = .\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 \n#include \n#include \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();\n py = (y >= 0.0).cast();\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 \\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= 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\n#include \n#include \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 \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n\n// STL\n#include \n#include \n#include \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 \nclass DiffusionProblemBasis\n{\npublic:\n\tDiffusionProblemBasis ();\n\tvoid run ();\n\n\tvoid output_global_solution_in_cell () const;\n\n\tconst FullMatrix& get_global_element_matrix () const;\n\tconst Vector& 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::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 &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 \t\t\ttriangulation;\n\tFE_Q \t\t\tfe;\n\tDoFHandler \t\t\tdof_handler;\n\n\tstd::vector> \t\tconstraints_vector;\n\tstd::vector> \t\t\t\t\tcorner_points;\n\n\tSparsityPattern \t\t\tsparsity_pattern;\n\tSparseMatrix \t\t\tdiffusion_matrix;\n\tSparseMatrix \t\t\tsystem_matrix;\n\n\tstd::string\tfilename_global;\n\n\t/*!\n\t * Solution vector.\n\t */\n\tstd::vector>\t\tsolution_vector;\n\n\t/*!\n\t * Contains the right-hand side.\n\t */\n\tVector \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\t\t\t\t\tsystem_rhs;\n\n\t/*!\n\t * Holds global multiscale element matrix.\n\t */\n\tFullMatrix \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 \t\t\tglobal_element_rhs;\n\n\t/*!\n\t * Weights of multiscale basis functions.\n\t */\n\tstd::vector \t\tglobal_weights;\n\tbool is_set_global_weights;\n\n\t/*!\n\t * Global solution\n\t */\n\tVector\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::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 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 \nDiffusionProblemBasis::DiffusionProblemBasis ()\n:\nfe (1),\ndof_handler (triangulation),\nconstraints_vector (GeometryInfo::vertices_per_cell),\ncorner_points (GeometryInfo::vertices_per_cell),\nfilename_global (\"\"),\nsolution_vector (GeometryInfo::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 \nvoid DiffusionProblemBasis::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 \nvoid DiffusionProblemBasis::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::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::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 \nvoid DiffusionProblemBasis::assemble_system ()\n{\n\tQGauss quadrature_formula(fe.degree + 1);\n\n\tFEValues \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 cell_diffusion_matrix (dofs_per_cell, dofs_per_cell);\n\tFullMatrix cell_mass_matrix (dofs_per_cell, dofs_per_cell);\n\tVector cell_rhs (dofs_per_cell);\n\n\tstd::vector 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 \t\tmatrix_coeff;\n\tstd::vector> \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 \tright_hand_side;\n\tstd::vector \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_indexget_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 \nvoid\nDiffusionProblemBasis::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\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& test_vec = solution_vector[i_test];\n\n\t\tfor (unsigned int i_trial=0;\n\t\t\t\ti_trial& 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 \nvoid DiffusionProblemBasis::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 \nconst FullMatrix&\nDiffusionProblemBasis::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 \nconst Vector&\nDiffusionProblemBasis::get_global_element_rhs () const\n{\n\treturn global_element_rhs;\n}\n\n/*!\n * Return filename for local pvtu record.\n */\ntemplate \nconst std::string&\nDiffusionProblemBasis::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 \nvoid\nDiffusionProblemBasis::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 \nvoid\nDiffusionProblemBasis::set_cell_data (typename Triangulation::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::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 \nvoid\nDiffusionProblemBasis::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 \nvoid\nDiffusionProblemBasis::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 \nvoid\nDiffusionProblemBasis::set_global_weights (const std::vector &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\nvoid\nDiffusionProblemBasis::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 \nvoid\nDiffusionProblemBasis::output_basis () const\n{\n\tDataOut data_out;\n\tdata_out.attach_dof_handler (dof_handler);\n\tfor (unsigned int index_basis=0;\n\t\t\t\tindex_basis::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 \nvoid\nDiffusionProblemBasis::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 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 \nvoid DiffusionProblemBasis::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::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 \n#include \n\nnamespace wav2midi::fft {\n namespace {\n using namespace std::complex_literals;\n\n constexpr auto pi = boost::math::constants::pi();\n\n // @see http://geisterchor.blogspot.jp/2015/05/cfft.html\n std::complex 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> & x, std::size_t n) {\n if (n <= 1) return;\n\n std::vector> x_e(n/2);\n std::vector> 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 & 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> & 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 \n#include \n#include \n#include \n#include \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\"< 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 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 \n#include \n#include \n#include \n\n// BGL includes\n#include \n#include \n#include \n\ntypedef std::size_t Index;\n\ntypedef boost::adjacency_list > weighted_graph;\ntypedef boost::property_map::type weight_map;\ntypedef boost::graph_traits::edge_descriptor edge_desc;\ntypedef boost::graph_traits::vertex_descriptor vertex_desc;\n// edge: (u,v,c)\ntypedef std::tuple Edge;\ntypedef std::vector 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> edge_in_mst(n, std::vector(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> mst_edges(n, std::vector(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> max_e_betw(n, std::vector(n, 0));\n for(int i = 0; i < n; i++) {\n std::stack> Q; // pair of (node, max edge on path form i to node)\n Q.push({i,0});\n std::vector 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::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 \n#include \n#include \n#include \n\n\nnamespace kv {\n\nnamespace ub = boost::numeric::ublas;\n\n\ntemplate bool cardano(const ub::vector< complex< interval > > &in, ub::vector< complex< interval > >& out)\n{\n\tcomplex< interval > 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 >(-1., sqrt(interval(3.))) / 2.;\n\n\ttmp = sqrt(pow(q, 2)/4. + pow(p, 3) / 27.) ;\n\tm = pow(-q / 2. + tmp, 1. / interval(3.));\n\tn = pow(-q / 2. - tmp, 1. / interval(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::hull(nn.real(), nt.real());\n\t\t\t\tnn.imag() = interval::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 bool ferrari(const ub::vector< complex< interval > > &in, ub::vector< complex< interval > >& out) \n{\n\tcomplex< interval > a, b, c, d, p, q, r, tmp;\n\tub::vector< complex< interval > > ci, co;\n\tcomplex< interval > 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::hull(nn.real(), nt.real());\n\t\t\t\tnn.imag() = interval::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": "//\n// Copyright 2019 Olzhas Zhumabek \n// Copyright 2021 Pranam Lashkari \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 \n#include \n#include \n#include \n#include \n// fixes ambigious call to std::abs, https://stackoverflow.com/a/30084734/4593721\n#include \n#include \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(-a) < x && x < static_cast(a))\n return normalized_sinc(x) / normalized_sinc(x / static_cast(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 >\ninline detail::kernel_2d 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(side_length * side_length);\n\n detail::kernel_2d 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 >\ninline detail::kernel_2d 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 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 >\ninline detail::kernel_2d 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 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(nominator / denominator);\n values[y * side_length + x] = value;\n }\n }\n\n return detail::kernel_2d(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 >\ninline detail::kernel_2d generate_dx_sobel(unsigned int degree = 1)\n{\n switch (degree)\n {\n case 0:\n {\n return detail::get_identity_kernel();\n }\n case 1:\n {\n detail::kernel_2d 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 >\ninline detail::kernel_2d generate_dx_scharr(unsigned int degree = 1)\n{\n switch (degree)\n {\n case 0:\n {\n return detail::get_identity_kernel();\n }\n case 1:\n {\n detail::kernel_2d 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 >\ninline detail::kernel_2d generate_dy_sobel(unsigned int degree = 1)\n{\n switch (degree)\n {\n case 0:\n {\n return detail::get_identity_kernel();\n }\n case 1:\n {\n detail::kernel_2d 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 >\ninline detail::kernel_2d generate_dy_scharr(unsigned int degree = 1)\n{\n switch (degree)\n {\n case 0:\n {\n return detail::get_identity_kernel();\n }\n case 1:\n {\n detail::kernel_2d 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 \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": "#include \n#include \n#include \n#include \n#include \n\nnamespace LogisticRegression\n{\n\t//Z(X₁,X₂)=1(θ₁X₁+θ₂X₂>800)\n\t//Z(X₁,X₂)=0(θ₁X₁+θ₂X₂<=800)\n\t//θ₁=10,θ₂=150,X₂=1\n\tstd::tuple 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₁ = std::rand() % 100 + 20, X₂ = 1;\n\t\t\ttrain_input(i, 0) = X₁;\n\t\t\ttrain_input(i, 1) = X₂;\n\t\t\tdouble θ₁ = 10, θ₂ = 150;\n\t\t\tdouble loss = /*std::rand() % 11 - 5;*/0;\n\t\t\tdouble hx = θ₁ * X₁ + θ₂ * X₂ + 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 * ∑y 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//θ = θ - α * 1/m * ∑(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": "#ifndef RBF_INTERPOLATION_HPP\n#define RBF_INTERPOLATION_HPP\n\n#include \n#include \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 \n#include \n#include \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": "/*=============================================================================\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 \n\n#ifdef SPRIG_USING_PRAGMA_ONCE\n#\tpragma once\n#endif\t// #ifdef SPRIG_USING_PRAGMA_ONCE\n\n#include \n#include \n\nnamespace sprig {\n\t//\n\t// catmull_rom_spline\n\t//\n\ttemplate\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\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\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\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\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\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\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\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\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\n\tSPRIG_INLINE sprig::catmull_rom_spline_f\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(p0, p1, p2, p3);\n\t}\n\t//\n\t// make_catmull_rom_spline_start\n\t//\n\ttemplate\n\tSPRIG_INLINE sprig::catmull_rom_spline_start_f\n\tmake_catmull_rom_spline_start(Point const& p0, Point const& p1, Point const& p2) {\n\t\treturn sprig::catmull_rom_spline_start_f(p0, p1, p2);\n\t}\n\t//\n\t// make_catmull_rom_spline_end\n\t//\n\ttemplate\n\tSPRIG_INLINE sprig::catmull_rom_spline_end_f\n\tmake_catmull_rom_spline_end(Point const& p0, Point const& p1, Point const& p2) {\n\t\treturn sprig::catmull_rom_spline_end_f(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": "#ifndef __NED_CLASS__\n#define __NED_CLASS__\n\n#include \"math.h\"\n#include \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 \n#include \n\n#include \n#include \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\nvoid geographic2geocentric(\n const Eigen::Ref lla,\n Eigen::Ref 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\nEigen::Vector3d geographic2geocentric(const Eigen::Ref 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\nvoid llr2ecef(\n const Eigen::Ref llr,\n Eigen::Ref 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\nEigen::Vector3d llr2ecef(const Eigen::Ref 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\nvoid lla2ecef(\n const Eigen::Ref lla,\n Eigen::Ref ecef)\n{\n geographic2geocentric<_ref>(lla, ecef);\n llr2ecef<_ref>(ecef, ecef);\n}\n\ntemplate\nEigen::Vector3d lla2ecef(const Eigen::Ref lla)\n{\n Eigen::Vector3d ecef;\n lla2ecef<_ref>(lla, ecef);\n return ecef;\n}\n\n// forward-declaration\ntemplate\nEigen::Matrix3d geo2ecef(const Eigen::Ref ll);\n\ntemplate\nstd::pair lla2ecef(\n const Eigen::Ref lla,\n const Eigen::QuaternionBase & 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\nvoid ecef2lla(\n const Eigen::Ref ecef,\n Eigen::Ref 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\nEigen::Vector3d ecef2lla(const Eigen::Ref ecef)\n{\n Eigen::Vector3d lla;\n ecef2lla<_ref>(ecef, lla);\n return lla;\n}\n\ntemplate\nstd::pair ecef2lla(\n const Eigen::Ref T_ecef,\n const Eigen::QuaternionBase & 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\nvoid ecef2llr(\n const Eigen::Ref ecef,\n Eigen::Ref 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\nEigen::Vector3d ecef2llr(const Eigen::Ref 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\nvoid geo2ecef(\n const Eigen::Ref ll,\n Eigen::Ref 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\nEigen::Matrix3d geo2ecef(\n const Eigen::Ref ll)\n{\n Eigen::Matrix3d M_ecef_ll;\n geo2ecef<_ref>(ll, M_ecef_ll);\n return M_ecef_ll;\n}\n\ntemplate\nvoid geo2ecef(\n const Eigen::QuaternionBase & qIn,\n const Eigen::Ref ll,\n Eigen::QuaternionBase & qOut)\n{\n qOut = Eigen::Quaterniond(geo2ecef<_ref>(ll)) * qIn;\n}\n\ntemplate\nEigen::Quaterniond geo2ecef(\n const Eigen::QuaternionBase & qIn,\n const Eigen::Ref 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\nvoid imu2nwu(\n const Eigen::QuaternionBase & qIn,\n const Eigen::Ref lla,\n Eigen::QuaternionBase & 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\nEigen::Quaterniond imu2nwu(\n const Eigen::QuaternionBase & qIn,\n const Eigen::Ref 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\nvoid nwu2imu(\n const Eigen::QuaternionBase & qIn,\n const Eigen::Ref lla,\n Eigen::QuaternionBase & 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\nEigen::Quaterniond nwu2imu(\n const Eigen::QuaternionBase & qIn,\n const Eigen::Ref 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\nbool lla2gnomonic(\n const Eigen::Ref lla,\n const Eigen::Ref llaRef,\n Eigen::Ref 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\nstd::pair lla2gnomonic(\n const Eigen::Ref lla,\n const Eigen::Ref llaRef)\n{\n std::pair 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\nvoid gnomonic2lla(\n const Eigen::Ref xyz,\n const Eigen::Ref llaRef,\n Eigen::Ref 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\nEigen::Vector3d gnomonic2lla(\n const Eigen::Ref xyz,\n const Eigen::Ref 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\nvoid lla2nwu(\n const Eigen::Ref lla,\n const Eigen::Ref llaRef,\n Eigen::Ref 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\nEigen::Vector3d lla2nwu(\n const Eigen::Ref lla,\n const Eigen::Ref llaRef)\n{\n Eigen::Vector3d nwu;\n lla2nwu<_ref>(lla, llaRef, nwu);\n return nwu;\n}\n\ntemplate\nvoid lla2nwu(\n const Eigen::Ref lla,\n const Eigen::Ref llaRef,\n const Eigen::QuaternionBase & qRef,\n Eigen::Ref nwu)\n{\n lla2nwu<_ref>(lla, llaRef, nwu);\n nwu = qRef.toRotationMatrix().transpose() * nwu;\n}\n\ntemplate\nEigen::Vector3d lla2nwu(\n const Eigen::Ref lla,\n const Eigen::Ref llaRef,\n const Eigen::QuaternionBase & 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\nvoid lla2nwu(\n const Eigen::Ref lla,\n const Eigen::QuaternionBase & q,\n const Eigen::Ref llaRef,\n const Eigen::QuaternionBase & qRef,\n Eigen::Ref nwu,\n Eigen::QuaternionBase & 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\nvoid lla2nwu(\n const Eigen::Ref lla,\n const Eigen::QuaternionBase & q,\n const Eigen::Ref llaRef,\n Eigen::Ref nwu,\n Eigen::QuaternionBase & 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\nvoid nwu2lla(\n const Eigen::Ref nwu,\n const Eigen::Ref llaRef,\n Eigen::Ref 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\nEigen::Vector3d nwu2lla(\n const Eigen::Ref nwu,\n const Eigen::Ref llaRef)\n{\n Eigen::Vector3d lla;\n nwu2lla<_ref>(nwu, llaRef, lla);\n return lla;\n}\n\ntemplate\nvoid nwu2lla(\n const Eigen::Ref nwu,\n const Eigen::Ref llaRef,\n const Eigen::QuaternionBase & qRef,\n Eigen::Ref lla)\n{\n lla = qRef.toRotationMatrix() * nwu;\n nwu2lla<_ref>(lla, llaRef, lla);\n}\n\ntemplate\nEigen::Vector3d nwu2lla(\n const Eigen::Ref nwu,\n const Eigen::Ref llaRef,\n const Eigen::QuaternionBase & 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\nvoid nwu2lla(\n const Eigen::Ref nwu,\n const Eigen::QuaternionBase & q,\n const Eigen::Ref llaRef,\n const Eigen::QuaternionBase & qRef,\n Eigen::Ref lla,\n Eigen::QuaternionBase & 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\nvoid nwu2lla(\n const Eigen::Ref lla,\n const Eigen::QuaternionBase & q,\n const Eigen::Ref llaRef,\n Eigen::Ref nwu,\n Eigen::QuaternionBase & 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\ndouble distCartesian(\n const Eigen::Ref pt1,\n const Eigen::Ref 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\ndouble distGeodesicVincenty(\n const Eigen::Ref pt1,\n const Eigen::Ref 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\ndouble distGreatCircle(\n const Eigen::Ref pt1,\n const Eigen::Ref 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 \n#include \n#include \n#include \n\nvoid print(const std::vector& v)\n{\n\t// In C++11, use a range-based for loop.\n\tfor (std::vector::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& v1, const std::vector& 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(result, std::abs(v1[j] - v2[j]));\n\t}\n\n\treturn result;\n}\n\nstd::pair HotSpotError(const std::vector& v1, const std::vector& 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(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(result, index);\n}\n\nstd::size_t findAbscissa(const std::vector& 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(xvar) + \" not in range \"\n\t\t\t+ \"(\" + boost::lexical_cast(x[0]) + \",\"\n\t\t\t+ boost::lexical_cast(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 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 x(n + 1);\n\tx[0] = a; x[x.size()-1] = b;\n\t\n\tdouble h = (b - a) / static_cast(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 CreateDiscreteFunction(std::size_t n, double a, double b, \n\t\t\t\t\t\t\t\t\t\t\tconst std::function& f)\n{ // Create a discrete function from a continuous function y = f(x)\n\n\tstd::vector y(n + 1);\n\n\tdouble h = (b - a) / static_cast(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 \n\tVector CreateDiscreteFunction(const std::vector& x, const std::function& 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 \n\tMatrix CreateDiscreteFunction2d(const std::vector& x , const std::vector& y,\n\t\t\t\t\t\t\t\t\tconst std::function& 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 \n#include \n\nusing namespace Eigen;\n\ndouble cross_entropy_error(MatrixXd&, MatrixXd&); // プロトタイプ宣言\ndouble cross_entropy_error(MatrixXd&, VectorXd&); // プロトタイプ宣言\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バージョンの のミニバッチ実装\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// 通常ラベルバージョンのミニバッチ実装\ndouble cross_entropy_error(MatrixXd& y, VectorXd& t){\n int batch_size = y.rows();\n VectorXd associated_label_vector = VectorXd::Zero(batch_size);\n // 使っているEigenのバージョンが3.3.9以上なら、 Fancy Indexが使えるはずだが、どうも違うようなのでこれで対応\n for(int i=0; i\n\n#include \n\n\nnamespace\n{\n\t//! Create a matrix proportional to identity\n\tdat::grid\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 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\n\trhsValues\n\t\t( size_t const & dim = 8u\n\t\t)\n\t{\n\t\tdat::grid 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\n\tnullGrid\n\t\t( dat::Extents const & hwSize = {}\n\t\t)\n\t{\n\t\tdat::grid grid(hwSize);\n\t\tstd::fill(std::begin(grid), std::end(grid), dat::nullValue());\n\t\treturn grid;\n\t}\n\n\t//! Grid version of matrix inverse\n\tdat::grid\n\tinverseGrid\n\t\t( dat::grid const & srcGrid\n\t\t)\n\t{\n\t\t// allocate input/output space\n\t\tdat::grid 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 const srcMat{ withGrid(srcGrid) };\n\t\tla::eigen::WriteMap invMat{ withGrid(&invGrid) };\n\n\t\t// Eigen matrix operation (here vanilla matrix inversion)\n\t\tinvMat = Eigen::Inverse >(srcMat);\n\n\t\treturn invGrid;\n\t}\n\n\t//! Least squares solution\n\tdat::grid\n\tsolutionFor\n\t\t( dat::grid const & normGrid\n\t\t, dat::grid 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 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 const normMat{ withGrid(normGrid) };\n\t\tla::eigen::WriteMap solnMat{ withGrid(&solnGrid) };\n\n\t\tla::eigen::ConstMap const rhs{ la::eigen::withGrid(rhsGrid) };\n\t\tsolnMat = Eigen::BDCSVD >\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 const normGrid{ normCoefficients() };\n\tdat::grid 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 invGrid{ inverseGrid(normGrid) };\n\tio::out() << invGrid.infoStringContents(\"invGrid\", \"%9.3f\") << std::endl;\n\n\t// compute least squares solution\n\tdat::grid 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": "#include \n#include \n\n#include \n\n#include \n\n#include \n#include \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 PointVectorPair;\ntypedef std::vector PointList;\ntypedef std::array 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 points(in_points.size());\n #pragma omp parallel for\n for(int i=0; i cov;\n\n CGAL::First_of_pair_property_map 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 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": "/* +------------------------------------------------------------------------+\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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace mrpt;\nusing namespace mrpt::math;\nusing namespace mrpt::system;\nusing namespace std;\n\n#include \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 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 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 Mfix(numbers);\n\n\tvector 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, 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": "#include \n#include \n#include \n#include \n#include \n\nnamespace matrixManipulation\n{\n using namespace std;\n using namespace boost::numeric::ublas;\n\n template \n void printMatrix(matrix &mat)\n {\n for (int row=0;row\n void rightRot(matrix &mat,int iOrigin,int jOrigin,int matSize)\n {\n if (matSize<2) {return;}\n pair runner(iOrigin,jOrigin),backRunner(0,0);\n \n for (int i=0;i\n void swapElement(matrix &mat, pair &index1, pair &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 \n void tunnel(matrix &mat, dataType target)\n {\n set rowSet,colSet;\n \n for (int row=0;row\n void setRow(matrix &mat, int row, dataType value)\n { for (int i=0;i\n void setCol(matrix &mat, int col, dataType value)\n { for (int i=0;i 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 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(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 \n#include \n#include \n#include \n#include \n#include \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& 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 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 © 2020 David Freifeld. All rights reserved.\n//\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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(1512775 * val + 1072632447) << 32;\n\treturn *reinterpret_cast(&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 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 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 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 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 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 \n#include \n#include \n#include \n#include \n#include \n\n#include \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 start, end;\n std::chrono::duration 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": "//==================================================================================================\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, atan2(y, x)\n is the angle in radians between the positive x-axis of a plane and the point\n given by the coordinates (x, y).\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 \n#include \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 \r\n#include \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 \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 \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 \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 \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 \n#include \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 \n#include \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": "/**\n * @brief Easing functions\n */\n\n#ifndef EASING_HPP\n#define EASING_HPP\n\n#include \"floating_point/tolerance_compare.hpp\"\n#include \n#include \n#include \n\nnamespace easing {\n\nnamespace impl {\ntemplate >\nclass has_in : public std::false_type {};\ntemplate \nclass has_in()))>>\n : public std::true_type {};\n} // namespace impl\n\ntemplate struct sine {\n static_assert(std::is_floating_point_v,\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()) * 0.5);\n }\n};\n\ntemplate struct quad {\n static_assert(std::is_floating_point_v,\n \"only makes sence for floating point types.\");\n static constexpr Float in(Float x) { return x * x; }\n};\n\ntemplate struct cubic {\n static_assert(std::is_floating_point_v,\n \"only makes sence for floating point types.\");\n static constexpr Float in(Float x) { return x * x * x; }\n};\n\ntemplate struct quart {\n static_assert(std::is_floating_point_v,\n \"only makes sence for floating point types.\");\n static constexpr Float in(Float x) { return x * x * x * x; }\n};\n\ntemplate struct quint {\n static_assert(std::is_floating_point_v,\n \"only makes sence for floating point types.\");\n static constexpr Float in(Float x) { return x * x * x * x * x; }\n};\n\ntemplate struct expo {\n static_assert(std::is_floating_point_v,\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 struct circ {\n static_assert(std::is_floating_point_v,\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 struct back {\n static_assert(std::is_floating_point_v,\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 struct elastic {\n static_assert(std::is_floating_point_v,\n \"only makes sence for floating point types.\");\n static constexpr Float in(Float x) {\n constexpr Float c4 = boost::math::constants::two_pi() / 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 struct bounce {\n static_assert(std::is_floating_point_v,\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 struct ease {\n static_assert(std::is_floating_point_v,\n \"only makes sence for floating point types.\");\n\n static constexpr param_type in(param_type x) {\n if constexpr (impl::has_in::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::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 constexpr Float linear(Float x) {\n static_assert(std::is_floating_point_v,\n \"only makes sence for floating point types.\");\n return x;\n}\n\ntemplate constexpr Float ease_in(Float x) {\n return ease, Float>::in(x);\n}\n\ntemplate constexpr Float ease_out(Float x) {\n return ease, Float>::out(x);\n}\n\ntemplate constexpr Float ease_inout(Float x) {\n return ease, 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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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 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 \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n\nusing boost::multiprecision::float128;\nconstexpr const int GRAPH_WIDTH = 700;\n\ntemplate\nvoid plot_psi(int grid_refinements = -1)\n{\n auto psi = boost::math::daubechies_wavelet();\n if (grid_refinements >= 0)\n {\n psi = boost::math::daubechies_wavelet(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\nvoid plot_dpsi(int grid_refinements = -1)\n{\n auto psi = boost::math::daubechies_wavelet();\n if (grid_refinements >= 0)\n {\n psi = boost::math::daubechies_wavelet(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\nvoid plot_convergence()\n{\n auto psi1 = boost::math::daubechies_wavelet(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(2);\n daub.add_fn(psi2, \"red\");\n\n auto psi21 = boost::math::daubechies_wavelet(21);\n daub.add_fn(psi21);\n\n daub.write_all();\n}\n\ntemplate\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();\n Real a = phi.support().first + 1000*std::sqrt(std::numeric_limits::epsilon());\n Real b = phi.support().second - 1000*std::sqrt(std::numeric_limits::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\nvoid do_ulp(int coarse_refinements, PsiPrecise psi_precise)\n{\n auto psi_coarse = boost::math::daubechies_wavelet(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(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(); });\n boost::hana::for_each(std::make_index_sequence<17>(), [&](auto i){ plot_dpsi(); });\n boost::hana::for_each(std::make_index_sequence<17>(), [&](auto i){ plot_condition_number(); });\n boost::hana::for_each(std::make_index_sequence<18>(), [&](auto i){ plot_convergence(); });\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(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(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": "/**\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 \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& 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& 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& 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 `` ).\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 \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 \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 \nusing std::cout; using std::endl;\n#include \nusing std::setw; using std::setprecision;\n#include \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 \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_(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 \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::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::max)();\n // (std::numeric_limits::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();\n bool is_rising = true; // So if result if guess^3 is too low, try increasing guess.\n eps_tolerance tol(get_digits);\n std::pair r = \n bracket_and_solve_root(cbrt_functor_1(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 \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(x) to use to get cube root of x.\n }\n std::pair 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 \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::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::max)();\n // the default (std::numeric_limits::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(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 \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(x) to get cube root of x,\n }\n\n // using boost::math::tuple; // to return three values.\n boost::math::tuple 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 \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::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::max)();\n // the default (std::numeric_limits::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(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::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’s 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 \n#include \n#include \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(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(dataMin);\n mDataMax = asEigen(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(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(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 \n#include \n#include \n#include \n#include \n#include \n\n#define PI 3.141592653589793238462643383279502884L\n\n#define _l_ std::cout<<__LINE__<& 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 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& 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 \n#include \nusing namespace std; \n#include \n#include \n \n// 李群李代数 库 \n#include \"sophus/so3.hpp\"\n#include \"sophus/se3.hpp\"\n\n#include\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 eulerTransformation;\n for(int i = 0; i < 6; i++){\n eulerTransformation(i, 0) = *(ptrEulerTransformation + i);\n }\n\n // cout<<\"eulerTransformation = \"< se3;\n\n Eigen::Matrix3d R = Eigen::Matrix3d::Identity();\n Eigen::AngleAxisd rotation_Z_vector ( eulerTransformation(0,0), Eigen::Vector3d ( 0,0,1 ) ); //沿 Z 轴旋转 yaw\n Eigen::AngleAxisd rotation_Y_vector ( eulerTransformation(1,0), Eigen::Vector3d ( 0,1,0 ) ); //沿 Y 轴旋转 pitch\n Eigen::AngleAxisd rotation_X_vector ( eulerTransformation(2,0), Eigen::Vector3d ( 1,0,0 ) ); //沿 X 轴旋转 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 SE3_Rt(R, t); // 从R,t构造SE(3)\n\n // cout<<\"SE3 = \"<\n\n#include \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> gen_wolstenholme_numerator(long lower, long upper) {\n vector> output(upper-lower);\n\n for(long i = lower; i < upper; ++i) {\n if(i <= 1){\n output[i] = Elt(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 (4*i - 2);\n }\n }\n return output;\n}\n\nvector> gen_wolstenholme_denominator(long lower, long upper){\n vector> output(upper-lower);\n\n for(long i = lower; i < upper; ++i) {\n if(i <= 1){\n output[i] = Elt(1);\n }\n else {\n output[i-lower] = Elt (i - 1);\n }\n }\n return output;\n}\n\n\nvector> gen_fourth_prime_power(long lower, long upper) {\n vector> 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(n);\n }\n else{\n output[i-lower] = Elt(1);\n }\n }\n return output;\n}\n\n\nvector> gen_fifth_prime_power(long lower, long upper) {\n vector> 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(n);\n }\n else {\n output[i-lower] = Elt(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 \n#include \"stdio.h\"\n#include \n#include \n#include \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 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 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 \n#include \n#include \n\n#include \n\n#include \"../include/calcPI.h\"\n\n#include \n\nusing namespace boost::multiprecision;\n//namespace mp = boost::multiprecision; // mp::pow\n\nconst long long ACCUR = 100000; // Кол-во знаков после запятой\nconst size_t DIGNUM = ACCUR+10;\n\ntypedef number< cpp_dec_float > cpp_dec_float_DIGNUM;\n\n\n/*\nНеэффективная реализация этой формулы:\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 >>::max_digits10) << \"pi = \" << pi << std::endl;\n}\n\n\n/*\nНеточное вычисление числа pi, с помощью этой формулы:\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 \n#include \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(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<\n#include \n#include \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 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();\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();\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 \n\nnamespace IPC {\n\ntemplate \nclass GivensQR {\npublic:\n static void compute(const Eigen::Matrix& A,\n Eigen::Matrix& Q,\n Eigen::Matrix& 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 * tiny.cpp Blitz++ TinyVector ray reflection example\n *\n * This example illustrates the TinyVector 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 \n#include \n\nBZ_USING_NAMESPACE(blitz)\n\nvoid reflect(TinyVector& reflection, const TinyVector& ray,\n const TinyVector& 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 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 \r\n#include \r\n#include \r\n\r\n//[golden_ratio_1\r\ntemplate \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 \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 result_type;\r\n\r\n std::pair 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 \r\nT tan(T a)\r\n{\r\n tan_fraction fract(a);\r\n return a / continued_fraction_b(fract, std::numeric_limits::epsilon());\r\n}\r\n//]\r\n//[cf_expint_fraction\r\ntemplate \r\nstruct expint_fraction\r\n{\r\n typedef std::pair result_type;\r\n expint_fraction(unsigned n_, T z_) : b(z_ + T(n_)), i(-1), n(n_) {}\r\n std::pair operator()()\r\n {\r\n std::pair result = std::make_pair(-static_cast((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 \r\ninline std::complex expint_as_fraction(unsigned n, std::complex const& z)\r\n{\r\n boost::uintmax_t max_iter = 1000;\r\n expint_fraction > f(n, z);\r\n std::complex result = boost::math::tools::continued_fraction_b(\r\n f,\r\n std::complex(std::numeric_limits::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 \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 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 \r\ninline std::complex gamma_Q_as_fraction(const std::complex& a, const std::complex& z)\r\n{\r\n upper_incomplete_gamma_fract > f(a, z);\r\n std::complex eps(std::numeric_limits::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 func;\r\n double gr = continued_fraction_a(\r\n func,\r\n std::numeric_limits::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 arg(3, 2);\r\n std::cout << expint_as_fraction(5, arg) << std::endl;\r\n\r\n std::complex 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’s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n\n#include \"AlgorithmUtils.hpp\"\n#include \n#include \n#include \n#include \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>;\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 X, index distance)\n{\n auto dist = static_cast(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 \nEigen::MatrixXd DistanceMatrix(const Eigen::PlainObjectBase& X,\n const Eigen::PlainObjectBase& Y,\n index distance)\n{\n auto dist = static_cast(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 \n#include \n#include \n#include \n#include \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 MeshArray(double LowerLimit, double UpperLimit, int Num)\t\t\t//N - amount of steps\n{\n\tvector 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& V)\n{\n\tfor (vector::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 \n#include \n#include \n#include \n#include \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 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 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&): calculate median of dataset stored in passed sorted STL container.\n\t*Type mode(const Container&): 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 \n#include \n#include \n#include \n#include \n#include \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\nstd::tuple 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(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 class Container, class Type, class Alloc = std::allocator>\nType median(const Container &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 class Container, class Type, class Alloc = std::allocator>\nType mode(const Container &values)\t\t\t\t\t\t\t\t\t\t\t\t/* Get mode of elements in passed container. */\n{\n\tstd::map uniqueCounts;\n\tstd::set 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(*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 \n#include \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 \n#include \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 motion_model;\n\n // Observation model (user defined)\n std::function observation_model;\n\n // Jacobian of the motion model\n std::function jacobian_F;\n \n // Jacobian of the observation model\n std::function 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 \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 salidaMulticapa(const vector& pesos,\n const vec& patron)\n{\n\t// Este multicapa va a tener salida lineal sólo en la capa de salida.\n\t// En las demás capas se va a usar salida sigmoidea.\n\tvector 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ás 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 última, 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& 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 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& 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 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ón.\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 epocaMulticapa(const mat& patrones,\n const mat& salidaDeseada,\n double tasaAprendizaje,\n double inercia,\n vector pesos)\n{\n\t//Entrenamiento\n\tvector 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 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 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álculo 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á.\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ón 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, 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 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ás 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::max();\n vector 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 época\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ó por tolerancia de error,\n // el for va a incrementar la variable una vez de más.\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ínea está 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ásico de valores de parámetros\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 \n\nnamespace ATK\n{\n template\n RobertBristowJohnsonLowPassCoefficients::RobertBristowJohnsonLowPassCoefficients(gsl::index nb_channels)\n :Parent(nb_channels)\n {\n }\n\n template \n void RobertBristowJohnsonLowPassCoefficients::setup()\n {\n Parent::setup();\n\n CoeffDataType w0 = 2 * boost::math::constants::pi() * 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 \n void RobertBristowJohnsonLowPassCoefficients::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 \n typename RobertBristowJohnsonLowPassCoefficients::CoeffDataType RobertBristowJohnsonLowPassCoefficients::get_Q() const\n {\n return Q;\n }\n\n template\n RobertBristowJohnsonHighPassCoefficients::RobertBristowJohnsonHighPassCoefficients(gsl::index nb_channels)\n :Parent(nb_channels)\n {\n }\n\n template \n void RobertBristowJohnsonHighPassCoefficients::setup()\n {\n Parent::setup();\n\n CoeffDataType w0 = 2 * boost::math::constants::pi() * 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 \n void RobertBristowJohnsonHighPassCoefficients::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 \n typename RobertBristowJohnsonHighPassCoefficients::CoeffDataType RobertBristowJohnsonHighPassCoefficients::get_Q() const\n {\n return Q;\n }\n\n template\n RobertBristowJohnsonBandPassCoefficients::RobertBristowJohnsonBandPassCoefficients(gsl::index nb_channels)\n :Parent(nb_channels)\n {\n }\n\n template \n void RobertBristowJohnsonBandPassCoefficients::setup()\n {\n Parent::setup();\n\n CoeffDataType w0 = 2 * boost::math::constants::pi() * 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 \n void RobertBristowJohnsonBandPassCoefficients::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 \n typename RobertBristowJohnsonBandPassCoefficients::CoeffDataType RobertBristowJohnsonBandPassCoefficients::get_Q() const\n {\n return Q;\n }\n\n template\n RobertBristowJohnsonBandPass2Coefficients::RobertBristowJohnsonBandPass2Coefficients(gsl::index nb_channels)\n :Parent(nb_channels)\n {\n }\n\n template \n void RobertBristowJohnsonBandPass2Coefficients::setup()\n {\n Parent::setup();\n\n CoeffDataType w0 = 2 * boost::math::constants::pi() * 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 \n void RobertBristowJohnsonBandPass2Coefficients::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 \n typename RobertBristowJohnsonBandPass2Coefficients::CoeffDataType RobertBristowJohnsonBandPass2Coefficients::get_Q() const\n {\n return Q;\n }\n \n template\n RobertBristowJohnsonBandStopCoefficients::RobertBristowJohnsonBandStopCoefficients(gsl::index nb_channels)\n :Parent(nb_channels)\n {\n }\n \n template \n void RobertBristowJohnsonBandStopCoefficients::setup()\n {\n Parent::setup();\n \n CoeffDataType w0 = 2 * boost::math::constants::pi() * 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 \n void RobertBristowJohnsonBandStopCoefficients::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 \n typename RobertBristowJohnsonBandStopCoefficients::CoeffDataType RobertBristowJohnsonBandStopCoefficients::get_Q() const\n {\n return Q;\n }\n\n template\n RobertBristowJohnsonAllPassCoefficients::RobertBristowJohnsonAllPassCoefficients(gsl::index nb_channels)\n :Parent(nb_channels)\n {\n }\n\n template \n void RobertBristowJohnsonAllPassCoefficients::setup()\n {\n Parent::setup();\n\n CoeffDataType w0 = 2 * boost::math::constants::pi() * 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 \n void RobertBristowJohnsonAllPassCoefficients::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 \n typename RobertBristowJohnsonAllPassCoefficients::CoeffDataType RobertBristowJohnsonAllPassCoefficients::get_Q() const\n {\n return Q;\n }\n \n template\n RobertBristowJohnsonBandPassPeakCoefficients::RobertBristowJohnsonBandPassPeakCoefficients(gsl::index nb_channels)\n :Parent(nb_channels)\n {\n }\n \n template \n void RobertBristowJohnsonBandPassPeakCoefficients::setup()\n {\n Parent::setup();\n \n CoeffDataType w0 = 2 * boost::math::constants::pi() * 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 \n void RobertBristowJohnsonBandPassPeakCoefficients::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 \n typename RobertBristowJohnsonBandPassPeakCoefficients::CoeffDataType RobertBristowJohnsonBandPassPeakCoefficients::get_Q() const\n {\n return Q;\n }\n \n template \n void RobertBristowJohnsonBandPassPeakCoefficients::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 \n typename RobertBristowJohnsonBandPassPeakCoefficients::CoeffDataType RobertBristowJohnsonBandPassPeakCoefficients::get_gain() const\n {\n return gain;\n }\n \n template\n RobertBristowJohnsonLowShelvingCoefficients::RobertBristowJohnsonLowShelvingCoefficients(gsl::index nb_channels)\n :Parent(nb_channels)\n {\n }\n \n template \n void RobertBristowJohnsonLowShelvingCoefficients::setup()\n {\n Parent::setup();\n \n CoeffDataType w0 = 2 * boost::math::constants::pi() * 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 \n void RobertBristowJohnsonLowShelvingCoefficients::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 \n typename RobertBristowJohnsonLowShelvingCoefficients::CoeffDataType RobertBristowJohnsonLowShelvingCoefficients::get_Q() const\n {\n return Q;\n }\n \n template \n void RobertBristowJohnsonLowShelvingCoefficients::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 \n typename RobertBristowJohnsonLowShelvingCoefficients::CoeffDataType RobertBristowJohnsonLowShelvingCoefficients::get_gain() const\n {\n return gain;\n }\n \n template\n RobertBristowJohnsonHighShelvingCoefficients::RobertBristowJohnsonHighShelvingCoefficients(gsl::index nb_channels)\n :Parent(nb_channels)\n {\n }\n \n template \n void RobertBristowJohnsonHighShelvingCoefficients::setup()\n {\n Parent::setup();\n \n CoeffDataType w0 = 2 * boost::math::constants::pi() * 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 \n void RobertBristowJohnsonHighShelvingCoefficients::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 \n typename RobertBristowJohnsonHighShelvingCoefficients::CoeffDataType RobertBristowJohnsonHighShelvingCoefficients::get_Q() const\n {\n return Q;\n }\n \n template \n void RobertBristowJohnsonHighShelvingCoefficients::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 \n typename RobertBristowJohnsonHighShelvingCoefficients::CoeffDataType RobertBristowJohnsonHighShelvingCoefficients::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 \n\n#include \n\nstatic void diagonalizeInertiaTensor( const Matrix3s& I, Matrix3s& R0, Vector3s& I0 )\n{\n // Inertia tensor should by symmetric\n assert( ( I - I.transpose() ).lpNorm() <= 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 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() <= 1.0e-9 );\n assert( ( R0.transpose() * R * R0 - Matrix3s{ I.asDiagonal() } ).lpNorm() <= 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() <= 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": "#include \n#include \n\n#include \n#include \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 \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 pos_hat(pos_hat_ptr);\n\t\tEigen::Matrix pos_delta = pos_hat - pos_measured_.template cast();\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(\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 \n bool operator()(const T* const pos_hat_ptr,\n const T* const q_hat_ptr,\n T* residuals_ptr) const { \n Eigen::Matrix residuals;\n \n Eigen::Matrix pos_hat(pos_hat_ptr);\n Eigen::Matrix pos_delta;\n residuals.template block<3, 1>(0, 0) = pos_hat - pos_measured_.template cast();\n\n Eigen::Quaternion q_hat(q_hat_ptr);\n Eigen::Quaternion q_delta = q_measured_.conjugate().template cast() * 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(\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 \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 residuals;\n\n // quat error\n const Eigen::Quaternion q_b(q_b_ptr);\n const Eigen::Quaternion q_e(q_e_ptr);\n \n Eigen::Quaternion q_new;\n Eigen::Quaternion q_add; \n \n // // https://gamedev.stackexchange.com/questions/108920/applying-angular-velocity-to-quaternion \n // Eigen::Quaternion q_omega;\n // // q_omega.w() = 0;\n // q_omega.vec() = omega_measured_.template cast() * 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();\n q_new = q_b * q_add;\n \n Eigen::Quaternion 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 bias(bias_ptr);\n const Eigen::Matrix vel_b(vel_b_ptr);\n const Eigen::Matrix vel_e(vel_e_ptr);\n residuals.template block<3, 1>(3, 0) = vel_b + (q_b * (acc_measured_.template cast() - bias) - GRAVITY) * DT - vel_e;\n\n // pos error\n const Eigen::Matrix pos_b(pos_b_ptr);\n const Eigen::Matrix 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(\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 \n bool operator()(const T* const q_b_ptr,\n const T* const q_e_ptr,\n T* residuals_ptr) const {\n Eigen::Matrix residuals;\n\n // quat error\n const Eigen::Quaternion q_b(q_b_ptr);\n const Eigen::Quaternion q_e(q_e_ptr);\n \n Eigen::Quaternion q_new;\n Eigen::Quaternion q_add; \n \n // // https://gamedev.stackexchange.com/questions/108920/applying-angular-velocity-to-quaternion \n // Eigen::Quaternion q_omega;\n // // q_omega.w() = 0;\n // q_omega.vec() = omega_measured_.template cast() * 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();\n q_new = q_b * q_add;\n \n Eigen::Quaternion 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(\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> readSensorData(std::string path) {\n std::vector> ret;\n\n std::ifstream csvFile;\n csvFile.open(path);\n\n std::string line;\n while(std::getline(csvFile, line)) {\n std::vector 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>& 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>& states,\n const std::vector>& 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> 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> states(cnt);\n std::vector> 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 \n\n#include \n\n#include \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 \n\n// C++ stl\n#include \n#include \n#include \n#include \n#include \n\n// Eigen\n#include \n\n// Polyvec\n#include \n#include \n#include \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 \n\tEigen::Matrix\n\t\t_bezier_value_at(const Eigen::MatrixBase& 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 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&\n\t\t_get_gauss_quad_locs() {\n\t\tstatic std::vector 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&\n\t\t_get_gauss_quad_weights() {\n\t\tstatic std::vector 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::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& ww = _get_gauss_quad_weights();\n const std::vector& 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& ww = _get_gauss_quad_weights();\n const std::vector& 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 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 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 \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 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 \n#include \n#include \n#include \n#include \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 &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 &v) {\n if (v.empty()) {\n return std::numeric_limits::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& v)\n{\n if (v.size() <= 1u)\n return std::numeric_limits::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 &xs) {\n using namespace boost::accumulators;\n accumulator_set> 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 \n#include \n#include \n#include \n#include \n#include \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 \n#include \n#include \n#include \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>> 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 to_edgearray() {\n vector 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 e = to_edgearray();\n sort(e.begin(), e.end(), sortbysec);\n int vectorlist[V + 1];\n int parentlist[V + 1];\n boost::disjoint_sets 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 \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 AB04MD\n * (Discrete-time <-> continuous-time conversion by bilinear transformation).\n */\n class BilinearTransformation {\n public:\n template\n struct mallocStructC2D {\n Eigen::ColPivHouseholderQR> HH;\n Eigen::ColPivHouseholderQR> HH2;\n Eigen::Matrix I;\n };\n\n template\n struct mallocStructD2C {\n Eigen::ColPivHouseholderQR> HH;\n Eigen::Matrix IMAC;\n Eigen::Matrix 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\n static void\n c2d(const systems::StateSpace *ss, double dt, double alpha,\n systems::StateSpace *out,\n mallocStructC2D *memStruct,\n LS_IS_DYNAMIC_DEFAULT(TStateDim, TInputDim, TOutputDim));\n\n template\n static void\n c2d(const systems::StateSpace *ss, double dt, double alpha,\n systems::StateSpace *out,\n mallocStructC2D *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\n static void\n d2c(const systems::StateSpace *ss, double dt, double alpha,\n systems::StateSpace *out,\n mallocStructD2C *memStruct,\n LS_IS_DYNAMIC_DEFAULT(TStateDim, TInputDim, TOutputDim));\n\n template\n static void\n d2c(const systems::StateSpace *ss, double dt, double alpha,\n systems::StateSpace *out,\n mallocStructD2C *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\nvoid\nls::analysis::BilinearTransformation::c2d(const ls::systems::StateSpace *ss,\n double dt, double alpha,\n ls::systems::StateSpace *out,\n mallocStructC2D *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>(\n memStruct->I - alpha * dt * (ss->getA()));\n memStruct->HH2 = Eigen::ColPivHouseholderQR>(\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\nvoid\nls::analysis::BilinearTransformation::c2d(const ls::systems::StateSpace *ss,\n double dt, double alpha,\n ls::systems::StateSpace *out,\n mallocStructC2D *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>(\n memStruct->I - alpha * dt * (ss->getA()));\n memStruct->HH2 = Eigen::ColPivHouseholderQR>(\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\nvoid\nls::analysis::BilinearTransformation::d2c(const ls::systems::StateSpace *ss,\n double dt, double alpha,\n ls::systems::StateSpace *out,\n mallocStructD2C *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>(\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\nvoid\nls::analysis::BilinearTransformation::d2c(const ls::systems::StateSpace *ss,\n double dt, double alpha,\n ls::systems::StateSpace *out,\n mallocStructD2C *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>(\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 \n#include \n#include \n#include \n#include \n#include \n#include \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< 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 \n#include \n#include \n#include \n#include \n#include \n#include \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 &entities,\n const Ref ¢roids,\n Ref weights,\n squaredNorm_t *norm\n ){\n const int entitiesNumber = entities.rows();\n const int centroidsNumber = centroids.rows();\n for(int i=0;i 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 &entities, \n Ref centroids, \n Ref 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_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 &entities,\n const Ref ¢roids,\n const Ref &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 &entities, \n const Ref &clusters,\n const Ref &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 &entities,\n Ref 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 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 &entities,\n const Ref ¢roids,\n Ref 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 &entities,\n Ref centroids,\n Ref 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()) * entities;\n for(int i=0;i &entities,\n Ref centroids,\n Ref weights,\n Ref 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 &entities,\n Ref 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 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 \n#include \n#include \n#include \n#include \n\ntemplate\nvoid print(const std::vector& 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\nstd::vector multiply_halfcomplex(const std::vector& A, const std::vector& 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 TA(N),TB(N);\n boost::math::fft::bsl_rdft 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 C(N);\n \n C[0]=TA[0]*TB[0];\n for(unsigned int i=1;i+1\nstd::vector multiply_complex(const std::vector& A, const std::vector& 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 > TA(N),TB(N);\n boost::math::fft::bsl_rdft 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 C(N);\n \n for(unsigned int i=0;i\nT difference(const std::vector& A, const std::vector& B)\n{\n using std::abs;\n T diff{};\n if(A.size()!=B.size()) return -1;\n for(unsigned int i=0;i\nvoid multiply() {\n using std::abs;\n std::vector A{1.,4.,-5.,1.,0.,0.,0.,0.};\n std::vector B{-1.,1.,2.,3.,0.,0.,0.,0.};\n std::vector C{-1,-3,11,5,3,-13,3,0};\n \n std::vector 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();\n multiply();\n multiply();\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 \n#include \n#include \n#include \n\n#include \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 \nstruct pow_kernel\n{\npublic:\n using size_type = arma::uword;\n using real_type = T;\n using vector_type = arma::Col;\n using matrix_type = arma::Mat;\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\n get_num_gauss_jacobi(real_type beta__, real_type eps__);\n static std::tuple\n get_num_gauss_legendre(real_type beta__, real_type eps__);\n};\n\ntemplate \nvoid pow_kernel::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 gaujac(N1, T(), beta__ - 1);\n gauss_legendre_rule 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 \nvoid pow_kernel::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::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 \ntypename pow_kernel::size_type\npow_kernel::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 \nstd::tuple::size_type, T>\npow_kernel::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 \nstd::tuple::size_type, T>\npow_kernel::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::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 \n#include \n#include \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 \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 \n#include \n#include \n#include \n#include \"ising/mp_wrapper.hpp\"\n#include \"ising/tc/square.hpp\"\n#include \"options.hpp\"\n#include \"square.hpp\"\n\ntemplate\nvoid calc0(const options2& opt) {\n using namespace ising::free_energy;\n typedef T real_t;\n real_t Jx = convert(opt.Jx);\n real_t Jy = convert(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(opt.Tmin);\n Tmax = convert(opt.Tmax);\n dT = convert(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::digits10)\n << \"# lattice: square\\n\"\n << \"# precision: \" << std::numeric_limits::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\nvoid calc(const options2& opt) {\n using namespace ising::free_energy;\n typedef T real_t;\n real_t Jx = convert(opt.Jx);\n real_t Jy = convert(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(opt.Tmin);\n Tmax = convert(opt.Tmax);\n dT = convert(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::digits10)\n << \"# lattice: square\\n\"\n << \"# precision: \" << std::numeric_limits::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(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::digits10) {\n calc(opt);\n } else if (opt.prec <= std::numeric_limits::digits10) {\n calc(opt);\n } else if (opt.prec <= std::numeric_limits>::digits10) {\n calc0>(opt);\n // calc>(opt);\n } else if (opt.prec <= std::numeric_limits>::digits10) {\n calc0>(opt);\n // calc>(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 \n#include \n\nusing namespace AMDiS;\n\n\nvoid convergence_factor(std::vector> const& error)\n{\n mtl::dense_vector rhs_res(error.size());\n mtl::dense2D 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 convergence(2);\n \n mtl::dense2D 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 b(trans(Q)*rhs_res);\n mtl::irange rows(0,num_cols(A_res));\n \n mtl::dense2D 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 >\n{\n double operator()(WorldVector 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& U = *prob.getSolution(0);\n DOFVector ErrVec(U), UExact(U);\n \n auto u_exact = exp(-10.0*(X()*X()));\n \n std::vector> error_vec_L2;\n std::vector> error_vec_H1;\n std::vector> 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 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 \n\n#include \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 const& iPoints)\n {\n return Compute(iPoints.data(), iPoints.size());\n }\n\n bool ComputePrincipalAxis::operator()(Vector const& iPoints)\n {\n return Compute(iPoints.data(), iPoints.size());\n }\n\n template \n bool ComputePrincipalAxis::Compute(Polygon const& iPoly)\n {\n if (iPoly.Border().size() == 0)\n {\n return false;\n }\n uint32_t numPt = iPoly.Border().size();\n Vector2 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 \n bool ComputePrincipalAxis::Compute(Vector2 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 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 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#include \n#include \n#include \n\n#include \"SQPOSIXOnWindowsWarningSupression.h\"\n#include \"SQPosixOnWindows.h\"\n#include \"SQEigenWarningSupression.h\"\n#include \nusing namespace Eigen;\n\n#include \"Tuple.hxx\"\n#include \"FlatIndex.h\"\n#include \"SQMacros.h\"\n\n//*****************************************************************************\ntemplate\nbool IsReal(std::complex &c, T eps=T(1.0e-6))\n{\n return (fabs(imag(c)) < eps);\n}\n\n//*****************************************************************************\ntemplate\nbool IsComplex(std::complex &c, T eps=T(1.0e-6))\n{\n return (fabs(imag(c)) >= eps);\n}\n\n//*****************************************************************************\ntemplate\nint fequal(T a, T b, T tol)\n{\n T pda=fabs(a);\n T pdb=fabs(b);\n pda=pda\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 \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 \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\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\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)1),T(0.99)*rhi,nlo,data);\n linspace(((T)1),rhi,nhi,data+nlo);\n\n int i=0;\n for (; i\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 \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 \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 \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\nvoid slowSort(T *a, int l, int r)\n{\n for (int i=l; il; --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\nbool IsNan(T *V)\n{\n bool nan=false;\n for (int i=0; i\nvoid Init(T *V, T *V_0, int n)\n{\n for (int i=0; i\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,j,k) << std::endl;\n }\n }\n }\n }\n return has;\n}\n\n//*****************************************************************************\ntemplate\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,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 \nvoid Magnitude(int *I, T * V, T * mV)\n{\n for (int k=0; k\nvoid Magnitude(\n size_t n,\n T * __restrict__ V,\n T * __restrict__ mV)\n{\n for (size_t q=0; q\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\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\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\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\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\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\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 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 \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 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 \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 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 \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\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\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\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\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\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]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\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 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\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 comp(V);\n\n // visit each output element\n for (size_t wi=0; wi\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 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 \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 \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 \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 \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 \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 \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 *)w,3) << \" \"\n // << \"V=\" << Tuple(&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 \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 J;\n J <<\n j11, j12, j13,\n j21, j22, j23,\n j31, j32, j33;\n\n // construct pressure corrected hessian\n Matrix S=0.5*(J+J.transpose());\n Matrix W=0.5*(J-J.transpose());\n Matrix HP=S*S+W*W;\n\n // compute eigen values, lambda\n Matrix e;\n SelfAdjointEigenSolver >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 \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 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 S=((TD)0.5)*(J+J.transpose());\n Matrix W=((TD)0.5)*(J-J.transpose());\n Matrix HP=S*S+W*W;\n\n // compute eigen values, lambda\n Matrix e;\n SelfAdjointEigenSolver >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 \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 J;\n J <<\n j11, j12, j13,\n j21, j22, j23,\n j31, j32, j33;\n\n // construct pressure corrected hessian\n Matrix S=0.5*(J+J.transpose());\n Matrix W=0.5*(J-J.transpose());\n Matrix HP=S*S+W*W;\n\n // compute eigen values, lambda\n Matrix e;\n SelfAdjointEigenSolver >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 \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 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 S=((TD)0.5)*(J+J.transpose());\n Matrix W=((TD)0.5)*(J-J.transpose());\n Matrix HP=S*S+W*W;\n\n // compute eigen values, lambda\n Matrix e;\n SelfAdjointEigenSolver >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 \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 \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 \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 \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 \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 \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 \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 \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 \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 \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 \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 J;\n J <<\n j11, j12, j13,\n j21, j22, j23,\n j31, j32, j33;\n\n // compute eigen values, lambda\n Matrix,3,1> e;\n EigenSolver >solver(J,false);\n e=solver.eigenvalues();\n\n std::complex &e1 = e(0);\n std::complex &e2 = e(1);\n std::complex &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 \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;\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;\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 \nusing std::cout; using std::endl;\nusing std::left; using std::fixed; using std::right; using std::scientific;\n#include \nusing std::setw;\nusing std::setprecision;\n#include \n\n#include \n#include \n#include \n\n#include \nusing boost::multiprecision::cpp_dec_float_50;\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nvoid gen_x_signed_exp(const double r, boost::random::mt19937& rng, int N, std::vector& vec)\n{\n boost::random::uniform_real_distribution<> runif;\n boost::random::exponential_distribution 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& vec, bool srtd = true)\n{\n boost::random::uniform_real_distribution<> runif;\n boost::random::exponential_distribution 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& 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& vec, bool srtd = true)\n{\n boost::random::uniform_real_distribution<> runif;\n boost::random::exponential_distribution rexp(r);\n\n for (int i = 0; i < N; ++i)\n {\n double x = rexp(rng);\n vec.push_back(static_cast(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(argv[2]);\n }\n\n unsigned long S = 17;\n if (argc >= 5)\n {\n S = boost::lexical_cast(argv[3]);\n std::cerr << S << endl;\n }\n boost::random::mt19937 rng(S);\n\n std::cout.precision(std::numeric_limits::digits10);\n\n if (fun == \"beta\")\n {\n std::vector A;\n gen_x_unsigned_exp(0.05, rng, N, A, false);\n std::vector B;\n gen_x_unsigned_exp(0.05, rng, N, B, false);\n\n std::vector 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 A;\n gen_k_unsigned_exp(0.01, rng, N, A, false);\n std::vector B;\n gen_k_unsigned_exp(0.01, rng, N, B, false);\n\n std::vector 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 A;\n gen_k_unsigned_exp(0.01, rng, N, A, false);\n std::vector B;\n gen_k_unsigned_exp(0.01, rng, N, B, false);\n\n std::vector X;\n gen_x_unsigned_unif(rng, N, X, false);\n\n std::vector Y;\n std::vector 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 A;\n gen_x_unsigned_exp(0.05, rng, N, A, false);\n std::vector B;\n gen_x_unsigned_exp(0.05, rng, N, B, false);\n\n std::vector X;\n gen_x_unsigned_unif(rng, N, X, false);\n\n std::vector Y;\n std::vector 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 J;\n std::vector 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 C;\n std::vector D;\n for (int i = 0; i < N; ++i)\n {\n cpp_dec_float_50 c = boost::math::binomial_coefficient(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 X;\n gen_x_signed_exp(0.2, rng, N, X);\n\n std::vector 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 X;\n gen_x_signed_exp(0.2, rng, N, X);\n\n std::vector 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 X;\n gen_x_unsigned_exp(0.05, rng, N, X);\n\n std::vector Y;\n std::vector 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 A;\n gen_x_unsigned_exp(0.1, rng, N, A);\n std::vector X;\n gen_x_unsigned_exp(0.1, rng, N, X, false);\n\n std::vector Y;\n std::vector Z;\n std::vector U;\n std::vector 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": "#include \n#include \n#include \n#include \n\n#include \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(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 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(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 \nusing namespace std;\n\n// Eigen includes\n#include \nusing namespace Eigen;\n\n// autodiff include\n#include \n#include \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 \n#include \n#include \n#include \n\nnamespace UpwindFiniteVolume {\n\n/* SAM_LISTING_BEGIN_1 */\nEigen::Matrix gradbarycoordinates(\n const Eigen::Matrix &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’s ’Real-Time Collision Detection’\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 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 \n#include \n#ifdef _MSC_VER\n#define _USE_MATH_DEFINES\n#endif\n#include \n\nconst double SMALL_EPS = 1e-10;\n\ntypedef Eigen::Matrix Vector6d;\ntypedef Eigen::Matrix 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)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() = 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() = 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 adj() const\n {\n Eigen::Matrix3d R = _r.toRotationMatrix();\n Eigen::Matrix 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 to_homogeneous_matrix() const\n {\n Eigen::Matrix 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 \n#include \n#include \n\n#include \n\n#include \n\nusing std::cout;\nusing std::endl;\n\nnamespace solver { \ntemplate\nclass Solver {\n private:\n // Function\n const std::function f_;\n // Derivative of the function\n const std::function 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 f,\n const std::function df\n ) :\n \n f_(f), df_(df)\n {\n h_ = std::sqrt(std::numeric_limits::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&)>> f_;\n //Eigen::Matrix 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&)>> &f\n ) :\n \n f_(f) {\n //h_ = std::sqrt(std::numeric_limits::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 solve(\n Eigen::Matrix x0\n ) \n {\n\n std::cout << \"h = \" << h_ << \"\\n\"\n << \"tol = \" << tol_ << \"\\n\\n\";\n\n using solver::differentiate;\n Eigen::Matrix jacobian, inv_jacobian;\n Eigen::Matrix 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(f_[i], x, j, h_);\n jacobian(i, j) = std::move(val);\n }\n }\n\n inv_jacobian = jacobian.inverse();\n \n Eigen::Matrix 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 f,\n const std::function 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 \r\n\r\n#include \r\n\r\n\r\ntemplate\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& function);\r\n void addCompositorFunction(const std::string& functionName, const std::vector& 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 parser;\r\n exprtk::expression expression;\r\n exprtk::symbol_table symbolTable;\r\n exprtk::function_compositor compositor;\r\n\r\n exprtk::parser_error::type error;\r\n\r\n std::string task;\r\n\r\n GCD gcd;\r\n LCM lcm;\r\n PrimeTest primeTest;\r\n\r\n void loadConstants();\r\n void loadFunctions();\r\n};\r\n\r\n\r\ntemplate\r\nMathSolver::MathSolver() :\r\n MathSolver(\"\")\r\n{\r\n}\r\n\r\ntemplate\r\nMathSolver::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\r\nbool MathSolver::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\r\nT MathSolver::getValue() const\r\n{\r\n return this->expression.value();\r\n}\r\n\r\ntemplate\r\nstd::string MathSolver::getTask() const\r\n{\r\n return this->task;\r\n}\r\n\r\ntemplate\r\nT MathSolver::getVariable(const std::string& variableName)\r\n{\r\n return this->symbolTable.get_variable(variableName)->ref();\r\n}\r\n\r\ntemplate\r\nstd::string MathSolver::getStringVariable(const std::string& variableName)\r\n{\r\n return this->symbolTable.get_stringvar(variableName)->value();\r\n}\r\n\r\ntemplate\r\nT MathSolver::getDerivative(T& variable)\r\n{\r\n return exprtk::derivative(this->expression, variable);\r\n}\r\n\r\ntemplate\r\nT MathSolver::getSecondDerivative(T& variable)\r\n{\r\n return exprtk::second_derivative(this->expression, variable);\r\n}\r\n\r\ntemplate\r\nT MathSolver::getThirdDerivative(T& variable)\r\n{\r\n return exprtk::third_derivative(this->expression, variable);\r\n}\r\n\r\ntemplate\r\nT MathSolver::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\r\nvoid MathSolver::setTask(const std::string& task)\r\n{\r\n this->task = task;\r\n}\r\n\r\ntemplate\r\nvoid MathSolver::addVariable(const std::string& variableName, T& variable)\r\n{\r\n this->symbolTable.add_variable(variableName, variable);\r\n}\r\n\r\ntemplate\r\nvoid MathSolver::addConstant(const std::string& constantName, T& variable)\r\n{\r\n this->symbolTable.add_constant(constantName, variable);\r\n}\r\n\r\ntemplate\r\nvoid MathSolver::addStringVar(const std::string& stringVariableName, std::string& variable)\r\n{\r\n this->symbolTable.add_stringvar(stringVariableName, variable);\r\n}\r\n\r\ntemplate\r\nvoid MathSolver::addFunction(const std::string& functionName, exprtk::ifunction& function)\r\n{\r\n this->symbolTable.add_function(functionName, function);\r\n}\r\n\r\ntemplate\r\nvoid MathSolver::addCompositorFunction(const std::string& functionName, const std::vector& parameters, const std::string& functionBody)\r\n{\r\n exprtk::function_compositor::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\r\nvoid MathSolver::removeVariable(const std::string& variableName)\r\n{\r\n this->symbolTable.remove_variable(variableName);\r\n}\r\n\r\ntemplate\r\nvoid MathSolver::removeStringVar(const std::string& stringVariableName)\r\n{\r\n this->symbolTable.remove_stringvar(stringVariableName);\r\n}\r\n\r\ntemplate\r\nvoid MathSolver::removeFunction(const std::string& functionName)\r\n{\r\n this->symbolTable.remove_function(functionName);\r\n}\r\n\r\ntemplate\r\nvoid MathSolver::clearTask()\r\n{\r\n this->task.clear();\r\n}\r\n\r\ntemplate\r\nvoid MathSolver::clearSymbols()\r\n{\r\n this->symbolTable.clear();\r\n}\r\n\r\ntemplate\r\nvoid MathSolver::loadConstants()\r\n{\r\n this->symbolTable.add_constants();\r\n this->symbolTable.add_constant(\"e\", boost::math::constants::e());\r\n}\r\n\r\ntemplate\r\nvoid MathSolver::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 \n#include \n#include \n#include \n#include \n#include \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 θ and cos θ\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 &V) {\n const double h = (rmax - rmin) / N;\n\n // array of ρ 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(ρ_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": "\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 \n\n#ifdef NYARUGA_UTIL_HAS_EIGEN\n\n#include \n#include \n#include \n#include \n\n// 二重数を用いた自動微分ライブラリ\n// TODO: std::xx -> xx (using ADL)\n\nnamespace nyaruga {\n\nnamespace util {\n\nnamespace detail {\n\ntemplate \nconstexpr auto make_init_value(int dim, int var_no) noexcept \n{\n Eigen::Matrix tmp = Eigen::Matrix::Zero(dim);\n tmp(var_no - 1) = 1.;\n return tmp; \n}\n\n} // namespace detail\n\n\ntemplate \nstruct var {\n\tusing value_type = R;\n\tusing diff_value_type = Eigen::Matrix;\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 \nconstexpr auto operator + (const var& lhs, const var& rhs) noexcept\n{\n\treturn var(lhs.val + rhs.val, static_cast::diff_value_type>(lhs.dval + rhs.dval));\n}\n\ntemplate \nconstexpr auto operator - (const var& lhs, const var& rhs) noexcept\n{\n\treturn var(lhs.val - rhs.val, static_cast::diff_value_type>(lhs.dval - rhs.dval));\n}\n\ntemplate \nconstexpr auto operator * (const var& lhs, const var& rhs) noexcept\n{\n\treturn var(lhs.val * rhs.val, static_cast::diff_value_type>(rhs.val*lhs.dval + lhs.val*rhs.dval));\n}\n\n// rhs.val != 0\ntemplate \nconstexpr auto operator / (const var& lhs, const var& rhs)\n{\n\treturn var(lhs.val / rhs.val, static_cast::diff_value_type>((lhs.dval*rhs.val - lhs.val*rhs.dval)/std::pow(rhs.val,2)));\n}\n\ntemplate \nconstexpr auto sin(const var& x) noexcept\n{\n\treturn var(std::sin(x.val), static_cast::diff_value_type>(std::cos(x.val)*x.dval));\n}\n\ntemplate \nconstexpr auto cos(const var& x) noexcept\n{\n\treturn var(std::cos(x.val), static_cast::diff_value_type>(-x.dval*std::sin(x.val)));\n}\n\ntemplate \nconstexpr auto exp(const var& x) noexcept\n{\n\treturn var(std::exp(x.val), static_cast::diff_value_type>(x.dval*std::exp(x.val)));\n}\n\n// x.val > 0\ntemplate \nconstexpr auto log(const var& x)\n{\n\treturn var(std::log(x.val), static_cast::diff_value_type>(x.dval/x.val));\n}\n\n// x.val != 0\ntemplate \nconstexpr auto pow(const var& x, float num)\n{\n\treturn var(std::pow(x.val,num), static_cast::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 \n\n#include \n#include \n#include \n#include \n#include \n#include \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(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(x));\n sum += log_of_e / l + log_of_e / (log_of_two + l) + log_of_e / std::log2(static_cast(2 * x + 1));\n }\n\n if (is_midpoint_odd)\n {\n sum += log_of_e / std::log2(static_cast(2 * node_end)) + log_of_e / std::log2(static_cast(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(x));\n sum += log_of_e / l + log_of_e / (log_of_two + l) + log_of_e / std::log2(static_cast(2 * x + 1));\n }\n }\n\n if (end_point & 1 && node_index == 0)\n {\n sum += log_of_e / std::log2(static_cast(end_point - 1));\n }\n\n end_point = start_point;\n }\n } \n}\n\nstd::pair\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(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 \n#include \n#include \n#include \n\n#include \n#include \n#include \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 obs_noise_distrib(0.0, obs_sigma);\n\n\n int N = 100;\n std::vector x_data(N), y_data(N);\n for (int i = 0; i < N; ++i)\n {\n x_data[i] = static_cast(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 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 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üttler, edited by Oliver Rietmann\n * @date 03.03.2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"mylinearloadvector.h\"\n\n#include \n#include \n#include \n\n#include \n#include \n\nnamespace ElementMatrixComputation {\n\n namespace {\n\n/* SAM_LISTING_BEGIN_1 */\n Eigen::Vector4d computeLoadVector(\n const Eigen::MatrixXd &vertices,\n std::function 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": "#include \n#include \n#include \n#include \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 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 loge(Matrix in)\n{\n Matrix out = in;\n\n out = out.array() + 1e-7f;\n\n for(int i=0; i output, Matrix expect)\n{\n Matrix 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 \n\n#ifdef NYARUGA_UTIL_HAS_EIGEN\n\n#include \n#include \n#include \n#include \n\nnamespace shijimi { namespace math {\n\nnamespace detail {\n\ntemplate \nconstexpr auto make_init_value(int var_no) noexcept \n{\n Eigen::Matrix tmp = Eigen::Matrix::Zero();\n tmp(var_no - 1) = 1.;\n return tmp; \n}\n\n} // namespace detail\n\ntemplate \nstruct var {\n\tusing value_type = R;\n static constexpr size_t dimention = dim;\n\tusing diff_value_type = Eigen::Matrix;\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(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 \nconstexpr auto operator + (const var& lhs, const var& rhs) noexcept\n{\n\treturn var(lhs.val + rhs.val, static_cast::diff_value_type>(lhs.dval + rhs.dval));\n}\n\ntemplate \nconstexpr auto operator - (const var& lhs, const var& rhs) noexcept\n{\n\treturn var(lhs.val - rhs.val, static_cast::diff_value_type>(lhs.dval - rhs.dval));\n}\n\ntemplate \nconstexpr auto operator * (const var& lhs, const var& rhs) noexcept\n{\n\treturn var(lhs.val * rhs.val, static_cast::diff_value_type>(rhs.val*lhs.dval + lhs.val*rhs.dval));\n}\n\n// rhs.val != 0\ntemplate \nconstexpr auto operator / (const var& lhs, const var& rhs)\n{\n\treturn var(lhs.val / rhs.val, static_cast::diff_value_type>((lhs.dval*rhs.val - lhs.val*rhs.dval)/std::pow(rhs.val,2)));\n}\n\ntemplate \nconstexpr auto sin(const var& x) noexcept\n{\n\treturn var(std::sin(x.val), static_cast::diff_value_type>(std::cos(x.val)*x.dval));\n}\n\ntemplate \nconstexpr auto cos(const var& x) noexcept\n{\n\treturn var(std::cos(x.val), static_cast::diff_value_type>(-x.dval*std::sin(x.val)));\n}\n\ntemplate \nconstexpr auto exp(const var& x) noexcept\n{\n\treturn var(std::exp(x.val), static_cast::diff_value_type>(x.dval*std::exp(x.val)));\n}\n\n// x.val > 0\ntemplate \nconstexpr auto log(const var& x)\n{\n\treturn var(std::log(x.val), static_cast::diff_value_type>(x.dval/x.val));\n}\n\n// x.val != 0\ntemplate \nconstexpr auto pow(const var& x, float num)\n{\n\treturn var(std::pow(x.val,num), static_cast::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 \n#include \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 \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#include // std::max\n#include \n#include \n#include \n#include \n#include /* log */\n#include \n#include \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::min(),std::numeric_limits::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_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 \r\n\r\nusing namespace std;\r\n#include \r\n#include \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 \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n/// @struct options\n/// @brief parsed command line options\nstruct Options {\n /// type of filter function\n using filter_function_type = std::function;\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::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::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(&options.max_number)->default_value(1000),\n \"generating primes up to this limit (default: 1000)\")\n (\"start-number\", po::value(&options.start_number)->default_value(2),\n \"printing primes >= this number (default: 2)\")\n (\"columns\", po::value(&options.max_columns)->default_value(10),\n \"number of columns (default: 10)\")\n (\"filter\", po::value(&filter_name)->default_value(\"\"),\n \"providing filter name (default: none).\")\n (\"sieve\", po::value(&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 \nstd::unique_ptr> create_sieve(const Options& options) noexcept {\n if (options.sieve == \"optimized\") {\n return std::unique_ptr>(\n new math::prime::sieve_of_eratosthenes_optimized(options.max_number));\n }\n\n return std::unique_ptr>(\n new math::prime::sieve_of_eratosthenes(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>(options);\n\n const auto sieve_duration = performance::measure([&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(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::count(*(primes.end()-1)) + 1;\n\n auto column = static_cast(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\n\n#include \n\n#include \n#include \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 > 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 > 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 > 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 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(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 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 \n#include \n//#include \n//#include \n#include \n#include \n\n// random number generator engine\nboost::mt19937 rng_g(std::time(0)) ;\nboost::normal_distribution normal_dist ;\nboost::variate_generator< boost::mt19937, boost::normal_distribution > 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 \n#include \n\ntypedef unsigned long long nombre;\ntypedef std::vector vecteur;\ntypedef std::vector 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 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 \n#include \n\n#include \n#include \n\nusing namespace sysid;\n\nstd::tuple, double> sysid::OLS(\n const std::vector& 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β + u, where y is the dependent observed variable, X is the matrix\n // of independent variables, β 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β)'(y - Xβ).\n // β = (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> y(\n data.data() + 0, rows, 1, Eigen::Stride<1, Eigen::Dynamic>(1, strd));\n\n Eigen::Map> X(\n data.data() + 1, rows, cols, Eigen::Stride<1, Eigen::Dynamic>(1, strd));\n\n // Calculate b = β 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": "//\n// Created by Jakub Tyrcha on 13/11/2017.\n//\n\n#include \"utilities.h\"\n#include \n#include \n#include \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 generate_prime_size() {\n std::vector 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 \n#include \n#include \n#include \n#include \n#include \n#include \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\nHyperplane svm(\n const StdVectorVectorDIM& f, \n const StdVectorVectorDIM& s) {\n\n QPWrappers::Problem svm_qp(DIM + 1);\n Matrix 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& pt : f) {\n Row 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::lowest(), -1);\n }\n\n for(const VectorDIM& pt : s) {\n Row 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::max());\n }\n\n\n QPWrappers::RLSS_SVM_QP_SOLVER::Engine solver;\n solver.setFeasibilityTolerance(1e-8);\n Vector result(DIM+1);\n auto ret = solver.init(svm_qp, result);\n// debug_message(\"svm optimization return value is \", ret);\n Hyperplane 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 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 \n#include \n#include \"mexHelpers.cpp\"\n#include \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 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(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 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(pA.data() + ii*block_size, dim, dim);\n\t\t//\n\t\tcurrAf = currA.cast(); // double -> single\n\t\tsvd3x3(currAf, U, s, V); // svd\n\t\tR = U * V.transpose(); // polar\n\t\tcurrA = R.cast();\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 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 \n#include \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 \n#include \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 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 \n\n#include \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 vertNorms = std::vector(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::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 \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\n#include \n#include \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 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\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(argv[1]) : 1000;\n \n // Generate N points on a sphere of radius 100.\n std::vector 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\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\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 \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;\nusing Mat5f = Eigen::Matrix;\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>\n{\n LOG_INFO(\"Creating Internal Penrose Polytope from data g={} and gamma={}\", g,gamma);\n\n using namespace quickhull;\n QuickHull qh;\n auto vertices = std::vector();\n auto g_penrose = PenroseRotation();\n g = g*g_penrose;\n auto unit_cube = std::vector();\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();\n auto indices = std::vector();\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 \n#include \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<\n#include \n#include \n#include \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(in);\n mNumDataPoints = input.rows();\n mMean = input.colwise().mean();\n MatrixXd X = (input.rowwise() - mMean.transpose());\n BDCSVD 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(bases);\n mValues = _impl::asEigen(values);\n mMean = _impl::asEigen(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(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(out) =\n mMean +\n (asEigen(in).transpose() * mBases.transpose()).transpose();\n }\n else\n {\n asEigen(out) = mMean + (asEigen(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(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(out) =\n (_impl::asEigen(in) * mBases.transpose()).rowwise() +\n mMean.transpose();\n\n else\n {\n _impl::asEigen(out) =\n (_impl::asEigen(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 \n#include \n#include \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;\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(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": "/* -*- 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. The license is also available online at\n.\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–73.\n*/\n\n#ifndef quantlib_optimization_particleswarmoptimization_hpp\n#define quantlib_optimization_particleswarmoptimization_hpp\n\n#include \n\n#if BOOST_VERSION >= 104700\n\n#include \n#include \n#include \n#include \n#include \n\n#include \ntypedef boost::mt19937 base_generator_type;\n\n#include \ntypedef boost::random::uniform_int_distribution 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,\n boost::shared_ptr 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,\n boost::shared_ptr 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 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_;\n boost::shared_ptr 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 *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 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(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(&(*V_)[i][0]);\n }\n }\n }\n private:\n MersenneTwisterUniformRng rng_;\n IsotropicLevyFlight flight_;\n Array personalBestF_;\n std::vector 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 *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 > clubs4particles_;\n std::vector > particles4clubs_;\n std::vector bestByClub_;\n std::vector 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{}\n\n @par Description\n\n 1. @code\n template T Gold();\n @endcode\n\n 2. @code\n template T Gold( boost::simd::as_ 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 \n#include \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": "/*\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 \n#include \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 x1(2, 2);\n x1 << 0, 1, 2, 3;\n\n // static matrix (note the delimiting of dimensions in the template)\n eig::Matrix x2;\n x2 << 5,2,3,1;\n \n eig::MatrixX 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 y1(2, 2); // having two 'X's is correct\n y1 << 2, 3, 4, 5;\n eig::Array y2; // also has a static option\n y2 << 5, 6, 7, 8;\n\n // conversion between the two: \n eig::MatrixX xtemp = y1.matrix();\n\n // note there are also vectors, but used to a far lesser extent\n eig::VectorX 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> x4(x1.data(), 1,x1.size());\n cout << \"reshape: \" << x4 << endl;\n // append a row\n eig::MatrixX 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 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::Identity() << endl;\n cout << \"zeros \\n\" << eig::Matrix::Zero() << endl;\n cout << \"ones\\n\" << eig::Matrix::Ones() << endl;\n cout << \"random\\n\" << eig::MatrixX::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 \n#include \n#include \n#include \n\nnamespace kkl {\n\tnamespace alg {\n\ntemplate\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 munkres\n * auto ans = munkres.solve( cost )\n************************************************/\ntemplate\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& 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> 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 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": "// 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 \r\n#include \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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace boost::numeric;\n\ntemplate\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\nint gmres(ublas::vector &y, ublas::matrix &A, ublas::vector &x, type tol, size_t m)\n{\n using namespace ublas;\n\n typedef vector Vec;\n typedef matrix Mat;\n\n int size = y.size();\n unit_vector 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 x(size, 0.0);\n ublas::vector y(size, 1.0);\n ublas::matrix 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": "/*\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 \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace boost::python;\n\ntemplate \nvector python_list_to_vector(list& l, T x){ // second argument used for template deduction\n\tvector res;\n\tfor(int i=0; i < len(l); i++){\n\t\tres.push_back(extract(l[i]));\n\t}\n\treturn res;\n}\n\ntemplate \nlist vector_to_python_list(vector v){\n\tlist res;\n\tfor(int i=0; i\nvector> python_list_of_lists_to_vector(list& l, T x){ // second argument used for template deduction\n\tvector> res;\n\tfor(int i=0; i < len(l); i++){\n\t\tvector line;\n\t\tfor(int j=0; j < len(l[i]); j++){\n\t\t\tline.push_back(extract(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 layers; \n\t\tvector>> weights;\n\t\tvector> bias;\n\n\tpublic:\n\t\t\n\t\t// constructor with random weights and bias\n\n\t\tvoid build_network(vector layers_){\n\t\t\tN_layers = layers_.size();\n\t\t\tdefault_random_engine generator(time(0));\n\t\t\tnormal_distribution distribution(0.,1.);\n\t\t\tint N_k;\n\t\t\tfor(int i=0; i> weights_layer;\n\t\t\t\tvector bias_layer;\n\t\t\t\tfor(int j=0; j 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 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 layers_, \n\t\t\t vector>> weights_, \n\t\t vector> 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(layers_[i]));\n\t\t\t\tvector> weights_layer;\n\t\t\t\tvector bias_layer;\n\t\t\t\tfor(int j=0; j weights_neuron;\n\t\t\t\t\tfor(int k=0; k(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(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 feedforward(vector x){\n\t\t\tfor(int i=0; i y;\n\t\t\t\tfor(int j=0; j 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> data, vector y_true_all){\n\t\t\tdouble res = 0.;\n\t\t\tfor(int i=0; i> data, vector 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 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> states;\n\t\t\t\t\tstates.push_back(x);\n\t\t\t\t\tfor(int i=0; i y;\n\t\t\t\t\t\tfor(int j=0; j>> d_ypred_d_x;\n\t\t\t\t\tvector>> d_ypred_d_weights;\n\t\t\t\t\tvector> 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> d_ypred_d_x_layer;\n\t\t\t\t\tvector d_ypred_d_x_neuron;\n\t\t\t\t\tvector> d_ypred_d_weights_layer;\n\t\t\t\t\tvector d_ypred_d_weights_neuron;\n\t\t\t\t\tvector d_ypred_d_bias_layer;\n\t\t\t\t\tfor(int k=0; k> d_ypred_d_x_layer;\n\t\t\t\t\t\tvector> d_ypred_d_weights_layer;\n\t\t\t\t\t\tvector d_ypred_d_bias_layer;\n\t\t\t\t\t\tfor(int j=0; j d_ypred_d_x_neuron;\n\t\t\t\t\t\t\tvector d_ypred_d_weights_neuron;\n\t\t\t\t\t\t\tfor(int k=0; k> 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_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> weights_layer;\n\t\t\t\tvector bias_layer;\n\t\t\t\tfor(int j=0; j weights_neuron;\n\t\t\t\t\tfile >> n_weights;\n\t\t\t\t\tfor(int k=0; k> 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\", init())\n\t\t.def(init())\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 \n*/\n// Include some headers\n#include \n#include \n#include \n\nusing namespace std::complex_literals; // Complex literals\n\ntypedef std::complex 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 \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 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 alphazero, betazero; // Ground state amplitude\n std::complex alphan, betan; // Excited state amplitude\n std::complex pos; // Positive energy state amplitude\n std::complex 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 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 \n#include \n#include \n#include \"../simple_lib/include/simple_activation.h\"\n\nusing namespace Eigen;\n\ndouble cross_entropy_error(MatrixXd &, MatrixXd &); // プロトタイプ宣言\n\nclass simpleNet\n{\nprivate:\n MatrixXd W = MatrixXd::Random(2, 3); // 乱数で初期化(本来はXavierの初期値とかにしたい?)\n\npublic:\n simpleNet(); // コンストラクタ\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; // この書き方をするには、上記のようにメモリ確保をしておく必要がある(でないとセグフォになる)\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をすべて1で初期化した場合)が正解\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) の計算\n W(i) = tmp_val + h; // 変数xのi番目の要素だけ増分を取った形に変更\n f_xh1 = simpleNet::loss(x, t);\n // f(x-h)の計算\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; // 元の値に戻す\n }\n\n return grad;\n}\n\n// one-hot labelバージョンの のミニバッチ実装\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 \n#include \n#include \n#include \n#include \n#include \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 given as argument (broadcast).\n// NB: it converts std::vectors tu arma::dmat-s\ndmat CastVecMat(const vector& 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 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 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 Map;\n\t\tMap[\"Gaussian\"] = 1;\n\t\tMap[\"Uniform\"] = 2;\n\t\n\tvector 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(MinDist(dOI, peakDay))/5;\n // filling the gaussian cumulative\n for (int i=0; i(dOI)*finalProb;\n // filling the uniform cumulative\n\t\t\t\t\t\tfor (int i=0; i(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 \n#include \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 .\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 \n#include \n\n#include \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\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\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() requires is_mutable\n {\n return Map>(static_cast<_Derived &>(*this).data() + 3);\n }\n\n /**\n * @brief Const access SO(3) part.\n */\n Map> so3() const\n {\n return Map>(static_cast(*this).data() + 3);\n }\n\n /**\n * @brief Access R3 part.\n */\n Eigen::Map> r3() requires is_mutable\n {\n return Eigen::Map>(static_cast<_Derived &>(*this).data());\n }\n\n /**\n * @brief Const access R3 part.\n */\n Eigen::Map> r3() const\n {\n return Eigen::Map>(static_cast(*this).data());\n }\n\n /**\n * @brief Return as 3D Eigen transform.\n */\n Eigen::Transform isometry() const\n {\n return Eigen::Translation(r3()) * so3().quat();\n }\n\n /**\n * @brief Tranformation action on 3D vector.\n */\n template\n Eigen::Vector3 operator*(const Eigen::MatrixBase & 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 project_se2() const\n {\n return SE2(so3().project_so2(), r3().template head<2>());\n }\n};\n\n// \\cond\ntemplate\nclass SE3;\n// \\endcond\n\n// \\cond\ntemplate\nstruct liebase_info>\n{\n static constexpr bool is_mutable = true;\n\n using Impl = SE3Impl<_Scalar>;\n using Scalar = _Scalar;\n\n template\n using PlainObject = SE3;\n};\n// \\endcond\n\n/**\n * @brief Storage implementation of SE3 Lie group.\n *\n * @see SE3Base for memory layout.\n */\ntemplate\nclass SE3 : public SE3Base>\n{\n using Base = SE3Base>;\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\n SE3(const SO3Base & so3, const Eigen::MatrixBase & r3)\n {\n Base::so3() = static_cast(so3);\n Base::r3() = static_cast(r3);\n }\n\n /**\n * @brief Construct from Eigen transform.\n */\n SE3(const Eigen::Transform & t)\n {\n Base::so3() = smooth::SO3(Eigen::Quaternion(t.rotation()));\n Base::r3() = t.translation();\n }\n};\n\n// \\cond\ntemplate\nstruct liebase_info>> : public liebase_info>\n{};\n// \\endcond\n\n/**\n * @brief Memory mapping of SE3 Lie group.\n *\n * @see SE3Base for memory layout.\n */\ntemplate\nclass Map> : public SE3Base>>\n{\n using Base = SE3Base>>;\n\n SMOOTH_MAP_API();\n};\n\n// \\cond\ntemplate\nstruct liebase_info>> : public liebase_info>\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\nclass Map> : public SE3Base>>\n{\n using Base = SE3Base>>;\n\n SMOOTH_CONST_MAP_API();\n};\n\nusing SE3f = SE3; ///< SE3 with float\nusing SE3d = SE3; ///< 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 \n#include \n#include \n#include \n#include\n#include \n#include\n#include \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> stockPrices = simulateStockPrices(numPaths, N, S0, T, u, sigma);\n vector> hedgedPortfolioAllStates = computeHedgingErrors(stockPrices, K, r, T, sigma, 'c');\n\n vector> callOptionPrices = getHedgedPortfolioParam(hedgedPortfolioAllStates, \"V\");\n vector> deltas = getHedgedPortfolioParam(hedgedPortfolioAllStates, \"DELTA\");\n vector> B = getHedgedPortfolioParam(hedgedPortfolioAllStates, \"B\");\n vector> 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> interestRateData = readCSV(\"Data/interest.csv\", 1, 2);\n //vector interestRateDateVec = stringtoDateVect(interestRateData[0]);\n vector interestRateDateVec = interestRateData[0];\n vector interestRateVec = stringToDoubleVect(interestRateData[1]);\n\n // reading stock data\n vector> stockData = readCSV(\"Data/sec_GOOG.csv\", 1, 2);\n //vector stockDateVec = stringtoDateVect(stockData[0]);\n vector stockDateVec = stockData[0];\n vector stockPriceVec = stringToDoubleVect(stockData[1]);\n\n // reading option data\n //vector> optionData = readCSV(\"Data/op_GOOG.csv\", 1, 6);\n string optionFilePath = \"Data/op_GOOG.csv\";\n ifstream infile(optionFilePath);\n string line;\n vector> 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 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 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 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 * 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–434, \n * doi:10.1007/BF02574699\n */\n\n#ifndef SDLP_HPP\n#define SDLP_HPP\n\n#include \n#include \n#include \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 \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 \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(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, °en);\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 \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 \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 \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 \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 \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(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(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(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(plane_i, imax, n_vec, new_n_vec);\n plane_down(plane_i, imax, d_vec, new_d_vec);\n }\n /* solve sub problem */\n status = linfracprog(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(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 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 \n inline double linprog(const Eigen::Matrix &c,\n const Eigen::Matrix &A,\n const Eigen::Matrix &b,\n Eigen::Matrix &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 n_vec;\n Eigen::Matrix d_vec;\n Eigen::Matrix opt;\n Eigen::Matrix 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(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 \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();\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; // 内部変数に格納するの忘れがち\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; // 内部変数に格納するの忘れがち\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": "/********************************************************************************\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 \n#include \n#include \n#include \n#include \n\n#include \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 to EAA\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 \n#include \n#include \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 a, pair 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(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 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(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> 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 a, pair 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": "//\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 \n#include \n#include \n#include \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;\n using shape = typename tensor::extents_type;\n using matrix = ublas::matrix;\n\n constexpr auto ones = ublas::ones{};\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;\n auto fones = boost::numeric::ublas::ones{};\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 \n#include \n#include \n\nnamespace state_estimation {\n\nstd::vector getEllipsePoints(double a, double b, const Eigen::Vector2d& offset,\n double angle, uint32_t num_pts) {\n std::vector pts(num_pts);\n\n // Sample the points evenly with respect to angle around the ellipse\n const Eigen::Rotation2D 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 get2DCovarianceEllipsePoints(const Eigen::Matrix2d& cov,\n const Eigen::Vector2d& offset,\n uint32_t num_pts) {\n // Get the eigen vectors\n Eigen::SelfAdjointEigenSolver> solver(cov);\n Eigen::Matrix vectors = solver.eigenvectors();\n Eigen::Matrix 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 \n#include \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 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": "/**\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 \n#include \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 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 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 \n\n#include \n#include \n#include \n#include \n\nnamespace lyapunov{\n \n \n template \n double projected_max_radius(const Eigen::MatrixBase & C0,\n const Eigen::MatrixBase & 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\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\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;\n using s_vec_t = Eigen::Matrix;\n \n using args = std::tuple, double, DIST*>;\n \n template \n fixed_ellipsoidal_lyap_t(const Eigen::MatrixBase &P,\n double gamma, DIST &dist):\n _gamma(gamma), _dist(dist){\n set_P(P);\n }\n \n template \n void compute(CARGS &&...cargs){\n // Just forwarding\n traj_t::compute(cargs...);\n }\n \n template \n void set_P(const Eigen::MatrixBase& P) {\n assert(P.rows() == dimx);\n assert(P.rows() == P.cols());\n \n // Compute cholesky\n Eigen::LLT> 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\n// bool intersect(const Eigen::MatrixBase &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\n// bool covers(const Eigen::MatrixBase &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\n// bool is_covered(const Eigen::MatrixBase &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 P = std::make_shared();\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 \n#include // std::length_error\n//\n//#include \n//#include \n#include \n#include \n//\n#include // tf quaternion\n#include // tf2 quaternion\n\nnamespace math_quat {\n\n static tf2::Quaternion getAverageQuaternion(\n const std::vector &quaternions,\n const std::vector &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 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 &quaternions,\n const std::vector &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 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 \n#include \n\n#include \n#include \n#include \n\n#include \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\n inline TFloat degToRad(const TFloat degree) {\n return static_cast(degree * DEGREE_TO_RAD);\n }\n\n template\n inline TFloat radToDeg(const TFloat radian) {\n return static_cast(radian * RAD_TO_DEGREE);\n }\n\n/// Convert [0, 360] degrees bearing into [-pi, pi] azimuth.\n template\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\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\n T Log2(T x) {\n return log(x) / log(2);\n }\n\n template\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\n bool AlmostEqualULPs(TFloat x, TFloat y, unsigned int maxULPs = 256) {\n static_assert(std::is_floating_point::value, \"\");\n static_assert(std::numeric_limits::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::exact IntType;\n typedef typename boost::uint_t::exact UIntType;\n\n IntType xInt = *reinterpret_cast(&x);\n IntType yInt = *reinterpret_cast(&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\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\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\n inline T id(T const &x) {\n return x;\n }\n\n template\n inline T sq(T const &x) {\n return x * x;\n }\n\n template\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\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\n inline bool between_s(T a, T b, T x) {\n return (a <= x && x <= b);\n }\n\n template\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(-static_cast(size)) & (align - 1));\n }\n\n template\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\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\n inline T NextModN(T x, T n) {\n return x + 1 == n ? 0 : x + 1;\n }\n\n template\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\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": "///////////////////////////////////////////////////////////////////\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 \n #include \n #include \n \n #include \n \n namespace boost { namespace math { namespace fft {\n \n namespace detail {\n \n template\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\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()/n;\n return RealType(cos(phase));\n }\n template\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()/n;\n return RealType(sin(phase));\n }\n \n template \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(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>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(len,j) }, \n sin{ complex_root_of_unity_imag(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 \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(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(len,-j) }, \n sin{ complex_root_of_unity_imag(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>1;!( (j^=k)&k );k>>=1);\n }\n }\n \n template\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(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(N,i*l*sign);\n sum_y += in_first[l] * complex_root_of_unity_imag(N,i*l*sign);\n }\n // if(i\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 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\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\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(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(N,i*l*sign);\n sum_y += in_first[j] * complex_root_of_unity_imag(N,i*l*sign);\n }\n // if(i\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 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\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 \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; \n using ComplexAllocator = typename std::allocator_traits::template rebind_alloc;\n \n const long n = static_cast(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 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 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(len,k*j);\n }else\n {\n tmp[0] = ComplexType{out[i + k ],-out[i+len_old-k]};\n for(long j=1;j(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(tmp.data(),tmp.data()+p,tmp.data(),1,alloc);\n }\n for(long j=0;jposy)\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\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 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\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 \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; \n using ComplexAllocator = typename std::allocator_traits::template rebind_alloc;\n \n const long n = static_cast(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 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 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;jposy)\n {\n tmp[j] = ComplexType{out[i+posy],out[i+posx]};\n }else // if(posx(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(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(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 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\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 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\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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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 svd(A, Eigen::ComputeThinU |Eigen::ComputeThinV);\n\tJ_pseudoInv = svd.matrixV()*svd.singularValues().inverse()*svd.matrixU().transpose();\n\t\n\tcout << \"Hello World! \"<\n#include \n\n#include \n#include \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 \n#include \n#include \n\n#include \n#include \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> vva(va, len);\n Eigen::Map> 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> eA(mA, M, N);\n Map> eB(mB, M, N);\n Map> eC(mC, M, N);\n eC = eA + eB;\n}\n\n// 例子1:创建2x2矩阵,逐元素赋值,然后输出\nstatic void eigen_example1()\n{\n LOGD(\"--- %s ---\\n\", __FUNCTION__);\n MatrixXd m(2,2); // MatrixXd是最常用的Eigen数据类型,X表示任意尺寸,d表示double。这里创建的是2x2规格的矩阵。\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; // 输出矩阵,直接std::cout即可,说明有重载<<操作符\n}\n\n// 矩阵乘以向量的例子。\nstatic void eigen_example2()\n{\n LOGD(\"--- %s ---\\n\", __FUNCTION__);\n MatrixXd m = MatrixXd::Random(3,3); //创建3x3矩阵,元素为[-1,1]之间的随机浮点数\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 // 也就是把原本在[-1,1]之间的各个元素,映射到[10, 110]之间\n\n cout << \"m=\" << endl << m << endl;\n\n VectorXd v(3); // 创建一个3行的列向量v\n\n v << 1, 2, 3; // 给列向量赋值,分别为1,2,3\n\n cout << \"m*v=\" << endl << m*v << endl; // 计算 m*v,也就是矩阵乘以向量,并输出结果\n}\n\n// eigen_example2的另一个版本:使用具体尺寸的类型,而不是MatrixXd和VectorXd\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// 访问系数(元素)\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// 用逗号表达式初始化\nstatic void eigen_example4()\n{\n LOGD(\"--- %s ---\\n\", __FUNCTION__);\n Matrix3f m; // 声明\n\n // 初始化。注意:必须先声明,才能用逗号表达式初始化;定义时直接用逗号表达式初始化会报错\n // 因为这个初始化其实是通过重载<<操作符实现的\n m << 1, 2, 3,\n 4, 5, 6,\n 7, 8, 9;\n cout << m << endl;\n}\n\n// 输出维度信息、元素个数;动态尺寸矩阵/向量的resize\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// 动态尺寸矩阵赋值,如果尺寸不同,则自动把等号左边的矩阵resize\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的修改,从固定尺寸(3x3)的矩阵,赋值给动态维度的2x2矩阵,隐式resize\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": "// 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 \n#include \n\n#include // fill, any_of, min_element, max_element\n#include // sqrt\n#include // 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 \n#include \n#include \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 dayCountFractionVector(myDoubles, myDoubles + sizeof(myDoubles) / sizeof(double));\n\n std::vector calculated_values = getTotalDayCountFractionVector(dayCountFractionVector);\n\n double myResults[] = {0.513888888889, 1.019444444444, 1.525000000000, 2.030555555556};\n std::vector 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 LAPACK.\n// 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 \n\n// Must be loaded in the following order\n#include \n#include \n\n#include \n#include \n\nint main( int argc, char** argv )\n{\n using std::size_t;\n using pair = std::pair;\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 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 Q = A;\n Matrix R = Matrix::Zero();\n Matrix QtimesR = Matrix::Zero();\n\n std::cout << \"A = \" << std::endl << A << std::endl << std::endl;\n\n // LAPACK -----------------------------------------------\n \n std::cout << \"--- LAPACK: ---\" << std::endl << std::endl;\n\n // Allocates memory\n Matrix tau;\n Matrix work;\n Matrix 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::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 qrEigen( A );\n // Generate Q\n Q = qrEigen.householderQ() * Matrix::Identity();\n // Copy the upper triangle to R\n R = qrEigen.matrixQR().block(0,0,n,n).triangularView();\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::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": "// 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 \n//] [polynomial_arithmetic_0\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \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 \nstring sign_str(T const &x)\n{\n return x < 0 ? \"-\" : \"+\";\n}\n\ntemplate \nstring inner_coefficient(T const &x)\n{\n string result(\" \" + sign_str(x) + \" \");\n if (abs(x) != T(1))\n result += lexical_cast(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 \nstring formula_format(polynomial const &a)\n{\n string result;\n if (a.size() == 0)\n result += lexical_cast(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(abs(a[i]));\n\n if (i > 0)\n {\n result += \"x\";\n if (i > 1)\n {\n result += \"^\" + lexical_cast(i);\n i--;\n for (; i != 1; i--)\n if (a[i])\n result += inner_coefficient(a[i]) + \"x^\" + lexical_cast(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(abs(a[i]));\n }\n }\n return result;\n} // string formula_format(polynomial 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 const d3a = {{10, -6, -4, 3}};\n polynomial const a(d3a.begin(), d3a.end());\n\n // With C++11 and later, you can also use initializer_list construction.\n polynomial 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 s = a + b;\n cout << \"a + b = \" << formula_format(s) << \"\\n\";\n polynomial d = a - b;\n cout << \"a - b = \" << formula_format(d) << \"\\n\";\n polynomial p = a * b;\n cout << \"a * b = \" << formula_format(p) << \"\\n\";\n polynomial q = a / b;\n cout << \"a / b = \" << formula_format(q) << \"\\n\";\n polynomial 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, polynomial > 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 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": "// 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 \r\n#include \r\n#include \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 \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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(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>(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 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 D = D_COO.makeSparse();\n Eigen::SparseMatrix> M = std::complex(0, 1) * D;\n\n // Stiffness matrix\n lf::assemble::COOMatrix 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 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": "#ifndef _COCONUT_PULP_MATH_QUATERNION_HPP_\n#define _COCONUT_PULP_MATH_QUATERNION_HPP_\n\n#include \n\n#include \"ScalarEqual.hpp\"\n#include \"Vector.hpp\"\n\nnamespace coconut {\nnamespace pulp {\nnamespace math {\n\ntemplate >\nclass Quaternion :\n\tboost::equality_comparable,\n\tboost::additive,\n\tboost::multipliable,\n\tboost::multiplicative, ScalarType\n\t>>>>\n{\npublic:\n\n\tusing Scalar = ScalarType;\n\n\tusing ScalarPart = Scalar;\n\n\tusing VectorPart = Vector;\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;\n\t\n\tElements elements_;\n\n};\n\ntemplate \nS dot(const Quaternion& lhs, const Quaternion& rhs) noexcept {\n\treturn lhs.dot(rhs);\n}\n\nusing Quat = Quaternion;\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 \n#include \n#include \n#include \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> 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 opK(K_);\n\t\tSpectra::SparseCholesky opM(massMat_);\n\n\t\tSpectra::SymGEigsSolver, Spectra::SparseCholesky, 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 opK(K_);\n\t\tSpectra::SparseCholesky opM(massMat_);\n\n\t\tSpectra::SymGEigsSolver, Spectra::SparseCholesky, 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;\n\t\tusing BOpType = Spectra::SparseSymMatProd;\n\t\tOpType op(K_, massMat_);\n\t\tBOpType Bop(massMat_);\n\n\t\tSpectra::SymGEigsShiftSolver 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 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 \n#include \n#include \n#include \n\nnamespace ei = Eigen;\nnamespace mp = mplotpp;\n\ntemplate\nstd::tuple,\n Eigen::Array>\nmeshgrid(const Eigen::Array& x,\n const Eigen::Array& y)\n{\n Eigen::Array X(y.size(), x.size());\n Eigen::Array 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 \n\n#include \n\n#include \n#include \n#include \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 xt = flat_tri_[t];\n\t\tMatrix ut = Matrix();\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 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": "#include \n#include \"mtao/optimization/line_search.hpp\"\n\n#include \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// 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/// (link).\n////////////////////////////////////////////////////////////////////////////////\n\n#include \n#include \n#include \n#include \n#include \n\n////////////////////////////////////////////////////////////////////////////////\n/// @brief Returns truncated integer square root of given number.\n/// @tparam IntType Integral type of the number.\n////////////////////////////////////////////////////////////////////////////////\ntemplate \ninline IntType sqrt_int(IntType n)\n{\n return static_cast( 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 \nstruct largest_prime_factors_filter\n{\n static_assert(std::is_integral::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 pe_3a \" << std::endl;\n });\n return EXIT_FAILURE;\n }\n\n stapl::counter exec_timer;\n exec_timer.start();\n\n // Read the dividend from command line.\n value_t num = boost::lexical_cast (argv[1]);\n\n // Create array container for storage and a view into it.\n stapl::array 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(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 \n\n#include \"warp.h\"\n\nvoid llcv_calc_persp_transform(float *matrixData, int matrixDataSize, bool rowMajor, const vector sourcePoints, const vector 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 Matrix8x8;\n typedef Eigen::Matrix 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& source_points, const cv::Rect& to_rect, Mat& output)\n{\n float matrix[16];\n\tvector 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(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 \n#include \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 \n auto arnoldi(const Eigen::MatrixBase& M, const Eigen::MatrixBase& b, Eigen::PlainObjectBase& Q, Eigen::PlainObjectBase& H) {\n const int N = H.rows() - 1;\n using Scalar = typename Derived::Scalar;\n constexpr Scalar eps = std::numeric_limits::epsilon();\n using Vec = Eigen::Matrix;\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 \n auto arnoldi(const Eigen::MatrixBase& M, const Eigen::MatrixBase& B, int N) {\n assert(M.rows() == M.cols());\n\n using Scalar = typename Derived::Scalar;\n using Mat = Eigen::Matrix;\n using DMat = Eigen::Matrix;\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 \n auto arnoldi(const Eigen::MatrixBase& M, const Eigen::MatrixBase& B) {\n assert(M.rows() == M.cols());\n\n using Scalar = typename Derived::Scalar;\n using Mat = Eigen::Matrix;\n using HMat = Eigen::Matrix;\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 \n auto arnoldi(const Eigen::MatrixBase& M, int N) {\n using Scalar = typename Derived::Scalar;\n auto B = Eigen::Matrix::Random(M.rows()) ;\n return arnoldi(M,B,N);\n }\n template \n auto arnoldi(const Eigen::MatrixBase& M) {\n using Scalar = typename Derived::Scalar;\n auto B = Eigen::Matrix::Random(M.rows()) ;\n return arnoldi(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 \n#include \n#include \n#include \n\n// BGL includes\n#include \n#include \n#include \n\ntypedef boost::adjacency_list graph;\ntypedef boost::graph_traits::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 mate_map(n); // exterior property map\n // const vertex_desc NULL_VERTEX = boost::graph_traits::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> characteristics(n);\n for(int i = 0; i < n; i++) {\n characteristics[i] = unordered_set(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 \n#include \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 \r\n#include \r\n#include \r\n#include \r\n\r\nusing boost::multiprecision::cpp_int;\r\n\r\nstd::vector 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 &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 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 &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 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 take_input() {\r\n std::string line;\r\n std::string number;\r\n std::vector 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": "/**\n * @file quaternion_algebra.hpp\n * @author Paul Furgale \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. “Pose Estimation using Linearized\n * Rotations and Quaternion Algebra”. 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 \n#include \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 \nEigen::Matrix quat2AxisAngle(Eigen::Matrix const& q);\nextern template Eigen::Matrix quat2AxisAngle(Eigen::Matrix const& q);\nextern template Eigen::Matrix quat2AxisAngle(Eigen::Matrix 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 quatJacobian(Eigen::Vector4d const& q);\nEigen::Vector4d updateQuat(Eigen::Vector4d const& q, Eigen::Vector3d const& dq);\nEigen::Matrix quatS(Eigen::Vector4d q);\nEigen::Matrix 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 quatLogJacobian(const Eigen::Vector4d& p);\n\n/// \\brief Jacobian of the quat exp function evaluated at vec\ntemplate \nEigen::Matrix quatExpJacobian(const Eigen::Matrix& vec);\n\ntemplate \nEigen::Matrix quatLogJacobian2(const Eigen::Matrix& p);\n\ntemplate \nconst Eigen::Matrix& quatV();\n\ntemplate \nEigen::Matrix logDiffMat(const Eigen::Matrix& vec);\n\ntemplate \nEigen::Matrix expDiffMat(const Eigen::Matrix& vec);\n\nextern template const Eigen::Matrix& quatV();\nextern template const Eigen::Matrix& quatV();\nextern template Eigen::Matrix quatExpJacobian(const Eigen::Matrix& vec);\nextern template Eigen::Matrix quatExpJacobian(const Eigen::Matrix& vec);\nextern template Eigen::Matrix quatLogJacobian2(const Eigen::Matrix& p);\nextern template Eigen::Matrix quatLogJacobian2(const Eigen::Matrix& p);\nextern template Eigen::Matrix logDiffMat(const Eigen::Matrix& vec);\nextern template Eigen::Matrix logDiffMat(const Eigen::Matrix& vec);\nextern template Eigen::Matrix expDiffMat(const Eigen::Matrix& vec);\nextern template Eigen::Matrix expDiffMat(const Eigen::Matrix& 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 \n#include \n\n#include \n#include \n\n#include \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 \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 \n std::vector 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 \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": "#include \n#include \n#include \n\n#include \"matrix_gemm.h\"\n#include \"common/pixel_benchmark.h\"\n#include \"common/pixel_check.h\"\n\n#include \n#include \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> eA(mA, M, K);\n Eigen::Map> eB(mB, K, N);\n Eigen::Map> 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 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\n#include \n#include \n\nnamespace Avogadro {\nnamespace QtPlugins {\nnamespace QTAIMMathUtilities {\n\nMatrix eigenvaluesOfASymmetricThreeByThreeMatrix(\n const Matrix& A)\n{\n SelfAdjointEigenSolver> eigensolver(A);\n return eigensolver.eigenvalues();\n}\n\nMatrix eigenvectorsOfASymmetricThreeByThreeMatrix(\n const Matrix& A)\n{\n SelfAdjointEigenSolver> eigensolver(A);\n return eigensolver.eigenvectors();\n}\n\nMatrix eigenvaluesOfASymmetricFourByFourMatrix(\n const Matrix& A)\n{\n SelfAdjointEigenSolver> eigensolver(A);\n return eigensolver.eigenvalues();\n}\n\nMatrix eigenvectorsOfASymmetricFourByFourMatrix(\n const Matrix& A)\n{\n SelfAdjointEigenSolver> 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& A)\n{\n SelfAdjointEigenSolver> eigensolver(A);\n Matrix eigenvalues = eigensolver.eigenvalues();\n\n return signOfARealNumber(eigenvalues(0)) + signOfARealNumber(eigenvalues(1)) +\n signOfARealNumber(eigenvalues(2));\n}\n\nqreal ellipticityOfASymmetricThreeByThreeMatrix(const Matrix& A)\n{\n SelfAdjointEigenSolver> eigensolver(A);\n Matrix eigenvalues = eigensolver.eigenvalues();\n\n return (eigenvalues(0) / eigenvalues(1)) - 1.0;\n}\n\nqreal distance(const Matrix& a, const Matrix& 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 sphericalToCartesian(const Matrix& rtp,\n const Matrix& 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 xyz(r * cosphi * sintheta + x0,\n r * sintheta * sinphi + y0, r * costheta + z0);\n\n return xyz;\n}\n\nMatrix sphericalToCartesian(const Matrix& rtp)\n{\n Matrix x0y0z0(0., 0., 0.);\n\n return sphericalToCartesian(rtp, x0y0z0);\n}\n\nMatrix cartesianToSpherical(const Matrix& xyz,\n const Matrix& 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 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 cartesianToSpherical(const Matrix& xyz)\n{\n Matrix 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 minusThreeSignatureLocatorGradient(\n const Matrix& g, const Matrix& H)\n{\n Matrix value;\n\n Matrix b = eigenvaluesOfASymmetricThreeByThreeMatrix(H);\n Matrix U = eigenvectorsOfASymmetricThreeByThreeMatrix(H);\n\n Matrix F = U.transpose() * g;\n\n Matrix 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 eval = eigenvaluesOfASymmetricFourByFourMatrix(A);\n\n Matrix lambda;\n lambda << eval(3), eval(3), eval(3);\n\n Matrix 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 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 minusOneSignatureLocatorGradient(\n const Matrix& g, const Matrix& H)\n{\n Matrix value;\n\n Matrix b = eigenvaluesOfASymmetricThreeByThreeMatrix(H);\n Matrix U = eigenvectorsOfASymmetricThreeByThreeMatrix(H);\n\n Matrix F = U.transpose() * g;\n\n Matrix A;\n A << b(0), 0., F(0), 0., b(1), F(1), F(0), F(1), 0.;\n\n Matrix eval = eigenvaluesOfASymmetricThreeByThreeMatrix(A);\n\n Matrix 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 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 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 plusOneSignatureLocatorGradient(\n const Matrix& g, const Matrix& H)\n{\n Matrix value;\n\n Matrix b = eigenvaluesOfASymmetricThreeByThreeMatrix(H);\n Matrix U = eigenvectorsOfASymmetricThreeByThreeMatrix(H);\n\n Matrix F = U * g;\n\n Matrix A;\n A << b(1), 0., F(1), 0., b(2), F(2), F(1), F(2), 0.;\n\n Matrix eval = eigenvaluesOfASymmetricThreeByThreeMatrix(A);\n\n Matrix 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 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 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 plusThreeSignatureLocatorGradient(\n const Matrix& g, const Matrix& H)\n{\n Matrix value;\n\n Matrix b = eigenvaluesOfASymmetricThreeByThreeMatrix(H);\n Matrix U = eigenvectorsOfASymmetricThreeByThreeMatrix(H);\n\n Matrix F = U * g;\n\n Matrix 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 eval = eigenvaluesOfASymmetricFourByFourMatrix(A);\n\n Matrix lambda;\n lambda << eval(0), eval(0), eval(0);\n\n Matrix 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 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 \n#include \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 \n#include \n#include \n#include \n#include \n#include \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& 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_vector, Matrix& 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& load_vector) {\n Matrix stiffness = Matrix::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 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::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 \n#include \n#include \n#include \n#include \"matrix_chain_order.hpp\"\n\n\nnamespace ch15 {\n\n//! foward declarations\ntemplate\nvoid\nbuild_chain(ch15::Chain& chain,\n const Range& dimensions,\n const typename Range::value_type& init_val = 0);\n\ntemplate\nvoid\nbuild_dimensions(const ch15::Chain& chain,\n Range& dimensions);\n\ntemplate\nvoid print_matrix_chain(const ch15::Chain& chain);\n\ntemplate\nch15::Matrix\nmatrix_chain_multiply(const ch15::Chain& 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\ninline void\nbuild_chain(ch15::Chain& 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(*it, *(it + 1), init_val);\n chain.push_back(mat);\n }\n}\n\n/**\n * @brief print_matrix_chain\n * @param chain\n */\ntemplate\ninline void\nprint_matrix_chain(const ch15::Chain& 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\ninline void\nbuild_dimensions(const ch15::Chain& 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\nch15::Matrix\nmatrix_chain_multiply(const ch15::Chain& chain)\n{\n //! type def for MatrixChainOrder's parameter\n using RangeType = std::vector;\n using SizeType = typename ch15::Matrix::size_type;\n\n //! build dimensions\n RangeType dimens;\n ch15::build_dimensions(chain, dimens);\n\n //! build optimal order\n ch15::MatrixChainOrder 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(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 \n//#include \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 v = {30,35,15,5,10,20,25};\n\n// ch15::Chain chain;\n// ch15::build_chain(chain, v, 2);\n// ch15::print_matrix_chain(chain);\n\n// std::vector 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 \n//#include \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 v = {30,35,15,5,10,20,25};\n\n// ch15::Chain 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#include \"BinomialCoefficient.hh\"\n#include \n\nnamespace kt84 {\n\ntemplate \nstruct PolynomialBasisGenT {\n enum { DimOut = PolynomialBasisGenT<_DimIn, _Degree - 1>::DimOut + BinomialCoefficient<_DimIn + _Degree - 1, _Degree>::Value };\n typedef Eigen::Matrix Point;\n typedef Eigen::Matrix Basis;\n typedef Eigen::Matrix Gradient;\n \n static Basis basis(const Point& x) {\n const int N = BinomialCoefficient<_DimIn + _Degree - 1, _Degree>::Value;\n Eigen::Matrix 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 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 \nstruct PolynomialBasisGenT<_DimIn, 0> {\n enum { DimOut = 1 };\n typedef Eigen::Matrix Point;\n typedef Eigen::Matrix Basis;\n typedef Eigen::Matrix 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 \n#include \n#include \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 \n#include \n#include \n#include \n#include \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 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 \n#include \n\nusing namespace Eigen;\n\ntemplate \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 \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 // For float_distance.\n#include \n#include \n\n//[root_finding_multiprecision_include_1\n#include // For cpp_bin_float_50.\n#include // For cpp_dec_float_50.\n#ifndef _MSC_VER // float128 is not yet supported by Microsoft compiler at 2013.\n# include // Requires libquadmath.\n#endif\n//] [/root_finding_multiprecision_include_1]\n\n#include \n// using std::cout; using std::endl;\n#include \n// using std::setw; using std::setprecision;\n#include \n// using std::numeric_limits;\n#include \n#include // pair, make_pair\n\n// #define BUILTIN_POW_GUESS // define to use std::pow function to obtain a guess.\n\ntemplate \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(x), static_cast(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(x), &exponent); // Get exponent of z (ignore mantissa).\n T guess = ldexp(static_cast(1.), exponent / 3); // Rough guess is to divide the exponent by three.\n T min = ldexp(static_cast(1.) / 2, exponent / 3); // Minimum possible value is half our guess.\n T max = ldexp(static_cast(2.), exponent / 3); // Maximum possible value is twice our guess.\n#endif\n\n int digits = std::numeric_limits::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(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 \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 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 \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 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(x) - value; // Difference (estimate x^3 - value).\n T dx = n * pow(x); // 1st derivative = 5x^4.\n T d2x = n * (n - 1) * pow(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 \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(1.), exponent / n); // Rough guess is to divide the exponent by three.\n T min = ldexp(static_cast(0.5), exponent / n); // Minimum possible value is half our guess.\n T max = ldexp(static_cast(2.), exponent / n); // Maximum possible value is twice our guess.\n\n int digits = std::numeric_limits::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(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 \nT show_cube_root(T value)\n{ // Demonstrate by printing the root using all definitely significant digits.\n std::cout.precision(std::numeric_limits::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::digits10);\n // or use cout.precision(max_digits10 = 2 + std::numeric_limits::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::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(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(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 \n#include \n\n#include \n#include \n#include \n#include \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 \nvoid foo(void)\n{\n std::cout << \"========================\" << std::endl;\n\n /* prints the numerical precision i.e. 64 */\n std::cout << std::numeric_limits::digits10 << std::endl;\n\n T a = 2;\n //T b = boost::math::constants::pi > >();\n T b = boost::math::constants::pi();\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::max_digits10) << a << std::endl;\n std::cout << std::setprecision(std::numeric_limits::max_digits10) << b << std::endl;\n std::cout << std::setprecision(std::numeric_limits::max_digits10) << c << std::endl;\n std::cout << std::setprecision(std::numeric_limits::max_digits10) << d << std::endl;\n std::cout << std::setprecision(std::numeric_limits::max_digits10) << e << std::endl;\n}\n\nint main(void)\n{\n //foo(); // see bug.cc\n foo();\n foo();\n foo();\n foo();\n foo > >();\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 \n\n#include \n#include \n\n#include \n#include \n\n#include \n\n#include \n#include \n\ntypedef CGAL::Simple_cartesian Kernel;\ntypedef CGAL::Surface_mesh PolygonMesh;\nusing namespace std;\nusing namespace CGAL;\nnamespace params = CGAL::parameters;\n\n// ======================================================================\ntemplate \nclass WLoop_mask_3 {\n typedef Poly PolygonMesh;\n\n typedef typename boost::graph_traits::vertex_descriptor vertex_descriptor;\n typedef typename boost::graph_traits::halfedge_descriptor halfedge_descriptor;\n\n typedef typename boost::property_map::type Vertex_pmap;\n typedef typename boost::property_traits::value_type Point;\n typedef typename boost::property_traits::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 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(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(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 \n#include \n#include \n#include \n#include \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 SdirkSolve(const Eigen::Vector2d &z0,\n unsigned int M, double T,\n double gamma) {\n // Solution vector\n std::vector 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 * \\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 \n#include \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 getConvexHull(\n std::vector 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 const& lhs,\n std::vector 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 \nnamespace fft = boost::math::fft;\n\n#include \n#include \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;\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 A{4, 3, 2, 1, 0, 0, 0, 0};\n std::vector 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 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 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(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 \n#include \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(lambda.col(0).data());\n// double * alphai = const_cast(lambda.col(1).data());\n// double * beta = const_cast(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 \"kabsch.h\"\n#include \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 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änkt), 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 \n#include \n\n\nusing namespace std;\n\n// Alleged error reported by Dragan Vidovic\n\ntemplate\nmtl::dense2D inv2 ( const mtl::dense2D & M )\n{\n mtl::dense2D 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 tmp(2, 2);\n tmp= 3, 5,\n\t 8, 9;\n\n mtl::dense2D 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 \n#include \n#include \n#include \n#include \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 \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 \nKDerived polynomial_kernel(LhsDerived &lhs,\n RhsDerived &rhs,\n const double degree,\n const double offset)\n{\n return (linear_kernel(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 \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 \nKDerived\nsigmoidal_kernel(LhsDerived &lhs, RhsDerived &rhs, const double a, const double b)\n{\n\n return (a * linear_kernel(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": "/* 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 \n\n#include \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 \n#include \n#include \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 &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 \n#include \n#include \n#include \n#include \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 &data, std::vector > &sim_vec, int sim_len, const int iterations){\n double sigma;\n double mu;\n double drift;\n std::vector log_returns;\n std::vector 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> acc;\n\n for(std::vector::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 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 &data_underlying, const double strike, const double risk_free_rate, const int days_to_exp, const int iterations){\n std::vector average_prices;\n std::vector payout;\n std::vector > 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::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::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 &data_underlying, const double strike, const double risk_free_rate, const int days_to_exp, const int iterations){\n std::vector average_prices;\n std::vector payout;\n std::vector > 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::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::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 &data_underlying, const double strike, const double risk_free_rate, const int days_to_exp, const int iterations){\n std::vector average_prices;\n std::vector payout;\n double maturity_price;\n std::vector > 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::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::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 &data_underlying, const double strike, const double risk_free_rate, const int days_to_exp, const int iterations){\n std::vector average_prices;\n std::vector payout;\n double maturity_price;\n std::vector > 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::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::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 &data_underlying, const double strike, const double risk_free_rate, const int days_to_exp, const int iterations){\n std::vector price;\n double iter_cont; // continuation value for this particular iteration\n std::vector > sim_vec;\n std::vector > cfm; // cash flow matrix\n std::vector 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>::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 xs;\n std::vector ys;\n std::vector 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>::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 &data_underlying, const double strike, const double risk_free_rate, const int days_to_exp, const int iterations){\n std::vector price;\n double iter_cont; // continuation value for this particular iteration\n std::vector > sim_vec;\n std::vector > cfm; // cash flow matrix\n std::vector 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>::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 xs;\n std::vector ys;\n std::vector 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>::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 \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 \n\n#include \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 \n#include \n#include \n\n#include \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\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\n class Polynomial\n {\n Eigen::Matrix coef;\n public:\n Polynomial()\n : coef( Eigen::Matrix::Zero() )\n {\n \n }\n \n Polynomial( const Eigen::Matrix &coefin )\n : coef( coefin )\n {\n\n }\n \n Polynomial( const Polynomial &polyin )\n : coef( polyin.coef )\n {\n\n }\n \n Polynomial( const double *coefin )\n : coef( Internal::vecmap( coefin ) )\n {\n \n }\n \n const Eigen::Matrix &coefficients() const\n {\n return coef;\n }\n\n Eigen::Matrix &coefficients()\n {\n return coef;\n }\n\n template\n Polynomial::value> operator+(const Polynomial &poly) const\n {\n Polynomial::value> p;\n p.coefficients().tail(degin+1) = poly.coefficients();\n p.coefficients().tail(deg+1) += coef;\n return p;\n }\n \n template\n Polynomial::value> operator-(const Polynomial &poly) const\n {\n Polynomial::value> p;\n p.coefficients().tail(deg+1) = coef;\n p.coefficients().tail(degin+1) -= poly.coefficients();\n return p;\n }\n \n template\n Polynomial operator*(const Polynomial &poly) const\n {\n Polynomial p;\n Internal::PolyConv::compute(p.coefficients(),coef,poly.coefficients());\n return p;\n }\n \n Polynomial operator*(const double c) const\n {\n return Polynomial(coef*c);\n }\n \n double eval(double x) const\n {\n return Internal::PolyVal::compute(coef,x);\n }\n \n void realRoots(std::vector &roots) const\n {\n if ( coef[0] == 0 )\n {\n Internal::RootFinder::compute(coef.tail(deg),roots);\n } else {\n Internal::RootFinder::compute(coef,roots);\n }\n }\n \n void realRootsSturm(const double lb, const double ub, std::vector &roots) const\n {\n if ( coef[0] == 0 )\n {\n Internal::SturmRootFinder sturm( coef.tail(deg) );\n sturm.realRoots( lb, ub, roots );\n } else {\n Internal::SturmRootFinder sturm( coef );\n sturm.realRoots( lb, ub, roots );\n }\n }\n \n void rootBounds( double &lb, double &ub )\n {\n Eigen::Matrix 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\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 &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 operator+(const Polynomial &poly) const\n {\n int deg = coef.rows()-1;\n int degin = poly.coef.rows()-1;\n Polynomial 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 operator-(const Polynomial &poly) const\n {\n int deg = coef.rows()-1;\n int degin = poly.coef.rows()-1;\n Polynomial 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 operator*(const Polynomial &poly) const\n {\n int deg = coef.rows()-1;\n int degin = poly.coef.rows()-1;\n Polynomial p( deg+degin );\n Internal::PolyConv::compute(p.coef,coef,poly.coef);\n return p;\n }\n \n Polynomial operator*(const double c) const\n {\n return Polynomial(coef*c);\n }\n \n double eval(double x) const\n {\n return Internal::PolyVal::compute(coef,x);\n }\n \n void realRoots(std::vector &roots) const\n {\n if ( coef[0] == 0 )\n {\n int deg = coef.rows()-1;\n Internal::RootFinder::compute(coef.tail(deg),roots);\n } else {\n Internal::RootFinder::compute(coef,roots);\n }\n }\n \n void realRootsSturm(const double lb, const double ub, std::vector &roots) const\n {\n if ( coef[0] == 0 )\n {\n int deg = coef.rows()-1;\n Internal::SturmRootFinder sturm( coef.tail(deg) );\n sturm.realRoots( lb, ub, roots );\n } else {\n Internal::SturmRootFinder 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 \n#include \n#include \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 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 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 \n#include // std::sort, std::stable_sort\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include // std::iota\n#include \n#include \n\nvoid m2::PcaImageFilter::initMatrix()\n{\n // this->GetValidIndices();\n auto input = this->GetIndexedInputs();\n auto mitkImage = dynamic_cast(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(it->GetPointer());\n mitk::ImagePixelReadAccessor 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 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 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 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": "#include \n#include \n#include \n#include \n#include \n#include \n#include \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(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 * @file\n * @brief NPDE homework ElementMatrixComputation code\n * @author Janik Schüttler, edited by Oliver Rietmann\n * @date 03.03.2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"mylinearfeelementmatrix.h\"\n\n#include \n#include \n#include \n#include \n\n#include \n\nnamespace ElementMatrixComputation {\n\n/* SAM_LISTING_BEGIN_1 */\nEigen::Matrix 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 elem_mat;\n#if SOLUTION\n // Initialize matrix containing the mass part of the element matrix\n Eigen::Matrix 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 \r\n#include \r\n#include \r\n\r\n\r\ntemplate \r\nclass Spline {\r\npublic:\r\n\r\n\t// A spline with x and y values\r\n\tSpline(const arma::Row& x, const arma::Col& 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 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 interpolate(const arma::Row& xx) const {\r\n\t\tif (mElements.empty()) return arma::Row(xx.size());\r\n\r\n\t\tarma::Col ys = arma::zeros>(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 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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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 \n\n\nvoid mandelbrot(\n std::pair resolution, \n std::pair, \n std::complex> 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(0.0, 1.);\n\n std::complex z0(0., 0.);\n std::complex z(z0);\n std::complex c;\n\n xt::xtensor xrange = xt::linspace(a0, a1, width);\n xt::xtensor yrange = xt::linspace(b0, b1, height);\n\n xt::xtensor counts = xt::zeros({ height, width });\n xt::xtensor norms = xt::zeros({ height, width });\n xt::xtensor args = xt::zeros({ 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(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(255 * scaled_counts));\n xt::dump_image(\"../../mandelbrot_norms.png\" , xt::cast(255 * scaled_norms ));\n xt::dump_image(\"../../mandelbrot_args.png\" , xt::cast(255 * scaled_args ));\n\n xt::xtensor image = xt::zeros({ height, width, channels });\n std::tuple 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(&xi)->default_value(-2.0), \"Lower Real Bound\")\n (\"xf\", opt::value(&xf)->default_value(1.0), \"Upper Real Bound\")\n (\"yi\", opt::value(&yi)->default_value(-1.5), \"Lower Imaginary Bound\")\n (\"yf\", opt::value(&yf)->default_value(1.5), \"Upper Imaginary Bound\")\n (\"radius,r\", opt::value(&r)->default_value(2.), \"Bail-Out Radius\")\n (\"power,p\", opt::value(&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(xi, yi), std::complex(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 \n#include \n#include \n#include \n#include \n#include \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 x, vector 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 x_n;\t// Stores values for x at generation n\n\tvector 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 \n#include \n#include \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 \nX Phi(X const& x) {\n return 0.5 * erfc(-one_div_root_two() * x);\n}\n\nenum class CP { call, put };\n\n// Assume zero annual dividend yield (q=0).\ntemplate \npromote 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(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 \n#include \n#include \n#include \n#include \n\nvoid plotData(std::vector 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 gradientDescent() {\n double logitError = computeLogitError();\n std::vector errorList (numIterations, 0.0);\n\n for(int i=0; i 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 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 \r\n#include \r\n#include \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 \n#include \n\n// Eigen\n#include \n\n// std\n#include \n\nusing namespace std;\n\nNAMESPACE_BEGIN ( polyvec )\nNAMESPACE_BEGIN ( Num )\n\ndouble\ndeterminant(Eigen::Ref 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 LHS,\n const Eigen::Ref 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 \n\n#include \n#include \n#include \n\nint main()\n{\n namespace bg = boost::geometry;\n typedef bg::model::point > point_type;\n typedef bg::model::linestring 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 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#include \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 \n#include \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& 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& p)\n {\n //remove duplicates\n std::vector 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(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& 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& 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& 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 \n#include \n#include \nusing namespace geometrycentral;\n\nARAP::ARAP(HalfedgeMesh* m, Geometry* g) : mesh(m), geom(g), vertexIndices(mesh), isoTriangleParam(mesh), uvCoords(mesh) {\n vertexIndices = mesh->getVertexIndices();\n}\n\nEigen::SparseMatrix> ARAP::createLaplaceMatrix() {\n size_t n = mesh->nVertices();\n Eigen::SparseMatrix> A(n,n);\n std::vector>> 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>(index1, index2, std::complex(-weight,0)));\n }\n\n // add diagonal weight\n triplets.push_back(Eigen::Triplet>(index1, index1, std::complex(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 ARAP::computeLRotations(VertexData const &u) {\n FaceData 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 ut = { u[he1.vertex()], u[he2.vertex()], u[he3.vertex()] };\n std::vector xt = { isoTriangleParam[he1], isoTriangleParam[he2], isoTriangleParam[he3] };\n std::vector 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 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 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 sub((xi-xj).x, (xi-xj).y); \n std::complex 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 sub((xi-xj).x, (xi-xj).y); \n std::complex 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> A = createLaplaceMatrix();\n Eigen::SimplicialLDLT>> 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 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 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 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!\"<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 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": "// 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 \n#include \n\nint main() {\n using namespace boost::math::differentiation;\n\n auto const x = make_fvar(13);\n auto const y = make_fvar(14);\n auto const z = 10 * x * x + 50 * x * y + 100 * y * y; // promoted to autodiff_fvar\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": "#include \n#include \n\n#include \n#include \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 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}}